diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a5d09d581..bbb8b3b84 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,6 +27,13 @@ jobs: - uses: actions/setup-python@v5 with: python-version: '3.12' + - name: Does this pull request need Rust checks? + if: github.event_name == 'pull_request' + id: rust + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: python3 tools/ci/rust_changes.py "$BASE_SHA" "$HEAD_SHA" >> "$GITHUB_OUTPUT" - name: Keep game artifacts out of Git run: | python tools/check_public_tree.py @@ -34,19 +41,23 @@ jobs: - name: Test offline research tooling run: python -m unittest discover -s tests -v - name: Install Rust toolchain and the ALSA and udev headers the client links against + if: steps.rust.outputs.required != 'false' run: | sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev rustup toolchain install stable --profile minimal --component rustfmt --component clippy --target wasm32-unknown-unknown # Dependencies and the workspace's own build, saved from main's runs (pull requests read main's cache). - uses: Swatinem/rust-cache@v2 + if: steps.rust.outputs.required != 'false' with: shared-key: verify save-if: ${{ github.ref == 'refs/heads/main' }} - name: Check formatting and lint + if: steps.rust.outputs.required != 'false' run: | cargo +stable fmt --all -- --check cargo +stable clippy --workspace --all-targets -- -D warnings - name: Test Rust core and voxel kernel correctness + if: steps.rust.outputs.required != 'false' run: cargo +stable test --workspace parity: if: >- diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3162b6f1b..38b3af3d0 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -154,7 +154,7 @@ jobs: client="$PWD/target/release/horizon-client" resources="$PWD/.local/horizon-client/$version" (cd "$home" && HORIZON_HOME="$home" HORIZON_NO_AUDIO=1 "$client" --resources "$resources" --offscreen \ - --world smoke --seed 1 --render-distance 4 --frames 1500 --timeout-seconds 180 \ + --world smoke --seed 1 --render-distance 4 --world-frames 1500 --timeout-seconds 180 \ --smoke-report "$home/smoke.json" > "$home/client.log" 2>&1) || { tail -40 "$home/client.log"; exit 1; } python3 - "$home/smoke.json" <<'EOF' import json, sys diff --git a/.gitignore b/.gitignore index ad41a3230..eb29ad10d 100644 --- a/.gitignore +++ b/.gitignore @@ -24,6 +24,8 @@ /horizon.txt /horizon-graphics.txt /horizon-controller.txt +/horizon-extras.txt +/horizon-player.txt /servers.dat /screenshots/ /crash-reports/ diff --git a/Cargo.lock b/Cargo.lock index d6bbf30d9..6ebc69964 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -178,6 +178,15 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" +[[package]] +name = "ascii-canvas" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef1e3e699d84ab1b0911a1010c5c106aa34ae89aeac103be5ce0c3859db1e891" +dependencies = [ + "term", +] + [[package]] name = "ash" version = "0.38.0+1.3.281" @@ -205,15 +214,30 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec 0.8.0", +] + [[package]] name = "bit-set" version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" dependencies = [ - "bit-vec", + "bit-vec 0.9.1", ] +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + [[package]] name = "bit-vec" version = "0.9.1" @@ -259,6 +283,16 @@ dependencies = [ "objc2 0.6.5", ] +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "bytes", + "cfg_aliases", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -450,6 +484,15 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + [[package]] name = "coords-hud" version = "0.1.0" @@ -754,6 +797,41 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "darling" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.119", +] + +[[package]] +name = "darling_macro" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.119", +] + [[package]] name = "dasp_sample" version = "0.11.0" @@ -771,6 +849,29 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", + "unicode-xid", +] + [[package]] name = "digest" version = "0.10.7" @@ -857,6 +958,15 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" +[[package]] +name = "ena" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eabffdaee24bd1bf95c5ef7cec31260444317e72ea56c4c91750e8b7ee58d5f1" +dependencies = [ + "log", +] + [[package]] name = "encoding_rs" version = "0.8.42" @@ -1120,6 +1230,58 @@ version = "0.30.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9" +[[package]] +name = "glsl-lang" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "983a18d0c2ecad18ac9ff3c94b069d6bd03b47405a200836d9d8d63def8e34de" +dependencies = [ + "glsl-lang-lexer", + "glsl-lang-types", + "lalrpop", + "lalrpop-util", + "lang-util", + "once_cell", + "thiserror 2.0.21", +] + +[[package]] +name = "glsl-lang-lexer" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abdbc0bdfbc81d557f4865e695457eb23d68031bfb061fda3444f56511b26eee" +dependencies = [ + "glsl-lang-pp", + "glsl-lang-types", + "lalrpop-util", + "lang-util", + "thiserror 2.0.21", +] + +[[package]] +name = "glsl-lang-pp" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88677876fb27f116015d0ecebda6d77bdf65f3a6fa3f5dfeed10b8c8f04cb2c5" +dependencies = [ + "arrayvec", + "derive_more", + "lang-util", + "string_cache", + "string_cache_codegen", + "thiserror 2.0.21", +] + +[[package]] +name = "glsl-lang-types" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd8b1532b424d40df634cf2dc2be56d59f994b9ac07fa7c1e3183fd33db9cb07" +dependencies = [ + "lang-util", + "thiserror 2.0.21", +] + [[package]] name = "gpu-allocator" version = "0.28.0" @@ -1255,6 +1417,7 @@ dependencies = [ "horizon-friends", "horizon-mods", "horizon-protocol", + "horizon-shaderpack", "horizon-telemetry", "horizon-theme", "horizon-world", @@ -1320,6 +1483,7 @@ dependencies = [ "horizon-mods", "log", "serde", + "serde_json", "toml", "wasmtime", "wit-component 0.239.0", @@ -1334,6 +1498,19 @@ dependencies = [ "horizon-mod-sdk", ] +[[package]] +name = "horizon-port-pack" +version = "0.1.0" +dependencies = [ + "horizon-mods", + "serde", + "serde_json", + "sha1", + "toml", + "ureq", + "zip", +] + [[package]] name = "horizon-prepare" version = "0.1.0" @@ -1364,6 +1541,16 @@ dependencies = [ "serde_json", ] +[[package]] +name = "horizon-shaderpack" +version = "0.1.0" +dependencies = [ + "glsl-lang", + "naga", + "pp-rs", + "zip", +] + [[package]] name = "horizon-telemetry" version = "0.1.0" @@ -1504,6 +1691,12 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + [[package]] name = "idna" version = "1.1.0" @@ -1686,6 +1879,73 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "keccak" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb26cec98cce3a3d96cbb7bced3c4b16e3d13f27ec56dbd62cbc8f39cfb9d653" +dependencies = [ + "cpufeatures", +] + +[[package]] +name = "lalrpop" +version = "0.22.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba4ebbd48ce411c1d10fb35185f5a51a7bfa3d8b24b4e330d30c9e3a34129501" +dependencies = [ + "ascii-canvas", + "bit-set 0.8.0", + "ena", + "itertools", + "lalrpop-util", + "petgraph 0.7.1", + "pico-args", + "regex", + "regex-syntax", + "sha3", + "string_cache", + "term", + "unicode-xid", + "walkdir", +] + +[[package]] +name = "lalrpop-util" +version = "0.22.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5baa5e9ff84f1aefd264e6869907646538a52147a755d494517a8007fb48733" +dependencies = [ + "regex-automata", + "rustversion", +] + +[[package]] +name = "lang-util" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1715a1e56998f119cd6d49ac8a69802dcbe4fca96d8291243d6dae87abeb913" +dependencies = [ + "derive_more", + "lalrpop-util", + "lang-util-derive", + "line-span", + "smol_str 0.3.6", + "text-size", +] + +[[package]] +name = "lang-util-derive" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f2acc66aedf0e445534e0a6b3f0f6ee20ef6ebb9647dbe10735e52ea8d6a096" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "lazy_static" version = "1.5.1" @@ -1742,6 +2002,12 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "line-span" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29fc123b2f6600099ca18248f69e3ee02b09c4188c0d98e9a690d90dec3e408a" + [[package]] name = "linux-raw-sys" version = "0.4.15" @@ -1853,7 +2119,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130" dependencies = [ "arrayvec", - "bit-set", + "bit-set 0.10.0", "bitflags 2.13.2", "cfg-if", "cfg_aliases", @@ -1866,6 +2132,7 @@ dependencies = [ "naga-types", "num-traits", "once_cell", + "pp-rs", "rustc-hash 1.1.0", "spirv", "thiserror 2.0.21", @@ -1914,6 +2181,12 @@ dependencies = [ "jni-sys 0.3.1", ] +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + [[package]] name = "nix" version = "0.31.3" @@ -2413,6 +2686,16 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "petgraph" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772" +dependencies = [ + "fixedbitset", + "indexmap", +] + [[package]] name = "petgraph" version = "0.8.3" @@ -2424,6 +2707,31 @@ dependencies = [ "indexmap", ] +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared", + "rand", +] + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + [[package]] name = "pin-project" version = "1.1.13" @@ -2542,6 +2850,21 @@ dependencies = [ "zerovec", ] +[[package]] +name = "pp-rs" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb458bb7f6e250e6eb79d5026badc10a3ebb8f9a15d1fff0f13d17c71f4d6dee" +dependencies = [ + "unicode-xid", +] + +[[package]] +name = "precomputed-hash" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" + [[package]] name = "presser" version = "0.3.1" @@ -2635,6 +2958,15 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_core", +] + [[package]] name = "rand_core" version = "0.6.4" @@ -2967,6 +3299,16 @@ dependencies = [ "digest", ] +[[package]] +name = "sha3" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77fd7028345d415a4034cf8777cd4f8ab1851274233b45f84e3d955502d93874" +dependencies = [ + "digest", + "keccak", +] + [[package]] name = "shlex" version = "2.0.1" @@ -2995,6 +3337,12 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + [[package]] name = "slab" version = "0.4.12" @@ -3044,6 +3392,16 @@ dependencies = [ "serde", ] +[[package]] +name = "smol_str" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aaa7368fcf4852a4c2dd92df0cace6a71f2091ca0a23391ce7f3a31833f1523" +dependencies = [ + "borsh", + "serde_core", +] + [[package]] name = "socket2" version = "0.5.10" @@ -3093,6 +3451,37 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +[[package]] +name = "string_cache" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf776ba3fa74f83bf4b63c3dcbbf82173db2632ed8452cb2d891d33f459de70f" +dependencies = [ + "new_debug_unreachable", + "parking_lot", + "phf_shared", + "precomputed-hash", + "serde", +] + +[[package]] +name = "string_cache_codegen" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c711928715f1fe0fe509c53b43e993a9a557babc2d0a3567d0a3006f1ac931a0" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "subtle" version = "2.6.1" @@ -3209,6 +3598,15 @@ version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" +[[package]] +name = "term" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8c27177b12a6399ffc08b98f76f7c9a1f4fe9fc967c784c5a071fa8d93cf7e1" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "termcolor" version = "1.4.1" @@ -3218,6 +3616,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "text-size" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f18aa187839b2bdb1ad2fa35ead8c4c2976b64e4363c386d45ac0f7ee85c9233" + [[package]] name = "thiserror" version = "1.0.69" @@ -3377,7 +3781,7 @@ checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" dependencies = [ "memchr", "nom", - "petgraph", + "petgraph 0.8.3", ] [[package]] @@ -4098,8 +4502,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14" dependencies = [ "arrayvec", - "bit-set", - "bit-vec", + "bit-set 0.10.0", + "bit-vec 0.9.1", "bitflags 2.13.2", "bytemuck", "cfg_aliases", @@ -4645,7 +5049,7 @@ dependencies = [ "rustix 0.38.44", "sctk-adwaita", "smithay-client-toolkit", - "smol_str", + "smol_str 0.2.2", "tracing", "unicode-segmentation", "wasm-bindgen", diff --git a/Cargo.toml b/Cargo.toml index 19fbabc55..1b4cb92d4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] +members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] resolver = "2" [workspace.package] diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index b9aeb7aea..19b4c81db 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -27,6 +27,8 @@ serde_json = { version = "1.0.151", features = ["raw_value"] } # Shader packs: pack.toml, and WGSL checked before it reaches wgpu. toml = "1.1" naga = { version = "30.0.1", features = ["wgsl-in"] } +# Java (OptiFine/Iris) shader packs, translated to WGSL. +horizon-shaderpack = { path = "../horizon-shaderpack" } cpal = "0.16" symphonia = { version = "0.5", default-features = false, features = ["ogg", "vorbis"] } miniz_oxide = "0.8" diff --git a/crates/horizon-client/examples/auto_jump_probe.rs b/crates/horizon-client/examples/auto_jump_probe.rs index 3dea957a2..e4a9848e8 100644 --- a/crates/horizon-client/examples/auto_jump_probe.rs +++ b/crates/horizon-client/examples/auto_jump_probe.rs @@ -100,6 +100,7 @@ fn main() -> Result<()> { player.auto_jump_enabled = p["enabled"].as_bool().unwrap(); player.auto_jump_time = p["time"].as_i64().unwrap() as i32; MotionWorld { + entities: &[], player: &mut player, scene: &mut scene, assets: &assets, diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 5762abcd6..087fd3edf 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -19,7 +19,7 @@ use horizon_client::{ }, mobs::{ Mob, MobData, MobEvent, MobTypes, MobWorld, PlayerView, Seen, Species, Who, - control::Operation, spawning::LocalDifficulty, + control::Operation, seen_grid::SeenGrid, spawning::LocalDifficulty, }, world::World, }; @@ -902,6 +902,10 @@ fn main() -> horizon_client::Result<()> { for flag in &spec.flags { match flag.as_str() { "persistent" => m.persistent = true, + "ridden" => { + m.extra.head = Some("minecraft:red_harness".into()); + m.rider = Some(horizon_client::mobs::equine::Rider::default()); + } "noai" => m.no_ai = true, // Warden.finalizeSpawn's own part. "digcooldown" | "emerge" => horizon_client::mobs::warden::finalize( @@ -1007,6 +1011,9 @@ fn main() -> horizon_client::Result<()> { // The MobWorld every step sees, over a snapshot of the mobs. macro_rules! mob_world { ($snapshot:expr) => { + mob_world!($snapshot, None) + }; + ($snapshot:expr, $grid:expr) => { MobWorld { teams: Default::default(), world: &world, @@ -1017,6 +1024,7 @@ fn main() -> horizon_client::Result<()> { data: &data, player: player.clone(), others: $snapshot, + others_grid: $grid, daylight: (world.day_time.rem_euclid(24000)) < 12000, game_time: world.game_time, day_time: world.day_time, @@ -1061,6 +1069,8 @@ fn main() -> horizon_client::Result<()> { p.yaw = yaw; } let mut snapshot: Vec = mobs.iter().filter(|m| !m.removed).map(seen).collect(); + // The snapshot by position, kept as the game keeps it. + let mut grid = SeenGrid::new(snapshot.iter().map(|e| e.bounds)); let w = mob_world!(&snapshot); let mut events = Vec::new(); let mut heart_events = Vec::new(); @@ -1126,7 +1136,7 @@ fn main() -> horizon_client::Result<()> { if mobs[i].removed { continue; } - let w = mob_world!(&snapshot); + let w = mob_world!(&snapshot, Some(&grid)); let m = &mut mobs[i]; horizon_client::mobs::apply_mob_pushes(m, &mut pushes); let from = events.len(); @@ -1242,9 +1252,10 @@ fn main() -> horizon_client::Result<()> { } // ServerLevel ticks entities one after another: the ones // after this mob see it as it is now. - if let Some(e) = snapshot.iter_mut().find(|e| e.id == mobs[i].id) { - *e = seen(&mobs[i]); - e.alive &= !mobs[i].removed; + if let Some(k) = snapshot.iter().position(|e| e.id == mobs[i].id) { + snapshot[k] = seen(&mobs[i]); + snapshot[k].alive &= !mobs[i].removed; + grid.update(k, snapshot[k].bounds); } } for m in &mut mobs { diff --git a/crates/horizon-client/examples/natural_spawn_fixture.rs b/crates/horizon-client/examples/natural_spawn_fixture.rs index 3ce9f6c5a..3fb3d5719 100644 --- a/crates/horizon-client/examples/natural_spawn_fixture.rs +++ b/crates/horizon-client/examples/natural_spawn_fixture.rs @@ -17,13 +17,16 @@ //! a `mobs::trial_spawner::TrialSpawner` with the game time advancing and //! print its states, events, spawns and ejected items. //! +//! Vault cases (`mode=vault`, tools/test_vault_parity.py) tick a +//! `vault::Vault` the same way, with players moving and using keys on it. +//! //! usage: natural_spawn_fixture RESOURCES INPUT OUTPUT use horizon_client::{ assets::Assets, biome::{Biomes, SpawnEntry}, blocks::BlockFacts, collisions::{self, LookupCollisions, no_collision_empty}, - items::Items, + items::{ItemStack, Items}, mobs::{ MobTypes, Species, data::MobData, @@ -35,8 +38,12 @@ use horizon_client::{ }, spawner::{Spawner, SpawnerAdded, SpawnerEvent, SpawnerLevel, SpawnerSpawn}, species::{self, Baby}, - trial_spawner::{TrialEvent, TrialPlayer, TrialSpawner, TrialSpawnerLevel, TrialState}, + trial_spawner::{ + Omen, TRIAL_OMEN_TICKS_PER_LEVEL, TrialEvent, TrialPlayer, TrialSpawner, + TrialSpawnerLevel, TrialState, + }, }, + vault::{Vault, VaultEvent, VaultLevel, VaultPlayer, VaultState}, }; use horizon_core::{ geometry::Aabb, @@ -115,8 +122,14 @@ struct World<'a> { placed: RefCell>, /// The game time (trial cases advance it). time: Cell, - /// The mobs a trial spawner added: UUID, position and box. - trial_mobs: RefCell>, + /// The mobs a trial spawner added: UUID, position, height and box. + trial_mobs: RefCell>, + /// How many mobs a trial spawner added (their UUIDs count up). + trial_count: Cell, + /// Each player's omen and its amplifier (`/trial_omen:A`, `/bad_omen:A`). + omens: RefCell>>, + /// Loot tables (trial cases). + loot: Option>, } impl World<'_> { fn biome_at(&self, x: i32, y: i32, z: i32) -> &str { @@ -378,6 +391,16 @@ impl TrialSpawnerLevel for World<'_> { eye: [p[0], p[1] + f64::from(1.62f32), p[2]], creative: mode == "creative", spectator: mode == "spectator", + position: *p, + height: 1.8, + alive: true, + omen: self + .omens + .borrow() + .get(i) + .copied() + .flatten() + .map(|(o, _)| o), }) .collect() } @@ -400,9 +423,38 @@ impl TrialSpawnerLevel for World<'_> { } fn entity_block(&self, uuid: [i32; 4]) -> Option<[i32; 3]> { let mobs = self.trial_mobs.borrow(); - let (_, p, _) = mobs.iter().find(|(u, ..)| *u == uuid)?; + let (_, p, ..) = mobs.iter().find(|(u, ..)| *u == uuid)?; Some(p.map(|v| v.floor() as i32)) } + fn entity_box(&self, uuid: [i32; 4]) -> Option<([f64; 3], f32)> { + let mobs = self.trial_mobs.borrow(); + let (_, p, h, _) = mobs.iter().find(|(u, ..)| *u == uuid)?; + Some((*p, *h)) + } + fn no_block_collision(&self, block: [i32; 3]) -> bool { + let lookup = |x: i32, y: i32, z: i32| self.state(x, y, z); + let mut scene = LookupCollisions { + block: &lookup, + binding: self.s.collision, + }; + let state = self.state(block[0], block[1], block[2]); + self.s + .collision + .collision_shape(&mut scene, state, block) + .map_or(true, |shape| shape.is_empty()) + } + fn loot_items(&self, table: &str, seed: i64) -> Vec { + let Some(loot) = &self.loot else { + return Vec::new(); + }; + loot.roll_split(table, &mut LegacyRandom::new(seed)) + .iter() + .map(horizon_client::structure_blocks::loot_item_with_components) + .collect() + } + fn seed(&self) -> i64 { + self.seed + } } /// The box a mob is left with by `finalizeSpawn` under the oracle's fixed random. @@ -472,7 +524,7 @@ fn main() -> horizon_client::Result<()> { let data = MobData::load(root, &facts); let items = Items::tags_only(root)?; // Trial spawner rewards: the loot tables and the configs. - let loot = if input.contains("mode=trial") { + let loot = if input.contains("mode=trial") || input.contains("mode=vault") { horizon_client::mobs::trial_spawner::load_registry(root); horizon_client::structure_blocks::loot_data(root) } else { @@ -581,6 +633,19 @@ fn main() -> horizon_client::Result<()> { bounds: Bx(b), }); } + // A player's third field: an omen and its amplifier. + let omens = indexed("p") + .iter() + .map(|p| { + let (effect, amplifier) = p.split('/').nth(2)?.split_once(':')?; + let omen = if effect == "trial_omen" { + Omen::Trial + } else { + Omen::Bad + }; + Some((omen, amplifier.parse().ok()?)) + }) + .collect(); let players = indexed("p") .into_iter() .map(|p| { @@ -667,6 +732,9 @@ fn main() -> horizon_client::Result<()> { placed: RefCell::new(Vec::new()), time: Cell::new(0), trial_mobs: RefCell::new(Vec::new()), + trial_count: Cell::new(0), + omens: RefCell::new(omens), + loot: loot.clone(), entities: RefCell::new( case_entities .iter() @@ -706,6 +774,9 @@ fn main() -> horizon_client::Result<()> { } else if mode == "trial" { let loot = loot.as_ref().ok_or("no loot tables")?; trial_case(&world, registry, loot, &get, &mut random, &mut log)?; + } else if mode == "vault" { + let loot = loot.as_ref().ok_or("no loot tables")?; + vault_case(world.players.clone(), loot, &get, &mut random, &mut log)?; } else if mode == "gen" { let mut gen_random = LegacyRandom::new(get("gseed", "0").parse()?); // The level random of the spawn predicates: no creature's predicate @@ -972,8 +1043,22 @@ fn trial_case( let scale = size as f32; let bounds = spawn_box(x, y, z, t.width as f32 * scale, t.height as f32 * scale); l.entities.borrow_mut().push((r.id.to_owned(), bounds)); - let uuid = [1, 0, 0, l.trial_mobs.borrow().len() as i32]; - l.trial_mobs.borrow_mut().push((uuid, r.position, bounds)); + let uuid = [1, 0, 0, l.trial_count.get()]; + l.trial_count.set(l.trial_count.get() + 1); + // Zombie.readAdditionalSaveData: IsBaby halves the box + // (getAgeScale); finalizeSpawn's fixed random never makes one. + let baby = match r + .entity + .get(&horizon_world::nbt::JavaString::from("IsBaby")) + { + Some(Tag::Byte(v)) => *v != 0, + Some(Tag::Int(v)) => *v != 0, + _ => false, + }; + let height = t.height as f32 * scale * if baby { 0.5 } else { 1.0 }; + l.trial_mobs + .borrow_mut() + .push((uuid, r.position, height, bounds)); spawned.push_back(format!( "{tick} spawn {} {} {} {} {}", r.id, @@ -1028,7 +1113,7 @@ fn trial_case( for e in events { match e { TrialEvent::BlockUpdated => log.push(format!("{tick} update")), - TrialEvent::LevelEvent(id, _, data) => { + TrialEvent::LevelEvent(id, p, data) => { // A spawn's events follow its tryAddFreshEntityWithPassengers, // a reward's its items. match id { @@ -1036,7 +1121,13 @@ fn trial_case( 3014 => log.append(&mut items), _ => {} } - log.push(format!("{tick} levent {id} {data}")); + match id { + 3020 | 3012 => log.push(format!( + "{tick} levent {id} {data} at {},{},{}", + p[0], p[1], p[2] + )), + _ => log.push(format!("{tick} levent {id} {data}")), + } } TrialEvent::Sound(name) => log.push(format!( "{tick} sound minecraft:{name} {} {} {} 1.0 1.0", @@ -1048,6 +1139,44 @@ fn trial_case( "{tick} gevent minecraft:entity_place {} {} {}", p[0], p[1], p[2] )), + TrialEvent::TrialOmen(uuid) => { + let i = (uuid[3] - 1) as usize; + let mut omens = world.omens.borrow_mut(); + let amplifier = omens.get(i).copied().flatten().map_or(0, |(_, a)| a); + log.push(format!("{tick} effect remove minecraft:bad_omen")); + log.push(format!( + "{tick} effect add minecraft:trial_omen {} 0", + TRIAL_OMEN_TICKS_PER_LEVEL * (amplifier + 1) + )); + if let Some(o) = omens.get_mut(i) { + *o = Some((Omen::Trial, 0)); + } + } + TrialEvent::Discard(uuid) => { + let mut mobs = world.trial_mobs.borrow_mut(); + if let Some(i) = mobs.iter().position(|(u, ..)| *u == uuid) { + let (.., b) = mobs.remove(i); + world.entities.borrow_mut().retain(|(_, e)| *e != b); + } + } + TrialEvent::SoundAt(name, b, pitch) => log.push(format!( + "{tick} sound minecraft:{name} {} {} {} 1.0 {pitch:?}", + bits(f64::from(b[0]) + 0.5), + bits(f64::from(b[1]) + 0.5), + bits(f64::from(b[2]) + 0.5) + )), + TrialEvent::ItemSpawner { + item, + position, + delay, + } => log.push(format!( + "{tick} ispawner {} {} {} {} {} {delay}", + item.item, + item.count, + bits(position[0]), + bits(position[1]), + bits(position[2]) + )), TrialEvent::OminousSet(set) => { ominous = set; world @@ -1101,3 +1230,195 @@ fn trial_case( log.push(format!("next {}", random.next_int_bound(1000).unwrap_or(0))); Ok(()) } + +/// What a vault reads: the game time and the case's players, moved by `move`. +struct VaultWorld { + time: i64, + players: Vec<([f64; 3], String)>, +} +impl VaultLevel for VaultWorld { + fn game_time(&self) -> i64 { + self.time + } + fn players(&self) -> Vec { + self.players + .iter() + .enumerate() + .map(|(i, (p, mode))| VaultPlayer { + uuid: [0, 0, 0, i as i32 + 1], + block: p.map(|v| v.floor() as i32), + spectator: mode == "spectator", + }) + .collect() + } +} +/// A UUID's low 64 bits, as the oracle prints players. +fn uuid_low(u: &[i32; 4]) -> String { + ((i64::from(u[2]) << 32) | i64::from(u[3] as u32)).to_string() +} +/// The display item and the connected players as the oracle prints them. +fn vault_shared(v: &Vault) -> String { + let mut connected: Vec = v.connected_players.iter().map(uuid_low).collect(); + connected.sort(); + format!( + "{} [{}]", + v.display_item + .as_ref() + .map_or_else(|| "-".to_owned(), |s| format!("{}*{}", s.item, s.count)), + connected.join(",") + ) +} + +/// `VaultBlockEntity.Server.tick` `ticks` times from game time `t0` at `spos` +/// on a vault block in state `state` (ominous with `ominous=1`) loaded from +/// `snbt` (base64 SNBT), with the case's key uses (`use`) and player moves +/// (`move`) before each tick, as the oracle logs it. +fn vault_case( + players: Vec<([f64; 3], String)>, + loot: &horizon_world::loot::LootData, + get: &dyn Fn(&str, &'static str) -> String, + random: &mut LegacyRandom, + log: &mut Vec, +) -> horizon_client::Result<()> { + let v: Vec = get("spos", "0,0,0") + .split(',') + .map(|n| n.parse().unwrap_or(0)) + .collect(); + let pos = [v[0], v[1], v[2]]; + let mut state = VaultState::from_name(&get("state", "inactive")).ok_or("bad state")?; + let ominous = get("ominous", "0") == "1"; + let text = horizon_client::skins::base64_decode(&get("snbt", "")).ok_or("bad snbt")?; + let tag = horizon_world::nbt::parse_snbt(&String::from_utf8(text)?)?.0; + let mut vault = Vault::load(&tag); + let schedule = |key: &str| -> Vec> { + get(key, "") + .split(';') + .filter(|s| !s.is_empty()) + .map(|s| s.split('/').map(str::to_owned).collect()) + .collect() + }; + let (uses, moves) = (schedule("use"), schedule("move")); + let ticks: i64 = get("ticks", "1").parse()?; + let t0: i64 = get("t0", "0").parse()?; + let seed: i64 = get("wseed", "0").parse()?; + let mut sequences = horizon_client::random_sequences::RandomSequences::default(); + let mut world = VaultWorld { time: t0, players }; + let center = pos.map(|v| f64::from(v) + 0.5); + for tick in 0..ticks { + world.time = t0 + tick; + let at = |s: &[String]| s[0].parse() == Ok(tick); + for m in moves.iter().filter(|m| at(m)) { + let v: Vec = m[2].split(',').map(|n| n.parse().unwrap_or(0.0)).collect(); + world.players[m[1].parse::()?].0 = [v[0], v[1], v[2]]; + } + let mut events = Vec::new(); + let mut roll = |table: &str, random: &mut LegacyRandom, sequence: bool| { + let drops = match loot.random_sequence(table).filter(|_| sequence) { + Some(s) => loot.roll_split(table, sequences.get(s, seed)), + None => loot.roll_split(table, random), + }; + drops + .iter() + .map(horizon_client::structure_blocks::loot_item_with_components) + .collect() + }; + for u in uses.iter().filter(|u| at(u)) { + let player: usize = u[1].parse()?; + let mut stack = ItemStack::new(&u[2], u[3].parse()?); + let used = vault.use_item_on( + &world, + random, + pos, + state, + ominous, + [0, 0, 0, player as i32 + 1], + Some(&stack), + &mut roll, + &mut events, + ); + if world.players[player].1 != "creative" { + stack.count -= used.unwrap_or(0); + } + vault_events(&mut events, &mut state, ominous, tick, center, &vault, log); + log.push(format!( + "{tick} use {} {}", + if used.is_some() { "ok" } else { "pass" }, + stack.count + )); + } + vault.server_tick(&world, random, pos, state, ominous, &mut roll, &mut events); + vault_events(&mut events, &mut state, ominous, tick, center, &vault, log); + } + let saved = vault.save(); + let config = saved + .iter() + .find(|(k, _)| *k == "config") + .and_then(|(_, t)| match t { + Tag::Compound(c) => { + let mut keys: Vec = c.keys().map(|k| k.to_string_lossy()).collect(); + keys.sort(); + Some(keys.join(",")) + } + _ => None, + }) + .unwrap_or_default(); + let eject: Vec = vault + .items_to_eject + .iter() + .map(|s| format!("{}*{}", s.item, s.count)) + .collect(); + log.push(format!( + "end state={} rewarded={} resumes={} eject={} total={} shared={} config={config}", + state.name(), + vault + .rewarded_players + .iter() + .map(uuid_low) + .collect::>() + .join(","), + vault.state_updating_resumes_at, + eject.join(","), + vault.total_ejections_needed, + vault_shared(&vault), + )); + log.push(format!("next {}", random.next_int_bound(1000).unwrap_or(0))); + Ok(()) +} +/// Logs a vault's events and applies its state changes. +fn vault_events( + events: &mut Vec, + state: &mut VaultState, + ominous: bool, + tick: i64, + center: [f64; 3], + vault: &Vault, + log: &mut Vec, +) { + for e in events.drain(..) { + match e { + VaultEvent::State(s) => { + *state = s; + log.push(format!("{tick} state {} {ominous}", s.name())); + } + VaultEvent::BlockUpdated => log.push(format!("{tick} update {}", vault_shared(vault))), + VaultEvent::LevelEvent(id, data) => log.push(format!("{tick} levent {id} {data}")), + VaultEvent::Sound(name, volume, pitch) => log.push(format!( + "{tick} sound minecraft:{name} {} {} {} {volume:?} {pitch:?}", + bits(center[0]), + bits(center[1]), + bits(center[2]) + )), + VaultEvent::Eject(stack, v) => log.push(format!( + "{tick} item {} {} {} {} {} {} {} {}", + stack.item, + stack.count, + bits(center[0]), + bits(center[1] + 0.7 - 0.125), + bits(center[2]), + bits(v[0]), + bits(v[1]), + bits(v[2]) + )), + } + } +} diff --git a/crates/horizon-client/examples/pick_block_data_fixture.rs b/crates/horizon-client/examples/pick_block_data_fixture.rs new file mode 100644 index 000000000..b47f56733 --- /dev/null +++ b/crates/horizon-client/examples/pick_block_data_fixture.rs @@ -0,0 +1,96 @@ +//! Block entity data on items for tools/test_pick_block_data_parity.py: reads +//! one JSON case per line (see VanillaPickBlockDataOracle) and prints the +//! picked item's component patch, a tab, then the placed block entity. +//! +//! usage: pick_block_data_fixture INPUT OUTPUT +use horizon_client::block_entity_item::{pick, place}; +use horizon_client::block_entity_nbt::canonical; +use horizon_client::java_text::{double_to_string, float_to_string}; +use horizon_world::nbt::{Tag, parse_snbt}; +use serde_json::Value; +use std::fs; + +/// ParityData.canon: sorted keys, typed numbers, Java's float text. +fn canon(tag: &Tag, out: &mut String) { + let join = |out: &mut String, prefix: &str, items: Vec| { + out.push_str(prefix); + out.push_str(&items.join(",")); + out.push(']'); + }; + match tag { + Tag::Float(v) => out.push_str(&format!("{}f", float_to_string(f32::from_bits(*v)))), + Tag::Double(v) => out.push_str(&format!("{}d", double_to_string(f64::from_bits(*v)))), + Tag::List(items) => join( + out, + "[", + items + .iter() + .map(|t| { + let mut s = String::new(); + canon(t, &mut s); + s + }) + .collect(), + ), + Tag::Compound(map) => { + let mut keys: Vec<_> = map.iter().map(|(k, v)| (k.to_string_lossy(), v)).collect(); + keys.sort_by(|a, b| a.0.cmp(&b.0)); + out.push('{'); + for (i, (k, v)) in keys.into_iter().enumerate() { + if i > 0 { + out.push(','); + } + out.push_str(&k); + out.push(':'); + canon(v, out); + } + out.push('}'); + } + other => out.push_str(&horizon_client::item_data::canon_tag(other)), + } +} + +fn snbt(value: &Value) -> Option { + parse_snbt(value.as_str()?).ok().map(|(tag, _)| tag) +} + +fn case(line: &str) -> Option { + let case: Value = serde_json::from_str(line).ok()?; + let saved = canonical(&snbt(&case["nbt"])?)?; + let picked = pick(&saved); + let patch = match case.get("patch") { + Some(p) => match snbt(p)? { + Tag::Compound(c) => c, + _ => return None, + }, + None => picked.clone(), + }; + let target = canonical(&snbt(&case["target"])?)?; + let Tag::Compound(mut placed) = place(&target, &patch, case["op"].as_bool()?) else { + return None; + }; + // keepPacked is the chunk's, not saveWithFullMetadata's. + placed.remove(&"keepPacked".into()); + let mut out = String::new(); + canon(&Tag::Compound(picked), &mut out); + out.push('\t'); + canon(&Tag::Compound(placed), &mut out); + Some(out) +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let input = fs::read_to_string( + args.get(1) + .ok_or("usage: pick_block_data_fixture INPUT OUTPUT")?, + )?; + let lines: Vec = input + .lines() + .map(|line| case(line).unwrap_or_else(|| "error".to_owned())) + .collect(); + fs::write( + args.get(2).ok_or("missing OUTPUT")?, + lines.join("\n") + "\n", + )?; + Ok(()) +} diff --git a/crates/horizon-client/examples/scene_collision_probe.rs b/crates/horizon-client/examples/scene_collision_probe.rs index f7ed87ea7..c1a1e77ad 100644 --- a/crates/horizon-client/examples/scene_collision_probe.rs +++ b/crates/horizon-client/examples/scene_collision_probe.rs @@ -2,6 +2,11 @@ #![forbid(unsafe_code)] use horizon_client::{assets, collisions, world}; use horizon_core::geometry::{Aabb, Vec3}; +use horizon_world::{ + collision_context::CollisionContext, + entity_obstruction::EntityIdentity, + world_movement::{self, CollisionCheckRequest, MovementRequest}, +}; use serde_json::Value; use std::{ fs, @@ -57,21 +62,55 @@ fn main() -> Result<()> { f["step"].as_str().ok_or("expected step bits")?, 16, )?); - let movement = scene.resolve( - bounds, - delta, - step, - f["grounded"].as_bool().ok_or("expected grounded flag")?, + let entities = f["entities"] + .as_array() + .into_iter() + .flatten() + .map(|v| { + let a = v.as_array().ok_or("expected entity box")?; + Ok(Aabb::new( + vector(&Value::Array(a[..3].to_vec()))?, + vector(&Value::Array(a[3..].to_vec()))?, + )) + }) + .collect::>>()?; + let mut selected = collisions::EntityCollisions { + blocks: scene, + entities: &entities, + }; + let movement = world_movement::resolve_world_movement( + &mut selected, + MovementRequest { + entity: EntityIdentity(0), + context: CollisionContext::position(bounds.min_position().y), + bounds, + movement: delta, + max_step: step, + on_ground: f["grounded"].as_bool().ok_or("expected grounded flag")?, + candidate_budget: 1_000_000, + }, )?; + let mut unobstructed = |bounds: Aabb| { + world_movement::no_world_collision( + &mut selected, + CollisionCheckRequest { + entity: EntityIdentity(0), + context: CollisionContext::position(bounds.min_position().y), + bounds, + candidate_budget: 1_000_000, + }, + ) + }; writeln!( output, "move {:016x} {:016x} {:016x} clear {} {}", movement.x.to_bits(), movement.y.to_bits(), movement.z.to_bits(), - scene.unobstructed(bounds)?, - scene.unobstructed(bounds.move_by(movement))? + unobstructed(bounds)?, + unobstructed(bounds.move_by(movement))? )?; + scene = selected.blocks; } Ok(()) } diff --git a/crates/horizon-client/examples/scene_motion_probe.rs b/crates/horizon-client/examples/scene_motion_probe.rs index 726ac278b..6caa51463 100644 --- a/crates/horizon-client/examples/scene_motion_probe.rs +++ b/crates/horizon-client/examples/scene_motion_probe.rs @@ -298,6 +298,7 @@ fn main() -> Result<()> { let mut travel: Option = None; for op in f["ops"].as_array().unwrap() { let mut world = MotionWorld { + entities: &[], player: &mut player, scene: &mut scene, assets: &assets, diff --git a/crates/horizon-client/examples/streaming_bench.rs b/crates/horizon-client/examples/streaming_bench.rs new file mode 100644 index 000000000..f99c594bb --- /dev/null +++ b/crates/horizon-client/examples/streaming_bench.rs @@ -0,0 +1,227 @@ +//! The chunk pipeline (generation, decoration, lighting, meshing) on its worker +//! pool, without a window: how fast a render distance fills with N workers, and +//! what the render thread pays for it in `Streaming::update`. +//! +//! streaming_bench RESOURCES [--threads N] [--radius R] [--seed S] [--fly CHUNKS_PER_S] [--seconds T] [--hz F] +//! +//! First the area around (0, 0) fills; then, with `--fly`, the centre moves along +x +//! at that speed for T seconds while frames run at F per second. Each phase reports +//! its wall time, chunks generated and sections meshed, and the time `update` +//! took on the calling thread (the render thread in the game): total, median, +//! p99 and slowest. Compile with HORIZON_BENCH_COUNT_ALLOCATIONS=1 to count the +//! allocations made on the calling thread during updates and by everything. +use horizon_client::{ + assets::Assets, + biome::Biomes, + blocks::BlockFacts, + light::LightTables, + mesher::MeshTables, + models, + streaming::{Streaming, WorkerContext}, + vanillagen::VanillaTerrain, + world::World, +}; +use std::{ + alloc::{GlobalAlloc, Layout, System}, + cell::Cell, + path::PathBuf, + sync::{ + Arc, + atomic::{AtomicU64, Ordering::Relaxed}, + }, + time::{Duration, Instant}, +}; + +const TRACK: bool = option_env!("HORIZON_BENCH_COUNT_ALLOCATIONS").is_some(); +static ALLOCATIONS: AtomicU64 = AtomicU64::new(0); +static BYTES: AtomicU64 = AtomicU64::new(0); +thread_local! { + static LOCAL: Cell<(u64, u64)> = const { Cell::new((0, 0)) }; +} +fn count(size: usize) { + if TRACK { + ALLOCATIONS.fetch_add(1, Relaxed); + BYTES.fetch_add(size as u64, Relaxed); + let _ = LOCAL.try_with(|c| { + let (n, b) = c.get(); + c.set((n + 1, b + size as u64)); + }); + } +} +struct CountingAllocator; +// Delegates every operation and layout unchanged to System. +unsafe impl GlobalAlloc for CountingAllocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + count(layout.size()); + unsafe { System.alloc(layout) } + } + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + count(layout.size()); + unsafe { System.alloc_zeroed(layout) } + } + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + unsafe { System.dealloc(ptr, layout) }; + } + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, size: usize) -> *mut u8 { + count(size); + unsafe { System.realloc(ptr, layout, size) } + } +} +#[global_allocator] +static ALLOCATOR: CountingAllocator = CountingAllocator; + +type Result = std::result::Result>; + +#[derive(Default)] +struct Phase { + updates: Vec, + local: (u64, u64), + uploads: usize, +} +impl Phase { + fn update(&mut self, streaming: &mut Streaming, world: &mut World) { + let before = LOCAL.with(Cell::get); + let started = Instant::now(); + let (uploads, _) = streaming.update(world); + self.updates.push(started.elapsed().as_secs_f64() * 1e3); + let after = LOCAL.with(Cell::get); + self.local.0 += after.0 - before.0; + self.local.1 += after.1 - before.1; + self.uploads += uploads.len(); + drop(uploads); + } + fn report(&self, name: &str, wall: Duration, streaming: &Streaming, generated: u64) { + let mut sorted = self.updates.clone(); + sorted.sort_by(f64::total_cmp); + let at = |p: f64| sorted[((sorted.len() as f64 * p) as usize).min(sorted.len() - 1)]; + let total: f64 = sorted.iter().sum(); + println!( + "{name}: {:.2} s, {} chunks generated, {} sections meshed; update {:.1} ms total over {} calls, p50 {:.3} p99 {:.3} max {:.2} ms", + wall.as_secs_f64(), + streaming.generated_total - generated, + self.uploads, + total, + sorted.len(), + at(0.5), + at(0.99), + sorted.last().copied().unwrap_or(0.0), + ); + if TRACK { + println!( + " update allocations: {} ({:.1} MiB)", + self.local.0, + self.local.1 as f64 / 1048576.0 + ); + } + } +} + +/// Nothing queued or in flight. Sections at the edge of the area stay dirty +/// (their outer neighbours are never lit), so they don't count. +fn settled(streaming: &Streaming) -> bool { + streaming + .stages() + .iter() + .all(|&(name, n)| name == "protos" || n == 0) +} + +fn main() -> Result<()> { + let args: Vec = std::env::args().skip(1).collect(); + let root = PathBuf::from(args.first().ok_or("usage: streaming_bench RESOURCES")?); + let flag = |name: &str, default: f64| -> f64 { + args.iter() + .position(|a| a == name) + .and_then(|i| args.get(i + 1)) + .and_then(|v| v.parse().ok()) + .unwrap_or(default) + }; + let auto = std::thread::available_parallelism().map_or(2, |n| n.get() - 1); + let threads = flag("--threads", auto as f64) as usize; + let radius = flag("--radius", 8.0) as i32; + let seed = flag("--seed", 1234.0) as i64; + let fly = flag("--fly", 0.0); + let seconds = flag("--seconds", 10.0); + let hz = flag("--hz", 240.0); + + let assets = Arc::new(Assets::load(&root)?); + let facts = BlockFacts::load(&root, assets.registry)?; + let biomes = Arc::new(Biomes::load(&root)?); + let tables = Arc::new(MeshTables::new( + &assets, + &facts, + models::load_visibility(&root, assets.registry)?, + )?); + let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?); + let terrain = Arc::new(VanillaTerrain::new( + &root.join("worldgen"), + assets.registry, + &biomes, + seed, + )?); + let context = Arc::new(WorkerContext { + assets, + tables, + biomes, + light, + }); + let mut world = World::new(facts.air, seed); + let mut streaming = Streaming::new(terrain, context, threads); + streaming.radius = radius; + streaming.center = (0, 0); + println!("{threads} workers, radius {radius}, seed {seed}"); + let (allocations, bytes) = (ALLOCATIONS.load(Relaxed), BYTES.load(Relaxed)); + + // Fill: update as often as the game would uncapped, until settled. + let mut phase = Phase::default(); + let started = Instant::now(); + let mut quiet = 0; + while quiet < 20 { + let uploads = phase.uploads; + phase.update(&mut streaming, &mut world); + quiet = if settled(&streaming) && phase.uploads == uploads { + quiet + 1 + } else { + 0 + }; + std::thread::sleep(Duration::from_micros(500)); + } + phase.report("fill", started.elapsed(), &streaming, 0); + + if fly > 0.0 { + let mut phase = Phase::default(); + let generated = streaming.generated_total; + let frame = Duration::from_secs_f64(1.0 / hz); + let started = Instant::now(); + let mut behind = Vec::new(); + while started.elapsed().as_secs_f64() < seconds { + let next = Instant::now() + frame; + let x = (started.elapsed().as_secs_f64() * fly) as i32; + streaming.center = (x, 0); + phase.update(&mut streaming, &mut world); + // Columns within 2 chunks of the player still missing their meshes. + let near = (-2..=2) + .flat_map(|dz| (-2..=2).map(move |dx| (x + dx, dz))) + .filter(|&(cx, cz)| !streaming.is_lit(cx, cz)) + .count(); + behind.push(near); + if let Some(wait) = next.checked_duration_since(Instant::now()) { + std::thread::sleep(wait); + } + } + phase.report("fly", started.elapsed(), &streaming, generated); + let unlit = behind.iter().filter(|&&n| n > 0).count(); + println!( + " frames with an unlit column within 2 chunks of the player: {unlit} of {} ({:.1}%)", + behind.len(), + unlit as f64 * 100.0 / behind.len().max(1) as f64 + ); + } + if TRACK { + println!( + "all threads: {} allocations ({:.1} MiB)", + ALLOCATIONS.load(Relaxed) - allocations, + (BYTES.load(Relaxed) - bytes) as f64 / 1048576.0 + ); + } + Ok(()) +} diff --git a/crates/horizon-client/src/bin/horizon-ctl/commands.rs b/crates/horizon-client/src/bin/horizon-ctl/commands.rs index af7306e3b..c5e716a03 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/commands.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/commands.rs @@ -256,8 +256,9 @@ pub const COMMANDS: &[Cmd] = &[ &[opt("all", Ty::Bool, "drop the whole stack")], mcp: true, local: false), cmd!("hold", Act, "hold KEY SECONDS", "press a key, wait, release it", "Keys as for key.", ["horizon-ctl hold w 2"], &[p("key", Ty::Str, "key name"), p("seconds", Ty::Num, "how long")], mcp: false, local: true), - cmd!("key", Act, "key KEY down|up|tap", "press or release a key (w a s d space shift ctrl e q esc f3 1-9 arrows ...)", "", - ["horizon-ctl key space tap"], &[p("key", Ty::Str, "key name"), p("action", Ty::Enum(&["down", "up", "tap"]), "what to do")], mcp: true, local: false), + cmd!("key", Act, "key KEY down|up|tap|repeat", "press, release or auto-repeat a key (w a s d space shift ctrl e q esc f3 1-9 arrows ...)", + "down holds the key until key ... up, release or stop; wait does not release it. move, goto, jump, break and the other actions release the movement keys when they end.", + ["horizon-ctl key space tap"], &[p("key", Ty::Str, "key name"), p("action", Ty::Enum(&["down", "up", "tap", "repeat"]), "what to do")], mcp: true, local: false), cmd!("mouse", Act, "mouse left|right|middle down|up|click", "press or release a mouse button in the world", "", ["horizon-ctl mouse right click"], &[p("button", Ty::Enum(&["left", "right", "middle"]), "button"), p("action", Ty::Enum(&["down", "up", "click"]), "what to do")], mcp: false, local: false), cmd!("pad", Act, "pad BUTTON down|up|tap | pad stick left|right X Y | pad trigger left|right V | pad release | pad status", "a virtual controller: buttons, sticks and triggers as a real pad would send them", @@ -323,7 +324,9 @@ pub const COMMANDS: &[Cmd] = &[ cmd!("summon", World, "summon KIND [X Y Z] [baby]", "spawn a mob", "", ["horizon-ctl summon cow"], &[p("kind", Ty::Str, "mob type")], mcp: true, local: false), cmd!("effect", World, "effect ID SECONDS [AMPLIFIER] | effect clear", "give a status effect", "", ["horizon-ctl effect speed 30 1"], &[], mcp: false, local: false), cmd!("render-distance", World, "render-distance N", "chunks, 2..64", "", ["horizon-ctl render-distance 8"], &[p("chunks", Ty::Int, "render distance")], mcp: false, local: false), - cmd!("wait", World, "wait TICKS", "wait until TICKS game ticks have passed (20 per second)", "", ["horizon-ctl wait 40"], + cmd!("wait", World, "wait TICKS", "wait until TICKS game ticks have passed (20 per second)", + "Keys and mouse buttons held with key ... down or mouse ... down stay held while it waits. Release them with key ... up, release or stop.", + ["horizon-ctl wait 40", "horizon-ctl key w down && horizon-ctl wait 40 && horizon-ctl key w up"], &[p("ticks", Ty::Int, "game ticks")], mcp: true, local: false), // Scripting cmd!("script", Scripting, "script [FILE] [--keep-going]", "run commands from FILE (or stdin), one per line", diff --git a/crates/horizon-client/src/block_entity_item.rs b/crates/horizon-client/src/block_entity_item.rs new file mode 100644 index 000000000..2361dcbfb --- /dev/null +++ b/crates/horizon-client/src/block_entity_item.rs @@ -0,0 +1,485 @@ +//! Block entities carried by items, vanilla 26.3: Ctrl + Pick Block in creative +//! (`ServerGamePacketListenerImpl.addBlockDataToItem`) and placing such an item +//! (`BlockItem.updateCustomBlockEntityTag`, then +//! `BlockEntity.applyComponentsFromItemStack`). Both work on the block entity's +//! saved NBT (`block_entity_nbt::canonical`) and the item's component patch. +//! +//! What a type turns into item components (`removeComponentsFromTag`, +//! `collectImplicitComponents`) leaves its NBT; the rest goes to +//! `minecraft:block_entity_data`, tagged with the type's id. +use crate::block_entity_nbt::{self, canonical}; +use horizon_world::nbt::{Compound, JavaString, Tag}; + +pub const BLOCK_ENTITY_DATA: &str = "minecraft:block_entity_data"; + +/// `BlockEntityTypes.OP_ONLY_CUSTOM_DATA`: the types whose data only a player +/// who can use game master blocks places (`BlockEntityType.onlyOpCanSetNbt`). +pub const OP_ONLY: [&str; 6] = [ + "minecraft:command_block", + "minecraft:lectern", + "minecraft:sign", + "minecraft:hanging_sign", + "minecraft:mob_spawner", + "minecraft:trial_spawner", +]; + +/// The `minecraft:block_entity_data` of `stack`: its type id and its data. +pub fn data(stack: &crate::items::ItemStack) -> Option<(String, &Tag)> { + let data = stack.data()?.other(BLOCK_ENTITY_DATA)?; + Some((block_entity_nbt::id(data)?, data)) +} + +/// `BlockItem.shouldPrintOpWarning` for a player with game master permission: +/// the item carries data of an op-only type. +pub fn op_warning(stack: &crate::items::ItemStack) -> bool { + data(stack).is_some_and(|(id, _)| OP_ONLY.contains(&id.as_str())) +} + +/// `Spawner.getSpawnEntityDisplayName` (`SpawnData.entity.id` of the item's +/// data, which `ItemStack.addDetailsToTooltip` reads for spawners and trial +/// spawners alike): the entity type a spawner item spawns. +pub fn spawner_entity(stack: &crate::items::ItemStack) -> Option { + let (_, data) = data(stack)?; + match data.get("SpawnData")?.get("entity")?.get("id")? { + Tag::String(id) => Some(id.to_string_lossy()), + _ => None, + } +} + +/// A part of a block entity's NBT that its item holds as a component. +#[derive(Clone, Copy)] +enum Part { + /// The NBT key and the component hold the same value. + Same(&'static str, &'static str), + /// `Items` as `minecraft:container`, in a container of this many slots. + Items(usize), + /// `LootTable` and `LootTableSeed` as `minecraft:container_loot`. + Loot, + /// `is_waxed` as `minecraft:waxed`. + Waxed, + /// A decorated pot's `item` as `minecraft:container`. + PotItem, + /// Left out of the item's data, with no component. + Drop(&'static str), +} +const NAME: Part = Part::Same("CustomName", "minecraft:custom_name"); +const LOCK: Part = Part::Same("lock", "minecraft:lock"); +const CONTAINER: &str = "minecraft:container"; + +/// Each type's `removeComponentsFromTag`, `collectImplicitComponents` and +/// `applyImplicitComponents`. +fn parts(id: &str) -> &'static [Part] { + match id { + "minecraft:chest" + | "minecraft:trapped_chest" + | "minecraft:barrel" + | "minecraft:shulker_box" => &[NAME, LOCK, Part::Items(27), Part::Loot], + "minecraft:dispenser" | "minecraft:dropper" | "minecraft:crafter" => { + &[NAME, LOCK, Part::Items(9), Part::Loot] + } + "minecraft:hopper" => &[NAME, LOCK, Part::Items(5), Part::Loot], + "minecraft:furnace" | "minecraft:smoker" | "minecraft:blast_furnace" => { + &[NAME, LOCK, Part::Items(3)] + } + "minecraft:brewing_stand" => &[NAME, LOCK, Part::Items(5)], + "minecraft:beacon" => &[NAME, LOCK], + "minecraft:enchanting_table" => &[NAME], + "minecraft:command_block" => &[NAME, Part::Drop("conditionMet"), Part::Drop("powered")], + "minecraft:campfire" => &[Part::Items(4)], + "minecraft:chiseled_bookshelf" => &[Part::Items(6)], + "minecraft:shelf" => &[Part::Items(3)], + "minecraft:beehive" => &[Part::Same("bees", "minecraft:bees")], + "minecraft:banner" => &[Part::Same("patterns", "minecraft:banner_patterns"), NAME], + "minecraft:decorated_pot" => &[ + Part::Same("sherds", "minecraft:pot_decorations"), + Part::PotItem, + ], + "minecraft:sign" | "minecraft:hanging_sign" => &[ + Part::Same("front_text", "minecraft:sign_text_front"), + Part::Same("back_text", "minecraft:sign_text_back"), + Part::Waxed, + ], + "minecraft:skull" => &[ + Part::Same("profile", "minecraft:profile"), + Part::Same("note_block_sound", "minecraft:note_block_sound"), + Part::Same("custom_name", "minecraft:custom_name"), + ], + _ => &[], + } +} + +/// The component a part reads, and what it holds for `tag` (None: unset). +fn collect(part: Part, tag: &Tag) -> Option<(&'static str, Option)> { + Some(match part { + Part::Same(key, component) => ( + component, + tag.get(key).cloned().or_else(|| unset(component)), + ), + Part::Items(_) => { + let slots = match tag.get("Items") { + Some(Tag::List(items)) => items.iter().filter_map(slot_entry).collect(), + _ => Vec::new(), + }; + (CONTAINER, Some(Tag::List(slots))) + } + Part::Loot => { + let table = tag.get("LootTable").cloned(); + let loot = table.map(|t| { + let mut entries = vec![("loot_table", t)]; + if let Some(seed) = tag.get("LootTableSeed") { + entries.push(("seed", seed.clone())); + } + Tag::compound(entries) + }); + ("minecraft:container_loot", loot) + } + Part::Waxed => ( + "minecraft:waxed", + matches!(tag.get("is_waxed"), Some(Tag::Byte(1))) + .then(|| Tag::Compound(Compound::new())), + ), + Part::PotItem => { + let slots = match tag.get("item") { + Some(Tag::Compound(item)) => Some(container_slot(0, item.clone())), + _ => None, + }; + (CONTAINER, Some(Tag::List(slots.into_iter().collect()))) + } + Part::Drop(_) => return None, + }) +} + +/// What a type that always collects `component` gives when its NBT leaves the +/// value out (its empty value, which the NBT omits). +fn unset(component: &str) -> Option { + Some(match component { + "minecraft:bees" | "minecraft:banner_patterns" => Tag::List(Vec::new()), + "minecraft:pot_decorations" => Tag::Compound(Compound::new()), + "minecraft:sign_text_front" | "minecraft:sign_text_back" => { + block_entity_nbt::sign_side(None) + } + _ => return None, + }) +} + +/// An `Items` entry as a `minecraft:container` slot. +fn slot_entry(entry: &Tag) -> Option { + let Tag::Compound(entry) = entry else { + return None; + }; + let mut item = entry.clone(); + let slot = match item.remove(&JavaString::from("Slot"))? { + Tag::Byte(s) => i32::from(s), + _ => return None, + }; + Some(container_slot(slot, item)) +} + +/// An `ItemContainerContents` slot: `ItemStackTemplate` leaves out a count of 1. +fn container_slot(slot: i32, mut item: Compound) -> Tag { + if item.get(&JavaString::from("count")) == Some(&Tag::Int(1)) { + item.remove(&JavaString::from("count")); + } + Tag::compound([("slot", Tag::Int(slot)), ("item", Tag::Compound(item))]) +} + +/// The value of `component` on the clone item of a type that collects it: a +/// picked item leaves it out of its patch, and a placed item without it in its +/// patch gives it to the block entity. +fn item_default(component: &str) -> Option { + Some(match component { + CONTAINER | "minecraft:bees" | "minecraft:banner_patterns" => Tag::List(Vec::new()), + "minecraft:pot_decorations" => { + let brick = || Tag::compound([("id", Tag::String("minecraft:brick".into()))]); + Tag::compound([ + ("back", brick()), + ("front", brick()), + ("left", brick()), + ("right", brick()), + ]) + } + "minecraft:sign_text_front" | "minecraft:sign_text_back" => { + block_entity_nbt::sign_side(None) + } + _ => return None, + }) +} + +const METADATA: [&str; 6] = ["id", "x", "y", "z", "keepPacked", "components"]; + +/// `saveCustomOnly`: the saved NBT without its id, position and components. +fn custom_only(saved: &Tag) -> Compound { + match saved { + Tag::Compound(c) => c + .iter() + .filter(|(k, _)| !METADATA.contains(&k.to_string_lossy().as_str())) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(), + _ => Compound::new(), + } +} + +/// `addBlockDataToItem`: the component patch Ctrl + Pick Block gives the clone +/// item of the block entity saved as `saved` (a full, canonical compound). +pub fn pick(saved: &Tag) -> Compound { + let id = block_entity_nbt::id(saved).unwrap_or_default(); + let mut patch = Compound::new(); + // BlockItem.setBlockEntityData after removeComponentsFromTag. + let mut data = custom_only(saved); + for part in parts(&id) { + let key = match *part { + Part::Same(key, _) | Part::Drop(key) => key, + Part::Items(_) => "Items", + Part::Loot => { + data.remove(&JavaString::from("LootTableSeed")); + "LootTable" + } + Part::Waxed => "is_waxed", + Part::PotItem => "item", + }; + data.remove(&JavaString::from(key)); + } + if !data.is_empty() { + data.insert("id".into(), Tag::String(id.as_str().into())); + patch.insert(BLOCK_ENTITY_DATA.into(), Tag::Compound(data)); + } + // ItemStack.applyComponents(collectComponents()): the block entity's own + // components, then the implicit ones; a value equal to the item's own is + // no change. + let mut collected = match saved.get("components") { + Some(Tag::Compound(c)) => c.clone(), + _ => Compound::new(), + }; + for part in parts(&id) { + if let Some((component, value)) = collect(*part, saved) { + match value { + Some(v) => collected.insert(component.into(), v), + None => collected.remove(&JavaString::from(component)), + }; + } + } + for (component, value) in collected { + if item_default(&component.to_string_lossy()).as_ref() == Some(&value) { + patch.remove(&component); + } else { + patch.insert(component, value); + } + } + patch +} + +/// The block entity saved as `saved` after an item with component patch +/// `components` is placed as it: `BlockItem.updateCustomBlockEntityTag` (the +/// item's data of the same type, op-only types only when `game_master`, the +/// player can use game master blocks), then `applyComponentsFromItemStack`. +pub fn place(saved: &Tag, components: &Compound, game_master: bool) -> Tag { + let Some(id) = block_entity_nbt::id(saved) else { + return saved.clone(); + }; + let Tag::Compound(mut tag) = saved.clone() else { + return saved.clone(); + }; + // TypedEntityData.loadInto: saveCustomOnly, merge, loadCustomOnly when changed. + if let Some(Tag::Compound(data)) = components.get(&JavaString::from(BLOCK_ENTITY_DATA)) + && data + .get(&JavaString::from("id")) + .is_some_and(|t| matches!(t, Tag::String(s) if s.to_string_lossy() == id)) + && (game_master || !OP_ONLY.contains(&id.as_str())) + { + let custom = custom_only(saved); + let mut merged = custom.clone(); + let mut data = data.clone(); + data.remove(&JavaString::from("id")); + crate::data_cmd::merge_compound(&mut merged, &data); + if merged != custom { + for key in METADATA { + if let Some(v) = tag.get(&JavaString::from(key)) { + merged.insert(key.into(), v.clone()); + } + } + if let Some(Tag::Compound(loaded)) = canonical(&Tag::Compound(merged)) { + tag = loaded; + } + } + } + // applyImplicitComponents, then the rest of the patch as the block + // entity's own components. + let mut read = vec![BLOCK_ENTITY_DATA, "minecraft:block_state"]; + // The item's components: its patch over its own defaults. + let get = |c: &str| match components.get(&JavaString::from(c)) { + Some(v) => Some(v.clone()), + None if components.contains_key(&JavaString::from(format!("!{c}").as_str())) => None, + None => item_default(c), + }; + let mut set = |key: &str, value: Option| match value { + Some(v) => tag.insert(key.into(), v), + None => tag.remove(&JavaString::from(key)), + }; + for part in parts(&id) { + match *part { + Part::Same(key, component) => { + read.push(component); + set(key, get(component)); + } + Part::Items(size) => { + read.push(CONTAINER); + let items = container_slots(get(CONTAINER).as_ref()) + .filter(|(slot, _)| (*slot as usize) < size) + .map(|(slot, mut item)| { + item.insert("Slot".into(), Tag::Byte(slot as i8)); + Tag::Compound(item) + }) + .collect(); + set("Items", Some(Tag::List(items))); + } + Part::Loot => { + read.push("minecraft:container_loot"); + if let Some(loot) = get("minecraft:container_loot") { + set("LootTable", loot.get("loot_table").cloned()); + set("LootTableSeed", loot.get("seed").cloned()); + } + } + Part::Waxed => { + read.push("minecraft:waxed"); + set( + "is_waxed", + Some(Tag::Byte(i8::from(get("minecraft:waxed").is_some()))), + ); + } + Part::PotItem => { + read.push(CONTAINER); + let first = container_slots(get(CONTAINER).as_ref()).find(|(slot, _)| *slot == 0); + set("item", first.map(|(_, item)| Tag::Compound(item))); + } + Part::Drop(_) => {} + } + } + let own: Compound = components + .iter() + .filter(|(k, _)| { + let k = k.to_string_lossy(); + !k.starts_with('!') && !read.contains(&k.as_str()) + }) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); + tag.insert("components".into(), Tag::Compound(own)); + let tag = Tag::Compound(tag); + canonical(&tag).unwrap_or(tag) +} + +/// The slots of a `minecraft:container` component. +fn container_slots(container: Option<&Tag>) -> impl Iterator + '_ { + let list = match container { + Some(Tag::List(list)) => list.as_slice(), + _ => &[], + }; + list.iter().filter_map(|entry| { + let slot = match entry.get("slot")? { + Tag::Int(s) => *s, + _ => return None, + }; + match entry.get("item")? { + Tag::Compound(item) => Some((slot, item.clone())), + _ => None, + } + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn snbt(text: &str) -> Tag { + horizon_world::nbt::parse_snbt(text).expect("snbt").0 + } + fn saved(text: &str) -> Tag { + canonical(&snbt(text)).expect("known type") + } + fn canon(patch: &Compound) -> String { + crate::item_data::canon_tag(&Tag::Compound(patch.clone())) + } + + #[test] + fn a_filled_named_chest_gives_its_items_and_name_as_components() { + let chest = saved( + "{id:\"minecraft:chest\",x:1,y:2,z:3,CustomName:\"Loot\",\ + Items:[{Slot:4b,id:\"minecraft:stone\",count:5}]}", + ); + let patch = pick(&chest); + assert_eq!( + canon(&patch), + crate::item_data::canon_tag(&snbt( + "{\"minecraft:container\":[{slot:4,item:{id:\"minecraft:stone\",count:5}}],\ + \"minecraft:custom_name\":\"Loot\"}" + )) + ); + // Placing it back gives the same chest. + let empty = saved("{id:\"minecraft:chest\",x:1,y:2,z:3}"); + assert_eq!(place(&empty, &patch, false), chest); + // An empty chest has nothing to carry. + assert!(pick(&empty).is_empty()); + } + + #[test] + fn a_command_block_keeps_its_command_in_block_entity_data() { + let block = saved( + "{id:\"minecraft:command_block\",x:0,y:0,z:0,Command:\"say hi\",auto:1b,powered:1b}", + ); + let patch = pick(&block); + let data = patch + .get(&JavaString::from(BLOCK_ENTITY_DATA)) + .expect("data"); + assert_eq!(data.get("Command"), Some(&Tag::String("say hi".into()))); + assert_eq!(data.get("powered"), None); + assert_eq!( + data.get("id"), + Some(&Tag::String("minecraft:command_block".into())) + ); + // Only a player who can use game master blocks places it. + let fresh = saved("{id:\"minecraft:command_block\",x:0,y:0,z:0}"); + assert_eq!(place(&fresh, &patch, false), fresh); + assert_eq!( + place(&fresh, &patch, true).get("Command"), + Some(&Tag::String("say hi".into())) + ); + // Data of another type is ignored. + let chest = saved("{id:\"minecraft:chest\",x:0,y:0,z:0}"); + assert_eq!(place(&chest, &patch, true), chest); + } + + #[test] + fn item_data_names_its_spawn_and_op_only_types() { + let item = |text: &str| { + let components = snbt(&format!("{{\"minecraft:block_entity_data\":{text}}}")); + let (damage, extra) = crate::item_data::decode_components(Some(&components)); + crate::items::ItemStack { + damage, + extra, + ..crate::items::ItemStack::new("minecraft:spawner", 1) + } + }; + let spawner = + item("{id:\"minecraft:mob_spawner\",SpawnData:{entity:{id:\"minecraft:zombie\"}}}"); + assert_eq!( + spawner_entity(&spawner).as_deref(), + Some("minecraft:zombie") + ); + assert!(op_warning(&spawner)); + let chest = item("{id:\"minecraft:chest\",LootTable:\"x\"}"); + assert_eq!(spawner_entity(&chest), None); + assert!(!op_warning(&chest)); + } + + #[test] + fn a_written_sign_gives_its_text_and_wax() { + let sign = saved( + "{id:\"minecraft:sign\",x:0,y:0,z:0,is_waxed:1b,\ + front_text:{messages:[\"a\",\"b\",\"\",\"\"]}}", + ); + let patch = pick(&sign); + let keys: Vec = patch.keys().map(|k| k.to_string_lossy()).collect(); + assert_eq!(keys, ["minecraft:sign_text_front", "minecraft:waxed"]); + let fresh = saved("{id:\"minecraft:sign\",x:0,y:0,z:0}"); + assert_eq!(place(&fresh, &patch, false), sign); + } +} diff --git a/crates/horizon-client/src/block_entity_nbt.rs b/crates/horizon-client/src/block_entity_nbt.rs index 3db290408..54d230eb4 100644 --- a/crates/horizon-client/src/block_entity_nbt.rs +++ b/crates/horizon-client/src/block_entity_nbt.rs @@ -259,7 +259,7 @@ fn is_pos(tag: &Tag) -> bool { matches!(tag, Tag::IntArray(v) if v.len() == 3) } /// The loaded `SignText` of one side, or the empty text. -fn sign_side(tag: Option<&Tag>) -> Tag { +pub(crate) fn sign_side(tag: Option<&Tag>) -> Tag { let empty = || string(""); let mut messages: Vec = match tag.and_then(|t| t.get("messages")) { Some(Tag::List(list)) => list.iter().filter_map(component).collect(), diff --git a/crates/horizon-client/src/chat_tests.rs b/crates/horizon-client/src/chat_tests.rs index dd6192edd..3cbac071b 100644 --- a/crates/horizon-client/src/chat_tests.rs +++ b/crates/horizon-client/src/chat_tests.rs @@ -163,3 +163,70 @@ fn locate_coordinates_fill_chat_with_teleport_without_submitting() { ); } } + +#[test] +fn history_arrows_recall_messages_and_restore_the_draft() { + use winit::keyboard::KeyCode::{ArrowDown, ArrowUp}; + + let font = font(); + let m = Measure(&font); + let registries = Registries::default(); + let commands = Commands { + dispatcher: crate::command::vanilla::game_dispatcher(), + registries: ®istries, + }; + let history = vec!["first message".to_owned(), "latest message".to_owned()]; + let mut screen = ChatScreen::new(&m, &commands, "unfinished draft", history.len(), 640, 360); + for (key, expected) in [ + (ArrowUp, "latest message"), + (ArrowUp, "first message"), + (ArrowUp, "first message"), + (ArrowDown, "latest message"), + (ArrowDown, "unfinished draft"), + (ArrowDown, "unfinished draft"), + ] { + assert_eq!( + screen.key(&m, &commands, &history, key, false, false), + ChatAction::None + ); + assert_eq!(screen.value(), expected); + } +} + +#[test] +fn mod_commands_are_coloured_and_complete_like_vanilla_ones() { + let font = font(); + let m = Measure(&font); + // Allow Commands off: a mod's command needs no level. + let registries = Registries::default(); + let vanilla = crate::command::vanilla::game_dispatcher(); + let modded = vanilla.with_mod_commands(["where", "coords"]); + let red = |screen: &ChatScreen| { + screen + .format(screen.value(), 0) + .spans + .iter() + .any(|s| s.style.color == Some(text::RED)) + }; + let typed = |dispatcher: &crate::command::Dispatcher, line: &str| { + let c = Commands { + dispatcher, + registries: ®istries, + }; + let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360); + screen.type_text(&m, &c, line); + screen + }; + // Unknown without the mod's tree (#456). + assert!(red(&typed(vanilla, "/coords"))); + for line in ["/coords", "/where", "/where me and you"] { + assert!(!red(&typed(&modded, line)), "{line}"); + } + let c = Commands { + dispatcher: &modded, + registries: ®istries, + }; + let mut screen = typed(&modded, "/coo"); + screen.key(&m, &c, &[], winit::keyboard::KeyCode::Tab, false, false); + assert_eq!(screen.value(), "/coords"); +} diff --git a/crates/horizon-client/src/clouds.rs b/crates/horizon-client/src/clouds.rs index 67223f7cb..70f29c132 100644 --- a/crates/horizon-client/src/clouds.rs +++ b/crates/horizon-client/src/clouds.rs @@ -68,9 +68,226 @@ pub fn cells(radius: i32) -> impl Iterator { }) } +/// Per-frame cloud inputs. Resources are immutable for the renderer's lifetime: +/// resource-pack reloads replace the renderer and its cache together. +pub struct Input<'a> { + pub texture: &'a (u32, u32, Vec), + pub uv: [f32; 2], + pub camera: glam::DVec3, + pub time: i64, + pub partial_tick: f64, + pub range: i32, + pub fast: bool, + pub color: [f32; 4], +} + +#[derive(Debug, PartialEq, Eq)] +struct MeshKey { + cell_x: i64, + cell_z: i64, + radius: i32, + fast: bool, + // The two vertical face tests include both surfaces at the boundaries. + top: bool, + bottom: bool, +} + +#[repr(C)] +#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] +pub(crate) struct Uniform { + offset: [f32; 4], + colors: [[f32; 4]; 4], +} + +impl Input<'_> { + fn state(&self) -> (MeshKey, Uniform) { + let (w, h, _) = self.texture; + let offset = self.time.rem_euclid(i64::from(*w) * 400) as f64 + self.partial_tick; + let mut x = self.camera.x + offset * 0.030_000_001; + let mut z = self.camera.z + 3.96; + let (tw, th) = (f64::from(*w) * 12.0, f64::from(*h) * 12.0); + x -= (x / tw).floor() * tw; + z -= (z / th).floor() * th; + let cell_x = (x / 12.0).floor() as i64; + let cell_z = (z / 12.0).floor() as i64; + let bottom = (192.33 - self.camera.y) as f32; + let key = MeshKey { + cell_x, + cell_z, + radius: radius_cells(self.range), + fast: self.fast, + top: bottom <= 0.0, + bottom: bottom + 4.0 >= 0.0, + }; + let colors = [1.0, 0.7, 0.8, 0.9].map(|shade| { + let [r, g, b, a] = self.color; + [r * shade, g * shade, b * shade, a] + .map(|v| (v.clamp(0.0, 1.0) * 255.0) as u8 as f32 / 255.0) + }); + ( + key, + Uniform { + offset: [ + -(x - cell_x as f64 * 12.0) as f32, + bottom, + -(z - cell_z as f64 * 12.0) as f32, + 0.0, + ], + colors, + }, + ) + } +} + +#[derive(Default)] +pub(crate) struct Mesh { + key: Option, + pub vertices: Vec, +} + +impl Mesh { + /// Returns true only when vertices must be uploaded. Sub-cell motion and + /// color changes update only the uniform, as in CloudRenderer.prepare. + pub fn prepare(&mut self, input: &Input<'_>) -> (bool, Uniform) { + let (key, uniform) = input.state(); + if self.key.as_ref() == Some(&key) { + return (false, uniform); + } + self.vertices.clear(); + let (w, h, cells) = input.texture; + let (w, h) = (i64::from(*w), i64::from(*h)); + let (cell_x, cell_z, radius) = (key.cell_x, key.cell_z, key.radius); + let bottom = uniform.offset[1]; + let uv = input.uv; + let filled = |cx: i64, cz: i64| cells[(cz.rem_euclid(h) * w + cx.rem_euclid(w)) as usize]; + for (dx, dz) in self::cells(radius) { + let (dx, dz) = (i64::from(dx), i64::from(dz)); + let (cx, cz) = (cell_x + dx, cell_z + dz); + if !filled(cx, cz) { + continue; + } + let x0 = dx as f32 * 12.0; + let z0 = dz as f32 * 12.0; + let (x1, z1, y0, y1) = (x0 + 12.0, z0 + 12.0, 0.0, 4.0); + let mut quad = |p: [[f32; 3]; 4], shade: u32| { + for v in p { + // Overlay 4: clouds (unlit, faded by the cloud fog end). + self.vertices.push(crate::mesher::Vertex { + normal: [0; 4], + pos: v, + uv, + layer: 4, + color: u32::MAX, + light: shade, + }); + } + }; + if input.fast { + for p in flat_cell(x0, z0, 0.0) { + quad(p, 0); + } + continue; + } + let quads = [ + ([[x1, y0, z0], [x1, y0, z1], [x0, y0, z1], [x0, y0, z0]], 1), + ([[x0, y1, z0], [x0, y1, z1], [x1, y1, z1], [x1, y1, z0]], 0), + ([[x0, y0, z0], [x0, y1, z0], [x1, y1, z0], [x1, y0, z0]], 2), + ([[x1, y0, z1], [x1, y1, z1], [x0, y1, z1], [x0, y0, z1]], 2), + ([[x0, y0, z1], [x0, y1, z1], [x0, y1, z0], [x0, y0, z0]], 3), + ([[x1, y0, z0], [x1, y1, z0], [x1, y1, z1], [x1, y0, z1]], 3), + ]; + let mask = face_mask( + dx as i32, + dz as i32, + bottom, + [ + !filled(cx, cz - 1), + !filled(cx, cz + 1), + !filled(cx - 1, cz), + !filled(cx + 1, cz), + ], + ); + for (direction, inside) in faces(mask) { + let (p, shade) = quads[usize::from(direction)]; + quad(if inside { [p[3], p[2], p[1], p[0]] } else { p }, shade); + } + } + self.key = Some(key); + (true, uniform) + } +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn cached_mesh_tracks_geometry_but_not_subcell_motion_or_color() { + let texture = (8, 8, (0..64).map(|i| i % 3 != 0).collect()); + let mut input = Input { + texture: &texture, + uv: [0.5; 2], + camera: glam::DVec3::new(1.0, 100.0, 1.0), + time: 0, + partial_tick: 0.0, + range: 2, + fast: false, + color: [1.0; 4], + }; + let mut mesh = Mesh::default(); + assert!(mesh.prepare(&input).0); + let vertices = bytemuck::cast_slice::<_, u8>(&mesh.vertices).to_vec(); + let pointer = mesh.vertices.as_ptr(); + for tick in 0..100 { + input.time = tick; + input.partial_tick = 0.5; + input.camera.x = 2.0; + input.camera.y = 101.0; + input.color = [0.8, 0.7, 0.6, 0.5]; + let (rebuilt, uniform) = mesh.prepare(&input); + assert!(!rebuilt); + assert_eq!(mesh.vertices.as_ptr(), pointer); + assert_eq!(bytemuck::cast_slice::<_, u8>(&mesh.vertices), vertices); + assert_eq!(uniform.offset[1], (192.33 - input.camera.y) as f32); + assert_eq!( + uniform.colors[1], + [0.8 * 0.7, 0.7 * 0.7, 0.6 * 0.7, 0.5].map(|v| (v * 255.0) as u8 as f32 / 255.0) + ); + for color in uniform.colors { + assert_eq!(color[3], 127.0 / 255.0); + } + } + for (x, y, z, range, fast) in [ + (13.0, 101.0, 1.0, 2, false), + (13.0, 101.0, -5.0, 2, false), + (13.0, 192.33, -5.0, 2, false), + (13.0, 196.34, -5.0, 2, false), + (13.0, 196.34, -5.0, 3, false), + (13.0, 196.34, -5.0, 3, true), + ] { + input.camera = glam::DVec3::new(x, y, z); + input.range = range; + input.fast = fast; + assert!(mesh.prepare(&input).0); + let mut fresh = Mesh::default(); + fresh.prepare(&input); + assert_eq!( + bytemuck::cast_slice::<_, u8>(&mesh.vertices), + bytemuck::cast_slice::<_, u8>(&fresh.vertices) + ); + assert!(!mesh.prepare(&input).0); + } + // Drift alone crosses a cell, even with a stationary camera. + input.time += 400; + assert!(mesh.prepare(&input).0); + // Resource reload constructs a new renderer and cache, including empty packs. + let mut reloaded = Mesh::default(); + let empty = (1, 1, vec![false]); + input.texture = ∅ + assert!(reloaded.prepare(&input).0); + assert!(reloaded.vertices.is_empty()); + assert!(!reloaded.prepare(&input).0); + } + #[test] fn settings_and_packed_alpha_gate_clouds() { for mode in ["false", "fast", "true"] { diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index b7d5be320..39fde56b5 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -65,6 +65,68 @@ pub struct SceneCollisions<'w, 'r> { /// The entity colliding, for powder snow; None: no fall, no boots. pub subject: Option, } +/// Already selected entity boxes alongside the resident block collision world. +pub struct EntityCollisions<'a, W> { + pub blocks: W, + pub entities: &'a [Aabb], +} +impl BlockCollisionWorld for EntityCollisions<'_, W> { + type Error = W::Error; + type Chunk = W::Chunk; + fn collision_chunk( + &mut self, + p: ChunkPos, + ) -> std::result::Result, Self::Error> { + self.blocks.collision_chunk(p) + } + fn collision_block( + &mut self, + chunk: Self::Chunk, + p: BlockPos, + ) -> std::result::Result { + self.blocks.collision_block(chunk, p) + } + fn is_suffocating( + &mut self, + chunk: Self::Chunk, + block: CollisionBlock, + p: BlockPos, + ) -> std::result::Result { + self.blocks.is_suffocating(chunk, block, p) + } + fn context_shape( + &mut self, + block: CollisionBlock, + p: BlockPos, + context: &CollisionContext<'_>, + ) -> std::result::Result { + self.blocks.context_shape(block, p, context) + } +} +impl> EntityMovementWorld for EntityCollisions<'_, W> { + type Error = io::Error; + fn entity_collisions( + &mut self, + entity: EntityIdentity, + bounds: Aabb, + ) -> io::Result> { + let mut shapes = self.blocks.entity_collisions(entity, bounds)?; + for &aabb in self.entities { + // EntityGetter.getEntityCollisions expands its entity query by 1e-7. + if aabb.intersects(bounds.inflate(Vec3::new(1.0e-7, 1.0e-7, 1.0e-7))) { + shapes.push(VoxelShape::from_box(aabb).map_err(io::Error::other)?); + } + } + Ok(shapes) + } + fn movement_border( + &mut self, + entity: EntityIdentity, + bounds: Aabb, + ) -> io::Result> { + self.blocks.movement_border(entity, bounds) + } +} impl SceneCollisions<'_, '_> { /// Position contexts permit geometric movement probes without inventing a /// player, inventory, effects or fluid-standing behavior; a lava walker @@ -147,21 +209,22 @@ where ) .unwrap_or(false) } -impl BlockCollisionWorld for SceneCollisions<'_, '_> { +impl<'w> BlockCollisionWorld for SceneCollisions<'w, '_> { type Error = io::Error; - type Chunk = ChunkPos; - fn collision_chunk(&mut self, p: ChunkPos) -> io::Result> { - Ok(self.world.chunks.contains_key(&(p.x, p.z)).then_some(p)) + /// The resident column, looked up once per chunk the scan enters. + type Chunk = &'w crate::chunk::Chunk; + fn collision_chunk(&mut self, p: ChunkPos) -> io::Result> { + Ok(self.world.chunks.get(&(p.x, p.z)).map(|chunk| &**chunk)) } - fn collision_block(&mut self, chunk: ChunkPos, p: BlockPos) -> io::Result { - let chunk = self - .world - .chunks - .get(&(chunk.x, chunk.z)) - .ok_or_else(|| io::Error::other("resident collision chunk disappeared"))?; + fn collision_block(&mut self, chunk: Self::Chunk, p: BlockPos) -> io::Result { self.binding.collision_block(chunk.block(p.x, p.y, p.z)) } - fn is_suffocating(&mut self, _: ChunkPos, _: CollisionBlock, _: BlockPos) -> io::Result { + fn is_suffocating( + &mut self, + _: Self::Chunk, + _: CollisionBlock, + _: BlockPos, + ) -> io::Result { Ok(false) } fn context_shape( diff --git a/crates/horizon-client/src/command/item.rs b/crates/horizon-client/src/command/item.rs index e0ed4a516..7c8abe84a 100644 --- a/crates/horizon-client/src/command/item.rs +++ b/crates/horizon-client/src/command/item.rs @@ -61,6 +61,33 @@ pub fn decode_component(id: &str, t: &Tag) -> Result<(), String> { _ => Err(not_map(t)), }, "minecraft:custom_name" | "minecraft:item_name" => super::component::decode(t), + // TypedEntityData.codec: the type is the compound's id. + "minecraft:block_entity_data" => match t { + Tag::Compound(c) => match c.get(&"id".into()) { + None => Err(format!("Expected 'id' field in {}", snbt(t))), + Some(Tag::String(id)) => { + let id = id.to_string_lossy(); + let id = if id.contains(':') { + id + } else { + format!("minecraft:{id}") + }; + let known = crate::block_entity_nbt::TYPES + .iter() + .chain(&crate::block_entity_nbt::NEWEST) + .any(|k| *k == id); + if known { + Ok(()) + } else { + Err(format!( + "Unknown registry key in ResourceKey[minecraft:root / minecraft:block_entity_type]: {id}" + )) + } + } + Some(_) => Ok(()), + }, + _ => Ok(()), + }, _ => Ok(()), } } @@ -609,3 +636,26 @@ pub fn suggest_predicate(builder: &mut SuggestionsBuilder, reg: &Registries) { fn _unused(t: &Tag) -> String { snbt(t) } + +#[cfg(test)] +mod tests { + use super::decode_component; + + fn check(snbt: &str) -> Result<(), String> { + let tag = horizon_world::nbt::parse_snbt(snbt).expect("snbt").0; + decode_component("minecraft:block_entity_data", &tag) + } + + #[test] + fn block_entity_data_needs_a_known_type() { + assert_eq!(check("{id:\"chest\",Lock:1}"), Ok(())); + assert_eq!( + check("{Command:\"say\"}"), + Err("Expected 'id' field in {Command:\"say\"}".into()) + ); + assert_eq!( + check("{id:\"minecraft:stone\"}"), + Err("Unknown registry key in ResourceKey[minecraft:root / minecraft:block_entity_type]: minecraft:stone".into()) + ); + } +} diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs index 3ff96d29b..52e76100a 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-client/src/command/mod.rs @@ -23,6 +23,9 @@ mod vanilla_order; use crate::text::Text; pub use args::{Arg, ArgType, Registries}; +/// The command id of a mod's command (`Dispatcher::with_mod_commands`). +pub const MOD_COMMAND: &str = "mod"; + /// A command error (CommandSyntaxException): the message and, for parse /// errors, the input and cursor it occurred at. #[derive(Clone, Debug, PartialEq)] @@ -770,6 +773,19 @@ impl Dispatcher { self.nodes[node].permission = level; node } + /// This tree plus the commands mods own (`docs/mods.md`), so the chat + /// colours and completes them like the others. Every player may use one, + /// and the text after its name goes to the mod as it was typed. + pub fn with_mod_commands<'a>(&self, names: impl IntoIterator) -> Dispatcher { + let mut d = self.clone(); + for name in names { + let command = d.literal(0, name); + d.executes(command, MOD_COMMAND); + let args = d.argument(command, "args", ArgType::Greedy); + d.executes(args, MOD_COMMAND); + } + d + } /// A root literal by name. pub fn find(&self, name: &str) -> Option { self.nodes[0] diff --git a/crates/horizon-client/src/command/tests.rs b/crates/horizon-client/src/command/tests.rs index 1bd23be82..2bdea1aba 100644 --- a/crates/horizon-client/src/command/tests.rs +++ b/crates/horizon-client/src/command/tests.rs @@ -570,3 +570,25 @@ fn place_template_tree() { assert!(run("place template minecraft:x ~ ~ ~ sideways").is_err()); assert!(run("place template minecraft:x ~ ~ ~ none none 2").is_err()); } +#[test] +fn mod_commands_join_the_tree_for_every_player() { + let reg = Registries { + permission: 0, + ..reg() + }; + let d = vanilla::game_dispatcher().with_mod_commands(["where"]); + for line in ["where", "where north 12"] { + let parse = d.parse(line, ®); + assert_eq!(parse.executable().unwrap().1, MOD_COMMAND, "{line}"); + } + let parse = d.parse("w", ®); + let names: Vec = d + .client_suggestions(&parse, 1, ®) + .1 + .into_iter() + .map(|s| s.text) + .collect(); + assert!(names.contains(&"where".to_owned()), "{names:?}"); + // The game's own tree is left as it was. + assert!(vanilla::game_dispatcher().find("where").is_none()); +} diff --git a/crates/horizon-client/src/command_block.rs b/crates/horizon-client/src/command_block.rs new file mode 100644 index 000000000..942e11ab6 --- /dev/null +++ b/crates/horizon-client/src/command_block.rs @@ -0,0 +1,256 @@ +//! `CommandBlockEntity` with its `BaseCommandBlock`: the command, the success +//! count comparators read, the output it keeps, and the powered, automatic +//! and condition flags `CommandBlock.tick` runs on. +use crate::{ + save::{number, text}, + text::Text, +}; +use horizon_world::nbt::Tag; + +/// `CommandBlockEntity.Mode`, in declaration order (the edit screen's mode +/// button cycles through it). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + Sequence, + Auto, + Redstone, +} + +impl Mode { + /// `CommandBlockEntity.getMode`: the block the entity sits in. + pub fn of_block(name: &str) -> Option { + match name { + "minecraft:command_block" => Some(Self::Redstone), + "minecraft:repeating_command_block" => Some(Self::Auto), + "minecraft:chain_command_block" => Some(Self::Sequence), + _ => None, + } + } + /// The block `ServerGamePacketListenerImpl.handleSetCommandBlock` puts + /// down for a mode. + pub fn block(self) -> &'static str { + match self { + Self::Sequence => "minecraft:chain_command_block", + Self::Auto => "minecraft:repeating_command_block", + Self::Redstone => "minecraft:command_block", + } + } + /// `CycleButton`: the next value, wrapping round. + pub fn next(self) -> Self { + match self { + Self::Sequence => Self::Auto, + Self::Auto => Self::Redstone, + Self::Redstone => Self::Sequence, + } + } + /// `CommandBlockEditScreen`'s label for the mode. + pub fn label(self) -> &'static str { + match self { + Self::Sequence => "advMode.mode.sequence", + Self::Auto => "advMode.mode.auto", + Self::Redstone => "advMode.mode.redstone", + } + } +} + +/// The `automatic` flag `CommandBlock` gives its entity: chain command blocks +/// are always active when placed. +pub fn automatic_block(name: &str) -> bool { + name == "minecraft:chain_command_block" +} + +#[derive(Clone, Debug, PartialEq)] +pub struct CommandBlock { + pub command: String, + pub success_count: i32, + /// `CustomName` as saved (a text component). + pub custom_name: Option, + pub track_output: bool, + pub last_output: Option, + pub update_last_execution: bool, + /// The game time of the last run, -1 for none. + pub last_execution: i64, + pub powered: bool, + pub auto: bool, + pub condition_met: bool, +} + +impl Default for CommandBlock { + fn default() -> Self { + Self { + command: String::new(), + success_count: 0, + custom_name: None, + track_output: true, + last_output: None, + update_last_execution: true, + last_execution: -1, + powered: false, + auto: false, + condition_met: false, + } + } +} + +impl CommandBlock { + /// `CommandBlockEntity.loadAdditional` with `BaseCommandBlock.load`. + pub fn load(tag: &Tag) -> Self { + let flag = |key: &str, default: bool| number(tag.get(key)).map_or(default, |v| v != 0); + let track_output = flag("TrackOutput", true); + let update_last_execution = flag("UpdateLastExecution", true); + Self { + command: text(tag.get("Command")).unwrap_or_default(), + success_count: number(tag.get("SuccessCount")).unwrap_or(0) as i32, + custom_name: tag.get("CustomName").cloned(), + track_output, + last_output: track_output + .then(|| tag.get("LastOutput")) + .flatten() + .map(|t| crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t))), + update_last_execution, + last_execution: if update_last_execution { + number(tag.get("LastExecution")).unwrap_or(-1) + } else { + -1 + }, + powered: flag("powered", false), + auto: flag("auto", false), + condition_met: flag("conditionMet", false), + } + } + /// `CommandBlockEntity.saveAdditional`. The last output is written as a + /// plain string component. + pub fn save(&self) -> Vec<(&'static str, Tag)> { + let mut out = vec![ + ("Command", Tag::String(self.command.as_str().into())), + ("SuccessCount", Tag::Int(self.success_count)), + ]; + if let Some(name) = &self.custom_name { + out.push(("CustomName", name.clone())); + } + out.push(("TrackOutput", Tag::Byte(i8::from(self.track_output)))); + if self.track_output + && let Some(last) = &self.last_output + { + out.push(("LastOutput", Tag::String(last.plain().as_str().into()))); + } + out.push(( + "UpdateLastExecution", + Tag::Byte(i8::from(self.update_last_execution)), + )); + if self.update_last_execution && self.last_execution != -1 { + out.push(("LastExecution", Tag::Long(self.last_execution))); + } + out.push(("powered", Tag::Byte(i8::from(self.powered)))); + out.push(("conditionMet", Tag::Byte(i8::from(self.condition_met)))); + out.push(("auto", Tag::Byte(i8::from(self.auto)))); + out + } + /// `BaseCommandBlock.setCommand`: a new command starts at no successes. + pub fn set_command(&mut self, command: &str) { + self.command = command.to_owned(); + self.success_count = 0; + } + /// `getLastOutput().getString()`: what the edit screen shows. + pub fn last_output_string(&self) -> String { + self.last_output + .as_ref() + .map(Text::plain) + .unwrap_or_default() + } + /// `getName`: the custom name, else `@`. + pub fn name(&self) -> Text { + self.custom_name.as_ref().map_or_else( + || Text::literal("@"), + |t| crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t)), + ) + } +} + +/// What `CommandBlock.tick` does with a block of `mode` whose condition was +/// `met` when last checked: run its command (`Some(true)`), clear the success +/// count of a conditional block (`Some(false)`), or nothing. Chain blocks +/// only run from the block before them (`executeChain`). +pub fn tick_action(mode: Mode, met: bool, conditional: bool) -> Option { + match mode { + Mode::Sequence => None, + _ if met => Some(true), + _ if conditional => Some(false), + _ => None, + } +} + +/// `CommandBlock.tick`: a repeating block ticks again next tick while powered +/// or always active. +pub fn repeats(mode: Mode, powered: bool, auto: bool) -> bool { + mode == Mode::Auto && (powered || auto) +} + +/// `CommandBlock.setPoweredAndUpdate`: a rising signal schedules the impulse +/// or repeating block's tick unless it is always active anyway. +pub fn power_schedules(mode: Mode, was_powered: bool, powered: bool, auto: bool) -> bool { + powered && !was_powered && !auto && mode != Mode::Sequence +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn modes_cycle_and_map_to_blocks() { + for mode in [Mode::Sequence, Mode::Auto, Mode::Redstone] { + assert_eq!(Mode::of_block(mode.block()), Some(mode)); + } + assert_eq!(Mode::Redstone.next(), Mode::Sequence); + assert_eq!(Mode::Sequence.next(), Mode::Auto); + assert!(automatic_block("minecraft:chain_command_block")); + assert!(!automatic_block("minecraft:repeating_command_block")); + } + + #[test] + fn tick_follows_the_condition() { + assert_eq!(tick_action(Mode::Redstone, true, false), Some(true)); + assert_eq!(tick_action(Mode::Redstone, false, true), Some(false)); + assert_eq!(tick_action(Mode::Auto, false, false), None); + assert_eq!(tick_action(Mode::Sequence, true, false), None); + assert!(repeats(Mode::Auto, false, true)); + assert!(!repeats(Mode::Auto, false, false)); + assert!(!repeats(Mode::Redstone, true, true)); + } + + #[test] + fn only_a_rising_edge_schedules() { + assert!(power_schedules(Mode::Redstone, false, true, false)); + assert!(!power_schedules(Mode::Redstone, true, true, false)); + assert!(!power_schedules(Mode::Redstone, false, true, true)); + assert!(!power_schedules(Mode::Sequence, false, true, false)); + } + + #[test] + fn saves_like_base_command_block() { + let block = CommandBlock { + command: "say hi".into(), + success_count: 1, + last_output: Some(Text::literal("[12:00:00] hi")), + last_execution: 42, + powered: true, + ..CommandBlock::default() + }; + let tag = Tag::compound(block.save()); + let back = CommandBlock::load(&tag); + assert_eq!(back.command, "say hi"); + assert_eq!(back.success_count, 1); + assert_eq!(back.last_output_string(), "[12:00:00] hi"); + assert_eq!(back.last_execution, 42); + assert!(back.powered && !back.auto && back.track_output); + // Not tracking output drops it, and no execution time is kept at -1. + let quiet = CommandBlock { + track_output: false, + last_output: Some(Text::literal("x")), + ..CommandBlock::default() + }; + let tag = Tag::compound(quiet.save()); + assert!(tag.get("LastOutput").is_none() && tag.get("LastExecution").is_none()); + assert_eq!(CommandBlock::load(&tag).last_output, None); + } +} diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 777e90054..46e73f067 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -70,8 +70,12 @@ pub enum BlockEntity { Spawner(Box), /// `TrialSpawnerBlockEntity` (`crate::mobs::trial_spawner`). TrialSpawner(Box), + /// `VaultBlockEntity` (`crate::vault`). + Vault(Box), /// `BeehiveBlockEntity` of beehives and bee nests (`crate::beehive`). Beehive(Box), + /// `CommandBlockEntity` of the three command blocks (`crate::command_block`). + CommandBlock(Box), } /// `CrafterBlockEntity`: nine slots that can be disabled, the powered flag /// and the ticks left in the crafting animation. @@ -192,12 +196,24 @@ impl BlockEntity { if name == "minecraft:trial_spawner" { return Some(Self::TrialSpawner(Box::default())); } + if name == "minecraft:vault" { + return Some(Self::Vault(Box::default())); + } if name == "minecraft:beehive" || name == "minecraft:bee_nest" { return Some(Self::Beehive(Box::default())); } if name == "minecraft:lectern" { return Some(Self::Lectern(Lectern::default())); } + if crate::command_block::Mode::of_block(name).is_some() { + // CommandBlock.newBlockEntity: setAutomatic(this.automatic). + return Some(Self::CommandBlock(Box::new( + crate::command_block::CommandBlock { + auto: crate::command_block::automatic_block(name), + ..Default::default() + }, + ))); + } if let Some(sculk) = crate::sculk::SculkEntity::for_block(name) { return Some(Self::Sculk(Box::new(sculk))); } @@ -272,7 +288,9 @@ impl BlockEntity { Self::CreakingHeart(_) => "minecraft:creaking_heart", Self::Spawner(_) => "minecraft:mob_spawner", Self::TrialSpawner(_) => "minecraft:trial_spawner", + Self::Vault(_) => "minecraft:vault", Self::Beehive(_) => "minecraft:beehive", + Self::CommandBlock(_) => "minecraft:command_block", } } pub fn contents(&self) -> Vec { @@ -286,7 +304,9 @@ impl BlockEntity { | Self::CreakingHeart(_) | Self::Spawner(_) | Self::TrialSpawner(_) - | Self::Beehive(_) => Vec::new(), + | Self::Vault(_) + | Self::Beehive(_) + | Self::CommandBlock(_) => Vec::new(), Self::Lectern(l) => l.book.iter().cloned().collect(), Self::Sculk(_) => Vec::new(), Self::Banner(_) => Vec::new(), @@ -308,7 +328,9 @@ impl BlockEntity { Self::CreakingHeart(_) | Self::Spawner(_) | Self::TrialSpawner(_) - | Self::Beehive(_) => &[], + | Self::Vault(_) + | Self::Beehive(_) + | Self::CommandBlock(_) => &[], } } pub fn slots_mut(&mut self) -> &mut [Option] { @@ -326,7 +348,9 @@ impl BlockEntity { Self::CreakingHeart(_) | Self::Spawner(_) | Self::TrialSpawner(_) - | Self::Beehive(_) => &mut [], + | Self::Vault(_) + | Self::Beehive(_) + | Self::CommandBlock(_) => &mut [], } } } diff --git a/crates/horizon-client/src/control.rs b/crates/horizon-client/src/control.rs index 3019d8dfa..9749cc9bd 100644 --- a/crates/horizon-client/src/control.rs +++ b/crates/horizon-client/src/control.rs @@ -467,13 +467,16 @@ impl FrameStats { } let total: f64 = sorted.iter().map(|&m| f64::from(m)).sum(); let percentile = |p: f64| sorted[((n as f64 * p).ceil() as usize).clamp(1, n) - 1]; - // Average frame time of the slowest 1% of frames, as frames per second. - let slowest = n.div_ceil(100); - let slow: f64 = sorted[n - slowest..] - .iter() - .map(|&m| f64::from(m)) - .sum::() - / slowest as f64; + // Average frame time of the slowest 1% (0.1%) of frames, as frames per second. + let low = |per: usize| { + let slowest = n.div_ceil(per); + let slow: f64 = sorted[n - slowest..] + .iter() + .map(|&m| f64::from(m)) + .sum::() + / slowest as f64; + 1000.0 / slow + }; // Where the slowest 1% of frames by CPU time go. let slow_phases = { let mut cpu = self.cpu.clone(); @@ -487,7 +490,8 @@ impl FrameStats { "frames": n, "seconds": total / 1000.0, "avg_fps": n as f64 * 1000.0 / total, - "low_1pct_fps": 1000.0 / slow, + "low_1pct_fps": low(100), + "low_01pct_fps": low(1000), "p50_ms": percentile(0.5), "p95_ms": percentile(0.95), "p99_ms": percentile(0.99), diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index e4a70811a..457ddf497 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -14,7 +14,7 @@ use serde_json::Value; use std::{ collections::{HashMap, HashSet}, fs, - path::Path, + path::{Path, PathBuf}, sync::Arc, }; @@ -1182,18 +1182,33 @@ impl Recipes { let mut crafting = Vec::new(); let mut cooking = Vec::new(); let mut meta = HashMap::new(); - let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/recipe"))? - .flatten() - .map(|e| e.path()) - .filter(|p| p.extension().is_some_and(|e| e == "json")) + let json_files = |dir: &Path| -> Result> { + let mut files: Vec<_> = fs::read_dir(dir)? + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == "json")) + .collect(); + files.sort(); + Ok(files) + }; + // Vanilla's recipes by bare name, then content mods' as `:`. + let mut files: Vec<(String, PathBuf)> = json_files(&root.join("data/minecraft/recipe"))? + .into_iter() + .map(|p| (String::new(), p)) .collect(); - files.sort(); - for path in files { - let name = path - .file_stem() - .and_then(|s| s.to_str()) - .unwrap_or("") - .to_owned(); + for namespace in crate::mod_content::namespaces(root) { + let dir = root.join(format!("data/{namespace}/recipe")); + if dir.is_dir() { + files.extend( + json_files(&dir)? + .into_iter() + .map(|p| (format!("{namespace}:"), p)), + ); + } + } + for (prefix, path) in files { + let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or(""); + let name = format!("{prefix}{stem}"); let v: Value = serde_json::from_slice(&fs::read(&path)?)?; let text = |k: &str| v[k].as_str().unwrap_or("").to_owned(); meta.insert(name.clone(), (text("category"), text("group"))); diff --git a/crates/horizon-client/src/creative.rs b/crates/horizon-client/src/creative.rs index 942bf13b9..80445d541 100644 --- a/crates/horizon-client/src/creative.rs +++ b/crates/horizon-client/src/creative.rs @@ -49,17 +49,24 @@ pub struct Names { } impl Names { pub fn load(root: &Path) -> Self { - let map = fs::read(root.join("assets/minecraft/lang/en_us.json")) - .ok() - .and_then(|b| serde_json::from_slice::>(&b).ok()) - .unwrap_or_default(); + let read = |namespace: &str| { + fs::read(root.join(format!("assets/{namespace}/lang/en_us.json"))) + .ok() + .and_then(|b| serde_json::from_slice::>(&b).ok()) + .unwrap_or_default() + }; + let mut map = read("minecraft"); + // Content mods' names (docs/modpacks.md); none in a vanilla root. + for namespace in crate::mod_content::namespaces(root) { + map.extend(read(&namespace)); + } Self { map } } pub fn item(&self, id: &str) -> String { - let path = id.trim_start_matches("minecraft:"); + let (namespace, path) = id.split_once(':').unwrap_or(("minecraft", id)); self.map - .get(&format!("item.minecraft.{path}")) - .or_else(|| self.map.get(&format!("block.minecraft.{path}"))) + .get(&format!("item.{namespace}.{path}")) + .or_else(|| self.map.get(&format!("block.{namespace}.{path}"))) .cloned() .unwrap_or_else(|| path.replace('_', " ")) } diff --git a/crates/horizon-client/src/datapack.rs b/crates/horizon-client/src/datapack.rs index b76a4f243..51a052ee9 100644 --- a/crates/horizon-client/src/datapack.rs +++ b/crates/horizon-client/src/datapack.rs @@ -34,6 +34,27 @@ impl DataPack { } } } + /// The files of `data///` for each kind, in the order + /// `list("data/")` gives them. A folder pack walks only those folders: + /// the built-in pack holds about 10,000 other data files. + fn list_kinds(&self, kinds: &[&str]) -> Vec { + debug_assert!(kinds.is_sorted(), "kinds in walk order"); + let Source::Dir(root) = &self.source else { + return self.list("data/"); + }; + let Ok(entries) = std::fs::read_dir(root.join("data")) else { + return Vec::new(); + }; + let mut namespaces: Vec<_> = entries.flatten().map(|e| e.path()).collect(); + namespaces.sort(); + let mut out = Vec::new(); + for ns in namespaces { + for kind in kinds { + walk(root, &ns.join(kind), &mut out); + } + } + out + } fn read(&self, path: &str) -> Option> { match &self.source { Source::Zip(z) => z.read(path).ok(), @@ -308,7 +329,7 @@ impl DataStore { pub fn load(packs: &[&DataPack]) -> Self { let mut s = Self::default(); for pack in packs { - for f in pack.list("data/") { + for f in pack.list_kinds(&["function", "item_modifier", "predicate", "tags/function"]) { if let Some(id) = resource_id(&f, "function", ".mcfunction") && let Some(bytes) = pack.read(&f) { @@ -505,4 +526,44 @@ mod tests { assert!(store.predicates.contains_key("mine:p")); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn folder_packs_list_the_needed_kinds_in_walk_order() { + let dir = std::env::temp_dir().join(format!("hz-datapack-kinds-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let pack = dir.join("datapacks/p"); + let files = [ + "data/b/function/z.mcfunction", + "data/b/function/a/y.mcfunction", + "data/b/loot_table/l.json", + "data/b/tags/block/t.json", + "data/b/tags/function/load.json", + "data/b/predicate/p.json", + "data/a/item_modifier/m.json", + "data/a/function/f.mcfunction", + "data/a/functions/old.mcfunction", + "data/a/recipe/r.json", + "data/a/tags/function/tick.json", + "data/c/worldgen/noise/n.json", + ]; + for f in files { + let path = pack.join(f); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, "{}").unwrap(); + } + std::fs::write(pack.join("pack.mcmeta"), "{}").unwrap(); + let p = DataPack::builtin(&pack); + let kinds = ["function", "item_modifier", "predicate", "tags/function"]; + let wanted: Vec = p + .list("data/") + .into_iter() + .filter(|f| { + let rest = f.splitn(3, '/').nth(2).unwrap_or_default(); + kinds.iter().any(|k| rest.starts_with(&format!("{k}/"))) + }) + .collect(); + assert_eq!(wanted.len(), 7); + assert_eq!(p.list_kinds(&kinds), wanted); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index 44ae40766..c6305c697 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -58,8 +58,8 @@ fn overlay_texel(overlay: u32) -> vec4 { if overlay >= 16u && overlay < 32u { return vec4(1.0, 1.0, 1.0, WHITE_OVERLAY_ALPHA[overlay - 16u]); } return vec4(1.0); } -@vertex fn vs_entity(@location(0) position: vec3, @location(1) uv: vec2, - @location(2) overlay: u32, @location(3) color: vec4, @location(4) light: vec4, @location(5) normal: vec4) -> Out { +fn entity_vertex(position: vec3, uv: vec2, + overlay: u32, color: vec4, light: vec4, normal: vec4) -> Out { var out: Out; out.clip = globals.view_proj * vec4(position, 1.0); out.proj = vec4(out.clip.xy * 0.5 + out.clip.w * 0.5, out.clip.zw); @@ -90,6 +90,19 @@ fn overlay_texel(overlay: u32) -> vec4 { if overlay == 4u { out.spherical = length(position); } return out; } +@vertex fn vs_entity(@location(0) position: vec3, @location(1) uv: vec2, + @location(2) overlay: u32, @location(3) color: vec4, @location(4) light: vec4, @location(5) normal: vec4) -> Out { + return entity_vertex(position, uv, overlay, color, light, normal); +} +struct CloudInfo { + offset: vec4, + colors: array, 4>, +} +@group(1) @binding(0) var cloud: CloudInfo; +@vertex fn vs_cloud(@location(0) position: vec3, @location(1) uv: vec2, + @location(2) overlay: u32, @location(3) color: vec4, @location(4) light: vec4, @location(5) normal: vec4) -> Out { + return entity_vertex(position + cloud.offset.xyz, uv, overlay, cloud.colors[light.x], light, normal); +} // rendertype_end_portal.fsh: the layer colours. const PORTAL_COLORS = array, 16>( vec3(0.022087, 0.098399, 0.110818), diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index eefce5ee2..309bf6df1 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -435,8 +435,8 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { }); } "minecraft:zombie" => { + map.insert("IsBaby".into(), Tag::Byte(i8::from(m.is_baby()))); for (key, value) in [ - ("IsBaby", Tag::Byte(0)), ("CanBreakDoors", Tag::Byte(0)), ("DrownedConversionTime", Tag::Int(-1)), ("InWaterTime", Tag::Int(-1)), @@ -845,6 +845,11 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.health = health; m.extra.flag2 = flag(tag, "wasOnGround"); } + // Zombie, Piglin and Zoglin.readAdditionalSaveData: IsBaby (the baby + // zombies of trial spawners). + if !crate::mobs::finalize::ageable(m.species()) && flag(tag, "IsBaby") { + crate::mobs::finalize::set_baby(&mut m, true); + } crate::mobs::raider::read_nbt(&mut m, tag); crate::mobs::riders::read_nbt(&mut m, tag); // A mob saved mid-death finishes dying; one saved dead is dropped. diff --git a/crates/horizon-client/src/fog.rs b/crates/horizon-client/src/fog.rs index 801b1e303..83f1a8bf5 100644 --- a/crates/horizon-client/src/fog.rs +++ b/crates/horizon-client/src/fog.rs @@ -119,22 +119,6 @@ impl FogState { } } -/// The fog tables and evolving state kept by the game. -pub struct FogRenderer { - pub tables: FogTables, - pub state: FogState, -} -impl FogRenderer { - pub fn load(root: &Path, biomes: &Biomes) -> Self { - Self { - tables: FogTables::load(root, biomes), - state: FogState::default(), - } - } - pub fn setup(&self, input: &FogInputs) -> FogData { - setup_fog(&self.tables, &self.state, input) - } -} /// `FluidState.getHeightForCamera`. fn camera_fluid_height(world: &World, facts: &BlockFacts, b: [i32; 3]) -> Option<(Fluid, f64)> { let s = facts.get(world.block(b[0], b[1], b[2])); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c05d41760..7d37d2127 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -10,6 +10,7 @@ mod banners; mod beacon; mod beehives; mod block_entity_anims; +mod block_items; mod blockctl; mod boats; mod books; @@ -19,6 +20,7 @@ mod cartography; mod chat; mod clipboard; mod combat; +mod command_blocks; mod command_harness; mod commands; mod composter; @@ -28,6 +30,7 @@ mod creaking; mod creatures; mod crossbow; mod debug_keys; +mod decorated_pot; mod dedicated; mod dispense_fixture; mod dispenser; @@ -46,18 +49,22 @@ mod frames; mod friends; mod functions; mod game_mode; +mod game_rules_screen; mod gamemode_switcher; mod ghasts; mod golems; mod growth; mod hand; mod initial_spawn; +mod integrated; mod item_draw; mod item_particles; mod jukebox; mod lan; mod lan_actions; mod lan_crafting; +mod lan_mobs; +mod lan_pvp; mod lan_screen; mod lan_trading; mod leads; @@ -80,6 +87,7 @@ mod natural_spawning; mod nautili; mod net_harness; mod nether_portal; +mod ominous_item_spawner; mod options; mod packs; mod pad; @@ -122,9 +130,11 @@ mod tnt; mod totem; mod trading; mod trial_spawner; +mod trial_visuals; mod trident; mod tweaks; mod ui_control; +mod vault; mod villagers; mod wandering_trader; mod wind; @@ -144,7 +154,7 @@ use horizon_client::{ creative::{Creative, Names}, entities::{Experience, ExperienceOrb, ItemEntity}, environment::Environment, - first_person::Hand, + first_person::{Hand, SwingAnimation}, gfx::{Frame, Renderer}, hud::{HudAtlas, HudBatch, rgba}, hud_layout, hud_overlays, @@ -194,6 +204,7 @@ use winit::{ window::{CursorGrabMode, Window, WindowId}, }; +#[derive(Clone)] struct Options { resources: PathBuf, distance: i32, @@ -202,6 +213,8 @@ struct Options { creative: bool, test_terrain: bool, frames: Option, + /// `--world-frames N`: exit after N frames drawn in the world (smoke runs; the world may load slowly). + world_frames: Option, screenshot_after: Option, timeout: Duration, report: Option, @@ -231,6 +244,11 @@ struct Options { benchmark: Option, /// `--dev-mod PATH` (repeatable): mods always on and reloaded when rebuilt. dev_mods: Vec, + /// `--server-thread` or `HORIZON_SERVER_THREAD=1`: single player runs on + /// an integrated server thread (game/integrated.rs). + server_thread: bool, + /// Set on the integrated server's own options: it draws nothing, so it skips meshing. + integrated: bool, } impl Options { /// The name to join servers with: the one given, else the offline name kept @@ -260,6 +278,7 @@ impl Options { creative: false, test_terrain: false, frames: None, + world_frames: None, screenshot_after: None, timeout: Duration::from_secs(120), report: None, @@ -281,6 +300,8 @@ impl Options { dedicated: None, benchmark: None, dev_mods: Vec::new(), + server_thread: std::env::var("HORIZON_SERVER_THREAD").is_ok_and(|v| v == "1"), + integrated: false, }; let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok(); let mut args = std::env::args().skip(1); @@ -288,7 +309,7 @@ impl Options { match arg.as_str() { "--help" | "-h" => { println!( - "Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\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 --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\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." + "Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\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 --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\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); } @@ -301,6 +322,7 @@ impl Options { "--no-pause" => o.no_pause = true, "--offscreen" => o.offscreen = true, "--control" => o.control = Some(horizon_client::control::default_path()), + "--server-thread" => o.server_thread = true, _ => { let value = args .next() @@ -326,6 +348,11 @@ impl Options { }) } "--frames" => o.frames = Some(value.parse()?), + "--world-frames" => { + o.world_frames = Some(value.parse()?); + // A frame-limited run in every other respect; --timeout-seconds still applies. + o.frames.get_or_insert(u64::MAX); + } "--timeout-seconds" => o.timeout = Duration::from_secs(value.parse()?), "--smoke-report" => o.report = Some(value.into()), "--screenshot-after" => o.screenshot_after = Some(value.parse()?), @@ -392,6 +419,8 @@ enum Screen { Advancements, /// WorldOptionsScreen (game/lan_screen.rs). WorldOptions, + /// CommandBlockEditScreen (game/command_blocks.rs). + CommandBlock, } struct Mining { pos: [i32; 3], @@ -420,6 +449,8 @@ struct GameLevel<'w> { seed: i64, behaviours: &'w Behaviours, items: &'w Items, + /// Container loot tables (`unpackLootTable`). + loot: Option>, registry: &'static horizon_world::registry::BlockRegistry, rules: horizon_world::level::GameRules, /// Block loot random sequences (`ServerLevel.getRandomSequence`). @@ -440,6 +471,9 @@ impl LevelAccess for GameLevel<'_> { state: BlockStateId, _direction: Direction, ) -> i32 { + if let Some(signal) = command_blocks::analog_signal(self.world, (pos.x, pos.y, pos.z)) { + return signal; + } if let Some(signal) = sculk::sensor_signal(self.world, self.behaviours, state, pos) { return signal; } @@ -597,6 +631,9 @@ impl LevelAccess for GameLevel<'_> { fn remove_block_entity(&mut self, pos: BlockPos, old: BlockStateId, side_effects: bool) -> u8 { self.remove_entity(pos, old, side_effects) } + fn set_command_block_powered(&mut self, pos: BlockPos, powered: bool) -> Option<(bool, bool)> { + command_blocks::set_powered(self.world, self.registry, (pos.x, pos.y, pos.z), powered) + } } /// FallingBlockEntity carrying a block state. #[derive(Clone, Debug)] @@ -618,43 +655,91 @@ struct FallingBlock { /// The UUID and compound it was loaded with, kept while it moves. saved: Option>, } +/// The data loaded once at startup and never changed: blocks, items, +/// recipes, biomes, mobs, collision and motion. Read-only and `Send + Sync`, +/// so the client and an integrated server thread can share one copy. pub struct Resources { - assets: Arc, facts: BlockFacts, items: Items, recipes: Recipes, transformers: horizon_client::block_transform::Transformers, biomes: Arc, environment: Environment, - atlas: HudAtlas, - panorama: horizon_client::gfx::panorama::Faces, - layer_names: HashMap, mob_types: HashMap>, mob_data: horizon_client::mobs::MobData, providers: Providers, block_entity_render: horizon_client::block_entity_render::BlockEntityRenderer, animate: horizon_client::animate_tick::AnimateTables, - fog: horizon_client::fog::FogRenderer, + fog: horizon_client::fog::FogTables, music: horizon_client::music::MusicTables, ambient: horizon_client::ambience::AmbientTables, - screen_fx: horizon_client::screen_effects::ScreenEffects, nether_environment: Environment, end_environment: Environment, behaviours: Behaviours, - names: Names, - /// clouds.png: (width, height, filled cells). - clouds: (u32, u32, Vec), - /// misc/forcefield.png: (width, height, RGBA) for the world border wall. - forcefield: (u32, u32, Vec), - context: Arc, + collision: BlockCollisionRegistry<'static>, + motion: MotionResources, threads: usize, player_arm: Option, player_type: Option>, - /// Item definitions, baked item models and special renderers. - item_renderer: Arc, /// Enchantments, workstation recipes and brewing (game/stations.rs). stations: horizon_client::stations::StationData, } +/// What a resource pack reload replaces (`Minecraft.reloadResourcePacks`): +/// block models and sprites with their meshing tables, item models, +/// translations and the textures read on the CPU. Each game holds its own; +/// cloning shares the loaded data. +#[derive(Clone)] +pub struct PackResources { + assets: Arc, + context: Arc, + layer_names: Arc>, + panorama: Arc, + /// Item definitions, baked item models and special renderers. + item_renderer: Arc, + names: Arc, + /// clouds.png: (width, height, filled cells). + clouds: Arc<(u32, u32, Vec)>, + /// misc/forcefield.png: (width, height, RGBA) for the world border wall. + forcefield: Arc<(u32, u32, Vec)>, +} +impl PackResources { + /// Everything a pack overlay at `root` provides, over `assets` loaded from it. + fn load( + root: &std::path::Path, + assets: Arc, + facts: &BlockFacts, + biomes: Arc, + light: Arc, + ) -> Result { + let visibility = models::load_visibility(root, assets.registry)?; + let tables = Arc::new(MeshTables::new(&assets, facts, visibility)?); + let item_renderer = horizon_client::item_render::ItemRenderer::load_with_library( + root, + assets.model_library.clone(), + )?; + Ok(Self { + layer_names: Arc::new( + assets + .sprite_layers + .iter() + .map(|(name, layer)| (*layer, name.trim_start_matches("minecraft:").to_owned())) + .collect(), + ), + context: Arc::new(WorkerContext { + assets: assets.clone(), + tables, + biomes, + light, + }), + assets, + panorama: Arc::new(horizon_client::gfx::panorama::Faces::load(root)), + item_renderer: Arc::new(item_renderer), + names: Arc::new(Names::load(root)), + clouds: Arc::new(load_clouds(root)), + forcefield: Arc::new(load_forcefield(root)), + }) + } +} /// A quick craft drag as the screen draws it: each dragged slot's count and /// whether the slot caps it (None: hidden), and what stays in hand. struct DragView { @@ -678,9 +763,17 @@ fn select_creative_tab( } struct Game<'a> { - res: &'a mut Resources, + /// Shared with an integrated server; `collision` and `motion` borrow from it. + res: Arc, collision: &'a BlockCollisionRegistry<'a>, motion: &'a MotionResources, + /// This game's resource packs (`reload_packs` replaces them). + pack: PackResources, + /// The GUI, font, particle, map and skin atlas. + atlas: HudAtlas, + /// `FogRenderer`'s evolving state. + fog: horizon_client::fog::FogState, + screen_fx: horizon_client::screen_effects::ScreenEffects, world: World, streaming: Streaming, options: Options, @@ -754,6 +847,8 @@ struct Game<'a> { renderer: Option, /// CPU geometry storage retained across frames, including empty/title frames. entity_vertices: Vec, + /// Name tags drawn over everything (`RenderPipelines.TEXT_SEE_THROUGH`). + see_through_vertices: Vec, started: Instant, previous: Instant, /// FramerateLimitTracker.latestInputTime. @@ -761,6 +856,8 @@ struct Game<'a> { /// Controllers (Horizon's own). pad: pad::Pads, frames: u64, + /// Frames drawn with the player in the world, for `--world-frames`. + world_frames: u64, fps: f32, fps_frames: u64, fps_at: Instant, @@ -792,8 +889,8 @@ struct Game<'a> { book: Option, /// Lecterns whose page-turn pulse is running (ticks left). lectern_pulses: Vec<((i32, i32, i32), i32)>, - /// Steps of the world spawn's chunk spiral taken so far. - spawn_search: u32, + /// LevelLoadingScreen.smoothedProgress while the player is not placed yet. + loading_progress: f32, /// The world spawn search's origin chunk and fallback height, once known. spawn_origin: Option<((i32, i32), i32)>, spawn_spiral: horizon_client::world_spawn::ChunkSpiral, @@ -943,6 +1040,8 @@ struct Game<'a> { hook: Option, tridents: Vec, rockets: Vec, + /// Ominous trial spawners' item spawners. + ominous_spawners: Vec, creaking: creaking::CreakingState, /// Monster spawners' display mobs (`game/spawner.rs`). spawners: spawner::SpawnerState, @@ -984,9 +1083,14 @@ struct Game<'a> { remote: Option, /// This world is open to the network (game/lan.rs). lan: Option, + /// Single player's server thread, which `remote` is connected to. + integrated: Option, /// The open world is shared behind an invite code (game/friends.rs). friends: Option, world_options: Option, + /// Chat Settings opened from RestrictionsScreen: Done returns to World Options. + options_to_world_options: bool, + command_block_screen: Option, /// KeyboardHandler's debug key state (game/debug_keys.rs), the physical /// keys held, and the debug renderers F3+B and F3+G switch on. debug_keys: horizon_client::debug_keys::DebugKeys, @@ -1007,6 +1111,9 @@ struct Game<'a> { saved_for_exit: bool, /// The block a guest is acting on (game/lan_actions.rs). forced_hit: Option, + /// A guest's `ServerboundUseItemPacket`: the held item alone, no block + /// or entity (`ServerGamePacketListenerImpl.handleUseItem`). + lan_item_only: bool, /// Level events of this tick for the guests, and the guest acting now. lan_events: Vec<(i32, [i32; 3], i32, Option)>, /// Block events (position, b0, b1, state) and entity events (id, event, @@ -1017,6 +1124,10 @@ struct Game<'a> { /// have each chest open. lid_openers: HashMap<(i32, i32, i32), i32>, lan_acting: Option, + /// The name of the guest `lan_acting` acts for (`Player.getName`). + lan_acting_name: Option, + /// Their UUID (`Player.getUUID`). + lan_acting_uuid: Option, /// Command feedback to forward to a guest. chat_capture: Option>, /// State of `/spectate`, `/posteffect`, `/debug`, `/waypoint` and friends. @@ -1085,6 +1196,27 @@ fn facing_offset(facing: &str) -> [i32; 3] { _ => [0, -1, 0], } } +/// How far along `dir` (within `reach`) a ray from `eye` enters `b`. +fn ray_box(eye: [f64; 3], dir: [f64; 3], reach: f64, b: Aabb) -> Option { + let (min, max) = (b.min_position(), b.max_position()); + let (lo, hi) = ([min.x, min.y, min.z], [max.x, max.y, max.z]); + let (mut t0, mut t1) = (0.0f64, reach); + for a in 0..3 { + if dir[a].abs() < 1e-9 { + if eye[a] < lo[a] || eye[a] > hi[a] { + return None; + } + continue; + } + let (mut ta, mut tb) = ((lo[a] - eye[a]) / dir[a], (hi[a] - eye[a]) / dir[a]); + if ta > tb { + std::mem::swap(&mut ta, &mut tb); + } + t0 = t0.max(ta); + t1 = t1.min(tb); + } + (t0 <= t1).then_some(t0) +} 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()] @@ -1106,7 +1238,7 @@ impl Game<'_> { let state = self.world.block(pos[0], pos[1], pos[2]); let f = self.res.facts.get(state); let o = if f.outline_offset { - self.res + self.pack .context .tables .offset(state, pos[0], pos[2]) @@ -1304,7 +1436,7 @@ impl Game<'_> { } fn particle_sprite(&self, state: BlockStateId) -> Option<(String, u32)> { let models = self - .res + .pack .assets .model_catalog .collect(state, horizon_core::position::BlockPos::new(0, 0, 0)) @@ -1314,7 +1446,7 @@ impl Game<'_> { .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 name = self.pack.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") { @@ -1330,7 +1462,7 @@ impl Game<'_> { fn particle_shape(&self, pos: [i32; 3], state: BlockStateId) -> Vec<[f64; 6]> { let f = self.res.facts.get(state); let offset = if f.outline_offset { - self.res + self.pack .context .tables .offset(state, pos[0], pos[2]) @@ -1404,7 +1536,7 @@ impl Game<'_> { state: BlockStateId, held: Option<&ItemStack>, ) -> Vec { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let dynamic = self.pending.dynamic(pos); match self.res.items.block_loot_sequence(registry, state) { Some(sequence) => { @@ -1442,13 +1574,15 @@ impl Game<'_> { return; }; self.player_drop(thrown); - self.swing_arm(); } /// `Player.drop`: the statistics and a thrown item entity in front of the player. fn player_drop(&mut self, thrown: ItemStack) { let Some(eye) = self.eye_position() else { return; }; + // LivingEntity.drop: every drop swings the main hand, a menu's + // THROW and a creative tab's drop included. + self.swing_hand(Hand::Main, SwingAnimation::DEFAULT); // Player.drop: the drop statistics. self.stats.add("dropped", &thrown.item, thrown.count as i32); self.stats.custom("drop", 1); @@ -1487,7 +1621,7 @@ impl Game<'_> { let environment = item.environment_tick( &self.world, &self.res.facts, - self.res.assets.registry, + self.pack.assets.registry, &self.res.items, ); // shortcut: age is the fresh-drop clock; use entity ticks for saved/frozen-age phase parity. @@ -1622,7 +1756,8 @@ impl Game<'_> { seed: self.level.seed, behaviours: &self.res.behaviours, items: &self.res.items, - registry: self.res.assets.registry, + loot: horizon_client::structure_blocks::loot_data(&self.options.resources), + registry: self.pack.assets.registry, rules, rand_sequences: &mut self.rand_sequences, pending: &mut self.pending, @@ -1822,6 +1957,11 @@ impl Game<'_> { pos, data, } => self.composter_fill_event(pos, data == 1), + LevelEvent::LevelEvent { + id: id @ 3011..=3021, + pos, + data, + } => self.trial_level_event(id, [pos.x, pos.y, pos.z], data), LevelEvent::LevelEvent { id, pos, .. } => { let c = Some([ f64::from(pos.x) + 0.5, @@ -1924,6 +2064,11 @@ impl Game<'_> { state, kind: "dispense", } => self.dispense_from(pos, state)?, + LevelEvent::BlockEvent { + pos, + kind: "command_block", + .. + } => self.command_block_tick(pos), LevelEvent::BlockEvent { pos, kind: "hatch", .. } => { @@ -1997,6 +2142,10 @@ impl Game<'_> { self.open_lectern(pos); return; } + if horizon_client::command_block::Mode::of_block(&name).is_some() { + self.open_command_block(key); + return; + } if &*name == "minecraft:crafting_table" { self.craft_size = 3; } else if &*name == "minecraft:ender_chest" { @@ -2318,17 +2467,18 @@ impl Game<'_> { { return Ok(Some(Hand::Main)); } - if self.interact_frame() - || self.interact_armor_stand() - || self.interact_boat() - || self.interact_cart() - || self.interact_mob()? - || self.interact_knot() + if !self.lan_item_only + && (self.interact_frame() + || self.interact_armor_stand() + || self.interact_boat() + || self.interact_cart() + || self.interact_mob()? + || self.interact_knot()) { return Ok(Some(Hand::Main)); } // An EntityHitResult may fall through to Item.use, never to useItemOn. - let block_hit = if self.entity_targeted() { + let block_hit = if self.lan_item_only || self.entity_targeted() { None } else { self.pick() @@ -2365,6 +2515,14 @@ impl Game<'_> { self.swing_arm(); return Ok(true); } + if self.use_vault(hit.pos, held.as_ref())? { + self.swing_arm(); + return Ok(true); + } + if self.use_decorated_pot(hit.pos, held.as_ref()) { + self.swing_arm(); + return Ok(true); + } match self.use_respawn_anchor(hit.pos, held.as_ref())? { respawn_anchor::AnchorUse::Charged => { self.swing_arm(); @@ -2394,7 +2552,7 @@ impl Game<'_> { .player .as_ref() .is_some_and(|p| p.health.food.food < 20), - game_master: false, + game_master: self.can_use_game_master_blocks(), }; let at = Vec3::new(hit.point[0], hit.point[1], hit.point[2]); let item = held.as_ref().map(|s| s.item.to_string()); @@ -2517,7 +2675,7 @@ impl Game<'_> { pitch: self.pitch, sneaking: self.keys.contains(&KeyCode::ShiftLeft), item: stack.item.to_string(), - can_use_game_master_blocks: false, + can_use_game_master_blocks: self.can_use_game_master_blocks(), }; let outcome = self.with_level(|b, level, ticks| b.place_block(level, ticks, &ctx)); let PlaceOutcome::Placed { pos, state } = outcome else { @@ -2531,15 +2689,21 @@ impl Game<'_> { }; let target = [pos.x, pos.y, pos.z]; if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) { - let sign = matches!(entity, BlockEntity::Sign(_)); - self.world - .block_entities - .insert((target[0], target[1], target[2]), entity); - self.fill_placed_box(target, &stack); - self.name_placed_container(target, &stack); - self.fill_placed_banner(target, &stack); - if sign { - self.open_sign_editor((target[0], target[1], target[2]), true); + let key = (target[0], target[1], target[2]); + self.world.block_entities.insert(key, entity); + let game_master = self.can_use_game_master_blocks(); + self.apply_placed_item(target, &stack, game_master); + // Block.setPlacedBy. + match self.world.block_entities.get(&key) { + Some(BlockEntity::CommandBlock(_)) => { + let data = stack.data().is_some_and(|d| { + d.other(horizon_client::block_entity_item::BLOCK_ENTITY_DATA) + .is_some() + }); + self.command_block_placed(key, !data); + } + Some(BlockEntity::Sign(sign)) if !sign.waxed => self.open_sign_editor(key, true), + _ => {} } } self.swing_arm(); @@ -2949,6 +3113,14 @@ impl Game<'_> { if self.remote.is_some() { return self.tick_remote(); } + // LevelLoadingScreen.tick. + self.loading_progress = match self.loading_reason() { + Some(_) => horizon_client::level_loading::smooth( + self.loading_progress, + self.level_load_progress(), + ), + None => 0.0, + }; self.ticks += 1; // `/tick freeze` stops the world but not the player. let running = self.clock.world_runs(); @@ -2991,6 +3163,7 @@ impl Game<'_> { self.tick_riding(keys)?; } let riding = self.riding.is_some(); + let ghast_collisions = self.happy_ghast_player_collisions(); let Some(player) = self.player.as_mut() else { // A dedicated server has no local player: the world still runs. if self.options.dedicated.is_some() { @@ -3076,9 +3249,10 @@ impl Game<'_> { ); if !riding { MotionWorld { + entities: &ghast_collisions, player, scene: &mut self.world, - assets: &self.res.assets, + assets: &self.pack.assets, collision_binding: self.collision, resources: self.motion, } @@ -3316,6 +3490,9 @@ impl Game<'_> { horizon_client::spans::time("tick_fishing", || self.tick_fishing()); horizon_client::spans::time("tick_tridents", || self.tick_tridents()); horizon_client::spans::time("tick_rockets", || self.tick_rockets()); + horizon_client::spans::time("tick_ominous_item_spawners", || { + self.tick_ominous_item_spawners() + }); } if running { horizon_client::spans::time("entity_portals", || self.handle_entity_portals()); @@ -3402,7 +3579,10 @@ impl Game<'_> { } else { self.keys.insert(key); } - if repeat { + // KeyboardHandler.keyPress: a repeat (InputConstants.REPEAT) reaches + // Screen.keyPressed and KeyMapping.click like a press, so holding + // key.drop keeps throwing, in game and over a menu slot. + if repeat && key != KeyCode::KeyQ { return Ok(()); } self.key_pressed(key) @@ -3468,7 +3648,7 @@ impl Game<'_> { } /// `Minecraft.pause`: a single-player game with a pausing screen open. fn pauses_game(&self) -> bool { - self.remote.is_none() + (self.remote.is_none() || self.integrated.is_some()) && self.lan.is_none() && self.title.is_none() && (matches!( @@ -3478,6 +3658,7 @@ impl Game<'_> { | Screen::Stats | Screen::Advancements | Screen::WorldOptions + | Screen::CommandBlock ) || self.book.is_some()) } fn capture(&mut self, capture: bool) { @@ -3518,7 +3699,7 @@ impl Game<'_> { let (stack, capped) = match drag.and_then(|d| d.slots.get(&slot)) { Some(None) => return, Some(Some((count, capped))) => { - batch.fill(&self.res.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); + batch.fill(&self.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); let carried = self .carried .clone() @@ -3613,10 +3794,10 @@ impl Game<'_> { 0, 0, &decorations, - &self.res.atlas.font, + &self.atlas.font, )); draws.push(hud_layout::GuiDraw::Pop); - hud_layout::paint(batch, &self.res.atlas, &draws); + hud_layout::paint(batch, &self.atlas, &draws); } fn hud(&mut self, size: [u32; 2]) -> HudBatch { let mut batch = self.hud_layers(size); @@ -3624,7 +3805,7 @@ impl Game<'_> { // and the toasts, so it is over everything, menus included. self.draw_debug_overlay(&mut batch, size); self.frame_graph - .draw(self.settings.horizon.overlay, &mut batch, &self.res.atlas); + .draw(self.settings.horizon.overlay, &mut batch, &self.atlas); self.draw_pad_cursor(&mut batch); batch } @@ -3637,17 +3818,20 @@ impl Game<'_> { } if let Some(title) = &mut self.title { title.poll_backup(); + if let Some(sound) = title.update_toast(self.settings.notification_display_time) { + self.audio.play(sound, None, 1.0, 1.0); + } } if let Some(title) = &self.title { if horizon_client::ui_theme::horizon() { let fade = self.backdrop_fade(); let mut ui = - horizon_client::ui_theme::Ui::new(&self.res.atlas, &mut batch, self.cursor); + horizon_client::ui_theme::Ui::new(&self.atlas, &mut batch, self.cursor); title.draw_horizon(&mut ui, fade); ui.finish(); } else { title.draw( - &self.res.atlas, + &self.atlas, &mut batch, self.cursor, self.settings.file.bool("hideSplashTexts"), @@ -3655,21 +3839,13 @@ impl Game<'_> { } return batch; } - let atlas_ptr: *const HudAtlas = &self.res.atlas; + let atlas_ptr: *const HudAtlas = &self.atlas; let _ = atlas_ptr; if self.remote_overlay(&mut batch) { return batch; } - if self.player.is_none() { - let text = if self.spawn_search > 0 { - "Finding a place to spawn..." - } else { - "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); + if let Some(reason) = self.loading_reason() { + self.draw_level_loading(&mut batch, reason); return batch; } // Hud.extractRenderState: F1 (keyToggleGui) hides camera overlays, the @@ -3692,7 +3868,7 @@ impl Game<'_> { hud_layout::full_attack_indicator(a, delay, self.crosshair_living()) }); let draws = hud_layout::crosshair(wi, hi, attack, full); - hud_layout::paint(&mut batch, &self.res.atlas, &draws); + hud_layout::paint(&mut batch, &self.atlas, &draws); } if !spectator { let inputs = hud_layout::HotbarInputs { @@ -3704,7 +3880,7 @@ impl Game<'_> { attack: (indicator == 2).then_some(strength), }; let draws = hud_layout::hotbar(wi, hi, &inputs); - hud_layout::paint(&mut batch, &self.res.atlas, &draws); + hud_layout::paint(&mut batch, &self.atlas, &draws); for d in &draws { if let hud_layout::GuiDraw::Item { slot, x, y, .. } = *d { let stack = if slot == 40 { @@ -3726,7 +3902,7 @@ impl Game<'_> { // Hud.extractSleepOverlay, under the sidebar, titles and chat. if let Some((_, ticks)) = self.sleeping { let draws = hud_overlays::sleep_overlay(wi, hi, ticks as i32); - hud_layout::paint(&mut batch, &self.res.atlas, &draws); + hud_layout::paint(&mut batch, &self.atlas, &draws); } if !self.ui.hide_gui { self.draw_titles(&mut batch); @@ -3742,7 +3918,7 @@ impl Game<'_> { && !spectator && let Some(p) = &mut self.player { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let width = |s: &str| HudBatch::text_width(atlas, s) as i32; let draws = hud_layout::experience( wi, @@ -3803,7 +3979,7 @@ impl Game<'_> { self.draw_selected_name(&mut batch, !self.creative); } } - let atlas = &self.res.atlas; + let atlas = &self.atlas; if !self.ui.hide_gui && let Some((text, at)) = &self.message && at.elapsed() < Duration::from_secs(3) @@ -3818,9 +3994,9 @@ impl Game<'_> { // PauseScreen(false): only its title, at the top. Screen::Paused => { let title = self.translate("menu.paused", "Game Paused"); - let tw = HudBatch::text_width(&self.res.atlas, &title); + let tw = HudBatch::text_width(&self.atlas, &title); batch.text( - &self.res.atlas, + &self.atlas, &title, ((batch.width / 2.0).floor() - (tw / 2.0).floor()).floor(), 10.0, @@ -3833,6 +4009,7 @@ impl Game<'_> { Screen::Stats => self.draw_stats(&mut batch), Screen::Advancements => self.draw_advancements(&mut batch), Screen::WorldOptions => self.draw_world_options(&mut batch), + Screen::CommandBlock => self.draw_command_block(&mut batch), Screen::Inventory => { self.draw_inventory(&mut batch); } @@ -3894,7 +4071,9 @@ impl Game<'_> { | BlockEntity::CreakingHeart(_) | BlockEntity::Spawner(_) | BlockEntity::TrialSpawner(_) - | BlockEntity::Beehive(_), + | BlockEntity::Vault(_) + | BlockEntity::Beehive(_) + | BlockEntity::CommandBlock(_), ) => {} None => { v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); @@ -4003,7 +4182,9 @@ impl Game<'_> { fn slot_view(&mut self, i: usize) -> Option { match i { 200 => self.craft_result(), - 309 => self.crafter_result(), + 309 if matches!(self.container_kind(), Some(BlockEntity::Crafter(_))) => { + self.crafter_result() + } _ => self.slot_mut(i).clone(), } } @@ -4033,7 +4214,7 @@ impl Game<'_> { let (sx, sy) = self.slot_position(i); if i == 504 && self.offhand.is_none() { batch.sprite( - &self.res.atlas, + &self.atlas, "gui/sprites/container/slot/shield", ox + sx, oy + sy, @@ -4042,7 +4223,7 @@ impl Game<'_> { if (500..504).contains(&i) && self.armor[i - 500].is_none() { let icon = ["helmet", "chestplate", "leggings", "boots"][i - 500]; batch.sprite( - &self.res.atlas, + &self.atlas, &format!("gui/sprites/container/slot/{icon}"), ox + sx, oy + sy, @@ -4058,7 +4239,7 @@ impl Game<'_> { } let (ox, oy) = self.inventory_origin(batch); { - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.fill( atlas, 0.0, @@ -4149,7 +4330,9 @@ impl Game<'_> { | BlockEntity::CreakingHeart(_) | BlockEntity::Spawner(_) | BlockEntity::TrialSpawner(_) - | BlockEntity::Beehive(_), + | BlockEntity::Vault(_) + | BlockEntity::Beehive(_) + | BlockEntity::CommandBlock(_), ) => {} None if self.mount_active() => self.draw_mount_background(batch, ox, oy), None => { @@ -4187,7 +4370,7 @@ impl Game<'_> { 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, + &self.atlas, ox + sx, oy + sy, 16.0, @@ -4298,8 +4481,8 @@ impl Game<'_> { let search = &self.creative_screen.search; self.text_selection.select(("creative.search", 0), search); } - let items = self.creative_screen.items(&self.res.names); - let first = self.creative_screen.first_row(&self.res.names); + let items = self.creative_screen.items(&self.pack.names); + let first = self.creative_screen.first_row(&self.pack.names); let shown = items.get(first * 9 + slot - Creative::DISPLAY); let catalog = &self.res.items; let max = |s: &ItemStack| catalog.get(&s.item).map_or(64, |i| i.max_stack); @@ -5213,7 +5396,7 @@ impl Game<'_> { m.height(), camera, fire_yaw, - &self.res.atlas.sprites, + &self.atlas.sprites, self.world.light( at.x.floor() as i32, at.y.floor() as i32, @@ -5235,7 +5418,7 @@ impl Game<'_> { p.dimensions.height, camera, fire_yaw, - &self.res.atlas.sprites, + &self.atlas.sprites, self.world.light( feet.x.floor() as i32, feet.y.floor() as i32, @@ -5258,7 +5441,7 @@ impl Game<'_> { 0.25, camera, fire_yaw, - &self.res.atlas.sprites, + &self.atlas.sprites, self.world.light( at.x.floor() as i32, at.y.floor() as i32, @@ -5277,7 +5460,7 @@ impl Game<'_> { 1.975 * scale, camera, fire_yaw, - &self.res.atlas.sprites, + &self.atlas.sprites, self.world.light( stand.position.x.floor() as i32, stand.position.y.floor() as i32, @@ -5289,14 +5472,20 @@ impl Game<'_> { } // `ItemEntityRenderer`. self.dropped_item_geometry(camera, alpha, &mut out); + // `VaultRenderer`. + self.vault_geometry(camera, alpha, &mut out); + self.ominous_item_spawner_geometry(camera, alpha, &mut out); // Mobs and their projectiles. self.mob_geometry(camera, alpha, &mut out); self.player_model_geometry(camera, alpha, &mut out); self.guest_model_geometry(camera, alpha, &mut out); self.fangs_geometry(camera, alpha, &mut out); - self.name_tag_geometry(camera, alpha, &mut out); + let mut see_through = std::mem::take(&mut self.see_through_vertices); + see_through.clear(); + self.name_tag_geometry(camera, alpha, &mut out, &mut see_through); + self.see_through_vertices = see_through; // Entity shadows (EntityRenderer.extractShadow). - if let Some(sprite) = self.res.atlas.sprites.get("misc/shadow").copied() { + if let Some(sprite) = self.atlas.sprites.get("misc/shadow").copied() { let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 }; let darken = self.sky_darken(); let a = alpha; @@ -5351,7 +5540,7 @@ impl Game<'_> { game_time: self.world.game_time, max_y: self.dim.max_y(), world: &self.world, - sprites: &self.res.atlas.sprites, + sprites: &self.atlas.sprites, nether: self.dim == Dim::Nether, lid: &lid, sign: &|p| match self.world.block_entities.get(&(p[0], p[1], p[2])) { @@ -5359,7 +5548,7 @@ impl Game<'_> { _ => None, }, banner: &|p| self.banner_layers_at(p), - glyph: &|c| self.res.atlas.glyph_cell(c), + glyph: &|c| self.atlas.glyph_cell(c), }; // Block entities outside the view frustum are skipped (with a // block of margin for models larger than their block). @@ -5404,7 +5593,6 @@ impl Game<'_> { } // Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet. if let Some(r) = self - .res .atlas .sprites .get("entity/experience/experience_orb") @@ -5517,7 +5705,7 @@ impl Game<'_> { &|b| world.light(b[0], b[1], b[2]), &mut out, ); - let atlas = &self.res.atlas; + let atlas = &self.atlas; // Breaking progress overlay (destroy_stage_0..9). if let Some(m) = &self.mining && m.progress > 0.0 @@ -5537,13 +5725,13 @@ impl Game<'_> { if self.res.facts.get(state).render_shape == horizon_client::blocks::RenderShape::Model && let Ok(models) = self - .res + .pack .assets .model_catalog .collect(state, BlockPos::new(m.pos[0], m.pos[1], m.pos[2])) { let offset = self - .res + .pack .context .tables .offset(state, m.pos[0], m.pos[2]) @@ -5596,31 +5784,41 @@ impl Game<'_> { if !m.alive() { continue; } - let b = m.bounds(); - let (min, max) = (b.min_position(), b.max_position()); - let (lo, hi) = ([min.x, min.y, min.z], [max.x, max.y, max.z]); - let (mut t0, mut t1) = (0.0f64, reach); - let mut hit = true; - for a in 0..3 { - if dir[a].abs() < 1e-9 { - if eye[a] < lo[a] || eye[a] > hi[a] { - hit = false; - } - continue; - } - let (mut ta, mut tb) = ((lo[a] - eye[a]) / dir[a], (hi[a] - eye[a]) / dir[a]); - if ta > tb { - std::mem::swap(&mut ta, &mut tb); - } - t0 = t0.max(ta); - t1 = t1.min(tb); - } - if hit && t0 <= t1 && best.is_none_or(|b| t0 < b.1) { - best = Some((i, t0)); + if let Some(t) = ray_box(eye, dir, reach, m.bounds()) + && best.is_none_or(|b| t < b.1) + { + best = Some((i, t)); } } best } + /// `Player.attack`'s damage against `target_kind` (with the attack + /// strength and whether it is a critical hit): the weapon and effects + /// scaled by the attack strength, a mace's smash, the critical hit, then + /// enchantments. + pub(super) fn melee_damage(&mut self, target_kind: &str) -> (f32, f32, bool) { + let hand_damage = 1.0 + + self + .held() + .and_then(|h| self.res.items.get(&h.item)) + .map_or(0.0, |i| i.attack_damage); + let damage = hand_damage + self.effect_attack_bonus(); + let scale = self.attack_strength_scale(); + let mut amount = damage * (0.2 + scale * scale * 0.8); + // Item.getAttackDamageBonus (a mace's smash), before the critical hit. + amount += self.smash_damage_bonus(target_kind); + let player = self.player.as_ref(); + // Player.canCriticalAttack: falling, off the ground, not sprinting. + let falling = + player.is_some_and(|p| !p.ground.on_ground && p.fall_distance > 0.0 && !p.sprinting); + let crit = scale > 0.9 && falling; + if crit { + amount *= 1.5; + } + // Enchantment damage (sharpness, smite, bane) scaled by the attack strength. + amount += self.enchant_damage_bonus(target_kind) * scale; + (amount, scale, crit) + } /// `Player.getAttackStrengthScale(0.5)`. fn attack_strength_scale(&self) -> f32 { let speed = self @@ -5678,6 +5876,7 @@ impl Game<'_> { || self.attack_boat(hand_damage) || self.attack_cart(hand_damage) || self.attack_dragon() + || self.attack_guest() { return true; } @@ -5694,23 +5893,9 @@ impl Game<'_> { return false; } } - let damage = hand_damage + self.effect_attack_bonus(); - let scale = self.attack_strength_scale(); - let mut amount = damage * (0.2 + scale * scale * 0.8); let target_kind = self.mobs[index].kind.id.clone(); let target_kind = format!("minecraft:{}", target_kind.trim_start_matches("minecraft:")); - // Item.getAttackDamageBonus (a mace's smash), before the critical hit. - amount += self.smash_damage_bonus(&target_kind); - let player = self.player.as_ref(); - // Player.canCriticalAttack: falling, off the ground, not sprinting. - let falling = - player.is_some_and(|p| !p.ground.on_ground && p.fall_distance > 0.0 && !p.sprinting); - let crit = scale > 0.9 && falling; - if crit { - amount *= 1.5; - } - // Enchantment damage (sharpness, smite, bane) scaled by the attack strength. - amount += self.enchant_damage_bonus(&target_kind) * scale; + let (amount, scale, crit) = self.melee_damage(&target_kind); self.attack_ticks = 0; if let Some(p) = self.player.as_mut() && !self.creative @@ -5807,6 +5992,7 @@ impl Game<'_> { self.tick_creaking_hearts()?; self.tick_spawners()?; self.tick_trial_spawners()?; + self.tick_vaults()?; self.tick_beehives(); let mut lit_changes = Vec::new(); for (pos, entity) in self.world.block_entities.iter_mut() { @@ -5818,11 +6004,11 @@ impl Game<'_> { } for ((x, y, z), lit) in lit_changes { let state = self.world.block(x, y, z); - if let Some(mut s) = self.res.assets.registry.state(state).cloned() + if let Some(mut s) = self.pack.assets.registry.state(state).cloned() && s.properties.contains_key("lit") { s.properties.insert("lit".into(), lit.to_string()); - if let Ok(id) = self.res.assets.registry.resolve(&s) { + if let Ok(id) = self.pack.assets.registry.resolve(&s) { self.world.set(x, y, z, id)?; } } @@ -5863,7 +6049,7 @@ impl Game<'_> { /// SkyRenderer.renderSunMoonAndStars: bodies on a frame rotated Y -90 then X by angle. fn celestial_geometry(&self, sky: &horizon_client::environment::Sky) -> Vec { let mut out = Vec::new(); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let frame = |angle: f32| { glam::Mat4::from_rotation_y((-90.0f32).to_radians()) * glam::Mat4::from_rotation_x(angle.to_radians()) @@ -5951,112 +6137,6 @@ impl Game<'_> { } out } - /// CloudRenderer: flat or 12x4x12 extruded cells drifting east. - fn cloud_geometry( - &self, - sky: &horizon_client::environment::Sky, - camera: glam::DVec3, - alpha: f64, - out: &mut Vec, - ) { - let (w, h, cells) = &self.res.clouds; - let (w, h) = (i64::from(*w), i64::from(*h)); - let Some(white) = self.res.atlas.sprites.get("horizon/white").copied() else { - return; - }; - let uv = [(white.u0 + white.u1) / 2.0, (white.v0 + white.v1) / 2.0]; - let cloud_height = 192.33; - let offset = (self.world.game_time.rem_euclid(w * 400)) as f64 + alpha; - let mut cloud_x = camera.x + offset * 0.030_000_001; - let mut cloud_z = camera.z + 3.96; - let (tw, th) = (w as f64 * 12.0, h as f64 * 12.0); - cloud_x -= (cloud_x / tw).floor() * tw; - cloud_z -= (cloud_z / th).floor() * th; - let cell_x = (cloud_x / 12.0).floor() as i64; - let cell_z = (cloud_z / 12.0).floor() as i64; - let x_in = (cloud_x - cell_x as f64 * 12.0) as f32; - let z_in = (cloud_z - cell_z as f64 * 12.0) as f32; - let bottom = (cloud_height - camera.y) as f32; - let filled = |cx: i64, cz: i64| cells[(cz.rem_euclid(h) * w + cx.rem_euclid(w)) as usize]; - // The Cloud Distance option, not the render distance. - let radius = horizon_client::clouds::radius_cells(self.settings.cloud_range); - let c = sky.cloud_color; - let color = |shade: f32| { - let ch = |v: f32| ((v * shade).clamp(0.0, 1.0) * 255.0) as u32; - ch(c[3].clamp(0.0, 1.0)) << 24 | ch(c[2]) << 16 | ch(c[1]) << 8 | ch(c[0]) - }; - let light = 240 | 240 << 8; - for (dx, dz) in horizon_client::clouds::cells(radius) { - let (dx, dz) = (i64::from(dx), i64::from(dz)); - let (cx, cz) = (cell_x + dx, cell_z + dz); - if !filled(cx, cz) { - continue; - } - let x0 = dx as f32 * 12.0 - x_in; - let z0 = dz as f32 * 12.0 - z_in; - let (x1, z1, y0, y1) = (x0 + 12.0, z0 + 12.0, bottom, bottom + 4.0); - let mut quad = |p: [[f32; 3]; 4], shade: f32| { - for v in p { - // Overlay 4: clouds (unlit, faded by the cloud fog end). - out.push(Vertex { - normal: [0; 4], - pos: v, - uv, - layer: 4, - color: color(shade), - light, - }); - } - }; - if self.settings.clouds == "fast" { - for p in horizon_client::clouds::flat_cell(x0, z0, bottom) { - quad(p, 1.0); - } - continue; - } - let faces = [ - ( - [[x1, y0, z0], [x1, y0, z1], [x0, y0, z1], [x0, y0, z0]], - 0.7, - ), - ( - [[x0, y1, z0], [x0, y1, z1], [x1, y1, z1], [x1, y1, z0]], - 1.0, - ), - ( - [[x0, y0, z0], [x0, y1, z0], [x1, y1, z0], [x1, y0, z0]], - 0.8, - ), - ( - [[x1, y0, z1], [x1, y1, z1], [x0, y1, z1], [x0, y0, z1]], - 0.8, - ), - ( - [[x0, y0, z1], [x0, y1, z1], [x0, y1, z0], [x0, y0, z0]], - 0.9, - ), - ( - [[x1, y0, z0], [x1, y1, z0], [x1, y1, z1], [x1, y0, z1]], - 0.9, - ), - ]; - let mask = horizon_client::clouds::face_mask( - dx as i32, - dz as i32, - bottom, - [ - !filled(cx, cz - 1), - !filled(cx, cz + 1), - !filled(cx - 1, cz), - !filled(cx + 1, cz), - ], - ); - for (direction, inside) in horizon_client::clouds::faces(mask) { - let (p, shade) = faces[usize::from(direction)]; - quad(if inside { [p[3], p[2], p[1], p[0]] } else { p }, shade); - } - } - } /// Load (or create) a world folder under saves/ and start streaming it. fn open_world( &mut self, @@ -6066,8 +6146,11 @@ impl Game<'_> { creative: bool, create: Option<&horizon_client::title::WorldOptions>, ) -> Result<()> { - self.perf.world_opening(); let save_root = std::env::current_dir()?.join("saves").join(folder); + if integrated::wanted(&self.options, &save_root) { + return self.open_integrated(folder, name, seed, creative, create); + } + self.perf.world_opening(); horizon_client::save::upgrade_older_world(&save_root)?; horizon_client::save::migrate_legacy(&save_root)?; self.session_lock = None; @@ -6225,7 +6308,6 @@ impl Game<'_> { yaw: *yaw, forced: *forced, }); - self.spawn_search = 0; self.spawn_origin = None; self.spawn_spiral = Default::default(); self.player_spawn = None; @@ -6272,14 +6354,14 @@ impl Game<'_> { world_root, dim.id(), ))); - let res = &*self.res; + let (res, pack) = (&*self.res, &self.pack); let flat = (dim == Dim::Overworld) .then(|| horizon_client::save::world_gen_settings(world_root)) .flatten() .and_then(|s| { horizon_client::flatgen::FlatTerrain::from_settings( &s, - res.assets.registry, + pack.assets.registry, &res.biomes, ) }); @@ -6288,26 +6370,26 @@ impl Game<'_> { Arc::new(Persistent { inner: Arc::new(inner), save: save.clone(), - registry: res.assets.clone(), + registry: pack.assets.clone(), biomes: res.biomes.clone(), }), - res.context.clone(), + pack.context.clone(), res.threads, ) } else if self.options.test_terrain && dim == Dim::Overworld { - let inner = Arc::new(TestTerrain::new(res.assets.registry, &res.biomes)?); + let inner = Arc::new(TestTerrain::new(pack.assets.registry, &res.biomes)?); Streaming::new( Arc::new(Persistent { inner, save: save.clone(), - registry: res.assets.clone(), + registry: pack.assets.clone(), biomes: res.biomes.clone(), }), - res.context.clone(), + pack.context.clone(), res.threads, ) } else { - let inner = Arc::new(VanillaTerrain::for_dimension(&self.options.resources.join("worldgen"), res.assets.registry, &res.biomes, seed, dim.id()).map_err(|e| { + let inner = Arc::new(VanillaTerrain::for_dimension(&self.options.resources.join("worldgen"), pack.assets.registry, &res.biomes, seed, dim.id()).map_err(|e| { format!("{e}\nPrepare the worldgen bundle with the launcher, or: horizon-prepare --prepare") })?); self.end.set_locator(Some(inner.clone())); @@ -6315,10 +6397,10 @@ impl Game<'_> { Arc::new(Persistent { inner, save: save.clone(), - registry: res.assets.clone(), + registry: pack.assets.clone(), biomes: res.biomes.clone(), }), - res.context.clone(), + pack.context.clone(), res.threads, ) }; @@ -6330,6 +6412,8 @@ impl Game<'_> { streaming.biome_zoom = BiomeZoom::new(obfuscate_seed(seed)); streaming.sky_light = dim != Dim::Nether; streaming.nether_shading = dim == Dim::Nether; + // The integrated server draws nothing (the dedicated server keeps its behaviour). + streaming.mesh = !self.options.integrated; Ok((streaming, save)) } /// Change dimension through a portal (Entity.changeDimension with @@ -6343,7 +6427,7 @@ impl Game<'_> { let keys: Vec<_> = self.world.modified.drain().collect(); let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k))); self.save - .save(&chunks, self.res.assets.registry, &self.res.biomes)?; + .save(&chunks, self.pack.assets.registry, &self.res.biomes)?; self.save_dimension_entities()?; // Coordinates scale by 8 between the Overworld and the Nether. let scale = match (self.dim, target) { @@ -6468,7 +6552,7 @@ impl Game<'_> { for x_axis in [true, false] { if let Some((origin, width, height)) = self.portal_shape(at, x_axis) { let d = if x_axis { [1, 0, 0] } else { [0, 0, 1] }; - let registry = &self.res.assets.registry; + let registry = &self.pack.assets.registry; let Some(default) = registry.default_state("minecraft:nether_portal") else { return Ok(false); }; @@ -6525,6 +6609,11 @@ impl Game<'_> { return Ok(()); } self.saved_for_exit = true; + if let Some(server) = self.integrated.take() { + // The server thread saves the world. + server.stop(); + return Ok(()); + } self.close_container(); if self.remote.is_none() { self.stats.custom("leave_game", 1); @@ -6741,7 +6830,7 @@ impl Game<'_> { } } } - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let id = self.world.block(pos[0], pos[1], pos[2]); let Some(state) = registry .state(id) @@ -6833,7 +6922,7 @@ impl Game<'_> { [-1, 0, 0] => "west", _ => "east", }; - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let (state, sound, loot, damage, particle) = { let around = Column { world: &self.world, @@ -6887,7 +6976,7 @@ impl Game<'_> { Ok(true) } fn set_state_named(&mut self, pos: [i32; 3], name: &str, keep: &[&str]) -> Result { - let registry = &self.res.assets.registry; + let registry = &self.pack.assets.registry; let old = self.world.block(pos[0], pos[1], pos[2]); let Some(default) = registry.default_state(name) else { return Ok(false); @@ -7067,7 +7156,7 @@ impl Game<'_> { return Ok(UseResult::Success { swing: true }); } if item == "honeycomb" { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let old = registry.state(clicked).cloned(); if let Some(waxed) = old.and_then(|old| self.res.transformers.waxed(registry, &old)) && let Ok(state) = registry.resolve(&waxed) @@ -7092,7 +7181,7 @@ impl Game<'_> { } let name = self.res.facts.get(clicked).name.clone(); if self.can_light(clicked, &name) { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let mut state = registry .state(clicked) .cloned() @@ -7441,13 +7530,7 @@ impl Game<'_> { let Some(arm) = self.res.player_arm.clone() else { continue; }; - let Some(r) = self - .res - .atlas - .sprites - .get("entity/player/wide/steve") - .copied() - else { + let Some(r) = self.atlas.sprites.get("entity/player/wide/steve").copied() else { continue; }; // renderPlayerArm (right arm) @@ -7517,7 +7600,7 @@ impl Game<'_> { "minecraft:trident" if using => ItemPose::Trident { ticks_used }, _ if using => { let components = self - .res + .pack .item_renderer .models .components(&horizon_client::item_render::stack_view(&stack)); @@ -7574,7 +7657,7 @@ impl Game<'_> { /// The renderer for the window, with the current block sprites, shared /// atlas and world border texture. fn new_renderer(&self, window: Arc) -> Result { - let assets = &self.res.assets; + let assets = &self.pack.assets; let mut renderer = pollster::block_on(Renderer::new( window, self.options.offscreen, @@ -7584,16 +7667,11 @@ impl Game<'_> { assets.texture_layers, &assets.sprite_mips, &assets.animations, - ( - &self.res.atlas.pixels, - self.res.atlas.width, - self.res.atlas.height, - ), - (&self.res.forcefield.2, self.res.forcefield.0), - &self.res.panorama, + (&self.atlas.pixels, self.atlas.width, self.atlas.height), + (&self.pack.forcefield.2, self.pack.forcefield.0), + &self.pack.panorama, ))?; renderer.hud.fire_animations = self - .res .atlas .fire_animations .iter() @@ -7714,7 +7792,7 @@ impl Game<'_> { if intensity <= 0.0 { return; } - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (Some(rain_tex), Some(snow_tex)) = ( atlas.sprites.get("environment/rain").copied(), atlas.sprites.get("environment/snow").copied(), @@ -7802,7 +7880,7 @@ impl Game<'_> { let night = (12542..23460).contains(&time) || self.world.weather.thundering; let state = self.world.block(pos[0], pos[1], pos[2]); let props = self - .res + .pack .assets .registry .state(state) @@ -7903,7 +7981,7 @@ impl Game<'_> { } /// Vanilla tooltip: dark box with a purple gradient border. fn tooltip(&self, batch: &mut HudBatch, text: &str, x: f32, y: f32) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let w = HudBatch::text_width(atlas, text); let (x, y) = (x + 12.0, y - 12.0); batch.fill(atlas, x - 3.0, y - 4.0, w + 6.0, 16.0, rgba(16, 0, 16, 240)); @@ -7925,7 +8003,7 @@ impl Game<'_> { ) }; batch.fill( - &self.res.atlas, + &self.atlas, 0.0, 0.0, batch.width, @@ -7936,7 +8014,7 @@ impl Game<'_> { for (i, t) in tabs.iter().enumerate() { if i != selected { let (tx, ty) = Creative::tab_position(t); - batch.sprite(&self.res.atlas, &tab_sprite(t, false), ox + tx, oy + ty); + batch.sprite(&self.atlas, &tab_sprite(t, false), ox + tx, oy + ty); } } let background = if tab.search { @@ -7946,13 +8024,13 @@ impl Game<'_> { } else { "gui/container/creative_inventory/tab_items" }; - if let Some(mut r) = self.res.atlas.sprites.get(background).copied() { + if let Some(mut r) = self.atlas.sprites.get(background).copied() { r.u1 = r.u0 + (r.u1 - r.u0) * Creative::WIDTH / r.w as f32; r.v1 = r.v0 + (r.v1 - r.v0) * Creative::HEIGHT / r.h as f32; batch.rect_uv(ox, oy, Creative::WIDTH, Creative::HEIGHT, r, u32::MAX); } let (tx, ty) = Creative::tab_position(&tab); - batch.sprite(&self.res.atlas, &tab_sprite(&tab, true), ox + tx, oy + ty); + batch.sprite(&self.atlas, &tab_sprite(&tab, true), ox + tx, oy + ty); for t in &tabs { let (tx, ty) = Creative::tab_position(t); let stack = ItemStack { @@ -7968,7 +8046,7 @@ impl Game<'_> { oy + ty + if t.top { 9.0 } else { 7.0 }, ); } - let atlas = &self.res.atlas; + let atlas = &self.atlas; if !tab.inventory { batch.text( atlas, @@ -8010,7 +8088,7 @@ impl Game<'_> { if Self::creative_trash_hovered(batch, self.cursor) { let (x, y) = Creative::TRASH_POSITION; batch.fill( - &self.res.atlas, + &self.atlas, ox + x, oy + y, 16.0, @@ -8021,7 +8099,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (x, y) = self.slot_position(slot); batch.fill( - &self.res.atlas, + &self.atlas, ox + x, oy + y, 16.0, @@ -8030,8 +8108,8 @@ impl Game<'_> { ); } } else { - let items = self.creative_screen.items(&self.res.names); - let first = self.creative_screen.first_row(&self.res.names); + let items = self.creative_screen.items(&self.pack.names); + let first = self.creative_screen.first_row(&self.pack.names); for r in 0..5 { for c in 0..9 { let Some(stack) = items.get((first + r) * 9 + c) else { @@ -8044,7 +8122,7 @@ impl Game<'_> { && self.cursor.1 >= y && self.cursor.1 < y + 16.0 { - batch.fill(&self.res.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); + batch.fill(&self.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); hovered = Some(stack.item.to_string()); } } @@ -8063,14 +8141,14 @@ impl Game<'_> { hovered = Some(stack.item.to_string()); } } - let scrollable = self.creative_screen.rows(&self.res.names) > 5; + let scrollable = self.creative_screen.rows(&self.pack.names) > 5; let scroller = if scrollable { "gui/sprites/container/creative_inventory/scroller" } else { "gui/sprites/container/creative_inventory/scroller_disabled" }; batch.sprite( - &self.res.atlas, + &self.atlas, scroller, ox + Creative::SCROLL_X, oy + Creative::SCROLL_Y + self.creative_screen.scroller_offset(), @@ -8096,7 +8174,7 @@ impl Game<'_> { } else if self.carried.is_none() && let Some(item) = hovered { - let name = self.res.names.item(&item); + let name = self.pack.names.item(&item); self.tooltip(batch, &name, self.cursor.0, self.cursor.1); } self.draw_inventory_effects(batch, (ox, oy), Creative::WIDTH as i32); @@ -8152,7 +8230,7 @@ impl Game<'_> { if !right && self .creative_screen - .press_scrollbar(cx - ox, cy - oy, &self.res.names) + .press_scrollbar(cx - ox, cy - oy, &self.pack.names) { return; } @@ -8271,7 +8349,7 @@ impl Game<'_> { let keys: Vec<_> = self.world.modified.drain().collect(); let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k))); self.save - .save_later(&chunks, self.res.assets.registry, &self.res.biomes)?; + .save_later(&chunks, self.pack.assets.registry, &self.res.biomes)?; if wait { self.save.flush(); } @@ -8289,6 +8367,7 @@ impl Game<'_> { self.save_schedule(); self.save_warden_tracker(); self.sync_level(); + self.store_owner(); self.level.write(&self.world_root)?; self.save_world_state(); self.message = Some(("Saved the game".into(), Instant::now())); @@ -8363,15 +8442,15 @@ impl Game<'_> { } let view = horizon_client::camera::view_matrix(view_yaw, view_pitch); let at = camera.to_array(); - // GameRenderer.renderLevel: the debug crosshair, first person with the HUD shown. + // GameRenderer.render3dHud: the debug crosshair, first person with the HUD shown. + let mut crosshair = horizon_client::gizmos::Gizmos::default(); if self.debug_crosshair() && self.camera_type.first_person() && !self.ui.hide_gui { - let mut g = horizon_client::gizmos::Gizmos::default(); let scale = HudBatch::new(size).scale; - g.debug_crosshair(at, view_pitch, view_yaw, scale); - on_top.extend(g.on_top); + crosshair.debug_crosshair(at, view_pitch, view_yaw, scale); } let debug_lines = horizon_client::gizmos::camera_relative(&lines, at, view); let debug_lines_on_top = horizon_client::gizmos::camera_relative(&on_top, at, view); + let debug_crosshair = horizon_client::gizmos::camera_relative(&crosshair.on_top, at, view); // LevelRenderer.renderHitOutline: the outline shape's edges. let outline = if self.screen == Screen::Playing && !self.spectator() { self.pick() @@ -8379,7 +8458,7 @@ impl Game<'_> { let state = self.world.block(h.pos[0], h.pos[1], h.pos[2]); let f = self.res.facts.get(state); let o = if f.outline_offset { - self.res + self.pack .context .tables .offset(state, h.pos[0], h.pos[2]) @@ -8400,7 +8479,9 @@ impl Game<'_> { let mut hud = horizon_client::spans::time("hud", || self.hud(size)); // Map textures changed since the last drawn frame (game/maps.rs). hud.patches.append(&mut self.map_patches); - let title = self.title.is_some(); + // LevelLoadingScreen (Reason.OTHER) draws the title's panorama. + let title = self.title.is_some() + || self.loading_reason() == Some(horizon_client::level_loading::Reason::Other); let (yaw, pitch) = if live { (view_yaw, view_pitch) } else if title { @@ -8431,6 +8512,7 @@ impl Game<'_> { // Keep the buffer local while builders need mutable access to the game. let mut entities = std::mem::take(&mut self.entity_vertices); entities.clear(); + self.see_through_vertices.clear(); if !title { entities = horizon_client::spans::time("entity_geometry", || { self.entity_geometry(camera, alpha, entities) @@ -8472,17 +8554,10 @@ impl Game<'_> { if !title { self.end_geometry(camera, &mut entities); } - if (!title || live) && self.dim == Dim::Overworld { - if horizon_client::clouds::visible(&self.settings.clouds, sky.cloud_color[3]) { - horizon_client::spans::time("clouds", || { - self.cloud_geometry(&sky, camera, alpha, &mut entities) - }); - } - if self.settings.horizon.weather { - horizon_client::spans::time("weather", || { - self.weather_geometry(camera, alpha, &mut entities) - }); - } + if (!title || live) && self.dim == Dim::Overworld && self.settings.horizon.weather { + horizon_client::spans::time("weather", || { + self.weather_geometry(camera, alpha, &mut entities) + }); } let water_fog = { let c = info.water_fog; @@ -8495,6 +8570,7 @@ impl Game<'_> { let border = (!title) .then(|| self.border_draw(camera.to_array(), alpha as f32)) .flatten(); + let see_through = std::mem::take(&mut self.see_through_vertices); let frame = Frame { shader: self.shader_inputs(camera, alpha as f32), nether_lighting: self.dim == Dim::Nether, @@ -8532,9 +8608,26 @@ impl Game<'_> { outline, debug_lines: &debug_lines, debug_lines_on_top: &debug_lines_on_top, + debug_crosshair: &debug_crosshair, hud: &hud, + clouds: ((!title || live) + && self.dim == Dim::Overworld + && horizon_client::clouds::visible(&self.settings.clouds, sky.cloud_color[3])) + .then(|| self.atlas.sprites.get("horizon/white")) + .flatten() + .map(|white| horizon_client::clouds::Input { + texture: &self.pack.clouds, + uv: [(white.u0 + white.u1) / 2.0, (white.v0 + white.v1) / 2.0], + camera, + time: self.world.game_time, + partial_tick: alpha, + range: self.settings.cloud_range, + fast: self.settings.clouds == "fast", + color: sky.cloud_color, + }), entities: &entities, additive: &additive, + see_through: &see_through, celestial: if self.settings.horizon.sky || title { &celestial } else { @@ -8550,15 +8643,14 @@ impl Game<'_> { .mining .as_ref() .and_then(|m| { - self.res.atlas.sprites.get(&format!( + self.atlas.sprites.get(&format!( "block/destroy_stage_{}", ((m.progress * 10.0) as u32).min(9) )) }) .map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0]), end_portal_sprites: ["environment/end_sky", "entity/end_portal/end_portal"].map(|n| { - self.res - .atlas + self.atlas .sprites .get(n) .map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0]) @@ -8566,7 +8658,7 @@ impl Game<'_> { ticks: self.ticks, darkness: self.darkness_lighting(alpha as f32), night_vision: self.night_vision_intensity(), - block_flicker: self.res.fog.state.block_light_flicker, + block_flicker: self.fog.block_light_flicker, post: if live { Some(horizon_client::post::PostGrade::FROST) } else if self.horizon_pause() { @@ -8582,17 +8674,76 @@ impl Game<'_> { }; // Restore storage even when rendering fails (for example, a lost surface). self.entity_vertices = entities; + self.see_through_vertices = see_through; result } + /// The LevelLoadingScreen shown while the player waits for its chunks: + /// opening a world, or after a portal or a respawn into another dimension. + fn loading_reason(&self) -> Option { + use horizon_client::level_loading::Reason; + if self.title.is_some() || self.remote.is_some() || self.player.is_some() { + return None; + } + Some( + if self.travelling.is_none() || self.respawn_travel.is_some() { + Reason::Other + } else if self.end_travel { + Reason::EndPortal + } else { + Reason::NetherPortal + }, + ) + } + /// `LevelLoadTracker.serverProgress`: the player's 7x7 chunks loaded. + fn level_load_progress(&self) -> f32 { + let (cx, cz) = self.streaming.center; + let ready = (-3..=3) + .flat_map(|dz| (-3..=3).map(move |dx| (cx + dx, cz + dz))) + .filter(|&(x, z)| self.streaming.is_lit(x, z)) + .count(); + horizon_client::level_loading::progress(ready) + } + /// `LevelLoadingScreen.extractBackground` and `extractRenderState`. + fn draw_level_loading( + &self, + batch: &mut HudBatch, + reason: horizon_client::level_loading::Reason, + ) { + use horizon_client::level_loading::{self, Reason, STATUS_RADIUS}; + let atlas = &self.atlas; + let (w, h) = (batch.width, batch.height); + match reason { + // The panorama and its blur are drawn by the renderer. + Reason::Other => { + horizon_client::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false) + } + Reason::NetherPortal => { + let overlay = hud_overlays::portal_overlay(w as i32, h as i32, 1.0); + hud_layout::paint(batch, atlas, &[overlay]); + } + Reason::EndPortal => batch.fill(atlas, 0.0, 0.0, w, h, rgba(20, 20, 20, 255)), + } + let (cx, cz) = self.streaming.center; + let status = |x: i32, z: i32| { + self.streaming.latest_status( + &self.world, + cx + x - STATUS_RADIUS, + cz + z - STATUS_RADIUS, + ) + }; + level_loading::draw(batch, atlas, Some(&status), Some(self.loading_progress)); + } /// `Screen.extractBlurredBackground` over the panorama: every classic /// screen of the title menus but the title itself (`TitleScreen` /// doesn't blur), when `menuBackgroundBlurriness` is at least 1. fn menu_blur(&self) -> Option { + let loading = self.loading_reason() == Some(horizon_client::level_loading::Reason::Other); let blurred = !horizon_client::ui_theme::horizon() - && self.title.as_ref().is_some_and(|t| { - self.screen == Screen::Options - || !matches!(t.mode, horizon_client::title::Mode::Main) - }); + && (loading + || self.title.as_ref().is_some_and(|t| { + self.screen == Screen::Options + || !matches!(t.mode, horizon_client::title::Mode::Main) + })); let radius = self.settings.menu_blur as f32; (blurred && radius >= 1.0).then_some(radius) } @@ -8661,7 +8812,8 @@ impl Game<'_> { Screen::Dead => {} Screen::Stats => self.screen = Screen::Paused, Screen::Advancements => self.close_advancements(), - Screen::WorldOptions => self.close_world_options(), + Screen::WorldOptions => self.world_options_escape(), + Screen::CommandBlock => self.close_command_block(), Screen::Chat => self.close_chat(), }, KeyCode::Digit1 @@ -8779,17 +8931,11 @@ impl Game<'_> { } MouseButton::Middle if pressed => { // Minecraft.pickBlockOrEntity -> the server's handlePickItemFromBlock: - // the block's clone item, picked from the inventory (`pick_item`). + // the block's clone item, with its block entity's data on Ctrl in + // creative, picked from the inventory (`pick_item`). 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" { - let stack = ItemStack { - item, - count: 1, - damage: 0, - extra: None, - }; + let include_data = self.creative && self.has_control_down(); + if let Some(stack) = self.picked_stack(hit.pos, include_data) { let infinite = self.creative; horizon_client::pick_item::pick( &mut self.inventory[..36], @@ -8836,7 +8982,7 @@ impl Game<'_> { if !modified.is_empty() && let Err(e) = horizon_client::spans::time("save_chunks", || { self.save - .save_later(&modified, self.res.assets.registry, &self.res.biomes) + .save_later(&modified, self.pack.assets.registry, &self.res.biomes) }) { log::warn!("Horizon: failed to save unloaded chunks: {e}"); @@ -8953,6 +9099,20 @@ impl ApplicationHandler for Game<'_> { if let WindowEvent::ModifiersChanged(m) = &event { self.modifiers = m.state(); } + // Fullscreen is a window shortcut, before screens consume keyboard input. + if let WindowEvent::KeyboardInput { event, .. } = &event + && event.state == ElementState::Pressed + && let PhysicalKey::Code(key) = event.physical_key + && horizon_client::keybinds::key_name(key) + == Some(self.settings.keys.get("key.fullscreen")) + && !(self.screen == Screen::Options && self.options_waiting_for_key()) + { + self.last_input = Instant::now(); + if !event.repeat { + self.toggle_fullscreen(); + } + return; + } // KeyboardHandler.keyPress: the debug keys come before the game's. if let WindowEvent::KeyboardInput { event: key_event, .. @@ -9040,6 +9200,7 @@ impl ApplicationHandler for Game<'_> { && !horizon_client::ui_theme::horizon() { title.drag(self.cursor, (b.width, b.height)); + title.drag_field(&self.atlas, self.cursor.0); } if self.dragging && self.screen == Screen::Options { let _ = b; @@ -9094,7 +9255,7 @@ impl ApplicationHandler for Game<'_> { self.options_scroll(d); } if self.screen == Screen::Creative && d != 0.0 { - self.creative_screen.wheel(f64::from(d), &self.res.names); + self.creative_screen.wheel(f64::from(d), &self.pack.names); } if self.screen == Screen::Inventory && d != 0.0 @@ -9105,6 +9266,9 @@ impl ApplicationHandler for Game<'_> { if self.screen == Screen::Stats && d != 0.0 { self.stats_scroll(d); } + if self.screen == Screen::WorldOptions && d != 0.0 { + self.world_options_scroll(d); + } if self.screen == Screen::Advancements { self.advancements_scroll(scaled(raw_x) as f32, d); } @@ -9126,6 +9290,7 @@ impl ApplicationHandler for Game<'_> { } if self.title.is_some() && self.screen != Screen::Options => { if let Some(title) = &mut self.title { title.release(); + title.release_field(); } } WindowEvent::MouseInput { @@ -9139,7 +9304,8 @@ impl ApplicationHandler for Game<'_> { .map(|r| [r.config.width, r.config.height]) .unwrap_or([1, 1]); let mut b = HudBatch::new(size); - let atlas = &self.res.atlas; + let atlas = &self.atlas; + let shift = self.has_shift_down(); let (action, sound) = self.title.as_mut().map_or((Action::None, false), |t| { if horizon_client::ui_theme::horizon() { ( @@ -9147,7 +9313,10 @@ impl ApplicationHandler for Game<'_> { false, ) } else { - t.click(self.cursor.0, self.cursor.1, (b.width, b.height)) + let clicked = + t.click(self.cursor.0, self.cursor.1, (b.width, b.height)); + t.press_field(atlas, self.cursor, (b.width, b.height), shift); + clicked } }); if sound { @@ -9249,6 +9418,9 @@ impl ApplicationHandler for Game<'_> { Screen::WorldOptions if pressed && button == MouseButton::Left => { self.world_options_click() } + Screen::CommandBlock if pressed && button == MouseButton::Left => { + self.command_block_click() + } Screen::Dead if pressed && button == MouseButton::Left => { self.death_click()? } @@ -9330,6 +9502,9 @@ impl ApplicationHandler for Game<'_> { { self.world_options_key(&event) } + WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::CommandBlock => { + self.command_block_key(&event) + } // Options consumes presses; releases still reach the bound // gameplay mapping below, including sneak/sprint toggles. WindowEvent::KeyboardInput { event, .. } @@ -9358,6 +9533,20 @@ impl ApplicationHandler for Game<'_> { t.confirm_edit(); } } + PhysicalKey::Code( + key @ (KeyCode::Backspace + | KeyCode::Delete + | KeyCode::ArrowLeft + | KeyCode::ArrowRight + | KeyCode::Home + | KeyCode::End), + ) if self.title.as_mut().is_some_and(|t| t.has_caret_field()) => { + let (ctrl, shift) = + (self.has_control_down(), self.has_shift_down()); + if let Some(t) = self.title.as_mut() { + t.field_key(key, ctrl, shift); + } + } PhysicalKey::Code(KeyCode::Backspace) => self.title_edit(None, true), PhysicalKey::Code(KeyCode::Tab) => { if let Some(t) = self.title.as_mut() { @@ -9406,14 +9595,22 @@ impl ApplicationHandler for Game<'_> { let elapsed = now.duration_since(self.previous); self.frame_ticks = elapsed.as_secs_f32() * 20.0; 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); + // Arrow-key camera controls belong to gameplay; chat and + // other screens use the same keys for their own navigation. + if self.screen == Screen::Playing + && self.title.is_none() + && self.sign_edit.is_none() + && self.book.is_none() + && !self.remote_chat_open() + { + 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_backdrop()?; horizon_client::ui_theme::set_backdrop(self.backdrop_fade()); if self.screen != Screen::Paused { @@ -9497,6 +9694,9 @@ impl ApplicationHandler for Game<'_> { } self.limit_frame(); self.pause = self.pauses_game(); + if let Some(server) = &self.integrated { + server.set_paused(self.pause); + } self.clock.end_frame(self.pause); let finished = self .renderer @@ -9534,6 +9734,7 @@ impl ApplicationHandler for Game<'_> { self.perf.title_shown(); } else if self.screen == Screen::Playing && self.player.is_some() { self.perf.frame(elapsed.as_secs_f32() * 1000.0); + self.world_frames += 1; } self.frames += 1; self.fps_frames += 1; @@ -9543,7 +9744,12 @@ impl ApplicationHandler for Game<'_> { self.fps_frames = 0; self.fps_at = Instant::now(); } - if self.options.frames.is_some_and(|f| self.frames >= f) { + if self.options.frames.is_some_and(|f| self.frames >= f) + || self + .options + .world_frames + .is_some_and(|f| self.world_frames >= f) + { event_loop.exit(); } } @@ -9619,6 +9825,324 @@ fn load_forcefield(root: &std::path::Path) -> (u32, u32, Vec) { .filter(|(w, h, _)| w == h && w.is_power_of_two()) .unwrap_or((1, 1, vec![0; 4])) } +impl<'a> Game<'a> { + /// A game with no world open, over the loaded resources: the window's, + /// or an integrated server's on its own thread. + fn new( + res: &'a Arc, + pack: PackResources, + atlas: HudAtlas, + options: Options, + settings: Settings, + audio: Audio, + ) -> Result { + let root = options.resources.clone(); + let registry = pack.assets.registry; + // Until a world is opened the streamer is idle. + let mut streaming = Streaming::new( + Arc::new(TestTerrain::new(registry, &res.biomes)?), + pack.context.clone(), + 1, + ); + streaming.paused = true; + let level = Level::default(); + let save = Arc::new(SaveDir::new( + std::env::current_dir()? + .join("saves") + .join(".horizon-title"), + )); + // These batches share the exported document instead of reparsing it per layer. + let (armor_stand_assets, boat_models, cart_models) = { + let document = horizon_client::mobs::EntityModelDocument::load(&root).ok(); + ( + armor_stands::ArmorStandAssets::load(&root, document.as_ref()), + boats::BoatModels::load(document.as_ref()), + minecarts::CartModels::load(document.as_ref()), + ) + }; + let world = World::new(res.facts.air, 0); + let creative = options.creative; + let inventory = vec![None; 36]; + let now = Instant::now(); + let look = options.look; + let particles = horizon_client::particles::ParticleEngine::new(&root, &atlas.sprites); + Ok(Game { + res: res.clone(), + collision: &res.collision, + motion: &res.motion, + pack, + atlas, + fog: Default::default(), + screen_fx: Default::default(), + world, + streaming, + options, + player: None, + spawn: None, + clock: FixedStep::default(), + previous_position: Vec3::ZERO, + eye: 1.62, + previous_eye: 1.62, + yaw: look.map_or(level.rotation[0], |l| l.0), + pitch: look.map_or(level.rotation[1], |l| l.1), + inventory, + selected: 0, + carried: None, + craft_grid: vec![None; 9], + craft_size: 2, + inv_drag: None, + tweaks: Default::default(), + inv_clicks: Default::default(), + last_inv_click: None, + last_quick_moved: None, + container: None, + station: None, + potions: Default::default(), + scratch_slot: None, + mining: None, + destroy_delay: 0, + use_delay: 0, + creative, + mode: if creative { + horizon_client::command::args::GameMode::Creative + } else { + horizon_client::command::args::GameMode::Survival + }, + keys: HashSet::new(), + physical_keys: HashSet::new(), + left: false, + right: false, + cursor: (0.0, 0.0), + captured: false, + focused: true, + modifiers: winit::keyboard::ModifiersState::empty(), + fullscreen: horizon_client::window::FullscreenState::new(false), + shader_packs: Default::default(), + mouse: MouseLook::default(), + agent_pointer: false, + smooth_camera: false, + toggles: Default::default(), + was_playing: false, + pause: false, + debug: false, + screen: Screen::Playing, + window: None, + renderer: None, + entity_vertices: Vec::new(), + see_through_vertices: Vec::new(), + health_hud: hud_layout::HealthHud::default(), + started: now, + previous: now, + last_input: now, + pad: Default::default(), + frames: 0, + world_frames: 0, + fps: 0.0, + fps_frames: 0, + fps_at: now, + ticks: 0, + error: None, + message: None, + save, + level, + session_lock: None, + audio, + music: Default::default(), + ambience: Default::default(), + sound_paused: false, + cart_sounds: HashSet::new(), + riding_cart_sounds: None, + dropped: Vec::new(), + next_entity: 0, + particles, + pickups: Default::default(), + sign_edit: None, + book: None, + lectern_pulses: Vec::new(), + loading_progress: 0.0, + spawn_origin: None, + spawn_spiral: Default::default(), + player_spawn: None, + mobs: Vec::new(), + creatures: Default::default(), + sculk: Default::default(), + raiding: Default::default(), + attack_ticks: 100, + last_hurt_by_player: HashSet::new(), + died: HashSet::new(), + be_anims: { + let mut anims = horizon_client::block_entity_anim::BlockEntityAnims::default(); + anims.classify(registry); + anims + }, + using: None, + view: Default::default(), + limiter: horizon_client::window::FramerateLimiter::new(0), + frame_clock: Default::default(), + scope_scale: 0.5, + frame_ticks: 0.0, + title: None, + armor: [None, None, None, None], + offhand: None, + hand: Hand::Main, + shield_cooldown: 0, + command_source: None, + titles: Default::default(), + tool_highlight: Default::default(), + applied_modifiers: Vec::new(), + experience: Experience::default(), + orbs: Vec::new(), + xp_delay: 0, + last_level_up: 0, + swing: Default::default(), + swings_started: 0, + heights: Default::default(), + sway: Default::default(), + visible_hands: [(0, None), (0, None)], + clicks: Default::default(), + attack_clicks: 0, + hand_strength: Default::default(), + settings, + options_from_title: false, + backdrop: Default::default(), + pause_since: None, + dragging: false, + avatar: Default::default(), + flash: 0, + sleeping: None, + dim: Dim::Overworld, + world_root: PathBuf::new(), + travelling: None, + portals: Default::default(), + end_travel: false, + respawn_config: None, + respawn_travel: None, + end_portal_travel: false, + end: Default::default(), + block_ticks: Ticks::new(0), + tick_chunks: Default::default(), + random_tick_sections: Default::default(), + level_events: Vec::new(), + falling: Vec::new(), + paintings: Vec::new(), + painting_variants: paintings::PaintingVariants::load(&root), + item_frames: Vec::new(), + frame_model: frames::bake_frame(&root, "item_frame"), + glow_frame_model: frames::bake_frame(&root, "glow_item_frame"), + map_frame_model: frames::bake_frame(&root, "item_frame_map"), + glow_map_frame_model: frames::bake_frame(&root, "glow_item_frame_map"), + armor_stands: Vec::new(), + others: Vec::new(), + armor_stand_assets, + boats: Vec::new(), + boat_models, + crystal_model: horizon_client::mobs::load_model(&root, "minecraft:end_crystal#main"), + carts: Vec::new(), + jukebox_sounds: HashMap::new(), + bolts: Vec::new(), + maps: maps::Maps::default(), + fight: dragon::Fight::default(), + dragon: None, + crystals: Vec::new(), + dragon_fireballs: Vec::new(), + breath_clouds: Vec::new(), + dragon_model: horizon_client::mobs::load_model(&root, "minecraft:ender_dragon#main"), + map_patches: Vec::new(), + skin_downloads: horizon_client::skins::Downloader::new( + std::env::current_dir() + .unwrap_or_default() + .join("assets/skins"), + ), + skin_slots: Vec::new(), + cart_models, + riding: None, + ender_items: vec![None; 27], + ender_open: None, + pending: Default::default(), + spill: Default::default(), + recipe_ui: Default::default(), + mount_menu: Default::default(), + hook: None, + tridents: Vec::new(), + rockets: Vec::new(), + ominous_spawners: Vec::new(), + creaking: Default::default(), + spawners: Default::default(), + trident_model: horizon_client::mobs::load_model(&root, "minecraft:trident#main"), + arrow_model: horizon_client::mobs::load_model(&root, "minecraft:arrow#main"), + tnts: Vec::new(), + hoppers: HashMap::new(), + creative_screen: Creative::load(&root)?, + control: None, + frame_stats: Default::default(), + perf: Default::default(), + pending_screenshot: None, + pending_bench: None, + flight: None, + ui_wait: Default::default(), + events: Default::default(), + agent: agent::Agent::default(), + view_frustum: None, + entity_culler: None, + pending_uploads: Vec::new(), + frame_graph: Default::default(), + extras: Default::default(), + mods: Default::default(), + sky_darken_memo: Default::default(), + persist: Default::default(), + remote: None, + lan: None, + integrated: None, + world_options: None, + options_to_world_options: false, + command_block_screen: None, + friends: None, + debug_keys: Default::default(), + debug_charts: Default::default(), + show_hitboxes: false, + show_chunk_borders: false, + pause_menu: true, + previous_mode: None, + gamemode_switcher: None, + clipboard: Default::default(), + text_selection: Default::default(), + saved_for_exit: false, + forced_hit: None, + lan_item_only: false, + lan_events: Vec::new(), + lan_block_events: Vec::new(), + lan_entity_events: Vec::new(), + lid_openers: HashMap::new(), + lan_acting: None, + lan_acting_name: None, + lan_acting_uuid: None, + chat_capture: None, + cmds: Default::default(), + ui: Default::default(), + combat: Default::default(), + mount: Default::default(), + stats: Default::default(), + score: Default::default(), + fns: Default::default(), + bosses: Default::default(), + exec: Default::default(), + rand_sequences: Default::default(), + border: Default::default(), + border_renderer: Default::default(), + border_state: Default::default(), + tab_list: Default::default(), + subtitles: Default::default(), + adv: Default::default(), + restore_player_environment: true, + stats_ui: Default::default(), + adv_ui: Default::default(), + camera_type: Default::default(), + fangs: Default::default(), + player_model: None, + }) + } +} + pub fn run() -> Result<()> { let Some(mut options) = Options::read()? else { return Ok(()); @@ -9631,6 +10155,11 @@ pub fn run() -> Result<()> { let vanilla_root = options.resources.clone(); let early_settings = Settings::load(&std::env::current_dir()?.join("options.txt")); options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs); + options.resources = mods::content_root( + &options.resources, + &early_settings.mods.enabled, + &options.dev_mods, + ); let assets = match Assets::load(&options.resources) { Ok(assets) => assets, // Minecraft.rollbackResourcePacks: the packs break loading, start @@ -9661,24 +10190,16 @@ pub fn run() -> Result<()> { let biomes = Arc::new(Biomes::load(&root)?); let environment = Environment::load(&root)?; log::info!("load biomes+env: {:.2}s", started.elapsed().as_secs_f32()); - let visibility = models::load_visibility(&root, assets.registry)?; - log::info!("load visibility: {:.2}s", started.elapsed().as_secs_f32()); - let tables = Arc::new(MeshTables::new(&assets, &facts, visibility)?); let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?); - log::info!("load tables: {:.2}s", started.elapsed().as_secs_f32()); + let pack = PackResources::load(&root, assets.clone(), &facts, biomes.clone(), light)?; + log::info!("load pack tables: {:.2}s", started.elapsed().as_secs_f32()); let atlas = HudAtlas::build(&root)?; - let panorama = horizon_client::gfx::panorama::Faces::load(&root); horizon_client::ui::load_metadata(&root); horizon_client::lang::set(horizon_client::lang::Language::load( &[&root], &early_settings.language, )); log::info!("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, registry_owner.registry)?; let motion = MotionResources::load(&root, ®istry_owner)?; @@ -9686,12 +10207,6 @@ pub fn run() -> Result<()> { "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 = early_settings.horizon.worker_threads(); log::info!( "Horizon: resources loaded in {:.1}s; {} block states, {} items, {} biomes; {} worker threads", @@ -9701,49 +10216,25 @@ pub fn run() -> Result<()> { biomes.list.len(), threads ); - // Until a world is opened the streamer is idle. - let mut streaming = Streaming::new( - Arc::new(TestTerrain::new(assets.registry, &biomes)?), - context.clone(), - 1, - ); - streaming.paused = true; - let level = Level::default(); - let save = Arc::new(SaveDir::new( - std::env::current_dir()? - .join("saves") - .join(".horizon-title"), - )); let audio = if options.dedicated.is_some() { Audio::silent(&root) } else { Audio::new(&root) }; - let world = World::new(facts.air, 0); - let creative = options.creative; let stations = horizon_client::stations::StationData::load(&root, &items); let animate = horizon_client::animate_tick::AnimateTables::load(&root, registry_owner.registry, &biomes)?; - let fog = horizon_client::fog::FogRenderer::load(&root, &biomes); - let item_renderer = Arc::new( - horizon_client::item_render::ItemRenderer::load_with_library( - &root, - assets.model_library.clone(), - )?, - ); - let mut resources = Resources { + let fog = horizon_client::fog::FogTables::load(&root, &biomes); + let resources = Arc::new(Resources { stations, - assets, facts, items, recipes, transformers, biomes, environment, - atlas, - panorama, - item_renderer, - layer_names, + collision, + motion, providers: Providers::load(&root), block_entity_render: horizon_client::block_entity_render::BlockEntityRenderer::load( &root, @@ -9753,37 +10244,20 @@ pub fn run() -> Result<()> { fog, music: horizon_client::music::MusicTables::load(&root), ambient: horizon_client::ambience::AmbientTables::load(&root), - screen_fx: Default::default(), nether_environment: Environment::load_dimension(&root, "the_nether", false)?, end_environment: Environment::load_dimension(&root, "the_end", false)?, behaviours: Behaviours::load(registry_owner.registry, &root)?, - names: Names::load(&root), - clouds: load_clouds(&root), - forcefield: load_forcefield(&root), mob_types: MobTypes::load(&root)? .types .into_iter() .map(|(k, v)| (k, Arc::new(v))) .collect(), mob_data, - context, threads, player_type: perspective::player_type(&root), player_arm: horizon_client::mobs::load_model(&root, "minecraft:player#main") .and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")), - }; - // These batches share the exported document instead of reparsing it per layer. - let (armor_stand_assets, boat_models, cart_models) = { - let document = horizon_client::mobs::EntityModelDocument::load(&root).ok(); - ( - armor_stands::ArmorStandAssets::load(&root, document.as_ref()), - boats::BoatModels::load(document.as_ref()), - minecarts::CartModels::load(document.as_ref()), - ) - }; - let inventory = vec![None; 36]; - let now = Instant::now(); - let game_root = options.resources.clone(); + }); let mut settings = Settings::load(&std::env::current_dir()?.join("options.txt")); horizon_client::ui_theme::load_preferences(&std::env::current_dir()?); // Scripted and frame-limited runs (the parity harnesses) see vanilla's @@ -9796,269 +10270,7 @@ pub fn run() -> Result<()> { if let Some(d) = options.distance_override { settings.render_distance = d; } - let look = options.look; - let particles = horizon_client::particles::ParticleEngine::new(&root, &resources.atlas.sprites); - 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: look.map_or(level.rotation[0], |l| l.0), - pitch: look.map_or(level.rotation[1], |l| l.1), - inventory, - selected: 0, - carried: None, - craft_grid: vec![None; 9], - craft_size: 2, - inv_drag: None, - tweaks: Default::default(), - inv_clicks: Default::default(), - last_inv_click: None, - last_quick_moved: None, - container: None, - station: None, - potions: Default::default(), - scratch_slot: None, - mining: None, - destroy_delay: 0, - use_delay: 0, - creative, - mode: if creative { - horizon_client::command::args::GameMode::Creative - } else { - horizon_client::command::args::GameMode::Survival - }, - keys: HashSet::new(), - physical_keys: HashSet::new(), - left: false, - right: false, - cursor: (0.0, 0.0), - captured: false, - focused: true, - modifiers: winit::keyboard::ModifiersState::empty(), - fullscreen: horizon_client::window::FullscreenState::new(false), - shader_packs: Default::default(), - mouse: MouseLook::default(), - agent_pointer: false, - smooth_camera: false, - toggles: Default::default(), - was_playing: false, - pause: false, - debug: false, - screen: Screen::Playing, - window: None, - renderer: None, - entity_vertices: Vec::new(), - health_hud: hud_layout::HealthHud::default(), - started: now, - previous: now, - last_input: now, - pad: Default::default(), - frames: 0, - fps: 0.0, - fps_frames: 0, - fps_at: now, - ticks: 0, - error: None, - message: None, - save, - level, - session_lock: None, - audio, - music: Default::default(), - ambience: Default::default(), - sound_paused: false, - cart_sounds: HashSet::new(), - riding_cart_sounds: None, - dropped: Vec::new(), - next_entity: 0, - particles, - pickups: Default::default(), - sign_edit: None, - book: None, - lectern_pulses: Vec::new(), - spawn_search: 0, - spawn_origin: None, - spawn_spiral: Default::default(), - player_spawn: None, - mobs: Vec::new(), - creatures: Default::default(), - sculk: Default::default(), - raiding: Default::default(), - attack_ticks: 100, - last_hurt_by_player: HashSet::new(), - died: HashSet::new(), - be_anims: { - let mut anims = horizon_client::block_entity_anim::BlockEntityAnims::default(); - anims.classify(registry_owner.registry); - anims - }, - using: None, - view: Default::default(), - limiter: horizon_client::window::FramerateLimiter::new(0), - frame_clock: Default::default(), - scope_scale: 0.5, - frame_ticks: 0.0, - title: None, - armor: [None, None, None, None], - offhand: None, - hand: Hand::Main, - shield_cooldown: 0, - command_source: None, - titles: Default::default(), - tool_highlight: Default::default(), - applied_modifiers: Vec::new(), - experience: Experience::default(), - orbs: Vec::new(), - xp_delay: 0, - last_level_up: 0, - swing: Default::default(), - swings_started: 0, - heights: Default::default(), - sway: Default::default(), - visible_hands: [(0, None), (0, None)], - clicks: Default::default(), - attack_clicks: 0, - hand_strength: Default::default(), - settings, - options_from_title: false, - backdrop: Default::default(), - pause_since: None, - dragging: false, - avatar: Default::default(), - flash: 0, - sleeping: None, - dim: Dim::Overworld, - world_root: PathBuf::new(), - travelling: None, - portals: Default::default(), - end_travel: false, - respawn_config: None, - respawn_travel: None, - end_portal_travel: false, - end: Default::default(), - block_ticks: Ticks::new(0), - tick_chunks: Default::default(), - random_tick_sections: Default::default(), - level_events: Vec::new(), - falling: Vec::new(), - paintings: Vec::new(), - painting_variants: paintings::PaintingVariants::load(&root), - item_frames: Vec::new(), - frame_model: frames::bake_frame(&root, "item_frame"), - glow_frame_model: frames::bake_frame(&root, "glow_item_frame"), - map_frame_model: frames::bake_frame(&root, "item_frame_map"), - glow_map_frame_model: frames::bake_frame(&root, "glow_item_frame_map"), - armor_stands: Vec::new(), - others: Vec::new(), - armor_stand_assets, - boats: Vec::new(), - boat_models, - crystal_model: horizon_client::mobs::load_model(&root, "minecraft:end_crystal#main"), - carts: Vec::new(), - jukebox_sounds: HashMap::new(), - bolts: Vec::new(), - maps: maps::Maps::default(), - fight: dragon::Fight::default(), - dragon: None, - crystals: Vec::new(), - dragon_fireballs: Vec::new(), - breath_clouds: Vec::new(), - dragon_model: horizon_client::mobs::load_model(&root, "minecraft:ender_dragon#main"), - map_patches: Vec::new(), - skin_downloads: horizon_client::skins::Downloader::new( - std::env::current_dir() - .unwrap_or_default() - .join("assets/skins"), - ), - skin_slots: Vec::new(), - cart_models, - riding: None, - ender_items: vec![None; 27], - ender_open: None, - pending: Default::default(), - spill: Default::default(), - recipe_ui: Default::default(), - mount_menu: Default::default(), - hook: None, - tridents: Vec::new(), - rockets: Vec::new(), - creaking: Default::default(), - spawners: Default::default(), - trident_model: horizon_client::mobs::load_model(&root, "minecraft:trident#main"), - arrow_model: horizon_client::mobs::load_model(&root, "minecraft:arrow#main"), - tnts: Vec::new(), - hoppers: HashMap::new(), - creative_screen: Creative::load(&game_root)?, - control: None, - frame_stats: Default::default(), - perf: Default::default(), - pending_screenshot: None, - pending_bench: None, - flight: None, - ui_wait: Default::default(), - events: Default::default(), - agent: agent::Agent::default(), - view_frustum: None, - entity_culler: None, - pending_uploads: Vec::new(), - frame_graph: Default::default(), - extras: Default::default(), - mods: Default::default(), - sky_darken_memo: Default::default(), - persist: Default::default(), - remote: None, - lan: None, - world_options: None, - friends: None, - debug_keys: Default::default(), - debug_charts: Default::default(), - show_hitboxes: false, - show_chunk_borders: false, - pause_menu: true, - previous_mode: None, - gamemode_switcher: None, - clipboard: Default::default(), - text_selection: Default::default(), - saved_for_exit: false, - forced_hit: None, - lan_events: Vec::new(), - lan_block_events: Vec::new(), - lan_entity_events: Vec::new(), - lid_openers: HashMap::new(), - lan_acting: None, - chat_capture: None, - cmds: Default::default(), - ui: Default::default(), - combat: Default::default(), - mount: Default::default(), - stats: Default::default(), - score: Default::default(), - fns: Default::default(), - bosses: Default::default(), - exec: Default::default(), - rand_sequences: Default::default(), - border: Default::default(), - border_renderer: Default::default(), - border_state: Default::default(), - tab_list: Default::default(), - subtitles: Default::default(), - adv: Default::default(), - restore_player_environment: true, - stats_ui: Default::default(), - adv_ui: Default::default(), - camera_type: Default::default(), - fangs: Default::default(), - player_model: None, - }; + let mut game = Game::new(&resources, pack, atlas, options, settings, audio)?; game.ui.vanilla_root = vanilla_root; if game.options.benchmark.is_some() { // The same conditions on every machine: no VSync, no frame cap, no @@ -10200,6 +10412,14 @@ mod tests { use horizon_client::container_screen::{Button, Clicks, Release, Target}; use horizon_client::keymapping::{KeyAction, SPRINT, ToggleKeys}; + /// An integrated server thread shares the loaded resources with the client. + #[test] + fn shared_resources_can_cross_threads() { + fn shared() {} + shared::(); + shared::(); + } + #[test] fn selecting_creative_tabs_does_not_drop_the_carried_stack_on_release() { let mut creative = Creative::from_json(&serde_json::json!({ diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 4d51ce5e4..24b6af2db 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -7,6 +7,7 @@ use horizon_client::{ hud::HudBatch, items::ItemStack, text::{self, Style, Text}, + toasts::Slide, }; use serde_json::Value; use std::{ @@ -68,51 +69,6 @@ impl Toast { (fully_for as f64 / (5000.0 * multiplier / n).max(1.0) % n) as usize } } -/// `ToastManager.ToastInstance`: slides a toast in and out over 600 ms, -/// eased by the square, and counts how long it has been fully shown. -#[derive(Default)] -struct Slide { - /// When it first updated; the times below are milliseconds since. - origin: Option, - begun: bool, - /// `animationStartTime`. - start: i64, - /// `becameFullyVisibleAt`. - fully_at: i64, - show: bool, - /// `visiblePortion`: 0 off screen, 1 fully in. - portion: f32, - /// `fullyVisibleFor`. - fully_for: i64, -} -impl Slide { - const MS: i64 = 600; - /// `ToastInstance.update` at `now`; `wants_show` is the toast's own - /// update. The visibility it switched to (the sound to play), and whether - /// it has finished sliding out. - fn update(&mut self, now: i64, wants_show: impl FnOnce(i64) -> bool) -> (Option, bool) { - let was = self.show; - if !self.begun { - self.begun = true; - self.start = now; - self.show = true; - } - if self.show && now - self.start <= Self::MS { - self.fully_at = now; - } - self.fully_for = now - self.fully_at; - let progress = ((now - self.start) as f32 / Self::MS as f32).clamp(0.0, 1.0); - let progress = progress * progress; - self.portion = if self.show { progress } else { 1.0 - progress }; - let wanted = wants_show(self.fully_for); - if wanted != self.show { - self.start = now - ((1.0 - self.portion) * Self::MS as f32) as i64; - self.show = wanted; - } - let finished = !self.show && now - self.start > Self::MS; - ((self.show != was).then_some(self.show), finished) - } -} #[derive(Default)] pub(super) struct AdvState { pub(super) tree: Arc, @@ -153,7 +109,7 @@ impl adv::World for View<'_, '_> { let name = self.0.res.facts.get(state).name.to_string(); let props = self .0 - .res + .pack .assets .registry .state(state) @@ -670,7 +626,7 @@ impl Game<'_> { } /// `EnterBlockTrigger`: the block, its state properties and the player. pub(super) fn trigger_enter_block(&mut self, state: horizon_world::registry::BlockStateId) { - let Some(definition) = self.res.assets.registry.state(state).cloned() else { + let Some(definition) = self.pack.assets.registry.state(state).cloned() else { return; }; let me = self.player_entity(); @@ -803,11 +759,11 @@ impl Game<'_> { if let Some((station, item)) = recipe { // RecipeToast: black description under a purple title, the // station at 0.6 scale in the corner over the cycling result. - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.sprite(atlas, "gui/sprites/toast/recipe", x, 0.0); let title = self.translate("recipe.toast.title", "New Recipe(s) Unlocked!"); let description = self.translate("recipe.toast.description", "Check your recipe book"); - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.text(atlas, &title, x + 30.0, 7.0, 0xFF50_0050, false); batch.text(atlas, &description, x + 30.0, 18.0, 0xFF00_0000, false); let start = batch.vertices.len(); @@ -816,7 +772,7 @@ impl Game<'_> { self.draw_item_model(batch, &item, x + 8.0, 8.0); return; } - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.sprite(atlas, "gui/sprites/toast/advancement", x, 0.0); let (key, color) = match frame { Frame::Task => ("advancements.toast.task", 0xFF00_FFFF), diff --git a/crates/horizon-client/src/game/advancements_screen.rs b/crates/horizon-client/src/game/advancements_screen.rs index 3340ca78a..5e1c0343b 100644 --- a/crates/horizon-client/src/game/advancements_screen.rs +++ b/crates/horizon-client/src/game/advancements_screen.rs @@ -257,7 +257,7 @@ impl Game<'_> { } /// `AdvancementWidget`'s title lines, description lines and width. fn adv_widget_text(&self, i: usize) -> (Vec, Vec, f32) { - let font = &self.res.atlas.font; + let font = &self.atlas.font; let a = &self.adv.tree.list[i]; let Some(d) = &a.display else { return (Vec::new(), Vec::new(), 0.0); @@ -320,7 +320,7 @@ impl Game<'_> { let (sx, sy) = self.adv_ui.scroll.unwrap_or_default(); let (sx, sy) = (sx.floor() as i32, sy.floor() as i32); self.adv_tick_hover(&view, sx, sy, left, top); - let atlas = &self.res.atlas; + let atlas = &self.atlas; ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); let title = Text::translate("gui.advancements", &[]); let tw = atlas.font.width_text(&title); @@ -432,7 +432,7 @@ impl Game<'_> { } let (x, y) = pos(i); let (x, y) = ((ox + x) as f32, (oy + y) as f32); - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.sprite_scaled( atlas, frame_sprite(d.frame, done), @@ -449,7 +449,7 @@ impl Game<'_> { } } // The window, tabs and title. - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.sprite_region( atlas, "gui/advancements/window", @@ -463,7 +463,7 @@ impl Game<'_> { let (x, y) = tab_pos(ty, i); let sprite = tab_sprite(ty, i, ty.3, Some(t) == tab); batch.sprite_scaled( - &self.res.atlas, + &self.atlas, &sprite, left + x, top + y, @@ -482,7 +482,7 @@ impl Game<'_> { } } } - let atlas = &self.res.atlas; + let atlas = &self.atlas; let title = tab.and_then(|t| tree.list[t].display.as_ref()).map_or_else( || Text::translate("gui.advancements", &[]), |d| text_of(&d.title), @@ -497,7 +497,7 @@ impl Game<'_> { } } // Done. - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (bx, by) = ((w / 2.0 - 100.0).floor(), h - FOOTER + 6.0); let hover = ui::hovered(self.cursor, bx, by, 200.0, 20.0); ui::button( @@ -520,7 +520,7 @@ impl Game<'_> { let (cx, cy) = self.cursor; if cx > x && cx < x + ty.1 && cy > y && cy < y + ty.2 { if let Some(d) = &tree.list[t].display { - ui::tooltip(batch, &self.res.atlas, &[text_of(&d.title)], self.cursor); + ui::tooltip(batch, &self.atlas, &[text_of(&d.title)], self.cursor); } break; } @@ -604,7 +604,7 @@ impl Game<'_> { ], ) }); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let progress_w = progress.as_ref().map_or(0.0, |t| atlas.font.width_text(t)) as i32; let top_side = title_bottom + desc_h >= INSIDE_H; let amount = if a.criteria.is_empty() || total == 0 { diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 62b4f8624..cd39606b3 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -51,7 +51,7 @@ pub(super) const HELP: &[&str] = &[ "scroll-at X Y STEPS turn the wheel at GUI pixel X Y (positive scrolls up)", "command TEXT run a /command", "pause open the pause menu", - "wait TICKS wait for game ticks to pass", + "wait TICKS wait for game ticks to pass (held keys stay held)", "stop cancel the running action and release every key", ]; @@ -231,6 +231,13 @@ enum TaskKind { report_tick: u64, }, } +impl TaskKind { + /// Whether the keys and buttons are released when the task ends. A wait + /// holds nothing, so what `key w down` pressed stays down through it. + fn releases_input(&self) -> bool { + !matches!(self, TaskKind::Wait { .. }) + } +} struct Goto { target: [f64; 3], near: f64, @@ -294,7 +301,7 @@ pub(super) enum Handled { impl Game<'_> { pub(super) fn state_string(&self, state: BlockStateId) -> String { - let Some(s) = self.res.assets.registry.state(state) else { + let Some(s) = self.pack.assets.registry.state(state) else { return "?".into(); }; if s.properties.is_empty() { @@ -389,6 +396,7 @@ impl Game<'_> { Screen::Stats => "stats", Screen::Advancements => "advancements", Screen::WorldOptions => "world-options", + Screen::CommandBlock => "command-block", } } pub(super) fn inventory_counts(&self) -> BTreeMap { @@ -630,7 +638,7 @@ impl Game<'_> { fn messages_value(&self, n: usize) -> Value { let titles = &self.titles; json!({ - "chat": self.ui.chat.recent_lines(n), + "chat": self.remote_chat(n).unwrap_or_else(|| self.ui.chat.recent_lines(n)), "order": "newest first", "title": (titles.time > 0).then(|| titles.title.as_ref().map(|t| t.plain())).flatten(), "subtitle": (titles.time > 0).then(|| titles.subtitle.as_ref().map(|t| t.plain())).flatten(), @@ -1654,7 +1662,9 @@ impl Game<'_> { let result = self.step_task(&mut task.kind, timed_out); match result { Some(value) => { - self.release_agent_keys(); + if task.kind.releases_input() { + self.release_agent_keys(); + } let _ = task.reply.send(value.to_string()); } None => self.agent.task = Some(task), @@ -1958,6 +1968,16 @@ impl Game<'_> { mod tests { use super::*; + #[test] + fn only_wait_keeps_held_input() { + assert!(!TaskKind::Wait { until_tick: 40 }.releases_input()); + let jump = TaskKind::Jump { + release_tick: 4, + from_y: 64.0, + }; + assert!(jump.releases_input()); + } + #[test] fn parses_flags_and_values() { let a = parse_args(&["1", "2", "--near", "3", "--sprint", "--timeout=9", "-4"]); diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index c856738a9..80e42169d 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -124,7 +124,7 @@ impl Game<'_> { continue; }; let (Some(r), Some(part)) = ( - self.res.atlas.sprites.get(texture.as_str()), + self.atlas.sprites.get(texture.as_str()), assets.player.get(layer), ) else { continue; @@ -379,7 +379,7 @@ impl Game<'_> { let mut dead = Vec::new(); for (i, a) in self.armor_stands.iter_mut().enumerate() { a.tick(&mut scene); - if !a.environment_tick(&self.world, &self.res.facts, self.res.assets.registry) { + if !a.environment_tick(&self.world, &self.res.facts, self.pack.assets.registry) { dead.push(i); } } @@ -403,7 +403,7 @@ impl Game<'_> { out: &mut Vec, ) { let assets = &self.armor_stand_assets; - let sprites = &self.res.atlas.sprites; + let sprites = &self.atlas.sprites; let uv_of = |name: &str| sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); let Some(wood) = uv_of("entity/armorstand/armorstand") else { return; @@ -668,12 +668,12 @@ impl Game<'_> { self.dim == super::Dim::Nether, )), }; - self.res.item_renderer.submit_special( + self.pack.item_renderer.submit_special( &special, &serde_json::Value::Null, false, pose, - &self.res.atlas.sprites, + &self.atlas.sprites, &self.item_host(), &mut sink, ); diff --git a/crates/horizon-client/src/game/backdrop.rs b/crates/horizon-client/src/game/backdrop.rs index 15ca99ba9..149cddefa 100644 --- a/crates/horizon-client/src/game/backdrop.rs +++ b/crates/horizon-client/src/game/backdrop.rs @@ -150,11 +150,11 @@ impl Game<'_> { .join("backdrop"); std::fs::create_dir_all(&root)?; let save = Arc::new(SaveDir::new(root.join(format!("{seed}")))); - let res = &*self.res; + let (res, pack) = (&*self.res, &self.pack); let inner = Arc::new( VanillaTerrain::new( &self.options.resources.join("worldgen"), - res.assets.registry, + pack.assets.registry, &res.biomes, seed, ) @@ -164,10 +164,10 @@ impl Game<'_> { Arc::new(Persistent { inner: inner.clone(), save: save.clone(), - registry: res.assets.clone(), + registry: pack.assets.clone(), biomes: res.biomes.clone(), }), - res.context.clone(), + pack.context.clone(), res.threads.min(6), ); streaming.radius = self.settings.render_distance.clamp(4, 10); diff --git a/crates/horizon-client/src/game/banners.rs b/crates/horizon-client/src/game/banners.rs index d3f0df42b..6875fcb7f 100644 --- a/crates/horizon-client/src/game/banners.rs +++ b/crates/horizon-client/src/game/banners.rs @@ -5,7 +5,6 @@ use super::Game; use horizon_client::{ banner::{self, BannerLayer}, containers::BlockEntity, - items::ItemStack, }; impl Game<'_> { @@ -17,19 +16,6 @@ impl Game<'_> { }; layer_textures(&self.res.stations.banners, &b.layers) } - /// A placed banner takes the item's layers and name. - pub(super) fn fill_placed_banner(&mut self, pos: [i32; 3], stack: &ItemStack) { - self.pending.banner.remove(&pos); - if !stack.item.ends_with("_banner") { - return; - } - if let Some(BlockEntity::Banner(b)) = - self.world.block_entities.get_mut(&(pos[0], pos[1], pos[2])) - { - b.layers = banner::layers(stack).to_vec(); - b.name = stack.custom_name().map(str::to_owned); - } - } } /// Texture names and tints of banner layers (`Sheets.getBannerSprite`). diff --git a/crates/horizon-client/src/game/beacon.rs b/crates/horizon-client/src/game/beacon.rs index 1526cad6f..15a7de79d 100644 --- a/crates/horizon-client/src/game/beacon.rs +++ b/crates/horizon-client/src/game/beacon.rs @@ -385,7 +385,7 @@ impl Game<'_> { let levels = self.beacon_levels(); let sel = self.station.as_ref().map_or([None; 2], |s| s.beacon); let paid = self.station.as_ref().is_some_and(|s| s.inputs[0].is_some()); - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.fill( atlas, 0.0, @@ -406,7 +406,7 @@ impl Game<'_> { ("block.minecraft.beacon.secondary", "Secondary Power", 169.0), ] { let text = self.translate(key, fallback); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let w = HudBatch::text_width(atlas, &text); batch.text( atlas, @@ -421,7 +421,7 @@ impl Game<'_> { let x = [20.0, 41.0, 63.0, 86.0, 108.0][i]; self.draw_item(batch, &ItemStack::new(item, 1), bx + x, by + 109.0); } - let atlas = &self.res.atlas; + let atlas = &self.atlas; let mut tooltip = None; let button = |batch: &mut HudBatch, x: f32, y: f32, active: bool, selected: bool, icon: &str| { @@ -503,7 +503,7 @@ impl Game<'_> { 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, + &self.atlas, ox + sx, oy + sy, 16.0, @@ -524,13 +524,7 @@ impl Game<'_> { } /// `BeaconRenderer`: each section's rotating solid beam and its glow. pub(super) fn beacon_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { - let Some(s) = self - .res - .atlas - .sprites - .get("entity/beacon/beacon_beam") - .copied() - else { + let Some(s) = self.atlas.sprites.get("entity/beacon/beacon_beam").copied() else { return; }; let time = (self.world.game_time.rem_euclid(40)) as f32 + alpha as f32; diff --git a/crates/horizon-client/src/game/beehives.rs b/crates/horizon-client/src/game/beehives.rs index eb74becc7..0520e4367 100644 --- a/crates/horizon-client/src/game/beehives.rs +++ b/crates/horizon-client/src/game/beehives.rs @@ -63,7 +63,7 @@ impl HiveHost for GameHive<'_, '_> { impl Game<'_> { fn hive_with_honey(&self, state: BlockStateId, level: i32) -> Option { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let mut s = registry.state(state)?.clone(); s.properties .insert("honey_level".to_owned(), level.to_string()); @@ -82,7 +82,7 @@ impl Game<'_> { { return None; } - let props = &self.res.assets.registry.state(state)?.properties; + let props = &self.pack.assets.registry.state(state)?.properties; let honey = props.get("honey_level").and_then(|v| v.parse().ok()); let facing = beehive::facing_step(props.get("facing").map(String::as_str)); Some((honey, facing)) diff --git a/crates/horizon-client/src/game/block_entity_anims.rs b/crates/horizon-client/src/game/block_entity_anims.rs index 446b56b55..d377aeb45 100644 --- a/crates/horizon-client/src/game/block_entity_anims.rs +++ b/crates/horizon-client/src/game/block_entity_anims.rs @@ -12,6 +12,7 @@ use horizon_client::{ save::number, }; use horizon_core::geometry::{Aabb, Vec3}; +use horizon_world::nbt::Tag; use std::collections::HashMap; /// The handle of the local player among a bell's gathered entities. @@ -279,7 +280,7 @@ impl Game<'_> { Ticker::Conduit => { let world = &self.world; let facts = &self.res.facts; - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let is_water = |p: [i32; 3]| { facts.get(world.block(p[0], p[1], p[2])).fluid == horizon_client::blocks::Fluid::Water @@ -340,8 +341,15 @@ impl Game<'_> { /// The End gateway at `pos` as its chunk was loaded: `Age` from the saved /// block entity (`getUpdateTag`), or a new gateway. fn gateway_loaded(&self, pos: [i32; 3]) -> EndGateway { - let age = self - .world + let age = self.saved_tag(pos).and_then(|t| number(t.get("Age"))); + EndGateway { + age: age.unwrap_or(0), + teleport_cooldown: 0, + } + } + /// The block entity at `pos` Horizon keeps as loaded, if any. + fn saved_tag(&self, pos: [i32; 3]) -> Option<&Tag> { + self.world .chunks .get(&(pos[0] >> 4, pos[2] >> 4)) .and_then(|c| c.saved.as_deref()) @@ -352,16 +360,26 @@ impl Game<'_> { .eq(&pos.map(|v| Some(i64::from(v)))) }) }) - .and_then(|t| number(t.get("Age"))); - EndGateway { - age: age.unwrap_or(0), - teleport_cooldown: 0, - } } - /// The renderer's view of the block entity at `pos`. + /// The renderer's view of the block entity at `pos`, with a decorated + /// pot's saved `sherds` (back, left, right, front). pub(super) fn block_anim(&self, pos: [i32; 3], partial: f32) -> BlockAnim { + let state = self.world.block(pos[0], pos[1], pos[2]); + let sherds = if &*self.res.facts.get(state).name == "minecraft:decorated_pot" { + let sherds = self.saved_tag(pos).and_then(|t| t.get("sherds")); + ["back", "left", "right", "front"].map(|side| match sherds.and_then(|s| s.get(side)) { + // An item id, or the item stack the processed templates hold. + Some(Tag::String(id)) => Some(id.to_string_lossy()), + Some(stack) => { + horizon_client::save::item_from_nbt(stack).map(|s| s.item.to_string()) + } + None => None, + }) + } else { + Default::default() + }; self.be_anims - .block_anim(pos, self.world.game_time, partial, Default::default()) + .block_anim(pos, self.world.game_time, partial, sherds) } /// `ChestLidController.getOpenness(partial)` at `pos`. pub(super) fn chest_lid(&self, pos: [i32; 3], partial: f32) -> f32 { diff --git a/crates/horizon-client/src/game/block_items.rs b/crates/horizon-client/src/game/block_items.rs new file mode 100644 index 000000000..b8012cce1 --- /dev/null +++ b/crates/horizon-client/src/game/block_items.rs @@ -0,0 +1,117 @@ +//! Block entities and the items that carry them +//! (`horizon_client::block_entity_item`): the item Pick Block gives, with the +//! block entity's data on Ctrl in creative, and the data and components a +//! placed item gives its block entity. +use super::Game; +use horizon_client::{ + block_entity_item, block_entity_nbt, containers::BlockEntity, item_data, items::ItemStack, save, +}; +use horizon_world::nbt::{Compound, Tag}; + +/// The component patch of `stack`. +fn components(stack: &ItemStack) -> Compound { + match item_data::encode_components(stack) { + Some(Tag::Compound(c)) => c, + _ => Compound::new(), + } +} + +impl Game<'_> { + /// The block entity at `key` as vanilla saves it, with its custom name. + fn saved_block_entity(&self, key: (i32, i32, i32)) -> Option { + let entity = self.world.block_entities.get(&key)?; + let block = &self + .res + .facts + .get(self.world.block(key.0, key.1, key.2)) + .name; + let mut tag = save::encode_block_entity(key, entity, block); + if let (Some(name), Tag::Compound(map)) = (self.world.block_names.get(&key), &mut tag) { + map.insert("CustomName".into(), Tag::String(name.as_str().into())); + } + block_entity_nbt::canonical(&tag) + } + + /// `BlockState.getCloneItemStack` of the block at `pos`, then, with + /// `include_data`, `ServerGamePacketListenerImpl.addBlockDataToItem`. + pub(super) fn picked_stack(&self, pos: [i32; 3], include_data: bool) -> Option { + let key = (pos[0], pos[1], pos[2]); + let state = self.world.block(pos[0], pos[1], pos[2]); + let facts = self.res.facts.get(state); + if &*facts.item == "minecraft:air" { + return None; + } + let mut stack = ItemStack::new(&facts.item, 1); + let mut patch = Compound::new(); + // BeehiveBlock.getCloneItemStack: the honey level as the item's block state. + if include_data + && let Some(level) = self + .pack + .assets + .registry + .state(state) + .filter(|s| matches!(s.name.as_str(), "minecraft:beehive" | "minecraft:bee_nest")) + .and_then(|s| s.properties.get("honey_level")) + { + patch.insert( + "minecraft:block_state".into(), + Tag::compound([("honey_level", Tag::String(level.as_str().into()))]), + ); + } + // AbstractBannerBlock.getCloneItemStack: the banner's own item + // (BannerBlockEntity.getItem), data or not. + let banner = matches!( + self.world.block_entities.get(&key), + Some(BlockEntity::Banner(_)) + ); + if (include_data || banner) + && let Some(saved) = self.saved_block_entity(key) + { + patch.extend(block_entity_item::pick(&saved)); + } + if !patch.is_empty() { + let mut all = components(&stack); + all.extend(patch); + (stack.damage, stack.extra) = item_data::decode_components(Some(&Tag::Compound(all))); + } + Some(stack) + } + + /// `BlockItem.updateCustomBlockEntityTag` and `updateBlockEntityComponents` + /// for the block entity just placed at `pos` from `stack`; `game_master`: + /// the placer can use game master blocks (a dispenser can't). + pub(super) fn apply_placed_item( + &mut self, + pos: [i32; 3], + stack: &ItemStack, + game_master: bool, + ) { + let key = (pos[0], pos[1], pos[2]); + self.pending.banner.remove(&pos); + let Some(saved) = self.saved_block_entity(key) else { + return; + }; + let placed = block_entity_item::place(&saved, &components(stack), game_master); + if placed == saved { + return; + } + let Some((_, mut entity)) = save::decode_block_entity(&placed) else { + return; + }; + // The new crafter's state flag (CrafterBlock.newBlockEntity), which + // its saved data has no part of. + if let (BlockEntity::Crafter(new), Some(BlockEntity::Crafter(old))) = + (&mut entity, self.world.block_entities.get(&key)) + { + new.state_triggered = old.state_triggered; + } + // Banners and signs keep their name themselves. + if !matches!(entity, BlockEntity::Banner(_) | BlockEntity::Sign(_)) { + match save::text(placed.get("CustomName")) { + Some(name) => self.world.block_names.insert(key, name), + None => self.world.block_names.remove(&key), + }; + } + self.world.block_entities.insert(key, entity); + } +} diff --git a/crates/horizon-client/src/game/blockctl.rs b/crates/horizon-client/src/game/blockctl.rs index 369e46316..993e0789e 100644 --- a/crates/horizon-client/src/game/blockctl.rs +++ b/crates/horizon-client/src/game/blockctl.rs @@ -33,7 +33,7 @@ fn parse_state(text: &str) -> Result { impl Game<'_> { fn state_text(&self, state: BlockStateId) -> String { - let Some(s) = self.res.assets.registry.state(state) else { + let Some(s) = self.pack.assets.registry.state(state) else { return "?".into(); }; if s.properties.is_empty() { @@ -69,7 +69,7 @@ impl Game<'_> { "setblock" => { let pos = [int(1)?, int(2)?, int(3)?]; let state = self - .res + .pack .assets .registry .resolve(&parse_state(words.get(4).ok_or("missing block")?)?)?; @@ -81,7 +81,7 @@ impl Game<'_> { "fill" => { let (a, b) = ([int(1)?, int(2)?, int(3)?], [int(4)?, int(5)?, int(6)?]); let state = self - .res + .pack .assets .registry .resolve(&parse_state(words.get(7).ok_or("missing block")?)?)?; diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index 40211161d..a5a609cac 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -712,7 +712,6 @@ impl Game<'_> { }; let folder = if b.chest { "chest_boat" } else { "boat" }; let Some(uv) = self - .res .atlas .sprites .get(&format!("entity/{folder}/{}", b.wood)) diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index 3904ab465..5603e8369 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -45,7 +45,7 @@ pub(super) enum BookScreen { } impl Game<'_> { fn book_lines(&self, page: &str) -> Vec { - self.res.atlas.font.split(&Text::literal(page), 114.0) + self.atlas.font.split(&Text::literal(page), 114.0) } /// `WritableBookItem.use` / `WrittenBookItem.use`. pub(super) fn use_book(&mut self, stack: &ItemStack) -> bool { @@ -242,7 +242,7 @@ impl Game<'_> { /// the page (`MultilineTextField.insertText`: line breaks kept, cut to /// the 1024 characters left, rejected when it overflows the 14 lines). fn book_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) { - let font = &self.res.atlas.font; + let font = &self.atlas.font; match self.book.as_mut() { Some(BookScreen::Edit { signing: true, @@ -363,7 +363,7 @@ impl Game<'_> { } fn set_lectern_property(&mut self, key: (i32, i32, i32), name: &str, value: bool) { let state = self.world.block(key.0, key.1, key.2); - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let Some(mut s) = registry.state(state).cloned() else { return; }; @@ -549,7 +549,7 @@ impl Game<'_> { } pub(super) fn draw_book(&self, batch: &mut HudBatch) { let Some(book) = &self.book else { return }; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); let (mx, my) = self.cursor; let hover = diff --git a/crates/horizon-client/src/game/cartography.rs b/crates/horizon-client/src/game/cartography.rs index a59a31669..86d5d5395 100644 --- a/crates/horizon-client/src/game/cartography.rs +++ b/crates/horizon-client/src/game/cartography.rs @@ -89,17 +89,17 @@ impl Game<'_> { if is_locked { locked = true; if scaling || locking { - batch.sprite(&self.res.atlas, error, ox + 35.0, oy + 31.0); + batch.sprite(&self.atlas, error, ox + 35.0, oy + 31.0); } } if scaling && scale >= 4 { locked = true; - batch.sprite(&self.res.atlas, error, ox + 35.0, oy + 31.0); + batch.sprite(&self.atlas, error, ox + 35.0, oy + 31.0); } } let sprite = |batch: &mut HudBatch, game: &Self, name: &str, x: f32, y: f32| { batch.sprite( - &game.res.atlas, + &game.atlas, &format!("gui/sprites/container/cartography_table/{name}"), ox + x, oy + y, diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index bd07107b0..8f6bed0ca 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -3,7 +3,7 @@ use super::{Dim, Game, Screen}; use horizon_client::{ chat::{Chat, ChatAction, ChatScreen, Commands, SYSTEM_INDICATOR}, - command::{Registries, vanilla}, + command::Registries, gamerules::GameRules, hud::{HudBatch, rgba}, screen_draw::Measure, @@ -226,7 +226,7 @@ impl Game<'_> { .map(|k| horizon_client::command::args::normalize(k)) .collect(); reg.block_tags.sort(); - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let mut blocks: BTreeMap>> = BTreeMap::new(); for id in 0..registry.len() { let Some(state) = registry.state(horizon_world::registry::BlockStateId(id as u32)) @@ -389,9 +389,9 @@ impl Game<'_> { .as_ref() .map_or([1280, 720], |r| [r.config.width, r.config.height]); let b = HudBatch::new(size); - let m = Measure(&self.res.atlas.font); + let m = Measure(&self.atlas.font); let c = Commands { - dispatcher: vanilla::game_dispatcher(), + dispatcher: self.mods.dispatcher(), registries: &self.ui.registries, }; let mut screen = ChatScreen::new( @@ -428,7 +428,7 @@ impl Game<'_> { let focused = self.screen == Screen::Chat; let heard = self.mods.mods.is_running().then(|| text.plain()); self.ui.chat.add( - &self.res.atlas, + &self.atlas, text, Some(SYSTEM_INDICATOR), self.ticks, @@ -441,9 +441,9 @@ impl Game<'_> { /// Keys while the chat screen is open. pub(super) fn chat_key(&mut self, event: &KeyEvent) { if let Some(shortcut) = self.edit_shortcut(event) { - let m = Measure(&self.res.atlas.font); + let m = Measure(&self.atlas.font); let c = Commands { - dispatcher: vanilla::game_dispatcher(), + dispatcher: self.mods.dispatcher(), registries: &self.ui.registries, }; if let Some(screen) = self.ui.chat_screen.as_mut() { @@ -487,9 +487,9 @@ impl Game<'_> { let Some(mut screen) = self.ui.chat_screen.take() else { return; }; - let m = Measure(&self.res.atlas.font); + let m = Measure(&self.atlas.font); let c = Commands { - dispatcher: vanilla::game_dispatcher(), + dispatcher: self.mods.dispatcher(), registries: &self.ui.registries, }; match screen.key(&m, &c, &self.ui.chat.recent, key, shift, ctrl) { @@ -513,9 +513,9 @@ impl Game<'_> { } /// Text typed into the chat box (control socket `chat`). pub(super) fn chat_type(&mut self, text: &str) { - let m = Measure(&self.res.atlas.font); + let m = Measure(&self.atlas.font); let c = Commands { - dispatcher: vanilla::game_dispatcher(), + dispatcher: self.mods.dispatcher(), registries: &self.ui.registries, }; if let Some(screen) = self.ui.chat_screen.as_mut() { @@ -536,7 +536,7 @@ impl Game<'_> { let heard = self.mods.mods.is_running().then(|| line.plain()); self.ui .chat - .add(&self.res.atlas, line, None, self.ticks, focused); + .add(&self.atlas, line, None, self.ticks, focused); if let Some(line) = heard { self.mods_chat(&line); } @@ -564,9 +564,9 @@ impl Game<'_> { let height = self.renderer.as_ref().map_or(720.0, |r| { HudBatch::new([r.config.width, r.config.height]).height }); - let m = Measure(&self.res.atlas.font); + let m = Measure(&self.atlas.font); let c = Commands { - dispatcher: vanilla::game_dispatcher(), + dispatcher: self.mods.dispatcher(), registries: &self.ui.registries, }; if let Some(screen) = self.ui.chat_screen.as_mut() { @@ -577,7 +577,7 @@ impl Game<'_> { return; } match self.ui.chat.click_at( - &self.res.atlas.font, + &self.atlas.font, height as i32, cursor.0 as f64, cursor.1 as f64, @@ -603,17 +603,15 @@ impl Game<'_> { if self.ui.hide_gui && !focused { return; } - self.ui - .chat - .draw(batch, &self.res.atlas, self.ticks, focused); + self.ui.chat.draw(batch, &self.atlas, self.ticks, focused); } pub(super) fn draw_chat_screen(&mut self, batch: &mut HudBatch) { let Some(mut screen) = self.ui.chat_screen.take() else { return; }; - let m = Measure(&self.res.atlas.font); + let m = Measure(&self.atlas.font); let c = Commands { - dispatcher: vanilla::game_dispatcher(), + dispatcher: self.mods.dispatcher(), registries: &self.ui.registries, }; screen.resize(&m, &c, batch.width as i32, batch.height as i32); @@ -629,7 +627,7 @@ impl Game<'_> { .chat_opened .map_or(0, |t| t.elapsed().as_millis() as u64); let draws = screen.draw(&m, mouse, blink, background); - horizon_client::screen_draw::paint(batch, &self.res.atlas, &draws); + horizon_client::screen_draw::paint(batch, &self.atlas, &draws); self.ui.chat_screen = Some(screen); } /// Advance the overworld clock (ServerClockManager.tick) when @@ -821,11 +819,11 @@ impl Game<'_> { let focused = self.screen == Screen::Chat; self.ui .chat - .add(&self.res.atlas, message, None, self.ticks, focused); + .add(&self.atlas, message, None, self.ticks, focused); } #[allow(dead_code)] fn chat_debug_fill(&self, batch: &mut HudBatch) { - batch.fill(&self.res.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0)); + batch.fill(&self.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0)); } } /// `yyyy-MM-dd_HH.mm.ss[_n].png` (Util.getFilenameFormattedDateTime, local time diff --git a/crates/horizon-client/src/game/clipboard.rs b/crates/horizon-client/src/game/clipboard.rs index 17a634c9a..b9558ddfd 100644 --- a/crates/horizon-client/src/game/clipboard.rs +++ b/crates/horizon-client/src/game/clipboard.rs @@ -46,6 +46,9 @@ impl Game<'_> { let Some(title) = self.title.as_mut() else { return; }; + if title.has_caret_field() { + return title.field_shortcut(shortcut, &mut self.clipboard); + } if let Some((id, value, max)) = title.focused_field() { let changed = Self::append_shortcut( &mut self.text_selection, @@ -60,15 +63,16 @@ impl Game<'_> { } } } - /// Typing or a backspace in an append-only field of the title screens: - /// Select All's selection is replaced first. + /// Typing or a backspace in a field of the title screens: in the server + /// screens' append-only fields Select All's selection is replaced first. pub(super) fn title_edit(&mut self, typed: Option<&str>, backspace: bool) { let Some(title) = self.title.as_mut() else { return; }; - let cleared = title - .focused_field() - .is_some_and(|(id, value, _)| self.text_selection.take(id, value)); + let cleared = !title.has_caret_field() + && title + .focused_field() + .is_some_and(|(id, value, _)| self.text_selection.take(id, value)); if cleared { title.search_changed(); } diff --git a/crates/horizon-client/src/game/command_blocks.rs b/crates/horizon-client/src/game/command_blocks.rs new file mode 100644 index 000000000..5a5fa11c8 --- /dev/null +++ b/crates/horizon-client/src/game/command_blocks.rs @@ -0,0 +1,638 @@ +//! Command blocks: `CommandBlock`'s placement (`setPlacedBy`), its scheduled +//! tick (`execute`, `executeChain`), `BaseCommandBlock.performCommand` +//! through the command system with the block's output, and +//! `CommandBlockEditScreen` with what `handleSetCommandBlock` does with it. +use super::{Game, Screen, commands::execute::Source}; +use horizon_client::{ + command_block::{self, CommandBlock, Mode}, + containers::BlockEntity, + hud::{HudBatch, rgba}, + text::{self, Text}, + ui::{self, EditBox}, + world::World, +}; +use horizon_core::position::BlockPos; +use horizon_world::{ + chunk::BlockState, + level::flags, + registry::{BlockRegistry, BlockStateId}, +}; +use winit::{ + event::{ElementState, KeyEvent}, + keyboard::{KeyCode, PhysicalKey}, +}; + +type Pos = (i32, i32, i32); + +/// The open `CommandBlockEditScreen`. +pub(super) struct CommandBlockScreen { + pos: Pos, + command: EditBox, + previous: EditBox, + track_output: bool, + mode: Mode, + conditional: bool, + auto: bool, +} + +#[derive(Clone, Copy, PartialEq)] +enum Button { + Output, + Mode, + Conditional, + Auto, + Done, + Cancel, +} + +/// `EditBox.textColorUneditable`. +const UNEDITABLE: u32 = 0xFF70_7070; + +impl CommandBlockScreen { + /// `AbstractCommandBlockEditScreen.init` and `CommandBlockEditScreen`'s + /// buttons, in GUI pixels of a `w`×`h` screen. + fn buttons(w: f32, h: f32) -> [(Button, f32, f32, f32); 6] { + let mid = (w / 2.0).floor(); + let low = (h / 4.0).floor() + 132.0; + [ + (Button::Output, mid + 130.0, 135.0, 20.0), + (Button::Mode, mid - 154.0, 165.0, 100.0), + (Button::Conditional, mid - 50.0, 165.0, 100.0), + (Button::Auto, mid + 54.0, 165.0, 100.0), + (Button::Done, mid - 154.0, low, 150.0), + (Button::Cancel, mid + 4.0, low, 150.0), + ] + } + fn label(&self, b: Button) -> Text { + let tr = |key: &str| Text::translate(key, &[]); + match b { + Button::Output => Text::literal(if self.track_output { "O" } else { "X" }), + Button::Mode => tr(self.mode.label()), + Button::Conditional => tr(if self.conditional { + "advMode.mode.conditional" + } else { + "advMode.mode.unconditional" + }), + Button::Auto => tr(if self.auto { + "advMode.mode.autoexec.bat" + } else { + "advMode.mode.redstoneTriggered" + }), + Button::Done => tr("gui.done"), + Button::Cancel => tr("gui.cancel"), + } + } + /// `updatePreviousOutput`. + fn show_previous(&mut self, block: &CommandBlock) { + let shown = if self.track_output { + block.last_output_string() + } else { + "-".to_owned() + }; + self.previous.set_value(&shown); + } +} + +fn state_of(registry: &BlockRegistry, state: BlockStateId) -> Option<&BlockState> { + registry.state(state) +} +fn facing_step(state: &BlockState) -> [i32; 3] { + match state.properties.get("facing").map(String::as_str) { + Some("down") => [0, -1, 0], + Some("up") => [0, 1, 0], + Some("south") => [0, 0, 1], + Some("west") => [-1, 0, 0], + Some("east") => [1, 0, 0], + _ => [0, 0, -1], + } +} +/// `Direction.toYRot`: south 0, west 90, north 180, east (and up/down) 270. +fn facing_yaw(state: &BlockState) -> f32 { + match state.properties.get("facing").map(String::as_str) { + Some("south") => 0.0, + Some("west") => 90.0, + Some("north") => 180.0, + _ => 270.0, + } +} +fn conditional(state: &BlockState) -> bool { + state + .properties + .get("conditional") + .is_some_and(|c| c == "true") +} +fn offset(pos: Pos, step: [i32; 3]) -> Pos { + (pos.0 + step[0], pos.1 + step[1], pos.2 + step[2]) +} +fn command_block_mut(world: &mut World, pos: Pos) -> Option<&mut CommandBlock> { + match world.block_entities.get_mut(&pos)? { + BlockEntity::CommandBlock(c) => Some(c), + _ => None, + } +} + +/// `CommandBlockEntity.markConditionMet`: a conditional block needs the +/// command block behind it to have succeeded. +pub(super) fn mark_condition_met(world: &mut World, registry: &BlockRegistry, pos: Pos) -> bool { + let Some(state) = state_of(registry, world.block(pos.0, pos.1, pos.2)) else { + return false; + }; + let mut met = true; + if conditional(state) { + let back = facing_step(state).map(|v| -v); + let behind = offset(pos, back); + let behind_block = state_of(registry, world.block(behind.0, behind.1, behind.2)) + .is_some_and(|s| Mode::of_block(&s.name).is_some()); + met = behind_block + && matches!(world.block_entities.get(&behind), + Some(BlockEntity::CommandBlock(c)) if c.success_count > 0); + } + if let Some(c) = command_block_mut(world, pos) { + c.condition_met = met; + } + met +} + +/// `CommandBlockEntity.setPowered` from `CommandBlock.setPoweredAndUpdate` +/// (the level's neighbour hook): the previous flag and `isAutomatic`; a +/// rising signal that will tick the block checks its condition. +pub(super) fn set_powered( + world: &mut World, + registry: &BlockRegistry, + pos: Pos, + powered: bool, +) -> Option<(bool, bool)> { + let mode = state_of(registry, world.block(pos.0, pos.1, pos.2)) + .and_then(|s| Mode::of_block(&s.name))?; + let c = command_block_mut(world, pos)?; + let (was, auto) = (c.powered, c.auto); + c.powered = powered; + if command_block::power_schedules(mode, was, powered, auto) { + mark_condition_met(world, registry, pos); + } + Some((was, auto)) +} + +/// `getAnalogOutputSignal`: the success count. +pub(super) fn analog_signal(world: &World, pos: Pos) -> Option { + match world.block_entities.get(&pos)? { + BlockEntity::CommandBlock(c) => Some(c.success_count), + _ => None, + } +} + +impl Game<'_> { + /// `Player.canUseGameMasterBlocks`: creative with game master commands. + pub(super) fn can_use_game_master_blocks(&self) -> bool { + self.creative && self.ui.registries.permission >= 2 + } + fn command_block(&self, pos: Pos) -> Option<&CommandBlock> { + match self.world.block_entities.get(&pos)? { + BlockEntity::CommandBlock(c) => Some(c), + _ => None, + } + } + fn block_state_at(&self, pos: Pos) -> Option<&'static BlockState> { + let registry = self.pack.assets.registry; + state_of(registry, self.world.block(pos.0, pos.1, pos.2)) + } + fn schedule_command_block(&mut self, pos: Pos) { + let at = BlockPos::new(pos.0, pos.1, pos.2); + self.with_level(|b, level, ticks| b.schedule_tick(level, ticks, at, 1)); + } + /// `CommandBlockEntity.scheduleTick`. + fn schedule_command_block_tick(&mut self, pos: Pos) { + mark_condition_met(&mut self.world, self.pack.assets.registry, pos); + self.schedule_command_block(pos); + } + fn update_output_signal(&mut self, pos: Pos) { + let at = BlockPos::new(pos.0, pos.1, pos.2); + self.with_level(|b, level, ticks| b.update_neighbour_for_output_signal(level, ticks, at)); + } + + /// `CommandBlock.setPlacedBy`: unless the item carried block entity data + /// (`defaults` false), output tracking follows `send_command_feedback` and + /// the block's own automatic flag; then the block takes the signal around it. + pub(super) fn command_block_placed(&mut self, pos: Pos, defaults: bool) { + let feedback = self.ui.rules.bool("send_command_feedback"); + let Some(name) = self.block_state_at(pos).map(|s| s.name.as_str()) else { + return; + }; + let auto = command_block::automatic_block(name); + if defaults && let Some(c) = command_block_mut(&mut self.world, pos) { + c.track_output = feedback; + c.auto = auto; + } + let at = BlockPos::new(pos.0, pos.1, pos.2); + let signal = self.with_level(|b, level, ticks| b.has_neighbor_signal(level, ticks, at)); + let registry = self.pack.assets.registry; + if let Some((was, auto)) = set_powered(&mut self.world, registry, pos, signal) + && signal + && !was + && !auto + && !command_block::automatic_block(name) + { + self.schedule_command_block(pos); + } + } + + /// `CommandBlock.tick`. + pub(super) fn command_block_tick(&mut self, pos: BlockPos) { + let key = (pos.x, pos.y, pos.z); + let Some(state) = self.block_state_at(key) else { + return; + }; + let Some(mode) = Mode::of_block(&state.name) else { + return; + }; + let Some(was_met) = self.command_block(key).map(|c| c.condition_met) else { + return; + }; + if mode == Mode::Auto { + mark_condition_met(&mut self.world, self.pack.assets.registry, key); + } + match command_block::tick_action(mode, was_met, conditional(state)) { + Some(true) => self.command_block_execute(key, state), + Some(false) => { + if let Some(c) = command_block_mut(&mut self.world, key) { + c.success_count = 0; + } + } + None => {} + } + if let Some(c) = self.command_block(key) + && command_block::repeats(mode, c.powered, c.auto) + { + self.schedule_command_block(key); + } + self.update_output_signal(key); + } + /// `CommandBlock.execute`: the command (or no successes without one), + /// then the chain in front. + fn command_block_execute(&mut self, pos: Pos, state: &BlockState) { + let has_command = self + .command_block(pos) + .is_some_and(|c| !c.command.is_empty()); + if has_command { + self.perform_command_block(pos); + } else if let Some(c) = command_block_mut(&mut self.world, pos) { + c.success_count = 0; + } + self.execute_chain(pos, facing_step(state)); + } + /// `CommandBlock.executeChain`: the chain command blocks in front, each + /// facing on to the next, up to `max_command_sequence_length`. + fn execute_chain(&mut self, start: Pos, mut step: [i32; 3]) { + let registry = self.pack.assets.registry; + let limit = self.ui.rules.int("max_command_sequence_length"); + let mut remaining = limit; + let mut pos = start; + while remaining > 0 { + remaining -= 1; + pos = offset(pos, step); + let Some(state) = self.block_state_at(pos) else { + break; + }; + if Mode::of_block(&state.name) != Some(Mode::Sequence) { + break; + } + let Some(c) = self.command_block(pos) else { + break; + }; + if c.powered || c.auto { + if mark_condition_met(&mut self.world, registry, pos) { + if !self.perform_command_block(pos) { + break; + } + self.update_output_signal(pos); + } else if conditional(state) + && let Some(c) = command_block_mut(&mut self.world, pos) + { + c.success_count = 0; + } + } + step = facing_step(state); + } + if remaining <= 0 { + log::warn!( + "Command Block chain tried to execute more than {} steps!", + limit.max(0) + ); + } + } + /// `BaseCommandBlock.performCommand`: runs the command as the block, at + /// game master level, counting the successful results. False when it + /// already ran this game tick. + fn perform_command_block(&mut self, pos: Pos) -> bool { + let game_time = self.world.game_time; + let Some(c) = command_block_mut(&mut self.world, pos) else { + return false; + }; + if c.last_execution == game_time { + return false; + } + if c.command.eq_ignore_ascii_case("Searge") { + c.last_output = Some(Text::literal("#itzlipofutzli")); + c.success_count = 1; + return true; + } + c.success_count = 0; + let command = c.command.clone(); + if self.ui.rules.bool("command_blocks_work") && !command.is_empty() { + if let Some(c) = command_block_mut(&mut self.world, pos) { + c.last_output = None; + } + let Some(state) = self.block_state_at(pos) else { + return false; + }; + let source = Source { + entity: None, + pos: [ + f64::from(pos.0) + 0.5, + f64::from(pos.1) + 0.5, + f64::from(pos.2) + 0.5, + ], + rot: [facing_yaw(state), 0.0], + eyes: false, + silent: false, + store: None, + elsewhere: false, + block: Some(pos), + }; + // performPrefixedCommand: a leading slash is allowed. + let line = command.strip_prefix('/').unwrap_or(&command).to_owned(); + let outer = self.cmds.results.replace(Vec::new()); + let level = std::mem::replace(&mut self.ui.registries.permission, 2); + self.with_source(source, |g| g.run_command(&line)); + self.ui.registries.permission = level; + let results = std::mem::replace(&mut self.cmds.results, outer).unwrap_or_default(); + let successes = results.iter().filter(|(success, _)| *success).count(); + if let Some(c) = command_block_mut(&mut self.world, pos) { + c.success_count = successes as i32; + } + } + if let Some(c) = command_block_mut(&mut self.world, pos) { + c.last_execution = if c.update_last_execution { + game_time + } else { + -1 + }; + } + true + } + /// `CloseableCommandBlockSource.sendSystemMessage`: the block's last + /// output, stamped with the time. Nothing when it doesn't track output + /// (`CommandSource.NULL`). + pub(super) fn command_block_output(&mut self, pos: Pos, message: Text) { + if let Some(c) = command_block_mut(&mut self.world, pos) + && c.track_output + { + let time = chrono::Local::now().format("[%H:%M:%S] ").to_string(); + c.last_output = Some(Text::literal(time).append(message)); + } + } + /// `CommandSourceStack.sendSuccess` from a command block: its output when + /// `send_command_feedback`, and `broadcastToAdmins` when + /// `command_block_output`. + pub(super) fn command_block_success(&mut self, pos: Pos, message: Text) { + let Some(name) = self + .command_block(pos) + .filter(|c| c.track_output) + .map(CommandBlock::name) + else { + return; + }; + let feedback = self.ui.rules.bool("send_command_feedback"); + if feedback { + self.command_block_output(pos, message.clone()); + } + if feedback && self.ui.rules.bool("command_block_output") { + let broadcast = Text::translate("chat.type.admin", &[name, message]) + .with_color(text::GRAY) + .italic(); + self.system_message(broadcast); + } + } + + /// `LocalPlayer.openCommandBlock`. + pub(super) fn open_command_block(&mut self, pos: Pos) { + let Some(block) = self.command_block(pos).cloned() else { + return; + }; + let Some(state) = self.block_state_at(pos) else { + return; + }; + let mut command = EditBox::new(0.0, 50.0, 300.0, 20.0); + command.max_length = 32500; + command.set_value(&block.command); + command.focused = true; + let mut previous = EditBox::new(0.0, 135.0, 276.0, 20.0); + previous.max_length = 32500; + previous.text_color = UNEDITABLE; + previous.focused = false; + let mut screen = CommandBlockScreen { + pos, + command, + previous, + track_output: block.track_output, + mode: Mode::of_block(&state.name).unwrap_or(Mode::Redstone), + conditional: conditional(state), + auto: block.auto, + }; + screen.show_previous(&block); + self.command_block_screen = Some(screen); + self.screen = Screen::CommandBlock; + self.capture(false); + } + pub(super) fn close_command_block(&mut self) { + self.command_block_screen = None; + self.screen = Screen::Playing; + self.capture(true); + } + pub(super) fn draw_command_block(&mut self, batch: &mut HudBatch) { + let Some(mut s) = self.command_block_screen.take() else { + return; + }; + // AbstractCommandBlockEditScreen.tick: the block is gone. + if self.command_block(s.pos).is_none() { + self.close_command_block(); + return; + } + let atlas = &self.atlas; + let (w, h) = (batch.width, batch.height); + let mid = (w / 2.0).floor(); + ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); + let title = Text::translate("advMode.setCommand", &[]); + let tw = atlas.font.width_text(&title); + batch.text_styled( + atlas, + &title, + (mid - tw / 2.0).floor(), + 20.0, + u32::MAX, + true, + ); + let grey = rgba(160, 160, 160, 255); + let label = Text::translate("advMode.command", &[]); + batch.text_styled(atlas, &label, mid - 149.0, 40.0, grey, true); + s.command.x = mid - 150.0; + s.command.draw(batch, atlas, None); + if !s.previous.value.is_empty() { + let label = Text::translate("advMode.previousOutput", &[]); + batch.text_styled(atlas, &label, mid - 149.0, 125.0, grey, true); + s.previous.x = mid - 150.0; + s.previous.draw(batch, atlas, None); + } + for (b, x, y, bw) in CommandBlockScreen::buttons(w, h) { + let hover = ui::hovered(self.cursor, x, y, bw, 20.0); + ui::button(batch, atlas, x, y, bw, 20.0, &s.label(b), true, hover); + } + self.command_block_screen = Some(s); + } + pub(super) fn command_block_click(&mut self) { + let Some(mut s) = self.command_block_screen.take() else { + return; + }; + let size = self + .renderer + .as_ref() + .map_or([1, 1], |r| [r.config.width, r.config.height]); + let b = HudBatch::new(size); + let hit = CommandBlockScreen::buttons(b.width, b.height) + .into_iter() + .find(|(_, x, y, bw)| ui::hovered(self.cursor, *x, *y, *bw, 20.0)) + .map(|b| b.0); + if hit.is_some() { + self.audio.play_button_click(); + } + match hit { + Some(Button::Output) => { + s.track_output = !s.track_output; + if let Some(block) = self.command_block(s.pos) { + s.show_previous(block); + } + } + Some(Button::Mode) => s.mode = s.mode.next(), + Some(Button::Conditional) => s.conditional = !s.conditional, + Some(Button::Auto) => s.auto = !s.auto, + Some(Button::Done) => { + self.set_command_block(&s); + self.close_command_block(); + return; + } + Some(Button::Cancel) => { + self.close_command_block(); + return; + } + None => {} + } + self.command_block_screen = Some(s); + } + /// `AbstractCommandBlockEditScreen.keyPressed`: Enter is Done, Escape + /// cancels, the rest edits the command. + pub(super) fn command_block_key(&mut self, event: &KeyEvent) { + if event.state != ElementState::Pressed { + return; + } + let PhysicalKey::Code(key) = event.physical_key else { + return; + }; + match key { + KeyCode::Escape => return self.close_command_block(), + KeyCode::Enter | KeyCode::NumpadEnter => { + if let Some(s) = self.command_block_screen.take() { + self.set_command_block(&s); + } + return self.close_command_block(); + } + _ => {} + } + let ctrl = self.keys.contains(&KeyCode::ControlLeft); + let shift = self.keys.contains(&KeyCode::ShiftLeft); + let shortcut = self.edit_shortcut(event); + let Some(s) = self.command_block_screen.as_mut() else { + return; + }; + if let Some(shortcut) = shortcut { + s.command.shortcut(shortcut, &mut self.clipboard); + } else if !s.command.key(key, ctrl, shift) && !ctrl { + self.command_block_type(event.text.as_deref().unwrap_or("")); + } + } + /// Characters typed into the command box (`StringUtil.isAllowedChatCharacter`). + pub(super) fn command_block_type(&mut self, typed: &str) { + let allowed: String = typed + .chars() + .filter(|&c| c != '\u{a7}' && c >= ' ' && c != '\u{7f}') + .collect(); + if let Some(s) = self.command_block_screen.as_mut() + && !allowed.is_empty() + { + s.command.insert_text(&allowed); + } + } + /// `ServerGamePacketListenerImpl.handleSetCommandBlock`. + fn set_command_block(&mut self, s: &CommandBlockScreen) { + if !self.can_use_game_master_blocks() { + self.system_message(Text::translate("advMode.notAllowed", &[])); + return; + } + let pos = s.pos; + let registry = self.pack.assets.registry; + let Some(current) = self.block_state_at(pos) else { + return; + }; + let Some(old_mode) = Mode::of_block(¤t.name) else { + return; + }; + if self.command_block(pos).is_none() { + return; + } + // The mode is the block, the conditional flag its state; the block + // entity stays. + let mut wanted = current.clone(); + wanted.name = s.mode.block().to_owned(); + wanted + .properties + .insert("conditional".into(), s.conditional.to_string()); + if let Ok(id) = registry.resolve(&wanted) + && wanted != *current + { + let entity = self.world.block_entities.remove(&pos); + let at = BlockPos::new(pos.0, pos.1, pos.2); + self.with_level(|b, level, ticks| { + b.set_block(level, ticks, at, id, flags::UPDATE_CLIENTS) + }); + if let Some(entity) = entity { + self.world.block_entities.insert(pos, entity); + } + let _ = self.process_level_events(); + } + let command = s.command.value.clone(); + let Some(c) = command_block_mut(&mut self.world, pos) else { + return; + }; + c.set_command(&command); + c.track_output = s.track_output; + if !s.track_output { + c.last_output = None; + } + // CommandBlockEntity.setAutomatic, then onModeSwitch. + let (was_auto, powered) = (c.auto, c.powered); + c.auto = s.auto; + if !was_auto && s.auto && !powered && s.mode != Mode::Sequence { + self.schedule_command_block_tick(pos); + } + if old_mode != s.mode && s.mode == Mode::Auto && (powered || s.auto) { + self.schedule_command_block_tick(pos); + } + if !command.is_empty() { + let key = if self.ui.rules.bool("command_blocks_work") { + "advMode.setCommand.success" + } else { + "advMode.setCommand.disabled" + }; + self.system_message(Text::translate(key, &[Text::literal(command)])); + } + } +} diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index a7385914b..6c4817f63 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -143,13 +143,22 @@ impl Game<'_> { if self.command_source.is_some_and(|s| s.silent) { return; } - self.system_message(Text::empty().append(message).with_color(text::RED)); + let message = Text::empty().append(message).with_color(text::RED); + if let Some(block) = self.command_source.and_then(|s| s.block) { + self.command_block_output(block, message); + return; + } + self.system_message(message); } /// sendSuccess honouring `send_command_feedback`. pub(super) fn feedback(&mut self, message: Text) { if self.command_source.is_some_and(|s| s.silent) { return; } + if let Some(block) = self.command_source.and_then(|s| s.block) { + self.command_block_success(block, message); + return; + } if self.ui.rules.bool("send_command_feedback") { self.system_message(message); } @@ -315,11 +324,15 @@ impl Game<'_> { /// Entity.getDisplayName. pub(super) fn target_name(&self, t: Target) -> Text { match t { - Target::Player => match self.score.board.players_team(PLAYER_NAME) { - // PlayerTeam.formatNameForTeam. - Some(team) => team.formatted_name(Text::literal(PLAYER_NAME)), - None => Text::literal(PLAYER_NAME), - }, + Target::Player => { + // A guest's commands name the guest. + let name = self.lan_acting_name.as_deref().unwrap_or(PLAYER_NAME); + match self.score.board.players_team(name) { + // PlayerTeam.formatNameForTeam. + Some(team) => team.formatted_name(Text::literal(name)), + None => Text::literal(name), + } + } Target::Item(id) => { let item = self .dropped @@ -327,7 +340,7 @@ impl Game<'_> { .find(|i| i.id == id) .map(|i| i.stack.item.to_string()) .unwrap_or_default(); - Text::literal(self.res.names.item(&item)) + Text::literal(self.pack.names.item(&item)) } Target::Mob(id) if self @@ -770,7 +783,7 @@ impl Game<'_> { _ => text::WHITE, }; Text::literal("[") - .append(Text::literal(self.res.names.item(item))) + .append(Text::literal(self.pack.names.item(item))) .append("]") .with_color(color) } @@ -803,7 +816,7 @@ impl Game<'_> { &[], ) } else { - Text::literal(self.res.names.item(item)) + Text::literal(self.pack.names.item(item)) }; let wrapped = Text::translate("chat.square_brackets", &[hover]); if empty { @@ -1443,7 +1456,7 @@ impl Game<'_> { name: b.id.clone(), properties: b.properties.iter().cloned().collect(), }; - self.res + self.pack .assets .registry .resolve(&state) @@ -1451,7 +1464,7 @@ impl Game<'_> { } /// BlockPredicateArgument test. fn block_matches(&self, b: &BlockInput, state: BlockStateId) -> bool { - let Some(s) = self.res.assets.registry.state(state) else { + let Some(s) = self.pack.assets.registry.state(state) else { return false; }; let name_ok = if b.tag { @@ -1726,7 +1739,7 @@ impl Game<'_> { let strict = ctx.has("strict"); // CloneCommands.clone sets every destination to a barrier first, so // each copied state but a barrier counts as placed. - let barrier = self.res.assets.registry.default_state("minecraft:barrier"); + let barrier = self.pack.assets.registry.default_state("minecraft:barrier"); let mut count = 0; for (_, to, s, entity) in copies { self.place_state(to, s, strict)?; @@ -2253,7 +2266,7 @@ impl Game<'_> { } /// `PoiTypes`: the point of interest type of a block state. fn poi_type(&self, state: horizon_world::registry::BlockStateId) -> Option<&'static str> { - let s = self.res.assets.registry.state(state)?; + let s = self.pack.assets.registry.state(state)?; let name = s.name.strip_prefix("minecraft:")?; Some(match name { "blast_furnace" => "minecraft:armorer", @@ -2529,7 +2542,7 @@ impl Game<'_> { let focused = self.screen == Screen::Chat; self.ui .chat - .add(&self.res.atlas, line, None, self.ticks, focused); + .add(&self.atlas, line, None, self.ticks, focused); Ok(1) } /// MessageArgument: `@p`-style selectors in a message become names. diff --git a/crates/horizon-client/src/game/commands/compute.rs b/crates/horizon-client/src/game/commands/compute.rs index 8ffcfac03..24552011d 100644 --- a/crates/horizon-client/src/game/commands/compute.rs +++ b/crates/horizon-client/src/game/commands/compute.rs @@ -494,7 +494,7 @@ impl Game<'_> { return false; }; let state = self.world.block(p[0], p[1], p[2]); - let Some(s) = self.res.assets.registry.state(state) else { + let Some(s) = self.pack.assets.registry.state(state) else { return false; }; let name = s.name.to_string(); diff --git a/crates/horizon-client/src/game/commands/data.rs b/crates/horizon-client/src/game/commands/data.rs index a10fff3bd..1d2321a1a 100644 --- a/crates/horizon-client/src/game/commands/data.rs +++ b/crates/horizon-client/src/game/commands/data.rs @@ -180,7 +180,7 @@ impl Game<'_> { } pub(in crate::game) fn data_block_name(&self, p: [i32; 3]) -> String { let state = self.world.block(p[0], p[1], p[2]); - self.res + self.pack .assets .registry .state(state) diff --git a/crates/horizon-client/src/game/commands/effects.rs b/crates/horizon-client/src/game/commands/effects.rs index ffa44d745..3e04f7179 100644 --- a/crates/horizon-client/src/game/commands/effects.rs +++ b/crates/horizon-client/src/game/commands/effects.rs @@ -227,7 +227,7 @@ impl Game<'_> { return Err(err( "commands.enchant.failed.incompatible", &[&stack.custom_name().map_or_else( - || self.res.names.item(&stack.item).to_string(), + || self.pack.names.item(&stack.item).to_string(), str::to_owned, )], )); @@ -247,7 +247,7 @@ impl Game<'_> { ), Some(item) => err( "commands.enchant.failed.incompatible", - &[&self.res.names.item(&item)], + &[&self.pack.names.item(&item)], ), }); } diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index a913b07c5..1fa67c8b6 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -26,6 +26,9 @@ pub(in crate::game) struct Source { /// `execute in` another dimension than the one Horizon has loaded: none /// of its chunks are loaded. pub elsewhere: bool, + /// The command block whose output this source is + /// (`BaseCommandBlock.CloseableCommandBlockSource`). + pub block: Option<(i32, i32, i32)>, } /// Where `execute store` writes. @@ -74,6 +77,7 @@ impl Game<'_> { silent: false, store: None, elsewhere: false, + block: None, } } /// The server as a source (function ticks and schedules): the world spawn. @@ -86,6 +90,7 @@ impl Game<'_> { silent: true, store: None, elsewhere: false, + block: None, } } pub(super) fn target_rotation(&self, t: Target) -> [f32; 2] { @@ -647,7 +652,7 @@ impl Game<'_> { let facts = self.res.facts.get(state); let blocks = facts.legacy_solid || facts.fluid != horizon_client::blocks::Fluid::None; let leaves = self - .res + .pack .assets .registry .state(state) diff --git a/crates/horizon-client/src/game/commands/place.rs b/crates/horizon-client/src/game/commands/place.rs index 502cb53f4..3e447a7fb 100644 --- a/crates/horizon-client/src/game/commands/place.rs +++ b/crates/horizon-client/src/game/commands/place.rs @@ -25,7 +25,7 @@ impl Game<'_> { .join("worldgen/blocks/structure-blocks.json"), ) .ok()?; - StateTransforms::from_json(&json, self.res.assets.registry.len()).ok() + StateTransforms::from_json(&json, self.pack.assets.registry.len()).ok() }) .as_ref() } @@ -64,7 +64,7 @@ impl Game<'_> { }; return Some(Arc::new(StructureTemplate::from_nbt( &named.tag, - self.res.assets.registry, + self.pack.assets.registry, transforms, ))); } diff --git a/crates/horizon-client/src/game/commands/terrain_cmds.rs b/crates/horizon-client/src/game/commands/terrain_cmds.rs index 048a7c71c..cee7a1d72 100644 --- a/crates/horizon-client/src/game/commands/terrain_cmds.rs +++ b/crates/horizon-client/src/game/commands/terrain_cmds.rs @@ -551,14 +551,14 @@ impl Game<'_> { Some(seq) => { let random = self.rand_sequences.get(&seq, self.level.seed); self.res.items.block_drops( - self.res.assets.registry, + self.pack.assets.registry, state, tool.as_ref(), random, ) } None => self.res.items.block_drops( - self.res.assets.registry, + self.pack.assets.registry, state, tool.as_ref(), &mut self.world.random, diff --git a/crates/horizon-client/src/game/composter.rs b/crates/horizon-client/src/game/composter.rs index 942e02eda..3e4cb7169 100644 --- a/crates/horizon-client/src/game/composter.rs +++ b/crates/horizon-client/src/game/composter.rs @@ -13,7 +13,7 @@ impl Game<'_> { /// The composter's `level` at `pos`, None when it isn't a composter. pub(super) fn composter_level(&self, pos: [i32; 3]) -> Option { let state = self.world.block(pos[0], pos[1], pos[2]); - let s = self.res.assets.registry.state(state)?; + let s = self.pack.assets.registry.state(state)?; if &*s.name != "minecraft:composter" { return None; } diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 921ca03db..e1169b2c8 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -11,7 +11,7 @@ use winit::{event::MouseButton, event_loop::ActiveEventLoop, keyboard::KeyCode}; const HELP: &[&str] = &[ "status game, player, streaming and renderer state", - "key KEY down|up|tap press or release a key (w a s d space shift ctrl e q esc f3 1-9 arrows ...)", + "key KEY down|up|tap|repeat press, release or auto-repeat a key (w a s d space shift ctrl e q esc f3 1-9 arrows ...)", "release release every key and mouse button", "mouse left|right|middle down|up|click", "look YAW PITCH set the view direction in degrees", @@ -201,7 +201,7 @@ impl Game<'_> { } // The zoom extra sees the key as the keyboard hook does. let action = arg(2)?; - self.extras_key(physical, action != "up", false); + self.extras_key(physical, action != "up", action == "repeat"); if action == "tap" { self.extras_key(physical, false, false); } @@ -233,6 +233,11 @@ impl Game<'_> { self.keys.remove(&key); self.physical_keys.remove(&key); } + // The system's auto-repeat while the key is held. + "repeat" => { + self.physical_keys.insert(physical); + self.mapped_key(key, true, true)?; + } "tap" => { self.control_key_down(key)?; self.keys.remove(&key); @@ -240,9 +245,10 @@ impl Game<'_> { self.debug_key(physical, horizon_client::debug_keys::KeyAction::Release); } other => { - return Err( - format!("key action must be down, up or tap, not {other}").into() - ); + return Err(format!( + "key action must be down, up, tap or repeat, not {other}" + ) + .into()); } } ok() @@ -420,7 +426,11 @@ impl Game<'_> { } match self.screen { Screen::Chat => self.chat_type(text), - Screen::Options => self.ui.options.type_text(&self.res.atlas, text), + Screen::CommandBlock => self.command_block_type(text), + Screen::Options => self.ui.options.type_text(&self.atlas, text), + // The port, or the game rules' search and number boxes. + Screen::WorldOptions if text == "\\b" => self.world_options_text(None), + Screen::WorldOptions => self.world_options_text(Some(text)), Screen::Inventory if self.recipe_search_focused() => { self.recipe_text(Some(text), false) } @@ -430,7 +440,7 @@ impl Game<'_> { } _ => { return Err( - "type needs the chat screen (key t tap), the language search or the creative search".into(), + "type needs the chat screen (key t tap), the language search, the creative search or World Options".into(), ); } } @@ -580,6 +590,18 @@ impl Game<'_> { fn control_key_down(&mut self, key: KeyCode) -> Result<()> { self.physical_keys.insert(key); + // A server's chat input takes the keys first, as remote_chat_key does. + if self.remote_chat_open() { + use winit::keyboard::NamedKey; + let named = match key { + KeyCode::Escape => Some(NamedKey::Escape), + KeyCode::Enter | KeyCode::NumpadEnter => Some(NamedKey::Enter), + KeyCode::Backspace => Some(NamedKey::Backspace), + _ => None, + }; + self.remote_chat_input(named, None); + return Ok(()); + } if self.screen == Screen::Chat { self.chat_key_code(key, None); return Ok(()); @@ -609,6 +631,7 @@ impl Game<'_> { Screen::Stats => "stats", Screen::Advancements => "advancements", Screen::WorldOptions => "world-options", + Screen::CommandBlock => "command-block", } } diff --git a/crates/horizon-client/src/game/copper_golems.rs b/crates/horizon-client/src/game/copper_golems.rs index 7cb6f946a..a12fbd416 100644 --- a/crates/horizon-client/src/game/copper_golems.rs +++ b/crates/horizon-client/src/game/copper_golems.rs @@ -168,7 +168,7 @@ impl Game<'_> { ] .into(), }; - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let Some(id) = registry.id(&state) else { return; }; diff --git a/crates/horizon-client/src/game/creaking.rs b/crates/horizon-client/src/game/creaking.rs index c87c98f7a..1caa419ff 100644 --- a/crates/horizon-client/src/game/creaking.rs +++ b/crates/horizon-client/src/game/creaking.rs @@ -84,7 +84,7 @@ impl HeartHost for Host<'_> { impl Game<'_> { fn heart_state_name(&self, state: BlockStateId) -> String { - self.res + self.pack .assets .registry .state(state) @@ -177,7 +177,7 @@ impl Game<'_> { } /// `Creaking.tearDown`: the crumble particles. pub(super) fn creaking_tear_down(&mut self, center: [f64; 3], spread: [f64; 3]) { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let crumble = |this: &mut Self, name: &str, props: &[(&str, &str)], count: i32| { let Some(mut state) = registry .default_state(name) @@ -229,7 +229,7 @@ impl Game<'_> { }); let state = self.world.block(key.0, key.1, key.2); let natural = self - .res + .pack .assets .registry .state(state) @@ -297,7 +297,7 @@ impl Game<'_> { /// entity (`newBlockEntity`) the first time their chunk is seen. fn scan_for_hearts(&mut self) { let Some(heart) = self - .res + .pack .assets .registry .default_state("minecraft:creaking_heart") diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 5adf6832b..32f92a43f 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -378,13 +378,14 @@ impl Game<'_> { let (rain, thunder) = self.world.weather.levels(1.0); MobWorld { world: &self.world, - registry: self.res.assets.registry, + registry: self.pack.assets.registry, facts: &self.res.facts, movement: &self.motion.blocks, collision: self.collision, data: &self.res.mob_data, player: self.player_view(), others, + others_grid: None, daylight: self.dim != Dim::Nether && self.sky_darken() < 4, game_time: self.world.game_time, day_time: self.world.day_time, @@ -514,6 +515,13 @@ impl Game<'_> { let mut dead = Vec::new(); let mut died = std::mem::take(&mut self.died); let ticking = self.entity_ticking_area(); + // With guests on, each mob sees its nearest player (game/lan_mobs.rs). + let guests = self.lan_guest_views(); + let mut bindings = match self.lan.as_mut() { + Some(host) if !guests.is_empty() => std::mem::take(&mut host.mob_players), + _ => Default::default(), + }; + let mut guest_events = Vec::new(); let level_random; { // The level random, lent to the mobs (brain behaviours draw from @@ -521,9 +529,28 @@ impl Game<'_> { let mut scratch = self.world.random.clone(); let mut pushes = Vec::new(); let mut keep = Vec::with_capacity(mobs.len()); + let mut grid = + horizon_client::mobs::seen_grid::SeenGrid::new(snapshot.iter().map(|s| s.bounds)); for i in 0..mobs.len() { - let w = self.mob_world_base(&snapshot); + let mut w = self.mob_world_base(&snapshot); + w.others_grid = Some(&grid); let m = &mut mobs[i]; + let seen_guest = if guests.is_empty() { + None + } else { + let bound = bindings.get(&m.id).copied(); + let conn = super::lan_mobs::player_for(m, w.player.as_ref(), &guests, bound); + match conn { + Some(conn) => { + bindings.insert(m.id, conn); + w.player = guests.iter().find(|g| g.0 == conn).map(|g| g.1.clone()); + } + None => { + bindings.remove(&m.id); + } + } + conn + }; if !w .world .loaded(m.position.x.floor() as i32, m.position.z.floor() as i32) @@ -547,6 +574,16 @@ impl Game<'_> { let from = events.len(); let kept = m.tick(&w, &mut scratch, &mut events); horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes); + if let Some(conn) = seen_guest { + let mut k = from; + while k < events.len() { + if super::lan_mobs::acts_on_player(&events[k]) { + guest_events.push((conn, events.remove(k))); + } else { + k += 1; + } + } + } // Killed during its own tick (drowning, burning, falling...). if !m.alive() && !m.removed && died.insert(m.id) { dead.push(m.clone()); @@ -559,6 +596,7 @@ impl Game<'_> { // after this mob see it as it is now. snapshot[i] = seen(m, uuid); snapshot[i].alive &= kept; + grid.update(i, snapshot[i].bounds); horizon_client::mobs::apply_brain_events(&mut mobs, &mut events, from); } let mut flags = keep.into_iter(); @@ -569,6 +607,12 @@ impl Game<'_> { level_random = scratch; } self.world.random = level_random; + if let Some(host) = self.lan.as_mut() + && !guests.is_empty() + { + bindings.retain(|id, _| mobs.iter().any(|m| m.id == *id)); + host.mob_players = bindings; + } self.mobs.append(&mut mobs); self.died = died; self.sync_riders(); @@ -581,6 +625,7 @@ impl Game<'_> { self.mob_died(&m); } self.handle_mob_events(events)?; + self.lan_guest_mob_events(guest_events); self.tick_projectiles()?; self.tick_fangs(); self.tick_allays(); @@ -950,7 +995,7 @@ impl Game<'_> { 0.8, ); } - if let Some(state) = self.res.assets.registry.default_state(name) { + if let Some(state) = self.pack.assets.registry.default_state(name) { self.world.set(pos[0], pos[1], pos[2], state)?; } } @@ -959,7 +1004,7 @@ impl Game<'_> { self.destroy_particles(pos, old); if drop { let drops = self.res.items.block_drops_in( - self.res.assets.registry, + self.pack.assets.registry, old, None, &mut self.world.random, @@ -1337,7 +1382,12 @@ impl Game<'_> { pub(super) fn mob_hits_player_kind(&mut self, amount: f32, from: [f64; 3], kind: &str) { self.mob_hits_player(amount, from, kind); } - fn mob_hits_player(&mut self, amount: f32, from: [f64; 3], damage_type: &str) -> bool { + pub(super) fn mob_hits_player( + &mut self, + amount: f32, + from: [f64; 3], + damage_type: &str, + ) -> bool { if self.creative { return false; } @@ -1350,8 +1400,8 @@ impl Game<'_> { .is_some_and(|t| t.contains(damage_type)); let blocking = self.player_blocking(Some(from), damage_type, false); let raised = blocking.is_some(); - // Melee: the attacker stands at `from`. - let attacker = (!projectile) + // Melee: the attacker stands at `from` (another player's hit has no mob behind it). + let attacker = (!projectile && damage_type != "minecraft:player_attack") .then(|| { self.mobs .iter() @@ -1536,12 +1586,24 @@ impl Game<'_> { // Arrows also hit minecarts (VehicleEntity is pickable). let mut arrow_targets = targets.clone(); arrow_targets.extend(self.carts.iter().map(|c| (Who::Mob(c.id), c.bounds()))); + // Mobs' projectiles also hit the guests (game/lan_mobs.rs). + let guests = self.lan_projectile_targets(); + let mut arrow_targets_guests = arrow_targets.clone(); + arrow_targets_guests.extend(guests.iter().copied()); + let mut targets_guests = targets.clone(); + targets_guests.extend(guests); let pw = ProjWorld { w: &w, targets }; + let pw_guests = ProjWorld { + w: &w, + targets: targets_guests, + }; projectiles.retain_mut(|p| { - let (keep, hit) = if p.arrow.is_some() { - horizon_client::arrows::tick(p, &scene, &arrow_targets) - } else { - p.tick(&pw) + let mob_shot = !matches!(p.owner, Some(Who::Player)); + let (keep, hit) = match (p.arrow.is_some(), mob_shot) { + (true, false) => horizon_client::arrows::tick(p, &scene, &arrow_targets), + (true, true) => horizon_client::arrows::tick(p, &scene, &arrow_targets_guests), + (false, false) => p.tick(&pw), + (false, true) => p.tick(&pw_guests), }; if let Some(a) = p.arrow.as_mut() { arrow_events.extend(a.events.drain(..).map(|e| (p.position, e))); @@ -1690,7 +1752,7 @@ impl Game<'_> { ) -> horizon_client::arrows::ArrowScene<'s, 's> { horizon_client::arrows::ArrowScene { world: &self.world, - registry: self.res.assets.registry, + registry: self.pack.assets.registry, facts: &self.res.facts, collision: self.collision, fluids: &self.motion.fluids, @@ -1722,7 +1784,7 @@ impl Game<'_> { self.creatures.projectiles.push(arrow); } } - fn projectile_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> { + pub(super) fn projectile_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> { self.combat.projectile_owner = match p.owner { Some(Who::Mob(id)) => Some(id), _ => None, @@ -1731,6 +1793,14 @@ impl Game<'_> { Hit::Entity { at, .. } | Hit::Block { at, .. } => at, Hit::None => return Ok(()), }; + if let Hit::Entity { + who: Who::Mob(id), + at, + } = hit + && self.lan_projectile_hit(p, id, at) + { + return Ok(()); + } if matches!( p.kind, ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge @@ -1938,7 +2008,7 @@ impl Game<'_> { .facts .is_air(self.world.block(fire[0], fire[1], fire[2])) && let Some(state) = - self.res.assets.registry.default_state("minecraft:fire") + self.pack.assets.registry.default_state("minecraft:fire") { self.world.set(fire[0], fire[1], fire[2], state)?; } @@ -2701,7 +2771,7 @@ impl Game<'_> { } /// Mob models and projectiles for the entity pass. pub(super) fn mob_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); let scale = f64::from(self.settings.entity_distance); for mob in &self.mobs { diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index 07488b51a..3aac02ae7 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -83,7 +83,7 @@ impl Game<'_> { // (EditBox.keyPressed); releases still reach KeyboardHandler. let typing = matches!( self.screen, - Screen::Chat | Screen::Options | Screen::WorldOptions + Screen::Chat | Screen::Options | Screen::WorldOptions | Screen::CommandBlock ) || self.sign_edit.is_some() || self.book.is_some() || (self.screen == Screen::Creative && self.creative_screen.tab().search) @@ -423,7 +423,7 @@ impl Game<'_> { )); } let (left, right) = d.columns(&self.debug_chart_lines()); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let mut draws = debug_overlay::draw(&atlas.font, [&left, &right], scale, width); let charts = self.debug_charts.draw( &atlas.font, diff --git a/crates/horizon-client/src/game/decorated_pot.rs b/crates/horizon-client/src/game/decorated_pot.rs new file mode 100644 index 000000000..3ac43566a --- /dev/null +++ b/crates/horizon-client/src/game/decorated_pot.rs @@ -0,0 +1,152 @@ +//! Decorated pots, which Horizon keeps as loaded (the chunk's saved block +//! entities): the loot table a trial chamber pot holds, rolled into its item +//! the first time the item is read (`RandomizableContainer.unpackLootTable`), +//! and `DecoratedPotBlock.useItemOn` / `useWithoutItem`. +use super::{Game, spill}; +use horizon_client::{ + first_person::Hand, + items::ItemStack, + mobs::Who, + particles::{ParticleOptions, ParticleType}, + random_sequences::RandomSequences, + save, +}; +use horizon_core::random::LegacyRandom; +use horizon_world::{loot::LootData, nbt::Tag}; + +/// `DecoratedPotBlockEntity.WobbleStyle` ordinals. +const WOBBLE_POSITIVE: i32 = 0; +const WOBBLE_NEGATIVE: i32 = 1; + +/// `RandomizableContainer.unpackLootTable(null)` on a pot's saved tag: the +/// loot table, if any, is removed and `LootTable.fill` puts its roll in +/// `item`. The roll draws from `LootTableSeed`, else the table's random +/// sequence, else the level random (`LootContext.Builder.create`). +pub(super) fn unpack_loot( + tag: &mut Tag, + loot: Option<&LootData>, + random: &mut LegacyRandom, + sequences: &mut RandomSequences, + world_seed: i64, +) { + let Tag::Compound(map) = tag else { + return; + }; + let Some(Tag::String(table)) = map.remove(&"LootTable".into()) else { + return; + }; + let seed = match map.remove(&"LootTableSeed".into()) { + Some(Tag::Long(seed)) => seed, + _ => 0, + }; + map.remove(&"item".into()); + let Some(loot) = loot else { + return; + }; + let table = table.to_string_lossy(); + // No origin biome: the pot tables have no location checks. + let slots = if seed != 0 { + loot.fill(&table, seed, 1, None) + } else if let Some(sequence) = loot.random_sequence(&table) { + loot.fill_with(&table, sequences.get(sequence, world_seed), 1, None) + } else { + loot.fill_with(&table, random, 1, None) + }; + if let Some(stack) = slots.into_iter().next().flatten() { + let item = horizon_client::structure_blocks::loot_item_with_components(&stack); + map.insert("item".into(), save::item_to_nbt(&item)); + } +} + +impl Game<'_> { + /// The pot's saved tag at `pos` with its loot unpacked (a new one for a + /// pot without), or None when no pot is there. + fn pot_tag(&mut self, pos: [i32; 3]) -> Option { + let state = self.world.block(pos[0], pos[1], pos[2]); + if &*self.res.facts.get(state).name != "minecraft:decorated_pot" { + return None; + } + let mut tag = spill::saved_entity(&self.world, pos).unwrap_or_else(|| { + Tag::compound([ + ("id", Tag::String("minecraft:decorated_pot".into())), + ("x", Tag::Int(pos[0])), + ("y", Tag::Int(pos[1])), + ("z", Tag::Int(pos[2])), + ]) + }); + let loot = horizon_client::structure_blocks::loot_data(&self.options.resources); + unpack_loot( + &mut tag, + loot.as_deref(), + &mut self.world.random, + &mut self.rand_sequences, + self.level.seed, + ); + Some(tag) + } + /// `DecoratedPotBlock.useItemOn` with `held`, then `useWithoutItem` on the + /// main hand's turn: true when the pot took the click. + pub(super) fn use_decorated_pot(&mut self, pos: [i32; 3], held: Option<&ItemStack>) -> bool { + let Some(mut tag) = self.pot_tag(pos) else { + return false; + }; + let mut pot_item = tag.get("item").and_then(save::item_from_nbt); + let insertable = held.filter(|stack| match &pot_item { + None => true, + Some(p) => p.same_item_same_components(stack) && p.count < self.max_stack(p), + }); + let center = pos.map(|v| f64::from(v) + 0.5); + let Some(stack) = insertable else { + spill::put_saved_entity(&mut self.world, pos, tag); + // TRY_WITH_EMPTY_HAND: only the main hand goes on to useWithoutItem. + if self.hand != Hand::Main { + return false; + } + self.audio.play( + "minecraft:block.decorated_pot.insert_fail", + Some(center), + 1.0, + 1.0, + ); + self.block_entity_event(pos, 1, WOBBLE_NEGATIVE); + self.post_block_game_event("minecraft:block_change", pos, Some(Who::Player), None); + return true; + }; + let stack = stack.clone(); + self.block_entity_event(pos, 1, WOBBLE_POSITIVE); + self.stats.add("used", &stack.item, 1); + // consumeAndReturn(1): one item goes in (a creative player keeps theirs). + let inserted = match &mut pot_item { + Some(p) => { + p.count += 1; + p + } + None => pot_item.insert(ItemStack { + count: 1, + ..stack.clone() + }), + }; + let pitch_bend = inserted.count as f32 / self.max_stack(inserted) as f32; + if let (Tag::Compound(map), Some(item)) = (&mut tag, &pot_item) { + map.insert("item".into(), save::item_to_nbt(item)); + } + spill::put_saved_entity(&mut self.world, pos, tag); + self.consume_held(); + self.audio.play( + "minecraft:block.decorated_pot.insert", + Some(center), + 1.0, + 0.7 + 0.5 * pitch_bend, + ); + self.particles.send_particles( + &ParticleOptions::simple(ParticleType::DustPlume), + [center[0], f64::from(pos[1]) + 1.2, center[2]], + [0.0; 3], + 0.0, + 7, + ); + self.post_block_game_event("minecraft:block_change", pos, Some(Who::Player), None); + self.trigger_block("minecraft:item_used_on_block", pos, &stack); + true + } +} diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index cd7744d87..01728b351 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -418,6 +418,7 @@ impl Game<'_> { enforces_secure_chat: false, accepts_transfers: props.accepts_transfers, announce: false, + listen: true, bypasses_limit: Some(Arc::new(move |uuid| { bypass_lists .lock() @@ -525,7 +526,7 @@ impl Game<'_> { /// Load the spawn area and find the world spawn as single player does, /// without keeping a player there. - fn settle_spawn(&mut self) -> Result<()> { + pub(super) fn settle_spawn(&mut self) -> Result<()> { let deadline = Instant::now() + Duration::from_secs(600); while self.player.is_none() { self.update_world(); @@ -541,7 +542,7 @@ impl Game<'_> { /// The chunks to keep loaded: the players' (lan_update_streaming), or /// the spawn chunk while nobody is online. - fn update_dedicated_streaming(&mut self) { + pub(super) fn update_dedicated_streaming(&mut self) { let center = self .lan .as_ref() diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index 0d8043ecc..ee8170bc5 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -224,7 +224,7 @@ impl Game<'_> { for p in crafter_positions { let state = self.world.block(p.0, p.1, p.2); let triggered = self - .res + .pack .assets .registry .state(state) diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index 15f24f82f..cb28aa1cc 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -308,7 +308,7 @@ pub(super) fn mob_set_slot(m: &mut Mob, slot: Slot, stack: ItemStack) { impl Game<'_> { fn prop(&self, state: BlockStateId, key: &str) -> Option { - self.res + self.pack .assets .registry .state(state)? @@ -318,11 +318,11 @@ impl Game<'_> { } /// The same block with other properties (`withProperty`). fn with_props(&self, state: BlockStateId, props: &[(&str, &str)]) -> Option { - let mut s = self.res.assets.registry.state(state)?.clone(); + let mut s = self.pack.assets.registry.state(state)?.clone(); for (k, v) in props { s.properties.insert((*k).to_owned(), (*v).to_owned()); } - self.res.assets.registry.resolve(&s).ok() + self.pack.assets.registry.resolve(&s).ok() } fn block_at(&self, p: Pos) -> BlockStateId { self.world.block(p.0, p.1, p.2) @@ -933,6 +933,21 @@ impl Game<'_> { LAUNCH, ), }; + self.shoot_projectile_item(at, dir, &stack, power, uncertainty); + (shrink(stack), event) + } + + /// `ProjectileItem.asProjectile` and `Projectile.spawnProjectileUsingShoot`: + /// one of `stack` fired from `at` along `dir`. + pub(super) fn shoot_projectile_item( + &mut self, + at: Vec3, + dir: [f64; 3], + stack: &ItemStack, + power: f32, + uncertainty: f32, + ) { + let item = stack.item.to_string(); let one = ItemStack { count: 1, ..stack.clone() @@ -967,7 +982,7 @@ impl Game<'_> { "minecraft:tipped_arrow" => ProjectileKind::Arrow { base_damage: 2.0, critical: false, - effect: tipped_effect(&stack), + effect: tipped_effect(stack), }, "minecraft:fire_charge" | "minecraft:wind_charge" => { // asProjectile aims with the level's random first; the @@ -1000,7 +1015,6 @@ impl Game<'_> { self.creatures.projectiles.push(shot); } } - (shrink(stack), event) } // ---- entities placed by items ---- @@ -1393,7 +1407,7 @@ impl Game<'_> { } }; let skull = self - .res + .pack .assets .registry .default_state("minecraft:wither_skeleton_skull") @@ -1456,7 +1470,7 @@ impl Game<'_> { && self.can_spawn_golem([target.0, target.1, target.2]) { if let Some(pumpkin) = self - .res + .pack .assets .registry .default_state("minecraft:carved_pumpkin") @@ -1527,8 +1541,7 @@ impl Game<'_> { let target = (placed.x, placed.y, placed.z); if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) { self.world.block_entities.insert(target, entity); - self.fill_placed_box([target.0, target.1, target.2], &stack); - self.name_placed_container([target.0, target.1, target.2], &stack); + self.apply_placed_item([target.0, target.1, target.2], &stack, false); } self.process_level_events()?; Ok((shrink(stack), CLICK)) @@ -2033,10 +2046,10 @@ impl Game<'_> { return None; } let twin = format!("minecraft:waxed_{n}"); - let mut s = self.res.assets.registry.state(state)?.clone(); - self.res.assets.registry.default_state(&twin)?; + let mut s = self.pack.assets.registry.state(state)?.clone(); + self.pack.assets.registry.default_state(&twin)?; s.name = twin; - self.res.assets.registry.resolve(&s).ok() + self.pack.assets.registry.resolve(&s).ok() }); let Some(waxed) = waxed.filter(|_| name.contains("copper") || name.contains("lightning_rod")) @@ -2095,7 +2108,7 @@ impl Game<'_> { 1.0, ); self.post_block_game_event("minecraft:fluid_place", [pos.0, pos.1, pos.2], None, None); - if let Some(mud) = self.res.assets.registry.default_state("minecraft:mud") { + if let Some(mud) = self.pack.assets.registry.default_state("minecraft:mud") { self.level_set([target.0, target.1, target.2], mud)?; } let bottle = ItemStack::new("minecraft:glass_bottle", 1); diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index 5d1eef394..ff91df583 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -582,7 +582,7 @@ impl Game<'_> { } /// `EndCrystal.tick`: the time and the fire below it in the End. fn tick_crystals(&mut self) { - let fire = self.res.assets.registry.default_state("minecraft:fire"); + let fire = self.pack.assets.registry.default_state("minecraft:fire"); for i in 0..self.crystals.len() { self.crystals[i].time += 1; let p = self.crystals[i].position; @@ -1702,7 +1702,7 @@ impl Game<'_> { } if !self.fight.previously_killed && let Some(egg) = self - .res + .pack .assets .registry .default_state("minecraft:dragon_egg") @@ -1866,9 +1866,9 @@ impl Game<'_> { batch.width as i32, batch.height as i32, &bars, - &self.res.atlas.font, + &self.atlas.font, ); - hud_layout::paint(batch, &self.res.atlas, &draws); + hud_layout::paint(batch, &self.atlas, &draws); } /// The dragon fight's boss bar shows (`EnderDragonFight.dragonEvent`, /// with `setCreateWorldFog`). @@ -1906,13 +1906,7 @@ impl Game<'_> { return; }; let a = alpha as f32; - let sprite = |n: &str| { - self.res - .atlas - .sprites - .get(n) - .map(|r| [r.u0, r.v0, r.u1, r.v1]) - }; + let sprite = |n: &str| self.atlas.sprites.get(n).map(|r| [r.u0, r.v0, r.u1, r.v1]); let (Some(skin), Some(eyes)) = ( sprite("entity/enderdragon/dragon"), sprite("entity/enderdragon/dragon_eyes"), @@ -2078,7 +2072,7 @@ impl Game<'_> { } /// `submitRays`: the death rays from a fixed seed, fading in white to magenta. fn dragon_rays(&self, base: glam::Mat4, t: f32, out: &mut Vec) { - let white = self.res.atlas.font.white(); + let white = self.atlas.font.white(); let uv = [white.u0, white.v0]; let over = if t > 0.8 { ((t - 0.8) / 0.2).min(1.0) @@ -2134,7 +2128,6 @@ impl Game<'_> { out: &mut Vec, ) { let Some(s) = self - .res .atlas .sprites .get("entity/end_crystal/end_crystal_beam") @@ -2196,7 +2189,6 @@ impl Game<'_> { out: &mut Vec, ) { let Some(s) = self - .res .atlas .sprites .get("entity/enderdragon/dragon_fireball") @@ -2610,7 +2602,7 @@ impl Game<'_> { /// and grown again with a guarded crystal. fn rebuild_spike(&mut self, spike: &horizon_world::worldgen::end_spike::EndSpike) { let (cx, cz, h) = (spike.center_x, spike.center_z, spike.height); - let air = self.res.assets.registry.default_state("minecraft:air"); + let air = self.pack.assets.registry.default_state("minecraft:air"); let Some(air) = air else { return; }; @@ -2685,7 +2677,7 @@ impl Game<'_> { } /// Iron bars connected north, south, west and east. fn set_bars(&mut self, pos: [i32; 3], sides: [bool; 4]) { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let Some(mut state) = registry .default_state("minecraft:iron_bars") .and_then(|d| registry.state(d).cloned()) diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index 4bebc8d9b..d02904872 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -142,7 +142,7 @@ impl Game<'_> { /// tinted 0x282828. The atlas does not wrap, so each face is 16×16 quads. pub(super) fn end_sky_geometry(&self) -> Vec { let mut out = Vec::with_capacity(6 * 256 * 4); - let Some(r) = self.res.atlas.sprites.get("environment/end_sky").copied() else { + let Some(r) = self.atlas.sprites.get("environment/end_sky").copied() else { return out; }; use std::f32::consts::FRAC_PI_2; @@ -184,7 +184,6 @@ impl Game<'_> { let intensity = self.end.flash.intensity(self.clock.fraction() as f32); if intensity > 1e-5 && let Some(r) = self - .res .atlas .sprites .get("environment/celestial/end_flash") @@ -237,7 +236,7 @@ impl Game<'_> { if &*stack.item != "minecraft:ender_eye" { return Ok(false); } - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let target = self.pick().and_then(|hit| { let state = registry.state(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]))?; (state.name == "minecraft:end_portal_frame").then(|| (hit, state.clone())) @@ -303,7 +302,7 @@ impl Game<'_> { /// ring (corners free) of filled frames, all facing the centre or all /// facing away from it. Returns the centre of the 3×3 opening. fn portal_ring_center(&self, frame: [i32; 3]) -> Option<[i32; 3]> { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; // (offset from the centre, facing when the frames face the centre) let mut ring = Vec::with_capacity(12); for i in -1..=1 { @@ -630,7 +629,7 @@ impl Game<'_> { &[], )?; } - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; for (facing, d) in [ ("north", [0, -1]), ("south", [0, 1]), @@ -898,8 +897,7 @@ impl Game<'_> { fn end_crystal_geometry(&self, camera: glam::DVec3, out: &mut Vec) { let (Some(model), Some(r)) = ( self.crystal_model.as_ref(), - self.res - .atlas + self.atlas .sprites .get("entity/end_crystal/end_crystal") .copied(), @@ -1052,7 +1050,7 @@ impl Game<'_> { /// ThrownItemRenderer: the ender eye item facing the camera. fn eye_geometry(&self, camera: glam::DVec3, out: &mut Vec) { - let Some(r) = self.res.atlas.sprites.get("item/ender_eye").copied() else { + let Some(r) = self.atlas.sprites.get("item/ender_eye").copied() else { return; }; let alpha = self.clock.fraction(); diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index b871e8df9..4ed2772c7 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -511,7 +511,7 @@ impl Game<'_> { // random sequence. let decay = (interaction == BlockInteraction::DestroyWithDecay).then_some(radius); let drops = self.res.items.block_drops_exploded( - self.res.assets.registry, + self.pack.assets.registry, state, None, &dynamic, diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index 1495800ec..c6ac6d25e 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -193,10 +193,10 @@ impl Game<'_> { if !self.extras.minimap.compose(view) { return; } - let Some(rect) = self.res.atlas.sprites.get(MINIMAP_SPRITE).copied() else { + let Some(rect) = self.atlas.sprites.get(MINIMAP_SPRITE).copied() else { return; }; - let (w, h) = (self.res.atlas.width as f32, self.res.atlas.height as f32); + let (w, h) = (self.atlas.width as f32, self.atlas.height as f32); self.map_patches.push(horizon_client::font::Patch { x: (rect.u0 * w).round() as u32, y: (rect.v0 * h).round() as u32, @@ -242,7 +242,7 @@ impl Game<'_> { let (map_corner, map_size) = (e.minimap_corner, f32::from(e.minimap_size)); let visible = |corner| !(self.debug && corner == Corner::TopLeft); let mut corners = Corners::new(batch.width, batch.height, self.effect_rows_height()); - let atlas = &self.res.atlas; + let atlas = &self.atlas; if let Some(view) = self.minimap_view() && visible(map_corner) && !self.extras.minimap.image.is_empty() @@ -286,7 +286,7 @@ impl Game<'_> { use_: self.extras.mouse[1], cps, }; - extras_hud::draw_keystrokes(batch, &self.res.atlas, &mut corners, keys_corner, &k); + extras_hud::draw_keystrokes(batch, &self.atlas, &mut corners, keys_corner, &k); } if mod_panels { self.draw_mod_panels(batch, &mut corners); diff --git a/crates/horizon-client/src/game/fangs.rs b/crates/horizon-client/src/game/fangs.rs index 2f09bc538..dd2b9bde6 100644 --- a/crates/horizon-client/src/game/fangs.rs +++ b/crates/horizon-client/src/game/fangs.rs @@ -108,7 +108,6 @@ impl Game<'_> { return; }; let Some(r) = self - .res .atlas .sprites .get("entity/illager/evoker_fangs") diff --git a/crates/horizon-client/src/game/fishing.rs b/crates/horizon-client/src/game/fishing.rs index eb7a54f99..8a63f2cfe 100644 --- a/crates/horizon-client/src/game/fishing.rs +++ b/crates/horizon-client/src/game/fishing.rs @@ -565,7 +565,6 @@ impl Game<'_> { return; }; let Some(r) = self - .res .atlas .sprites .get("entity/fishing/fishing_hook") diff --git a/crates/horizon-client/src/game/fov.rs b/crates/horizon-client/src/game/fov.rs index 778c0f0a2..7825d6514 100644 --- a/crates/horizon-client/src/game/fov.rs +++ b/crates/horizon-client/src/game/fov.rs @@ -171,6 +171,6 @@ impl Game<'_> { } let draws = hud_overlays::spyglass(batch.width as i32, batch.height as i32, self.scope_scale); - hud_layout::paint(batch, &self.res.atlas, &draws); + hud_layout::paint(batch, &self.atlas, &draws); } } diff --git a/crates/horizon-client/src/game/frames.rs b/crates/horizon-client/src/game/frames.rs index 26e195d4e..3ffa0e67e 100644 --- a/crates/horizon-client/src/game/frames.rs +++ b/crates/horizon-client/src/game/frames.rs @@ -301,7 +301,7 @@ impl Game<'_> { } /// ItemFrameRenderer: the frame model, then the item half size on its face. pub(super) fn frame_geometry(&mut self, camera: glam::DVec3, out: &mut Vec) { - let sprites = &self.res.atlas.sprites; + let sprites = &self.atlas.sprites; let mut maps: Vec<(i32, glam::Mat4, u32)> = Vec::new(); let mut items: Vec<(ItemStack, u32, glam::Mat4, u8)> = Vec::new(); for f in &self.item_frames { diff --git a/crates/horizon-client/src/game/game_rules_screen.rs b/crates/horizon-client/src/game/game_rules_screen.rs new file mode 100644 index 000000000..d99a7ab5b --- /dev/null +++ b/crates/horizon-client/src/game/game_rules_screen.rs @@ -0,0 +1,593 @@ +//! InWorldGameRulesScreen (AbstractGameRulesScreen), opened from World +//! Options: the rules by category under a search box, a switch or a number +//! box each, and Done sending the changed ones (ServerboundSetGameRulePacket). +//! Leaving with changes asks first (ConfirmScreen). +use horizon_client::{ + font::Font, + gamerules::{self, GameRules, RULES, Rule, Value}, + hud::{HudAtlas, HudBatch}, + lang, + text::{Style, Text, named_color}, + ui::{self, EditBox}, +}; + +/// HeaderAndFooterLayout(12 + 9 + 15, 33): the title over the search box. +const HEADER: f32 = 36.0; +const FOOTER: f32 = 33.0; +/// RuleList: 24 pixel entries in AbstractSelectionList's 220 pixel rows. +const ROW: f32 = 24.0; +const ROW_WIDTH: f32 = 220.0; +const SEARCH_WIDTH: f32 = 200.0; +/// EditBox text colours (`hud::rgba` order, ABGR): IntegerRuleEntry's valid +/// (-2039584) and invalid (-65536). +const VALID: u32 = 0xFFE0_E0E0; +const INVALID: u32 = 0xFF00_00FF; + +#[derive(Clone, Copy)] +enum Row { + Category(&'static str), + Rule(&'static Rule), +} + +/// What a click or Escape asks of World Options. +#[derive(Debug, PartialEq)] +pub(super) enum Exit { + /// Done: the rules that changed. + Apply(Vec<(&'static str, Value)>), + /// Cancel, or discarding the changes. + Discard, +} + +pub(super) struct RulesScreen { + search: EditBox, + values: GameRules, + initial: GameRules, + /// IntegerRuleEntry's boxes, by rule. + numbers: Vec<(&'static str, EditBox)>, + scroll: f32, + /// ConfirmScreen "Game Rule Changes" in its place. + confirm: bool, +} + +fn name_key(r: &Rule) -> String { + format!("gamerule.minecraft.{}", r.name) +} +fn category_key(category: &str) -> String { + format!("gamerule.category.minecraft.{category}") +} +/// GameRule.deserialize of an integer rule: Brigadier's readInt (digits, +/// '.' and '-' only, nothing after), then the rule's range. +fn parse(r: &Rule, s: &str) -> Option { + let number = !s.is_empty() + && s.chars() + .all(|c| c.is_ascii_digit() || c == '-' || c == '.'); + number + .then(|| s.parse::().ok()) + .flatten() + .filter(|v| (r.min..=r.max).contains(v)) +} +fn widest(font: &Font, lines: &[Text]) -> f32 { + lines.iter().map(|l| font.width_text(l)).fold(0.0, f32::max) +} +fn lines(font: &Font, t: &Text, width: f32) -> Vec { + font.split_lines(t, width) + .into_iter() + .map(|(line, _)| line) + .collect() +} +fn row_left(w: f32) -> f32 { + (w / 2.0).trunc() - ROW_WIDTH / 2.0 +} +/// A rule's switch or box: 44 by 20, 45 from the entry content's right. +fn control_x(w: f32) -> f32 { + row_left(w) + 2.0 + (ROW_WIDTH - 4.0) - 45.0 +} +/// The header's LinearLayout (title, 4, search box) centred in its 36 pixels. +fn search_at(w: f32) -> (f32, f32) { + (((w - SEARCH_WIDTH) / 2.0).trunc(), 4.0 + 9.0 + 4.0) +} +/// The footer's Done and Cancel, 150 wide and 8 apart. +fn footer(w: f32, h: f32) -> [(f32, f32); 2] { + let x = ((w - 308.0) / 2.0).trunc(); + [(x, h - FOOTER + 6.0), (x + 158.0, h - FOOTER + 6.0)] +} +fn yellow() -> u32 { + named_color("yellow").unwrap_or(0xFFFF55) +} + +/// ConfirmScreen: the title, the message (at most `width - 50` wide), and +/// Yes / No 16 below, 4 apart, all centred. +struct Confirm { + lines: Vec<(Text, f32, f32)>, + buttons: [(f32, f32); 2], +} +impl Confirm { + fn new(font: &Font, (w, h): (f32, f32)) -> Self { + let title = Text::translate("editGamerule.inGame.discardChanges.title", &[]); + let message = Text::translate("editGamerule.inGame.discardChanges.message", &[]); + let message: Vec = lines(font, &message, w - 50.0) + .into_iter() + .take(15) + .collect(); + let (tw, mw) = (font.width_text(&title), widest(font, &message)); + let mh = 9.0 * message.len() as f32; + let col = tw.max(mw).max(304.0); + let total = 9.0 + 8.0 + mh + 8.0 + 36.0; + let (lx, ly) = (((w - col) / 2.0).trunc(), ((h - total) / 2.0).trunc()); + let cell = |cw: f32| lx + ((col - cw) / 2.0).trunc(); + let mid = cell(mw) + (mw / 2.0).trunc(); + let mut out = vec![(title, cell(tw), ly)]; + for (i, line) in message.into_iter().enumerate() { + let x = mid - (font.width_text(&line) / 2.0).trunc(); + out.push((line, x, ly + 17.0 + 9.0 * i as f32)); + } + let (bx, by) = (cell(304.0), ly + 9.0 + 8.0 + mh + 8.0 + 16.0); + Self { + lines: out, + buttons: [(bx, by), (bx + 154.0, by)], + } + } +} + +impl RulesScreen { + pub(super) fn new(rules: &GameRules) -> Self { + // setInitialFocus: the search box. + let search = EditBox::new(0.0, 0.0, SEARCH_WIDTH, 15.0); + let numbers = RULES + .iter() + .filter(|r| matches!(r.default, Value::Int(_))) + .map(|r| { + let mut b = EditBox::new(0.0, 0.0, 44.0, 20.0); + b.focused = false; + b.set_value(&rules.int(r.name).to_string()); + b.text_color = VALID; + (r.name, b) + }) + .collect(); + Self { + search, + values: rules.clone(), + initial: rules.clone(), + numbers, + scroll: 0.0, + confirm: false, + } + } + + /// RuleList.populateChildren: the rules matching the search (id, name, + /// category or description), by category, each sorted by description id. + fn rows(&self) -> Vec { + let filter = self.search.value.to_lowercase(); + let has = |s: &str| s.to_lowercase().contains(&filter); + let mut categories: Vec<(&'static str, Vec<&'static Rule>)> = Vec::new(); + for r in RULES { + let key = name_key(r); + let description = format!("{key}.description"); + let matches = has(r.name) + || has(&lang::get(&key)) + || has(&lang::get(&category_key(r.category))) + || (lang::has(&description) && has(&lang::get(&description))); + if !matches { + continue; + } + match categories.iter_mut().find(|(c, _)| *c == r.category) { + Some((_, rules)) => rules.push(r), + None => categories.push((r.category, vec![r])), + } + } + // By the categories' ids, then the rules' description ids. + categories.sort_by_key(|(c, _)| *c); + categories + .into_iter() + .flat_map(|(c, mut rules)| { + rules.sort_by_key(|r| name_key(r)); + std::iter::once(Row::Category(c)).chain(rules.into_iter().map(Row::Rule)) + }) + .collect() + } + fn max_scroll(rows: usize, h: f32) -> f32 { + (ROW * rows as f32 + 4.0 - (h - HEADER - FOOTER)).max(0.0) + } + /// Entry `i`'s top: 2 under the list's top, less the scroll. + fn row_top(&self, i: usize) -> f32 { + HEADER + 2.0 - self.scroll.trunc() + ROW * i as f32 + } + /// getEntryAtPosition: the row under the pointer, inside the list. + fn hovered(&self, rows: usize, (x, y): (f32, f32), (w, h): (f32, f32)) -> Option { + let left = row_left(w); + let inside = y >= HEADER && y < h - FOOTER && x >= left && x < left + ROW_WIDTH; + let i = ((y - self.row_top(0)) / ROW).floor(); + (inside && i >= 0.0 && (i as usize) < rows).then_some(i as usize) + } + fn number(&mut self, name: &str) -> Option<&mut EditBox> { + self.numbers + .iter_mut() + .find(|(n, _)| *n == name) + .map(|(_, b)| b) + } + /// An invalid number disables Done (markInvalid). + fn invalid(&self) -> bool { + self.numbers + .iter() + .any(|(name, b)| gamerules::rule(name).is_none_or(|r| parse(r, &b.value).is_none())) + } + fn changes(&self) -> Vec<(&'static str, Value)> { + RULES + .iter() + .filter_map(|r| { + let value = self.values.get(r.name)?; + (Some(value) != self.initial.get(r.name)).then_some((r.name, value)) + }) + .collect() + } + /// InWorldGameRulesScreen.onClose: pending changes ask first. + fn close(&mut self) -> Option { + if self.changes().is_empty() { + Some(Exit::Discard) + } else { + self.confirm = true; + None + } + } + /// Escape: ConfirmScreen answers no; the rules close. + pub(super) fn escape(&mut self) -> Option { + if self.confirm { + self.confirm = false; + None + } else { + self.close() + } + } + /// The mouse wheel (AbstractSelectionList: half an entry a step). + pub(super) fn wheel(&mut self, delta: f32, h: f32) { + if !self.confirm { + let max = Self::max_scroll(self.rows().len(), h); + self.scroll = (self.scroll - delta * ROW / 2.0).clamp(0.0, max); + } + } + fn focused(&mut self) -> Option<(Option<&'static str>, &mut EditBox)> { + if self.search.focused { + return Some((None, &mut self.search)); + } + self.numbers + .iter_mut() + .find(|(_, b)| b.focused) + .map(|(n, b)| (Some(*n), b)) + } + /// The focused box changed: the search filters again from the top; a + /// number sets its rule when valid (IntegerRuleEntry's responder). + fn edited(&mut self, rule: Option<&'static str>) { + let Some(name) = rule else { + self.scroll = 0.0; + return; + }; + let Some(r) = gamerules::rule(name) else { + return; + }; + let value = self.number(name).map(|b| parse(r, &b.value)); + if let Some(Some(v)) = value { + self.values.set(name, Value::Int(v)); + } + if let Some(b) = self.number(name) { + b.text_color = if matches!(value, Some(Some(_))) { + VALID + } else { + INVALID + }; + } + } + /// Run an edit on the focused box, then its responder. + pub(super) fn edit(&mut self, f: impl FnOnce(&mut EditBox)) { + let Some((rule, b)) = self.focused() else { + return; + }; + let before = b.value.clone(); + f(b); + if b.value != before { + self.edited(rule); + } + } + pub(super) fn typing(&self) -> bool { + !self.confirm && (self.search.focused || self.numbers.iter().any(|(_, b)| b.focused)) + } + + /// A left click; Some when the screen closes. + pub(super) fn click( + &mut self, + atlas: &HudAtlas, + cursor: (f32, f32), + size: (f32, f32), + ) -> Option { + let (w, h) = size; + let on = |x: f32, y: f32, bw: f32, bh: f32| ui::hovered(cursor, x, y, bw, bh); + if self.confirm { + let c = Confirm::new(&atlas.font, size); + let [(yx, yy), (nx, ny)] = c.buttons; + if on(yx, yy, 150.0, 20.0) { + return Some(Exit::Discard); + } + if on(nx, ny, 150.0, 20.0) { + self.confirm = false; + } + return None; + } + let [(dx, dy), (cx, cy)] = footer(w, h); + if on(dx, dy, 150.0, 20.0) && !self.invalid() { + return Some(Exit::Apply(self.changes())); + } + if on(cx, cy, 150.0, 20.0) { + return self.close(); + } + // A click moves the focus to the widget under it. + let (sx, sy) = search_at(w); + if on(sx, sy, SEARCH_WIDTH, 15.0) { + self.unfocus(); + self.search.focused = true; + self.search.reset_blink(); + self.search.click(atlas, cursor.0, false, false); + return None; + } + let rows = self.rows(); + let i = self.hovered(rows.len(), cursor, size)?; + let Row::Rule(r) = rows[i] else { + return None; + }; + if !on(control_x(w), self.row_top(i) + 2.0, 44.0, 20.0) { + return None; + } + self.unfocus(); + match r.default { + Value::Bool(_) => { + let on = self.values.bool(r.name); + self.values.set(r.name, Value::Bool(!on)); + } + Value::Int(_) => { + if let Some(b) = self.number(r.name) { + b.focused = true; + b.reset_blink(); + b.click(atlas, cursor.0, false, false); + } + } + } + None + } + fn unfocus(&mut self) { + self.search.focused = false; + for (_, b) in &mut self.numbers { + b.focused = false; + } + } + /// Whether a click lands on a button (for its sound). + pub(super) fn clicks_button( + &self, + atlas: &HudAtlas, + cursor: (f32, f32), + size: (f32, f32), + ) -> bool { + let (w, h) = size; + let on = |(x, y): (f32, f32)| ui::hovered(cursor, x, y, 150.0, 20.0); + if self.confirm { + return Confirm::new(&atlas.font, size).buttons.into_iter().any(on); + } + let [done, cancel] = footer(w, h); + if (on(done) && !self.invalid()) || on(cancel) { + return true; + } + let rows = self.rows(); + self.hovered(rows.len(), cursor, size).is_some_and(|i| { + matches!(rows[i], Row::Rule(r) if matches!(r.default, Value::Bool(_))) + && ui::hovered(cursor, control_x(w), self.row_top(i) + 2.0, 44.0, 20.0) + }) + } + + pub(super) fn draw(&mut self, batch: &mut HudBatch, atlas: &HudAtlas, cursor: (f32, f32)) { + let (w, h) = (batch.width, batch.height); + ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); + if self.confirm { + let c = Confirm::new(&atlas.font, (w, h)); + for (line, x, y) in &c.lines { + batch.text_styled(atlas, line, *x, *y, u32::MAX, true); + } + for ((bx, by), key) in c.buttons.into_iter().zip(["gui.yes", "gui.no"]) { + let hover = ui::hovered(cursor, bx, by, 150.0, 20.0); + let label = Text::translate(key, &[]); + ui::button(batch, atlas, bx, by, 150.0, 20.0, &label, true, hover); + } + return; + } + let rows = self.rows(); + self.scroll = self.scroll.clamp(0.0, Self::max_scroll(rows.len(), h)); + // RuleList: the in-world list background, its entries clipped to it, + // then the separators and scrollbar. + ui::list_background(batch, atlas, HEADER, h - FOOTER, true); + let first = batch.vertices.len(); + let hovered = self.hovered(rows.len(), cursor, (w, h)); + let (left, x) = (row_left(w), control_x(w)); + for (i, row) in rows.iter().enumerate() { + let top = self.row_top(i); + if top + ROW < HEADER || top > h - FOOTER { + continue; + } + let (cx, cy) = (left + 2.0, top + 2.0); + match *row { + Row::Category(c) => { + // A FocusableTextWidget padded by 4, centred in the entry. + let label = Text::translate(&category_key(c), &[]) + .bold() + .underlined() + .with_color(yellow()); + let lw = atlas.font.width_text(&label); + let mid = cx + (ROW_WIDTH - 4.0) / 2.0; + let lx = mid - (lw / 2.0).trunc(); + batch.text_styled(atlas, &label, lx, cy + 10.0 - 8.0 + 4.0, u32::MAX, true); + } + Row::Rule(r) => { + let name = lines(&atlas.font, &Text::translate(&name_key(r), &[]), 170.0); + match name.as_slice() { + [one] => { + batch.text_styled(atlas, one, cx, cy + 5.0, u32::MAX, true); + } + [one, two, ..] => { + batch.text_styled(atlas, one, cx, cy, u32::MAX, true); + batch.text_styled(atlas, two, cx, cy + 10.0, u32::MAX, true); + } + [] => {} + } + let hover = hovered == Some(i) && ui::hovered(cursor, x, cy, 44.0, 20.0); + match r.default { + Value::Bool(_) => { + let key = if self.values.bool(r.name) { + "options.on" + } else { + "options.off" + }; + let label = Text::translate(key, &[]); + ui::button(batch, atlas, x, cy, 44.0, 20.0, &label, true, hover); + } + Value::Int(_) => { + if let Some(b) = self.number(r.name) { + b.x = x; + b.y = cy; + b.draw(batch, atlas, None); + } + } + } + } + } + } + batch.clip_since(first, 0.0, HEADER, w, h - FOOTER); + ui::separators(batch, atlas, HEADER, h - FOOTER, true); + let content = ROW * rows.len() as f32 + 4.0; + let bar_x = left + ROW_WIDTH + 6.0 + 2.0; + ui::scrollbar( + batch, + atlas, + bar_x, + HEADER, + h - FOOTER, + content, + self.scroll.trunc(), + ); + // The header: the title centred over the search box. + let title = Text::translate("editGamerule.title", &[]); + let tw = atlas.font.width_text(&title); + let (sx, sy) = search_at(w); + let lw = tw.max(SEARCH_WIDTH); + let lx = ((w - lw) / 2.0).trunc(); + batch.text_styled( + atlas, + &title, + lx + ((lw - tw) / 2.0).trunc(), + 4.0, + u32::MAX, + true, + ); + self.search.x = sx; + self.search.y = sy; + self.search.draw(batch, atlas, None); + if self.search.value.is_empty() && !self.search.focused { + // EditBox.SEARCH_HINT_STYLE: gray and italic. + let hint = Text::translate("gui.game_rule.search", &[]).with_style(&Style { + color: named_color("gray"), + italic: Some(true), + ..Style::default() + }); + let (hx, hy) = (self.search.text_x(), self.search.text_y()); + batch.text_styled(atlas, &hint, hx, hy, u32::MAX, true); + } + let invalid = self.invalid(); + for ((bx, by), (key, active)) in footer(w, h) + .into_iter() + .zip([("gui.done", !invalid), ("gui.cancel", true)]) + { + let hover = active && ui::hovered(cursor, bx, by, 150.0, 20.0); + let label = Text::translate(key, &[]); + ui::button(batch, atlas, bx, by, 150.0, 20.0, &label, active, hover); + } + // The hovered rule's tooltip: its id, description and default. + if let Some(Row::Rule(r)) = hovered.map(|i| rows[i]) { + let mut tip = vec![Text::literal(r.name).with_color(yellow())]; + let description = format!("{}.description", name_key(r)); + if lang::has(&description) { + tip.extend(lines( + &atlas.font, + &Text::translate(&description, &[]), + 150.0, + )); + } + let gray = named_color("gray").unwrap_or(0xAAAAAA); + tip.push( + Text::translate( + "editGamerule.default", + &[Text::literal(r.default.to_string())], + ) + .with_color(gray), + ); + ui::tooltip(batch, atlas, &tip, cursor); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn box_colours_are_vanillas() { + assert_eq!(VALID, horizon_client::hud::rgba(224, 224, 224, 255)); + assert_eq!(INVALID, horizon_client::hud::rgba(255, 0, 0, 255)); + } + + #[test] + fn numbers_parse_like_brigadier_within_the_rule() { + let r = gamerules::rule("max_snow_accumulation_height").unwrap(); + assert_eq!(parse(r, "8"), Some(8)); + assert_eq!(parse(r, "9"), None); + assert_eq!(parse(r, "-1"), None); + for s in ["", "+3", " 3", "3 ", "3.0", "x"] { + assert_eq!(parse(r, s), None, "{s:?}"); + } + let r = gamerules::rule("fire_spread_radius_around_player").unwrap(); + assert_eq!(parse(r, "-1"), Some(-1)); + } + + #[test] + fn rows_group_categories_and_rules_by_description_id() { + let s = RulesScreen::new(&GameRules::default()); + let rows = s.rows(); + assert_eq!(rows.len(), RULES.len() + 7); + assert!(matches!(rows[0], Row::Category("chat"))); + let categories: Vec<_> = rows + .iter() + .filter_map(|r| match r { + Row::Category(c) => Some(*c), + Row::Rule(_) => None, + }) + .collect(); + assert_eq!( + categories, + [ + "chat", "drops", "misc", "mobs", "player", "spawning", "updates" + ] + ); + } + + #[test] + fn edits_change_rules_and_bad_numbers_hold_done() { + let mut s = RulesScreen::new(&GameRules::default()); + assert!(s.changes().is_empty()); + s.unfocus(); + s.number("random_tick_speed").unwrap().focused = true; + s.edit(|b| b.set_value("10")); + assert_eq!(s.changes(), vec![("random_tick_speed", Value::Int(10))]); + s.edit(|b| b.set_value("ten")); + assert!(s.invalid()); + // The last valid value stays, as the responder left it. + assert_eq!(s.changes(), vec![("random_tick_speed", Value::Int(10))]); + // Leaving with changes asks; No returns, Yes discards. + assert_eq!(s.escape(), None); + assert!(s.confirm); + assert_eq!(s.escape(), None); + assert!(!s.confirm); + } +} diff --git a/crates/horizon-client/src/game/gamemode_switcher.rs b/crates/horizon-client/src/game/gamemode_switcher.rs index e7826ba22..5f73080f4 100644 --- a/crates/horizon-client/src/game/gamemode_switcher.rs +++ b/crates/horizon-client/src/game/gamemode_switcher.rs @@ -39,7 +39,7 @@ impl Game<'_> { }; switcher.hover(w, h, (self.cursor.0 as i32, self.cursor.1 as i32)); let selected = switcher.selected; - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.sprite_region( atlas, "gui/container/gamemode_switcher", @@ -62,14 +62,14 @@ impl Game<'_> { for (index, mode) in MODES.into_iter().enumerate() { let (x, y) = slot_origin(w, h, index); batch.sprite( - &self.res.atlas, + &self.atlas, "gui/sprites/gamemode_switcher/slot", x as f32, y as f32, ); if mode == selected { batch.sprite( - &self.res.atlas, + &self.atlas, "gui/sprites/gamemode_switcher/selection", x as f32, y as f32, diff --git a/crates/horizon-client/src/game/ghasts.rs b/crates/horizon-client/src/game/ghasts.rs index 40b4a574d..8ce0a4231 100644 --- a/crates/horizon-client/src/game/ghasts.rs +++ b/crates/horizon-client/src/game/ghasts.rs @@ -6,10 +6,26 @@ use horizon_client::{ items::ItemStack, mobs::{MobEvent, happy_ghast}, }; -use horizon_core::geometry::Vec3; +use horizon_core::geometry::{Aabb, Vec3}; use horizon_world::registry::BlockStateId; impl Game<'_> { + /// Client `EntityGetter.getEntityCollisions`: only solid happy ghasts, + /// excluding the player's own vehicle. + pub(super) fn happy_ghast_player_collisions(&self) -> Vec { + let Some(p) = &self.player else { + return Vec::new(); + }; + self.mobs + .iter() + .filter(|m| { + m.species() == horizon_client::mobs::Species::HappyGhast + && Some(m.id) != self.riding + && happy_ghast::collides_with_player(m, p.position.y) + }) + .map(|m| m.bounds()) + .collect() + } /// `HappyGhast.mobInteract`. Returns whether the click was used. pub(super) fn interact_happy_ghast(&mut self, index: usize, item: &str) -> bool { let m = &self.mobs[index]; @@ -94,7 +110,7 @@ impl Game<'_> { f64::from(pos[2]) + 0.5, ]; let facing = self - .res + .pack .assets .registry .state(state) diff --git a/crates/horizon-client/src/game/golems.rs b/crates/horizon-client/src/game/golems.rs index 990ce4271..2bfeda70d 100644 --- a/crates/horizon-client/src/game/golems.rs +++ b/crates/horizon-client/src/game/golems.rs @@ -146,7 +146,7 @@ impl Game<'_> { let below = [head[0], head[1] - 1, head[2]]; let copper = self.world.block(below[0], below[1], below[2]); let pumpkin = self.world.block(head[0], head[1], head[2]); - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let facing = registry .state(pumpkin) .and_then(|s| s.properties.get("facing").cloned()) diff --git a/crates/horizon-client/src/game/growth.rs b/crates/horizon-client/src/game/growth.rs index 7e5ad08ce..18591b0fe 100644 --- a/crates/horizon-client/src/game/growth.rs +++ b/crates/horizon-client/src/game/growth.rs @@ -15,7 +15,7 @@ impl Game<'_> { } let dir = self.options.resources.join("worldgen"); let started = std::time::Instant::now(); - let features = vanillagen::shared_data(&dir, self.res.assets.registry) + let features = vanillagen::shared_data(&dir, self.pack.assets.registry) .map_err(|e| e.to_string()) .and_then(|data| LiveFeatures::new(&data).map_err(|e| e.to_string())); match features { diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index 3d5f7ca44..76d626716 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -143,6 +143,7 @@ impl Game<'_> { || before(self.cart_hit().map(|h| h.1)) || before(self.dragon_hit().map(|h| h.1)) || before(self.mob_hit().map(|h| h.1)) + || before(self.guest_hit().map(|h| h.1)) } /// `LocalPlayer.isHandsBusy`: paddling a boat. fn hands_busy(&self) -> bool { @@ -256,7 +257,7 @@ impl Game<'_> { .or_else(|| self.held()); if let Some(stack) = active { let components = self - .res + .pack .item_renderer .models .components(&horizon_client::item_render::stack_view(stack)); diff --git a/crates/horizon-client/src/game/initial_spawn.rs b/crates/horizon-client/src/game/initial_spawn.rs index d35484390..5fcd90517 100644 --- a/crates/horizon-client/src/game/initial_spawn.rs +++ b/crates/horizon-client/src/game/initial_spawn.rs @@ -72,7 +72,7 @@ impl Game<'_> { fn spawn_columns(&self) -> Columns<'_, '_> { Columns { world: &self.world, - properties: &self.res.assets.properties, + properties: &self.pack.assets.properties, binding: self.collision, } } @@ -82,7 +82,7 @@ impl Game<'_> { horizon_client::save::world_gen_settings(&self.world_root).and_then(|s| { horizon_client::flatgen::FlatTerrain::from_settings( &s, - self.res.assets.registry, + self.pack.assets.registry, &self.res.biomes, ) }) @@ -107,7 +107,6 @@ impl Game<'_> { None => *self.spawn_origin.insert(self.spawn_origin()?), }; while let Some((dx, dz)) = self.spawn_spiral.current() { - self.spawn_search = self.spawn_spiral.steps() as u32; if self.spawn_spiral.tested() { let (cx, cz) = (ox + dx, oz + dz); if !self.streaming.is_lit(cx, cz) { diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs new file mode 100644 index 000000000..6edbb6e40 --- /dev/null +++ b/crates/horizon-client/src/game/integrated.rs @@ -0,0 +1,289 @@ +//! The integrated server (`IntegratedServer`): single player's world runs on +//! its own "Server thread", as vanilla's does, and the window joins it as a +//! player through memory, so a world tick never holds up a frame. +//! +//! Opt-in for now (`--server-thread` or `HORIZON_SERVER_THREAD=1`): the +//! player joins as a network player, and the server side of a network player +//! does not do everything single player does yet. Worlds whose player is +//! outside the Overworld open the usual way, since network players stay in +//! the Overworld so far. +use super::{ + Dim, Game, Options, PackResources, Resources, + lan::{LanSettings, Owner}, +}; +use horizon_client::{ + Result, + audio::Audio, + hud::HudAtlas, + lan::{MAX_PLAYERS, NetConfig, hub::HubConfig}, + save::Level, + settings::Settings, + title::WorldOptions, +}; +use horizon_protocol::connection::Pipe; +use horizon_protocol::{crypto::offline_uuid, text::translatable}; +use std::{ + path::Path, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + mpsc::{Sender, channel}, + }, + thread::JoinHandle, + time::{Duration, Instant}, +}; + +/// What the window tells its server thread. +#[derive(Default)] +struct Flags { + /// `Minecraft.pause`: a single-player pause screen is open. + paused: AtomicBool, + stop: AtomicBool, +} + +/// The window's handle on its server thread. +pub(super) struct Integrated { + flags: Arc, + thread: Option>, +} +impl Integrated { + /// `IntegratedServer.tickServer` skips the world while the game is paused. + pub fn set_paused(&self, paused: bool) { + self.flags.paused.store(paused, Ordering::Relaxed); + } + /// `IntegratedServer.halt(true)`: returns once the world is saved and let go. + pub fn stop(mut self) { + self.halt(); + } + fn halt(&mut self) { + self.flags.stop.store(true, Ordering::Relaxed); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} +impl Drop for Integrated { + fn drop(&mut self) { + self.halt(); + } +} + +/// The world to open and the player who owns it. +struct Launch { + folder: String, + name: Option, + seed: Option, + creative: bool, + create: Option, + /// The window's profile: the only one let in, and the world's player. + owner: u128, +} + +/// Whether this world opens on a server thread: asked for, and its player +/// (if any yet) in the Overworld. +pub(super) fn wanted(options: &Options, world: &Path) -> bool { + options.server_thread + && options.dedicated.is_none() + && Level::read(world).is_none_or(|l| Dim::from_id(&l.dimension) == Dim::Overworld) +} + +impl Game<'_> { + /// `Minecraft.doWorldLoad`: start the server thread on the world, wait + /// until it can be joined, then join it through memory. + pub(super) fn open_integrated( + &mut self, + folder: &str, + name: Option<&str>, + seed: Option, + creative: bool, + create: Option<&WorldOptions>, + ) -> Result<()> { + let auth = horizon_client::auth::current(); + let player = auth + .as_ref() + .map_or_else(|| self.options.player_name(), |a| a.name.clone()); + let launch = Launch { + folder: folder.to_owned(), + name: name.map(str::to_owned), + seed, + creative, + create: create.cloned(), + // An offline-mode server names its players by their offline profile. + owner: offline_uuid(&player), + }; + let mut options = self.options.clone(); + // A server without a console: no local player, no window, no control socket. + options.dedicated = Some(Vec::new()); + options.server_thread = false; + options.integrated = true; + options.control = None; + options.benchmark = None; + options.frames = None; + options.world_frames = None; + options.report = None; + options.server = None; + options.world = None; + options.dev_mods.clear(); + let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone()); + let flags = Arc::new(Flags::default()); + let (ready_tx, ready) = channel(); + let server_flags = flags.clone(); + let thread = std::thread::Builder::new() + .name("Server thread".into()) + .spawn(move || { + let result = serve( + &res, + pack, + options, + settings, + launch, + &server_flags, + &ready_tx, + ); + if let Err(e) = result { + log::error!("Horizon: integrated server: {e}"); + let _ = ready_tx.send(Err(e.to_string())); + } + })?; + let handle = Integrated { + flags, + thread: Some(thread), + }; + let pipe = match ready.recv() { + Ok(Ok(pipe)) => pipe, + Ok(Err(e)) => return Err(e.into()), + Err(_) => return Err("the integrated server stopped".into()), + }; + self.connect_local(pipe, &player)?; + self.integrated = Some(handle); + Ok(()) + } + + /// The server thread's loop (`MinecraftServer.runServer`): 20 ticks a + /// second, the world held while the window is paused. + fn run_integrated( + &mut self, + launch: Launch, + flags: &Flags, + ready: &Sender>, + ) -> Result<()> { + self.open_world( + &launch.folder, + launch.name.as_deref(), + launch.seed, + launch.creative, + launch.create.as_ref(), + )?; + let saved = Box::new(self.level.clone()); + let view_distance = self.settings.render_distance.clamp(2, 32); + let config = HubConfig { + default_game_mode: self.level.mode(), + guest_commands: true, + force_game_mode: false, + hardcore: self.level.hardcore, + view_distance, + simulation_distance: self.settings.simulation_distance.clamp(2, 32), + dimension: self.dim.id().to_owned(), + seed: self.level.seed, + max_players: MAX_PLAYERS, + // No player of its own: the hub runs without a host. + dedicated: true, + }; + let owner = launch.owner; + let net = NetConfig { + // No network until it is opened to the LAN. + listen: false, + // A memory connection is not compressed (`Connection.isMemoryConnection`). + compression_threshold: -1, + enable_status: false, + announce: false, + gate: Some(Arc::new(move |_, uuid, _| { + (uuid != owner).then(|| translatable("multiplayer.disconnect.not_whitelisted", &[])) + })), + ..NetConfig::lan(0, self.level.name.clone(), MAX_PLAYERS) + }; + let settings = LanSettings { + port: 0, + guest_commands: true, + force_game_mode: false, + }; + self.lan_host(settings, net, config, None)?; + let commands = self.allow_commands(); + let pipe = { + let host = self + .lan + .as_mut() + .ok_or("the integrated server did not start")?; + // The owner is an operator when the world allows commands + // (`IntegratedPlayerList`, `MinecraftServer.getProfilePermissions`). + host.hub.ops.insert(owner, if commands { 4 } else { 0 }); + host.owner = Some(Owner { + uuid: owner, + saved: Some(saved), + }); + host.hub.lan.connect_local()? + }; + let _ = ready.send(Ok(pipe)); + self.settle_spawn()?; + let mut next = Instant::now(); + while !flags.stop.load(Ordering::Relaxed) { + self.update_dedicated_streaming(); + self.update_world(); + if flags.paused.load(Ordering::Relaxed) { + // Only the connections run. + self.tick_lan(); + } else { + self.tick()?; + } + let rate = self.clock.rate().max(1.0); + next += Duration::from_secs_f64(1.0 / f64::from(rate)); + let now = Instant::now(); + if next > now { + std::thread::sleep(next - now); + } else if now - next > Duration::from_secs(2) { + next = now; + } + } + self.stop_integrated() + } + + /// `MinecraftServer.stopServer`: the players are saved and sent away, + /// then the world is saved. + fn stop_integrated(&mut self) -> Result<()> { + if let Some(mut host) = self.lan.take() { + for g in &host.hub.guests { + self.save_guest(&host, g); + } + let conns: Vec = host.hub.guests.iter().map(|g| g.conn).collect(); + for conn in conns { + host.hub.kick( + conn, + translatable("multiplayer.disconnect.server_shutdown", &[]), + ); + } + self.lan = Some(host); + } + std::thread::sleep(Duration::from_millis(100)); + self.save_game()?; + self.lan_close(false); + self.save.flush(); + self.session_lock = None; + Ok(()) + } +} + +/// The server thread: a game of its own over the shared resources. +fn serve( + res: &Arc, + pack: PackResources, + options: Options, + settings: Settings, + launch: Launch, + flags: &Flags, + ready: &Sender>, +) -> Result<()> { + let atlas = HudAtlas::build(&options.resources)?; + let audio = Audio::silent(&options.resources); + let mut server = Game::new(res, pack, atlas, options, settings, audio)?; + server.run_integrated(launch, flags, ready) +} diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index 87599042e..aae200b50 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -31,7 +31,7 @@ impl ItemEnv for Env<'_, '_> { } fn grass_color(&self, temperature: f64, downfall: f64) -> i32 { self.game - .res + .pack .item_renderer .grass_color(temperature, downfall) } @@ -43,7 +43,7 @@ impl ItemEnv for Env<'_, '_> { else { return 0.0; }; - let prototypes = &self.game.res.item_renderer.models.prototypes; + let prototypes = &self.game.pack.item_renderer.models.prototypes; let mut total = 0.0f64; for item in items { let id = item["id"].as_str().unwrap_or(""); @@ -216,7 +216,7 @@ impl Game<'_> { && self.inventory.get(slot).and_then(Option::as_ref) == Some(stack) { let view = item_render::stack_view(stack); - let duration = use_duration(&self.res.item_renderer.models.components(&view)); + let duration = use_duration(&self.pack.item_renderer.models.components(&view)); owner.using_this_item = true; owner.use_duration = duration; owner.use_item_remaining_ticks = duration - ticks as i32; @@ -239,7 +239,7 @@ impl Game<'_> { seed: i32, ) -> ItemRenderState { let level = self.item_level(); - self.res.item_renderer.resolve( + self.pack.item_renderer.resolve( &item_render::stack_view(stack), display, owner, @@ -254,8 +254,8 @@ impl Game<'_> { let state = self.resolve_item(stack, DisplayContext::Gui, Some(&owner), 0); item_render::gui::draw( &state, - &self.res.item_renderer, - &self.res.atlas.sprites, + &self.pack.item_renderer, + &self.atlas.sprites, &self.item_host(), batch, x, @@ -278,8 +278,8 @@ impl Game<'_> { lights: Some(diffuse_lights(self.dim == Dim::Nether)), }; state.submit( - &self.res.item_renderer, - &self.res.atlas.sprites, + &self.pack.item_renderer, + &self.atlas.sprites, &self.item_host(), pose, &mut sink, @@ -299,8 +299,8 @@ impl Game<'_> { lights: None, }; state.submit( - &self.res.item_renderer, - &self.res.atlas.sprites, + &self.pack.item_renderer, + &self.atlas.sprites, &self.item_host(), pose, &mut sink, @@ -360,7 +360,7 @@ impl Game<'_> { (q.y + 0.1).floor() as i32, q.z.floor() as i32, ); - let seed = i64::from(self.res.item_renderer.item_id(&item.stack.item)) + let seed = i64::from(self.pack.item_renderer.item_id(&item.stack.item)) + i64::from(item.stack.damage); for copy in item_render::cluster_poses( &state, diff --git a/crates/horizon-client/src/game/jukebox.rs b/crates/horizon-client/src/game/jukebox.rs index 3bde15818..235ad7c24 100644 --- a/crates/horizon-client/src/game/jukebox.rs +++ b/crates/horizon-client/src/game/jukebox.rs @@ -21,7 +21,7 @@ impl Game<'_> { } fn set_has_record(&mut self, pos: [i32; 3], has: bool) { let state = self.world.block(pos[0], pos[1], pos[2]); - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let Some(mut s) = registry.state(state).cloned() else { return; }; diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 9bdbac2e0..c416c202f 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -53,6 +53,19 @@ pub(super) struct LanHost { pub broken: Vec<[f64; 3]>, /// Hurt and death state of the mobs guests see. mob_state: HashMap, + /// The guest each mob sees as its player, when not the host (game/lan_mobs.rs). + pub mob_players: HashMap, + /// An integrated server's owner (game/integrated.rs). + pub owner: Option, +} + +/// The player who owns an integrated server's world: a guest whose state is +/// the world's own player (`players/data/.dat`), as in +/// single player. +pub(super) struct Owner { + pub uuid: u128, + /// The world's player as loaded, until the owner joins. + pub saved: Option>, } /// A stable UUID for an entity that has none. @@ -335,6 +348,14 @@ impl Game<'_> { "placed": g.placed, "loaded": g.loaded, "game_mode": g.game_mode, + "sneaking": g.sneaking, + "health": g.health, + // FoodData: food level, saturation and exhaustion. + "food": [ + f64::from(g.food), + f64::from(g.saturation), + g.motion.as_ref().map_or(0.0, |m| f64::from(m.health.food.exhaustion)), + ], "chunks": g.sent_chunks.len(), "tracked": g.tracker.len(), // The armour the host draws on this guest, head to feet. @@ -430,7 +451,7 @@ impl Game<'_> { encoder.tables = Some( self.save .tables - .get_or_init(|| Arc::new(horizon_client::save::SaveTables::new(&self.res.assets))) + .get_or_init(|| Arc::new(horizon_client::save::SaveTables::new(&self.pack.assets))) .clone(), ); let lan = Lan::start_with(sync.clone(), net)?; @@ -454,6 +475,8 @@ impl Game<'_> { play: HashMap::new(), broken: Vec::new(), mob_state: HashMap::new(), + mob_players: HashMap::new(), + owner: None, }); self.audio.capture = Some(Vec::new()); Ok(()) @@ -466,7 +489,7 @@ impl Game<'_> { return; }; for g in &host.hub.guests { - playerdata::save(g, &self.world_root); + self.save_guest(&host, g); } host.hub.disconnect_all(); // Give the writer threads a moment to flush the disconnect packets. @@ -483,6 +506,30 @@ impl Game<'_> { } } + /// Save a guest when they leave or the world closes: an integrated + /// server's owner with the world (`save_game`), anyone else in their file. + pub(super) fn save_guest(&mut self, host: &LanHost, guest: &horizon_client::lan::guest::Guest) { + if host.owner.as_ref().is_some_and(|o| o.uuid == guest.uuid) { + if guest.placed { + playerdata::store(guest, &mut self.level); + } + } else { + playerdata::save(guest, &self.world_root); + } + } + /// The integrated server's owner into the world's player, for `Level::write`. + pub(super) fn store_owner(&mut self) { + let Some(host) = &self.lan else { + return; + }; + let Some(uuid) = host.owner.as_ref().map(|o| o.uuid) else { + return; + }; + if let Some(g) = host.hub.guests.iter().find(|g| g.uuid == uuid && g.placed) { + playerdata::store(g, &mut self.level); + } + } + /// The world's default game mode (`defaultgamemode`). pub(super) fn set_default_game_mode(&mut self, mode: i32) { self.level.game_mode = mode; @@ -601,7 +648,7 @@ impl Game<'_> { next_entity: &mut self.next_entity, spawn, difficulty: i32::from(self.ui.difficulty), - difficulty_locked: false, + difficulty_locked: self.level.difficulty_locked, clock_rate: if self.ui.rules.bool("advance_time") { self.ui.clock.rate } else { @@ -653,7 +700,7 @@ impl Game<'_> { self.container_openers_changed(pos, false); } self.lan_crafting_left(&mut host, &mut guest); - playerdata::save(&guest, &self.world_root); + self.save_guest(&host, &guest); host.models.remove(&guest.conn); if self.options.dedicated.is_some() && guest.placed { super::dedicated::log( @@ -696,10 +743,20 @@ impl Game<'_> { let default_mode = host.hub.config.default_game_mode; let force = host.hub.config.force_game_mode; let root = self.world_root.clone(); + let owner = host.owner.as_mut(); let Some(g) = host.hub.guest_mut(conn) else { return; }; - let known = playerdata::load(g, &root); + let saved = owner + .filter(|o| o.uuid == g.uuid) + .and_then(|o| o.saved.take()); + let known = match saved { + Some(level) => { + playerdata::apply(g, &level); + level.position.is_some() + } + None => playerdata::load(g, &root), + }; if !known || force { g.game_mode = default_mode; } @@ -716,7 +773,7 @@ impl Game<'_> { next_entity: &mut self.next_entity, spawn, difficulty: i32::from(self.ui.difficulty), - difficulty_locked: false, + difficulty_locked: self.level.difficulty_locked, clock_rate: self.ui.clock.rate, tick_rate: self.clock.rate(), tick_frozen: self.clock.frozen(), @@ -875,7 +932,7 @@ impl Game<'_> { let Some(host) = &self.lan else { return; }; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); for m in host.models.values() { let entity_start = out.len(); diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 7c8303c82..6bf76f160 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -11,8 +11,11 @@ use horizon_client::{ containers::BlockEntity, entities::Experience, items::ItemStack, - lan::{guest::SPECTATOR, menu::Rules}, - motion::{MotionWorld, PlayerMotion}, + lan::{ + guest::SPECTATOR, + menu::{Rules, Slots}, + }, + motion::{MotionEvent, MotionWorld, PlayerMotion}, }; use horizon_core::geometry::Vec3; use horizon_protocol::{ @@ -145,10 +148,22 @@ impl Game<'_> { self.right = play.using.is_some() || self.using.is_some(); let riding = self.riding.take(); let host_station = self.station.take(); + // The guest's own ender inventory; one the host has open goes back + // into the host's while the guest acts. + let host_ender = self.ender_open; + self.close_ender_chest(); + std::mem::swap(&mut self.ender_items, &mut g.ender_items); self.lan_acting = Some(conn); + self.lan_acting_name = Some(g.name.clone()); + self.lan_acting_uuid = Some(g.uuid); let result = f(self); self.lan_acting = None; + self.lan_acting_name = None; + self.lan_acting_uuid = None; + // An ender chest the guest opened: the menu shows their inventory + // itself (lan_open_container), not a stand-in block entity. + self.close_ender_chest(); // What the action opened: handed to the guest instead of the host. let opened = self.container.take(); @@ -172,6 +187,13 @@ impl Game<'_> { self.keys.remove(&KeyCode::ShiftLeft); } let g = &mut host.hub.guests[i]; + std::mem::swap(&mut self.ender_items, &mut g.ender_items); + if let Some(key) = host_ender { + self.world + .block_entities + .insert(key, BlockEntity::Chest(self.ender_items.clone())); + self.ender_open = Some(key); + } let new_xp = std::mem::replace(&mut self.experience, xp); g.xp_level = new_xp.level; g.xp_progress = new_xp.progress; @@ -240,30 +262,51 @@ impl Game<'_> { /// Hand a container the guest opened over (ServerPlayer.openMenu); /// false when it is not one a guest can open. fn lan_open_container(&mut self, host: &mut LanHost, conn: u32, pos: (i32, i32, i32)) -> bool { - let Some(entity) = self.world.block_entities.get(&pos) else { - return false; - }; - let (menu, title) = match entity { - BlockEntity::Chest(items) => match items.len() { - 27 => ("minecraft:generic_9x3", "container.chest"), - 9 => ("minecraft:generic_3x3", "container.dispenser"), - 5 => ("minecraft:hopper", "container.hopper"), - _ => return false, - }, - _ => return false, - }; let name = &self .res .facts .get(self.world.block(pos.0, pos.1, pos.2)) .name; - let title = match &**name { - "minecraft:barrel" => "container.barrel", - "minecraft:dropper" => "container.dropper", - n if n.ends_with("shulker_box") => "container.shulkerBox", - _ => title, + let (menu, title, slots) = if &**name == "minecraft:ender_chest" { + // EnderChestBlock.useWithoutItem: the player's own inventory. + ( + "minecraft:generic_9x3", + "container.enderchest", + Slots::Ender, + ) + } else if let Some((other, right)) = self.chest_partner(pos) { + // ChestBlock.combine: the right half's slots come first. + let halves = if right { + Slots::Double(pos, other) + } else { + Slots::Double(other, pos) + }; + ("minecraft:generic_9x6", "container.chestDouble", halves) + } else { + let Some(BlockEntity::Chest(items)) = self.world.block_entities.get(&pos) else { + return false; + }; + let (menu, title) = match items.len() { + 27 => ("minecraft:generic_9x3", "container.chest"), + 9 => ("minecraft:generic_3x3", "container.dispenser"), + 5 => ("minecraft:hopper", "container.hopper"), + _ => return false, + }; + let title = match &**name { + "minecraft:barrel" => "container.barrel", + "minecraft:dropper" => "container.dropper", + n if n.ends_with("shulker_box") => "container.shulkerBox", + _ => title, + }; + (menu, title, Slots::Block(pos)) + }; + let Some(items) = host + .hub + .guest(conn) + .and_then(|g| slots.read(&self.world, g)) + else { + return false; }; - let items = entity.slots().to_vec(); // ServerPlayer.openMenu closes the menu that was open. self.guest_container_closed(host, conn); host.hub.open_container( @@ -271,6 +314,7 @@ impl Game<'_> { menu, horizon_protocol::text::translatable(title, &[]), pos, + slots, items, ); true @@ -401,8 +445,13 @@ impl Game<'_> { if spectator { return; } + // handleUseItem: the client's rotation, then the item alone. What it + // looked at a moment ago (a block, a mob) is UseItemOn's or Interact's. self.as_guest(host, conn, |g| { + (g.yaw, g.pitch) = (p.yaw, p.pitch); + g.lan_item_only = true; let _ = g.use_item(); + g.lan_item_only = false; }); } S::Attack(p) => self.guest_attack(host, conn, p.id), @@ -582,6 +631,12 @@ impl Game<'_> { if host.hub.guests[gi].spectator() { return; } + if let Some(victim) = Self::pvp_victim(host, conn, id) { + if let Some(Some(strike)) = self.as_guest(host, conn, |g| g.pvp_strike()) { + self.pvp_land(host, victim, &strike); + } + return; + } let (old_yaw, old_pitch) = (host.hub.guests[gi].yaw, host.hub.guests[gi].pitch); if self.look_at_entity(host, gi, id).is_none() { return; @@ -589,6 +644,10 @@ impl Game<'_> { self.as_guest(host, conn, |g| { g.attack(); }); + // The mob now answers to this guest (game/lan_mobs.rs). + if let Ok(id) = u32::try_from(id) { + host.mob_players.insert(id, conn); + } host.hub.guests[gi].yaw = old_yaw; host.hub.guests[gi].pitch = old_pitch; } @@ -766,48 +825,98 @@ impl Game<'_> { } /// The guest's body on the server each tick: ServerPlayer.tick's damage - /// clock and Entity.baseTick's fluid phase, then - /// ServerPlayer.doCheckFallDamage for each move the guest made (the fall - /// distance grows while they go down and hurts them where they land, as - /// the host's own landing does; water resets it, lava halves it), then - /// regeneration and the food tick (ServerPlayer.doTick). + /// clock and Entity.baseTick's fluid phase (burning), then for each move + /// the guest made ServerGamePacketListenerImpl.handleMovePlayer's jump + /// (`ServerPlayer.jumpFromGround`'s exhaustion), + /// ServerPlayer.doCheckFallDamage (the fall distance grows while they go + /// down and hurts them where they land, as the host's own landing does; + /// water resets it, lava halves it) and checkMovementStatistics (the + /// exhaustion of sprinting and swimming), then LivingEntity.baseTick's + /// hazards (drowning, lava, fire blocks, suffocation, the void), and + /// regeneration and the food tick (ServerPlayer.doTick). Their hurt + /// sounds are heard at the guest. fn guest_server_tick(&mut self, host: &mut LanHost, conn: u32) { let Some(g) = host.hub.guest_mut(conn) else { return; }; let moves = std::mem::take(&mut g.moves); + let from_ground = if moves.is_empty() { + g.on_ground + } else { + g.moves_from_ground + }; if g.spectator() { return; } - self.as_guest(host, conn, |game| { + let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height()); + let at = g.position; + let sounds = self.as_guest(host, conn, |game| { let (rules, health) = (game.world.health_rules, &game.motion.health); let Some(player) = game.player.as_mut() else { - return; + return Vec::new(); }; let mut w = MotionWorld { + entities: &[], player, scene: &mut game.world, - assets: &game.res.assets, + assets: &game.pack.assets, collision_binding: game.collision, resources: game.motion, }; w.player.health.advance_clock(); let _ = w.fluid_base_tick(); + w.player.ground.on_ground = from_ground; for (moved, on_ground) in moves { let movement = Vec3::new(moved[0], moved[1], moved[2]); + if w.player.ground.on_ground && !on_ground && moved[1] > 0.0 { + let sprinting = w.player.sprinting; + w.player + .health + .food + .add_exhaustion(if sprinting { 0.2 } else { 0.05 }); + } let landed = (|| -> horizon_client::Result<()> { w.set_on_ground_with_movement(on_ground, false, movement)?; let pos = w.legacy_on_position()?; let state = w.block_state(pos)?; - w.check_fall_damage(moved[1], on_ground, state, pos) + w.check_fall_damage(moved[1], on_ground, state, pos)?; + w.check_movement_statistics(movement) })(); if landed.is_err() { break; } } + let _ = w.tick_environment_damage(); + let _ = w.apply_fire_contact(); + let _ = w.server_hazards_tick(in_wall); let _ = w.player.peaceful_regeneration(rules); let _ = w.player.food_tick(health, rules); + std::mem::take(&mut w.player.events) + .into_iter() + .filter_map(|e| match e { + MotionEvent::HurtSound(sound) => Some(sound), + _ => None, + }) + .collect::>() }); + for sound in sounds.into_iter().flatten() { + self.player_hurt_sound(sound, at); + } + } + + /// `Player.isInWall`: a suffocating block in the 0.48-wide box at the + /// eyes. Suffocating is a full collision box that is also a full render + /// cube (`BlockBehaviour.isSuffocating`'s default; glass and the like + /// opt out), as the mobs' check has it. + fn in_wall(&self, at: [f64; 3], eye_height: f64) -> bool { + let (y, half) = ((at[1] + eye_height).floor() as i32, 0.24); + let range = |v: f64| (v - half).floor() as i32..=(v + half).floor() as i32; + range(at[0]).any(|x| { + range(at[2]).any(|z| { + let f = self.res.facts.get(self.world.block(x, y, z)); + f.full_collision && f.solid_render + }) + }) } /// The crack animation other players see. diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs new file mode 100644 index 000000000..7cef7cda6 --- /dev/null +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -0,0 +1,305 @@ +//! Mobs and the guests of an open world. The mob code sees one player +//! (`MobWorld.player`, `Who::Player`); with guests on, each mob sees the +//! player vanilla's `Level.getNearestPlayer` would give it, and keeps the +//! guest it targets until it lets go. What it then does to `Who::Player` +//! (hits, pushes, fire, its projectiles) runs with that guest swapped in. +use super::{Game, lan::LanHost}; +use horizon_client::{ + mobs::{Mob, MobEvent, PlayerView, Who}, + projectiles::{Hit, Projectile}, +}; +use horizon_core::geometry::{Aabb, Vec3}; +use horizon_protocol::packets::play::{self, Clientbound as C}; + +/// The guests mobs can see this tick, by connection. +pub(super) type GuestViews = Vec<(u32, PlayerView)>; + +/// The player a mob sees this tick: `None` for the host, else a guest. +/// A mob that targets a guest, or that a guest hurt in the last 100 ticks +/// (`LivingEntity.getLastHurtByMob`), keeps them while they are still a +/// valid target; otherwise it sees the nearest player +/// (`TargetingConditions`: alive, neither creative nor spectator), or the +/// nearest one that is not a spectator if none qualifies. +pub(super) fn player_for( + m: &Mob, + host: Option<&PlayerView>, + guests: &GuestViews, + bound: Option, +) -> Option { + let targeting = m.ai.target == Some(Who::Player) + || m.ai.last_hurt_by == Some(Who::Player) && m.age as i32 - m.ai.last_hurt_by_time <= 100; + choose(m.position, targeting, host, guests, bound) +} + +fn choose( + at: Vec3, + targeting: bool, + host: Option<&PlayerView>, + guests: &GuestViews, + bound: Option, +) -> Option { + let targetable = |v: &PlayerView| v.alive && !v.creative && !v.spectator; + if targeting + && let Some(conn) = bound + && guests.iter().any(|(c, v)| *c == conn && targetable(v)) + { + return Some(conn); + } + let d = |v: &PlayerView| at.distance_squared(v.position); + let nearest = |ok: &dyn Fn(&PlayerView) -> bool| { + let mut best = host.filter(|v| ok(v)).map(|v| (None, d(v))); + for (conn, v) in guests.iter().filter(|(_, v)| ok(v)) { + if best.is_none_or(|(_, b)| d(v) < b) { + best = Some((Some(*conn), d(v))); + } + } + best + }; + nearest(&targetable) + .or_else(|| nearest(&|v: &PlayerView| v.alive && !v.spectator)) + .and_then(|(conn, _)| conn) +} + +/// The events of a mob's tick that act on the player it sees. +pub(super) fn acts_on_player(e: &MobEvent) -> bool { + matches!( + e, + MobEvent::AttackPlayer(..) + | MobEvent::DamagePlayer { .. } + | MobEvent::Push { + target: Who::Player, + .. + } + | MobEvent::Ignite { + target: Who::Player, + .. + } + | MobEvent::Launch { + target: Who::Player, + .. + } + ) +} + +impl Game<'_> { + /// How mobs see each guest in play (`player_view` with the guest swapped + /// in; what the host alone tracks, such as its last attacker, stays out). + pub(super) fn lan_guest_views(&mut self) -> GuestViews { + let Some(mut host) = self.lan.take() else { + return Vec::new(); + }; + let conns: Vec<(u32, u128, [f64; 3])> = host + .hub + .guests + .iter() + .filter(|g| g.placed && g.loaded && !g.dead) + .map(|g| { + let moved = [0, 1, 2].map(|k| g.position[k] - g.previous_position[k]); + (g.conn, g.uuid, moved) + }) + .collect(); + let mut views = Vec::new(); + for (conn, uuid, moved) in conns { + if let Some(Some(mut v)) = self.as_guest(&mut host, conn, |g| g.player_view()) { + v.hurt_by = None; + v.last_hurt = None; + v.hero = false; + v.velocity = Vec3::new(moved[0], moved[1], moved[2]); + v.uuid = horizon_client::lan::playerdata::uuid_ints(uuid); + v.allies = Default::default(); + views.push((conn, v)); + } + } + self.lan = Some(host); + views + } + + /// Mob events aimed at a guest, run as that guest (`guest_hit_by`). + pub(super) fn lan_guest_mob_events(&mut self, events: Vec<(u32, MobEvent)>) { + if events.is_empty() { + return; + } + let Some(mut host) = self.lan.take() else { + return; + }; + for (conn, e) in events { + self.guest_hit_by(&mut host, conn, |g| { + let _ = g.handle_mob_events(vec![e]); + }); + } + self.lan = Some(host); + } + + /// The guests a projectile can hit, under their entity ids. + pub(super) fn lan_projectile_targets(&self) -> Vec<(Who, Aabb)> { + let Some(host) = self.lan.as_ref() else { + return Vec::new(); + }; + host.hub + .guests + .iter() + .filter(|g| g.placed && g.loaded && !g.dead && !g.spectator()) + .map(|g| (Who::Mob(g.entity_id as u32), guest_bounds(g))) + .collect() + } + + /// A projectile that hit a guest: its hit runs as theirs. False when + /// `id` is not a guest. + pub(super) fn lan_projectile_hit(&mut self, p: &Projectile, id: u32, at: Vec3) -> bool { + let Some(mut host) = self.lan.take() else { + return false; + }; + let conn = host + .hub + .guests + .iter() + .find(|g| g.entity_id as u32 == id) + .map(|g| g.conn); + if let Some(conn) = conn { + self.guest_hit_by(&mut host, conn, |g| { + let hit = Hit::Entity { + who: Who::Player, + at, + }; + let _ = g.projectile_hit(p, hit); + }); + } + self.lan = Some(host); + conn.is_some() + } +} + +impl Game<'_> { + /// Hurt a guest: `f` runs as them, and the knockback it gave reaches + /// their client (`hurtMarked`: ClientboundSetEntityMotionPacket). + pub(super) fn guest_hit_by( + &mut self, + host: &mut LanHost, + conn: u32, + f: impl FnOnce(&mut Self) -> R, + ) -> Option { + let (result, pushed) = self.as_guest(host, conn, |g| { + let before = g.player.as_ref().map(|p| p.velocity); + let result = f(g); + let after = g.player.as_ref().map(|p| p.velocity); + (result, after.filter(|v| Some(*v) != before)) + })?; + if let (Some(v), Some(g)) = (pushed, host.hub.guest(conn)) { + g.send(&C::SetEntityMotion(play::SetEntityMotion { + id: g.entity_id, + velocity: [v.x, v.y, v.z], + })); + } + Some(result) + } +} + +/// A guest as the blocks that look for players see them +/// (`PlayerDetector`, `level.getPlayers`: the dead ones too). +pub(super) struct Present { + pub uuid: [i32; 4], + pub position: [f64; 3], + pub eye: [f64; 3], + pub height: f32, + pub creative: bool, + pub spectator: bool, + pub alive: bool, +} + +impl Game<'_> { + /// Every guest in the world (`ServerLevel.getPlayers` past the host). + pub(super) fn lan_present(&self) -> Vec { + let guests = self.lan.iter().flat_map(|h| &h.hub.guests); + guests + .filter(|g| g.placed && g.loaded) + .map(|g| { + let [x, y, z] = g.position; + Present { + uuid: horizon_client::lan::playerdata::uuid_ints(g.uuid), + position: g.position, + eye: [x, y + g.eye_height(), z], + height: if g.sneaking { 1.5 } else { 1.8 }, + creative: g.creative(), + spectator: g.spectator(), + alive: !g.dead, + } + }) + .collect() + } + /// The UUID of the player acting: the guest `as_guest` runs, else the host. + pub(super) fn acting_uuid(&self) -> [i32; 4] { + self.lan_acting_uuid + .map(horizon_client::lan::playerdata::uuid_ints) + .or(self.level.player_uuid) + .unwrap_or_default() + } +} + +/// A guest's bounding box (0.6 wide, 1.8 tall, 1.5 crouching). +pub(super) fn guest_bounds(g: &horizon_client::lan::guest::Guest) -> Aabb { + let [x, y, z] = g.position; + let height = if g.sneaking { 1.5 } else { 1.8 }; + Aabb::new( + Vec3::new(x - 0.3, y, z - 0.3), + Vec3::new(x + 0.3, y + height, z + 0.3), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn view(x: f64, creative: bool) -> PlayerView { + PlayerView { + position: Vec3::new(x, 64.0, 0.0), + bounds: Aabb::new(Vec3::new(x, 64.0, 0.0), Vec3::new(x, 65.8, 0.0)), + eye: [x, 65.62, 0.0], + alive: true, + creative, + sneaking: false, + look: [0.0; 3], + main_hand: None, + off_hand: None, + head: None, + armor_cover: 0.0, + spectator: false, + gold_armor: false, + hurt_by: None, + last_hurt: None, + velocity: Vec3::ZERO, + yaw: 0.0, + hero: false, + uuid: [0; 4], + allies: Default::default(), + } + } + + const MOB: Vec3 = Vec3::new(0.0, 64.0, 0.0); + + #[test] + fn the_nearest_survival_player_is_seen() { + let host = view(10.0, false); + let guests = vec![(7, view(3.0, false)), (8, view(-5.0, false))]; + assert_eq!(choose(MOB, false, Some(&host), &guests, None), Some(7)); + // A creative guest is passed over for the host further away. + let guests = vec![(7, view(3.0, true))]; + assert_eq!(choose(MOB, false, Some(&host), &guests, None), None); + // Nobody targetable: the nearest one is still seen. + let host = view(10.0, true); + assert_eq!(choose(MOB, false, Some(&host), &guests, None), Some(7)); + assert_eq!(choose(MOB, false, None, &Vec::new(), None), None); + } + + #[test] + fn a_targeted_guest_stays_the_target() { + let host = view(1.0, false); + let guests = vec![(7, view(12.0, false))]; + assert_eq!(choose(MOB, true, Some(&host), &guests, Some(7)), Some(7)); + // Gone creative: the mob looks again. + let guests = vec![(7, view(12.0, true))]; + assert_eq!(choose(MOB, true, Some(&host), &guests, Some(7)), None); + // Without a target the nearest player wins. + let guests = vec![(7, view(12.0, false))]; + assert_eq!(choose(MOB, false, Some(&host), &guests, Some(7)), None); + } +} diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs new file mode 100644 index 000000000..dc91744de --- /dev/null +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -0,0 +1,110 @@ +//! Players hitting players in an open world (`Player.attack` on a player): +//! the host hits a guest, a guest hits the host or another guest. The hit +//! is worked out as the attacker (weapon, attack strength, critical hit, +//! enchantments, a mace's smash) and lands on the victim like any player +//! attack (blocking, armour, knockback), when the `pvp` game rule allows it +//! (`ServerPlayer.canHarmPlayer`, `isPvpAllowed`). +use super::{Game, lan::LanHost, lan_mobs::guest_bounds, ray_box, view_vector}; + +/// Who a player's attack lands on. +#[derive(Clone, Copy)] +pub(super) enum Victim { + Host, + Guest(u32), +} + +/// The attacker's side of the hit. +pub(super) struct Strike { + amount: f32, + scale: f32, + crit: bool, + from: [f64; 3], +} + +impl Game<'_> { + /// The guest on the host's crosshair and how far, within reach. + pub(super) fn guest_hit(&self) -> Option<(u32, f64)> { + let host = self.lan.as_ref()?; + let eye = self.eye_position()?; + let dir = view_vector(self.yaw, self.pitch); + let reach = if self.creative { 5.0 } else { 3.0 }; + host.hub + .guests + .iter() + .filter(|g| g.placed && g.loaded && !g.dead && !g.spectator()) + .filter_map(|g| Some((g.conn, ray_box(eye, dir, reach, guest_bounds(g))?))) + .min_by(|a, b| a.1.total_cmp(&b.1)) + } + + /// The host's attack on the guest under the crosshair, when no mob or + /// block is nearer. + pub(super) fn attack_guest(&mut self) -> bool { + let Some((conn, d)) = self.guest_hit() else { + return false; + }; + if self.mob_hit().is_some_and(|(_, m)| m < d) || !self.before_block(d) { + return false; + } + let Some(mut host) = self.lan.take() else { + return false; + }; + if let Some(strike) = self.pvp_strike() { + self.pvp_land(&mut host, Victim::Guest(conn), &strike); + } + self.lan = Some(host); + true + } + + /// The player `id` that guest `conn` attacks, if it is one. + pub(super) fn pvp_victim(host: &LanHost, conn: u32, id: i32) -> Option { + if id == host.host_entity { + return Some(Victim::Host); + } + host.hub + .guests + .iter() + .find(|g| g.entity_id == id && g.conn != conn && g.placed && !g.dead) + .map(|g| Victim::Guest(g.conn)) + } + + /// The attacker's side of `Player.attack` (the host, or a guest swapped + /// in): the damage, the charge reset, the exhaustion and the swing. + pub(super) fn pvp_strike(&mut self) -> Option { + let p = self.player.as_ref()?; + let from = [p.position.x, p.position.y, p.position.z]; + let (amount, scale, crit) = self.melee_damage("minecraft:player"); + self.attack_ticks = 0; + if let Some(p) = self.player.as_mut() + && !self.creative + { + p.health.food.exhaustion = (p.health.food.exhaustion + 0.1).min(40.0); + } + self.swing_arm(); + Some(Strike { + amount, + scale, + crit, + from, + }) + } + + /// The hit landing on the victim, then the attacker's attack sound. + pub(super) fn pvp_land(&mut self, host: &mut LanHost, victim: Victim, s: &Strike) { + let hurt = self.ui.rules.bool("pvp") + && match victim { + Victim::Host => self.mob_hits_player(s.amount, s.from, "minecraft:player_attack"), + Victim::Guest(conn) => self + .guest_hit_by(host, conn, |g| { + g.mob_hits_player(s.amount, s.from, "minecraft:player_attack") + }) + .unwrap_or(false), + }; + let sound = match (hurt, s.crit, s.scale > 0.9) { + (false, ..) => "minecraft:entity.player.attack.nodamage", + (true, true, _) => "minecraft:entity.player.attack.crit", + (true, false, true) => "minecraft:entity.player.attack.strong", + (true, false, false) => "minecraft:entity.player.attack.weak", + }; + self.audio.play(sound, Some(s.from), 1.0, 1.0); + } +} diff --git a/crates/horizon-client/src/game/lan_screen.rs b/crates/horizon-client/src/game/lan_screen.rs index b9ba56c5e..2402a5286 100644 --- a/crates/horizon-client/src/game/lan_screen.rs +++ b/crates/horizon-client/src/game/lan_screen.rs @@ -2,11 +2,17 @@ //! that opens the world to the local network (the 26.3 replacement of the //! old "Open to LAN" screen): default and personal game mode, cheats, //! difficulty, LAN on/off with its port, command access for guests and -//! forcing the game mode. -use super::{Game, Screen, lan::LanSettings}; +//! forcing the game mode. Its difficulty lock asks first (PopupScreen), and +//! Restrictions opens RestrictionsScreen. +use super::{ + Game, Screen, + game_rules_screen::{Exit, RulesScreen}, + lan::LanSettings, +}; use horizon_client::{ + font::Font, hud::{HudBatch, rgba}, - text::Text, + text::{Text, named_color}, ui::{self, EditBox}, }; use winit::{event::KeyEvent, keyboard::PhysicalKey}; @@ -22,7 +28,27 @@ pub(super) struct WorldOptions { hint: u16, guest_commands: bool, force: bool, + hardcore: bool, + /// The level's own lock (LevelData.isDifficultyLocked). + difficulty_locked: bool, + /// wantedDifficultyLocked: the lock icon, from the lock or hardcore. + locked: bool, initial: Snapshot, + /// ScrollableLayout's scroll amount. + scroll: f32, + view: View, + /// InWorldGameRulesScreen, while it is open. + rules: Option, +} +/// The screen on show: the options, the lock's question over them, or the +/// RestrictionsScreen or InWorldGameRulesScreen they opened (all return to +/// the same options). +#[derive(Clone, Copy, Debug, PartialEq)] +enum View { + Options, + LockQuestion, + Restrictions, + GameRules, } #[derive(Clone, PartialEq)] struct Snapshot { @@ -30,6 +56,7 @@ struct Snapshot { personal_mode: i32, cheats: bool, difficulty: u8, + locked: bool, lan: bool, port: u16, guest_commands: bool, @@ -39,12 +66,33 @@ struct Snapshot { const MODES: [&str; 4] = ["survival", "creative", "adventure", "spectator"]; const DIFFICULTIES: [&str; 4] = ["peaceful", "easy", "normal", "hard"]; -#[derive(Clone, Copy, PartialEq)] +/// HeaderAndFooterLayout's header and footer heights. +const HEADER: f32 = 33.0; +const FOOTER: f32 = 33.0; +/// The scrolled content: both grids, each padded by 8 and 8 apart. +const CONTENT: f32 = 218.0; +/// The category headings' tops (FocusableTextWidget, padding 4). +const GENERAL_TOP: f32 = 8.0; +const MULTIPLAYER_TOP: f32 = 145.0; +/// The port box's top beside the LAN button. +const PORT_TOP: f32 = 166.0; +/// PopupScreen: 250 wide less its 18 pixel border each side, two buttons +/// `min((214 - 6) / 2, 150)` wide and 6 apart, rows 12 apart. +const POPUP_CONTENT: f32 = 214.0; +const POPUP_BUTTON: f32 = 104.0; +/// RestrictionsScreen's text widgets: 250 wide, padded by 4. +const RESTRICTION_WIDTH: f32 = 250.0; + +#[derive(Clone, Copy, Debug, PartialEq)] enum Button { DefaultMode, PersonalMode, Cheats, Difficulty, + /// DifficultyButtons.lockButton (LockIconButton). + Lock, + GameRules, + Restrictions, Lan, CommandAccess, Force, @@ -72,6 +120,7 @@ impl WorldOptions { personal_mode: self.personal_mode, cheats: self.cheats, difficulty: self.difficulty, + locked: self.locked, lan: self.lan, port: if self.lan { self.parsed_port().unwrap_or(0) @@ -86,26 +135,56 @@ impl WorldOptions { let valid = !self.lan || self.parsed_port().is_some(); valid && self.snapshot() != self.initial } - fn buttons(w: f32) -> Vec<(Button, f32, f32, f32)> { - let x = (w / 2.0 - 154.0).floor(); + /// The scrolled content's top: under the header, less the scroll. + fn top(&self) -> f32 { + HEADER - self.scroll.trunc() + } + /// The grids' left edge: the content (308 wide, padded by 8) centred + /// in a ScrollableLayout reserving 10 pixels for the scrollbar each side. + fn left(w: f32) -> f32 { + (w / 2.0).floor() - 154.0 + } + /// The scrolled widgets: each grid's rows 4 apart, columns 8 apart. + fn buttons(w: f32, top: f32) -> Vec<(Button, f32, f32, f32)> { + let x = Self::left(w); let right = x + 158.0; vec![ - (Button::DefaultMode, x, 38.0, 308.0), - (Button::PersonalMode, x, 62.0, 308.0), - (Button::Cheats, x, 86.0, 150.0), - (Button::Difficulty, right, 86.0, 150.0), - (Button::Lan, x, 126.0, 150.0), - (Button::CommandAccess, x, 150.0, 150.0), - (Button::Force, right, 150.0, 150.0), + (Button::DefaultMode, x, top + 29.0, 308.0), + (Button::PersonalMode, x, top + 53.0, 308.0), + (Button::Cheats, x, top + 77.0, 150.0), + // DifficultyButtons: the cycle button gives the lock its 20 pixels. + (Button::Difficulty, right, top + 77.0, 130.0), + (Button::Lock, right + 130.0, top + 77.0, 20.0), + (Button::GameRules, x, top + 101.0, 150.0), + (Button::Restrictions, right, top + 101.0, 150.0), + (Button::Lan, x, top + 166.0, 150.0), + (Button::CommandAccess, x, top + 190.0, 150.0), + (Button::Force, right, top + 190.0, 150.0), ] } + /// The footer's two buttons, centred in its 33 pixels (FrameLayout + /// truncates the 6.5 pixel offset). fn footer(w: f32, h: f32) -> [(Button, f32, f32, f32); 2] { - let x = (w / 2.0 - 154.0).floor(); + let x = Self::left(w); [ - (Button::Apply, x, h - 28.0, 150.0), - (Button::Cancel, x + 158.0, h - 28.0, 150.0), + (Button::Apply, x, h - FOOTER + 6.0, 150.0), + (Button::Cancel, x + 158.0, h - FOOTER + 6.0, 150.0), ] } + /// The widgets under the pointer's row: scrolled ones only inside the + /// scroll area. + fn hit(&self, (x, y): (f32, f32), (w, h): (f32, f32)) -> Option