diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..417a1867c --- /dev/null +++ b/.dockerignore @@ -0,0 +1,8 @@ +# Docker builds (the relay) need the Rust sources only. +target/ +.local/ +**/node_modules/ +website/ +benchmarks/ +packs/ +mods/ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 57b7842b1..de509fdda 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -54,7 +54,7 @@ jobs: (github.event.pull_request.head.repo.full_name == github.repository && github.event.action != 'labeled') || (github.event.action == 'labeled' && github.event.label.name == 'run-parity')) runs-on: [self-hosted, horizon-game] - timeout-minutes: 45 + timeout-minutes: 120 # a change to core crates reruns ~300 harnesses: ~60-90 min on the Mac mini steps: - uses: actions/checkout@v4 with: diff --git a/.github/workflows/telemetry-server.yml b/.github/workflows/telemetry-server.yml new file mode 100644 index 000000000..e543721f9 --- /dev/null +++ b/.github/workflows/telemetry-server.yml @@ -0,0 +1,34 @@ +name: telemetry-server +# The ingest server is its own workspace (crates/horizon-telemetry-server), so the checks job doesn't build +# it: this one does, when it or the crate it shares with the launcher and the game changes. +on: + push: + branches: [main] + paths: + - 'crates/horizon-telemetry/**' + - 'crates/horizon-telemetry-server/**' + - '.github/workflows/telemetry-server.yml' + pull_request: + paths: + - 'crates/horizon-telemetry/**' + - 'crates/horizon-telemetry-server/**' + - '.github/workflows/telemetry-server.yml' +permissions: + contents: read +jobs: + check: + runs-on: ubuntu-latest + timeout-minutes: 20 + defaults: + run: + working-directory: crates/horizon-telemetry-server + steps: + - uses: actions/checkout@v4 + - run: rustup toolchain install stable --profile minimal --component rustfmt --component clippy + - uses: Swatinem/rust-cache@v2 + with: + workspaces: crates/horizon-telemetry-server + save-if: ${{ github.ref == 'refs/heads/main' }} + - run: cargo +stable fmt --check + - run: cargo +stable clippy --all-targets --locked -- -D warnings + - run: cargo +stable test --locked diff --git a/Cargo.lock b/Cargo.lock index 0753fc7d0..587845037 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -24,6 +24,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + [[package]] name = "ahash" version = "0.8.12" @@ -322,6 +332,30 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20", + "cipher", + "poly1305", + "zeroize", +] + [[package]] name = "chrono" version = "0.4.45" @@ -333,6 +367,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", + "zeroize", +] + [[package]] name = "clipboard-win" version = "5.4.1" @@ -493,6 +538,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", + "rand_core", "typenum", ] @@ -502,6 +548,32 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "fiat-crypto", + "rand_core", + "rustc_version", + "subtle", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "dasp_sample" version = "0.11.0" @@ -527,6 +599,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", + "subtle", ] [[package]] @@ -631,6 +704,12 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "find-msvc-tools" version = "0.1.14" @@ -886,6 +965,24 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + [[package]] name = "horizon-assets" version = "0.1.0" @@ -896,6 +993,14 @@ dependencies = [ "serde_json", ] +[[package]] +name = "horizon-bench" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "horizon-client" version = "0.1.0" @@ -909,8 +1014,11 @@ dependencies = [ "gilrs", "glam", "horizon-assets", + "horizon-bench", "horizon-core", + "horizon-friends", "horizon-protocol", + "horizon-telemetry", "horizon-theme", "horizon-world", "log", @@ -918,7 +1026,9 @@ dependencies = [ "naga", "png", "pollster", + "serde", "serde_json", + "sha2", "symphonia", "ureq", "wgpu", @@ -934,6 +1044,21 @@ dependencies = [ "libm", ] +[[package]] +name = "horizon-friends" +version = "0.1.0" +dependencies = [ + "chacha20poly1305", + "getrandom 0.3.4", + "hkdf", + "if-addrs", + "serde", + "serde_json", + "sha2", + "socket2", + "spake2", +] + [[package]] name = "horizon-prepare" version = "0.1.0" @@ -955,6 +1080,26 @@ dependencies = [ "sha1", ] +[[package]] +name = "horizon-relay" +version = "0.1.0" +dependencies = [ + "getrandom 0.3.4", + "horizon-friends", + "serde_json", +] + +[[package]] +name = "horizon-telemetry" +version = "0.1.0" +dependencies = [ + "getrandom 0.3.4", + "ruzstd", + "serde", + "serde_json", + "ureq", +] + [[package]] name = "horizon-theme" version = "0.1.0" @@ -1099,6 +1244,16 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "if-addrs" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b2eeee38fef3aa9b4cc5f1beea8a2444fc00e7377cafae396de3f5c2065e24" +dependencies = [ + "libc", + "windows-sys 0.59.0", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -1129,6 +1284,15 @@ dependencies = [ "libc", ] +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + [[package]] name = "itoa" version = "1.0.18" @@ -1857,6 +2021,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + [[package]] name = "orbclient" version = "0.3.55" @@ -2006,6 +2176,17 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures", + "opaque-debug", + "universal-hash", +] + [[package]] name = "portable-atomic" version = "1.15.0" @@ -2090,6 +2271,15 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + [[package]] name = "raw-window-handle" version = "0.6.2" @@ -2266,6 +2456,15 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "ruzstd" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69e4ce4a039f42bf25920b95667e4d789e98749ab11bbb8d2c2936f788421bb5" +dependencies = [ + "twox-hash", +] + [[package]] name = "same-file" version = "1.0.6" @@ -2313,6 +2512,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", + "serde_derive", ] [[package]] @@ -2453,6 +2653,28 @@ dependencies = [ "serde", ] +[[package]] +name = "socket2" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "spake2" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5482afe85a0b6ce956c945401598dbc527593c77ba51d0a87a586938b1b893a" +dependencies = [ + "curve25519-dalek", + "hkdf", + "rand_core", + "sha2", +] + [[package]] name = "spirv" version = "0.4.0+sdk-1.4.341.0" @@ -2758,6 +2980,12 @@ version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +[[package]] +name = "twox-hash" +version = "2.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" + [[package]] name = "typenum" version = "1.20.1" @@ -2782,6 +3010,16 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + [[package]] name = "untrusted" version = "0.9.0" diff --git a/Cargo.toml b/Cargo.toml index 2af3d37a4..584a87e5e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] -exclude = ["launcher"] -members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "xtask"] +exclude = ["launcher", "crates/horizon-telemetry-server"] +members = ["crates/horizon-core", "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", "xtask"] resolver = "2" [workspace.package] diff --git a/benchmarks/entity-model-document-2026-10-14/README.md b/benchmarks/entity-model-document-2026-10-14/README.md new file mode 100644 index 000000000..eeb8f6673 --- /dev/null +++ b/benchmarks/entity-model-document-2026-10-14/README.md @@ -0,0 +1,78 @@ +# Entity model document loading + +The three startup batches (boats/chest boats, minecarts, armor stands/player armor) +now share one parsed document. For this fixture, that replaces 43 full document +reads/parses (boat discovery plus 42 selected layers) with one. Selected models +still produce independent `Part` trees; the document is dropped after the batches +are built. Other entity loaders retain their existing behavior. + +## Reproduce + +From the repository root: + +```sh +python3 benchmarks/entity-model-document-2026-10-14/generate_fixture.py /tmp/horizon-entity-model-document-fixture.json +ENTITY_MODEL_BENCH_DOCUMENT=/tmp/horizon-entity-model-document-fixture.json \ + CARGO_TARGET_DIR=/home/bob/Documents/horizon/target \ + cargo test -p horizon-client --profile fast --bin horizon-client \ + entity_model_document_benchmark -- --ignored --nocapture +``` + +`CARGO_TARGET_DIR` is optional and can be changed for another machine. Supply a +prepared `entity-models.json` through `ENTITY_MODEL_BENCH_DOCUMENT` to benchmark +that document instead; the harness copies only that file to a temporary root. +`ENTITY_MODEL_BENCH_REPETITIONS` controls repetitions (default 15). + +The opt-in Rust test calls the actual three optimized production loaders and +compares every selected part name, pose, polygon normal/vertex and child against +the previous algorithm using the compatible per-model `load_model` API. Timings +include reading, parsing, constructing, normalizing into a common result map, and +dropping the result. Each variant gets three warmups and 15 measured calls, with +order alternating. `black_box` consumes inputs/results. No other builds or +optimization benchmarks ran during the measured calls. + +## Input and limitations + +Prepared resources were unavailable in the repository and local Horizon asset +directories. This is a **synthetic** 2,473,695-byte document with 458 model layers, +each containing 12 posed parts with six exported quads and normals. It selects 22 +boat/chest-boat layers, six minecart layers and 14 armor/player layers (42 total). +One wood name is synthetic (`test_wood`); boat discovery accepts arbitrary wood +names. The extra layers model the cost of parsing a full production-size document +for each selected model. + +File data is warm in the OS page cache. Equipment files are absent, so equipment +texture loading is excluded. This measures the entity-model batch only and does +not establish overall startup, frame time or FPS improvement. Shapes/layer counts +in real prepared documents can produce different absolute timings. + +Machine: AMD Ryzen 5 5600X (6 cores / 12 threads), Linux x86_64, +Rust 1.99.0 (b940084d7, LLVM 23.1.1), Cargo `fast` profile (opt-level 3, +16 codegen units, no LTO). Baseline algorithm corresponds to main +`73a019967e9665c6b96332988c13cb66679d8477`. + +## Results + +| Variant | Median batch time | Full document reads/parses | +| --- | ---: | ---: | +| Previous per-model algorithm | 1,434.974 ms | 43 | +| Shared document | 33.420 ms | 1 | + +The measured batch is **42.94× faster** on this synthetic input. All 15 samples +for both variants, warmup count, document size and selected model count are in +[`results.json`](results.json). + +## Validation + +```sh +cargo fmt --all -- --check +CARGO_TARGET_DIR=/home/bob/Documents/horizon/target \ + cargo test -p horizon-client --profile fast --bin horizon-client \ + entity_model_loading_tests -- --nocapture +CARGO_TARGET_DIR=/home/bob/Documents/horizon/target \ + cargo clippy -p horizon-client --profile fast --lib --bin horizon-client --tests -- -D warnings +``` + +The regular tests cover full/sparse documents, unrelated layers, a missing file, +invalid JSON, non-object JSON, missing model keys, independent model trees, and +equipment loading when the document is unavailable. diff --git a/benchmarks/entity-model-document-2026-10-14/generate_fixture.py b/benchmarks/entity-model-document-2026-10-14/generate_fixture.py new file mode 100644 index 000000000..624a7abe1 --- /dev/null +++ b/benchmarks/entity-model-document-2026-10-14/generate_fixture.py @@ -0,0 +1,31 @@ +"""Generate a production-size synthetic document; no prepared assets required.""" +import json +import pathlib +import sys + +woods = "oak spruce birch jungle acacia dark_oak mangrove cherry bamboo pale_oak test_wood".split() +carts = "minecart chest_minecart hopper_minecart furnace_minecart tnt_minecart command_block_minecart".split() +keys = [f"minecraft:{prefix}/{wood}#main" for prefix in ("boat", "chest_boat") for wood in woods] +keys += [f"minecraft:{cart}#main" for cart in carts] +keys += [f"minecraft:{model}#{slot}" for model in ("player", "armor_stand", "armor_stand_small") + for slot in ("helmet", "chestplate", "leggings", "boots")] +keys += [f"minecraft:{model}#main" for model in ("armor_stand", "armor_stand_small")] + +face = [[0, 0, 0, 0, 0], [16, 0, 0, 1, 0], [16, 16, 0, 1, 1], [0, 16, 0, 0, 1]] +part = {"pose": [1, 2, 3, 0.25, -0.5, 0.75, 1, 1, 1], "polygons": [face] * 6, + "normals": [[0, 0, 1]] * 6} +model = {"pose": [0, 0, 0, 0, 0, 0, 1, 1, 1], + "children": {f"part_{i}": part for i in range(12)}} +encoded = json.dumps(model, separators=(",", ":")) +entries = [json.dumps(key) + ":" + encoded for key in keys] +size = 2 + sum(map(len, entries)) + len(entries) - 1 +index = 0 +while size < 2_470_000: + entry = json.dumps(f"minecraft:fixture_{index}#main") + ":" + encoded + entries.append(entry) + size += 1 + len(entry) + index += 1 +output = pathlib.Path(sys.argv[1]) +output.write_text("{" + ",".join(entries) + "}") +print(json.dumps({"path": str(output), "bytes": output.stat().st_size, + "layers": len(entries), "selected_layers": len(keys)})) diff --git a/benchmarks/entity-model-document-2026-10-14/results.json b/benchmarks/entity-model-document-2026-10-14/results.json new file mode 100644 index 000000000..1ef0c6576 --- /dev/null +++ b/benchmarks/entity-model-document-2026-10-14/results.json @@ -0,0 +1,43 @@ +{ + "baseline_median_ms": 1434.973835, + "baseline_ms": [ + 1400.008286, + 1406.761694, + 1408.9131360000001, + 1418.6680549999999, + 1419.149658, + 1427.082872, + 1433.088092, + 1434.973835, + 1449.7688150000001, + 1452.143883, + 1453.987998, + 1455.518231, + 1457.0334540000001, + 1458.588552, + 1485.34133 + ], + "document_bytes": 2473695, + "optimized_median_ms": 33.419768000000005, + "optimized_ms": [ + 32.64795, + 32.812732, + 33.054488, + 33.056914, + 33.102999000000004, + 33.23532, + 33.28287, + 33.419768000000005, + 33.610569, + 33.874749, + 33.915657, + 33.93877, + 34.009893999999996, + 34.550526, + 36.096408000000004 + ], + "repetitions": 15, + "selected_models": 42, + "speedup": 42.937875421516985, + "warmup_pairs": 3 +} diff --git a/benchmarks/model-state-parse-2026-10-14.md b/benchmarks/model-state-parse-2026-10-14.md new file mode 100644 index 000000000..15a50e8ff --- /dev/null +++ b/benchmarks/model-state-parse-2026-10-14.md @@ -0,0 +1,69 @@ +# Reuse parsed model states + +`models::prepare` parsed `model-states.json` to select blocks, then +`StateModels::load` reopened and parsed the same document for binding and baking. +`StateModels::from_facts` now borrows the first parsed map. The public `load` +entry point still reads, parses and validates its own document. Both paths retain +the `fs::read` + `serde_json::from_slice` strategy merged in PR #205. + +The shared map uses `BTreeMap`, preserving the original catalog loader's JSON +validation, including rejection of top-level `null`. The old selection map was +`serde_json::Map`, also backed by a BTreeMap with the project's current features. +Catalog binding, model selection and baking are unchanged. Preparation no longer +holds a second complete JSON tree while constructing the catalog; no persistent +cache or extra clones were added. + +## Measurement + +The committed `model_states_bench` example runs main's two-parse sequence after PR #205 +(first a serde JSON map, then `StateModels::load`) and the new one-parse sequence +(first a BTreeMap, then `StateModels::from_facts`). Both select blocks from the +same generated document with slice parsing and call the actual catalog binding/baking code. Timing +includes file reads, parsing, filtering, binding, baking and result destruction. +Fixture generation and equality checks run outside the timed region. + +Prepared Minecraft resources were unavailable locally, so this is a synthetic +2,836,696-byte document containing 843 block schemas and 53,952 states. Schemas +combine integer and named properties. Blockstate resources use weighted and +conditional multipart choices with rotations and UV locking, sharing one model +with a baked face. Its absent texture uses the normal missing-sprite fallback. +Both paths read identical files with a warm OS cache. The workload does not +represent the full diversity of production model and texture assets. + +On AMD Ryzen 5 5600X, Linux 7.2.8-zen1-2-zen x86_64, rustc 1.99.0 +(b940084d7 2026-09-28), Cargo `fast` profile, serial execution: + +| Path | Median (15 samples) | +| --- | ---: | +| Before: parse twice, with #205 slice readers | 96.080 ms | +| After: reuse first parse, with #205 slice readers | 73.585 ms | + +**1.306x speedup; 23.41% less elapsed time** for this loading segment after PR #205. Each path +has two warmups, sample order alternates, and inputs/results use `black_box`. +This excludes gallery placements, GPU work and overall application startup. + +These measurements supersede the original unbuffered-reader timings +(2732.004 ms → 1386.060 ms, 1.971x) after rebasing onto main at +`e96e1571`. The reviewer measured approximately 1.05x with real prepared resources; +the generated fixture's balance of parsing and binding differs from production. +The change still removes one complete document read, parse and JSON tree. + +Equality validation compares every state's selected variants and baked geometry +at three positions, plus sprite layers and opacity/translucency flags. The +focused test also checks matching schema/registry errors, malformed/missing +source files, rejection of `null`, and successful shared-facts loading after the +source file has been deleted. + +## Reproduce + +```sh +export CARGO_TARGET_DIR=/home/bob/Documents/horizon/target +export CARGO_INCREMENTAL=0 +cargo run -p horizon-client --profile fast --example model_states_bench -- 15 +cargo test -p horizon-client --profile fast --example model_states_bench +cargo clippy -p horizon-client --all-targets --profile fast -- -D warnings +cargo fmt --all -- --check +``` + +The target directory can be changed for another machine. The example creates and +removes its fixtures in the system temporary directory. diff --git a/benchmarks/overlay-real-packs-2026-10-15.json b/benchmarks/overlay-real-packs-2026-10-15.json new file mode 100644 index 000000000..f664be6c4 --- /dev/null +++ b/benchmarks/overlay-real-packs-2026-10-15.json @@ -0,0 +1,54 @@ +{ + "date": "2026-10-15", + "environment": "Linux x86_64/ext4/NVMe, Ryzen5 5600X, Rust1.99.0, Cargo fast", + "scope": "actual resource_root vs original wrapper/builder; warmed storage; output equivalence outside timing", + "warmups": 2, + "median_samples": 11, + "prepared_minecraft": "26.3", + "prepared_schema": 7, + "prepared_manifest_sha256": "fd03c686302748748e132ef3978b7b0bcf42024257e802985a5cc7175cc74298", + "packs": [ + { + "project": "faithful-32x", + "version": "lDYpMiqk", + "version_name": "[26.3] Faithful 32x \u2013 September 2026 Release", + "publisher_page": "https://modrinth.com/resourcepack/faithful-32x/version/lDYpMiqk", + "download_url": "https://cdn.modrinth.com/data/w0TnApzs/versions/lDYpMiqk/Faithful%2032x%20-%2026.3.zip", + "zip_bytes": 13116019, + "zip_sha512": "e90ec63af7f239dbb99aa20c98b23d830e76898f65d3e31b7f0b53bb36db12dcd8c38d6930c743237c9c3db7bf708423fa1d1b2fd497dd6c281dbe216b779db9", + "asset_files": 5063, + "assets_uncompressed_bytes": 12524266, + "original_ms": 159.827, + "cold_ms": 162.711, + "hit_ms": 0.707 + }, + { + "project": "default-hd-128x", + "version": "rErHu3BE", + "version_name": "Default HD 128x Demo/Alpha 1.8.2.7", + "publisher_page": "https://modrinth.com/resourcepack/default-hd-128x/version/rErHu3BE", + "download_url": "https://cdn.modrinth.com/data/orfTV6nk/versions/rErHu3BE/Default%20HD%20128x%20Demo%201.8.2.7.zip", + "zip_bytes": 16876419, + "zip_sha512": "f5f9606e92b986cd9c8b8e5ff2bb52db720cc7b38e013355bdc90089e01975a08d09750ef2fd727f753d88ec3fbcd067355179b490587f667b2995f8be81640f", + "asset_files": 2318, + "assets_uncompressed_bytes": 17315416, + "original_ms": 111.501, + "cold_ms": 114.386, + "hit_ms": 0.31 + }, + { + "project": "fpbr", + "version": "dynf82xk", + "version_name": "support 1.21.9 and newer", + "publisher_page": "https://modrinth.com/resourcepack/fpbr/version/dynf82xk", + "download_url": "https://cdn.modrinth.com/data/nvEpbd8t/versions/dynf82xk/FPBR-Main-1.21.9-R1.3.zip", + "zip_bytes": 46737770, + "zip_sha512": "64f1bbd036e205118f1d9c49a79558db2c1356ee988fb939c0023db1967d78e1bd05047f341ce6d65355717ba7ddb1330af57edbb4d5b8713c96ae62987274c5", + "asset_files": 7001, + "assets_uncompressed_bytes": 56356903, + "original_ms": 347.639, + "cold_ms": 348.012, + "hit_ms": 0.448 + } + ] +} diff --git a/crates/horizon-bench/Cargo.toml b/crates/horizon-bench/Cargo.toml new file mode 100644 index 000000000..b945577b0 --- /dev/null +++ b/crates/horizon-bench/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "horizon-bench" +version = "0.1.0" +edition = "2021" +license = "MIT" +description = "The benchmark report format (docs/benchmark-report.md), shared by the game, the launcher and the upload" + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" diff --git a/crates/horizon-bench/src/hardware.rs b/crates/horizon-bench/src/hardware.rs new file mode 100644 index 000000000..4e41a0405 --- /dev/null +++ b/crates/horizon-bench/src/hardware.rs @@ -0,0 +1,259 @@ +//! The machine a report was measured on. CPU, RAM and OS are detected here; the GPU and the display +//! come from the program that rendered (the game knows its adapter, the launcher its window). + +use std::process::Command; + +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Hardware { + /// `macos`, `linux`, `windows`. + pub os: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub os_version: Option, + pub arch: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cpu: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cpu_threads: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ram_mb: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub gpu: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub display: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Gpu { + pub name: String, + pub vendor: String, + pub driver: String, + /// `metal`, `vulkan`, `dx12`, `gl`. + pub backend: String, + /// `integrated`, `discrete`, `virtual`, `cpu`, `other`. + pub kind: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Display { + /// Physical pixels. + pub width: u32, + pub height: u32, + pub scale: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub refresh_hz: Option, +} + +impl Hardware { + pub fn detect() -> Hardware { + Hardware { + os: std::env::consts::OS.to_owned(), + os_version: os_version(), + arch: std::env::consts::ARCH.to_owned(), + cpu: cpu(), + cpu_threads: std::thread::available_parallelism().ok().map(|n| n.get()), + ram_mb: ram_bytes().map(|b| b >> 20), + gpu: None, + display: None, + } + } +} + +/// The one-minute load average: above about the number of threads the machine was busy. +pub fn load_average() -> Option { + if cfg!(target_os = "macos") { + // "{ 1.23 1.10 1.00 }" + output("sysctl", &["-n", "vm.loadavg"])? + .trim_start_matches('{') + .split_whitespace() + .next()? + .parse() + .ok() + } else { + std::fs::read_to_string("/proc/loadavg") + .ok()? + .split_whitespace() + .next()? + .parse() + .ok() + } +} + +/// `ac` or `battery`; `None` where it can't be read (and on machines without a battery on Linux). +pub fn power_source() -> Option<&'static str> { + if cfg!(target_os = "macos") { + let batt = output("pmset", &["-g", "batt"])?; + return Some(if batt.contains("'Battery Power'") { + "battery" + } else { + "ac" + }); + } + let mut on_battery = None; + for entry in std::fs::read_dir("/sys/class/power_supply").ok()?.flatten() { + let read = + |name: &str| std::fs::read_to_string(entry.path().join(name)).unwrap_or_default(); + match read("type").trim() { + "Mains" if read("online").trim() == "1" => return Some("ac"), + "Battery" => on_battery = Some("battery"), + _ => {} + } + } + on_battery +} + +/// Resident memory of a process, in bytes (macOS, Linux). +pub fn rss_bytes(pid: u32) -> Option { + if cfg!(target_os = "macos") { + return output("ps", &["-o", "rss=", "-p", &pid.to_string()])? + .parse::() + .ok() + .map(|kb| kb * 1024); + } + let status = std::fs::read_to_string(format!("/proc/{pid}/status")).ok()?; + let line = status.lines().find(|l| l.starts_with("VmRSS:"))?; + line.split_whitespace() + .nth(1)? + .parse::() + .ok() + .map(|kb| kb * 1024) +} + +/// CPU time a process has used, user and system, in seconds (macOS, Linux). +pub fn cpu_seconds(pid: u32) -> Option { + if cfg!(target_os = "macos") { + // "[[dd-]hh:]mm:ss.cc" + let time = output("ps", &["-o", "time=", "-p", &pid.to_string()])?; + let (rest, days) = match time.split_once('-') { + Some((d, rest)) => (rest.to_owned(), d.parse::().ok()?), + None => (time, 0.0), + }; + let seconds = rest.split(':').try_fold(0.0, |acc, part| { + part.parse::().ok().map(|v| acc * 60.0 + v) + })?; + return Some(days * 86_400.0 + seconds); + } + // utime and stime, fields 14 and 15, in clock ticks (100 per second on Linux). + let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; + let fields: Vec<&str> = stat.rsplit_once(')')?.1.split_whitespace().collect(); + let ticks: f64 = fields.get(11)?.parse::().ok()? + fields.get(12)?.parse::().ok()?; + Some(ticks / 100.0) +} + +fn output(program: &str, args: &[&str]) -> Option { + let out = Command::new(program).args(args).output().ok()?; + let text = String::from_utf8(out.stdout).ok()?.trim().to_owned(); + (out.status.success() && !text.is_empty()).then_some(text) +} + +#[cfg(target_os = "macos")] +fn os_version() -> Option { + output("sw_vers", &["-productVersion"]) +} + +#[cfg(target_os = "macos")] +fn cpu() -> Option { + output("sysctl", &["-n", "machdep.cpu.brand_string"]) +} + +#[cfg(target_os = "macos")] +fn ram_bytes() -> Option { + output("sysctl", &["-n", "hw.memsize"])?.parse().ok() +} + +#[cfg(target_os = "linux")] +fn os_version() -> Option { + let release = std::fs::read_to_string("/etc/os-release").ok()?; + let name = key_value(&release, "PRETTY_NAME", '=')? + .trim_matches('"') + .to_owned(); + Some(match output("uname", &["-r"]) { + Some(kernel) => format!("{name} (kernel {kernel})"), + None => name, + }) +} + +#[cfg(target_os = "linux")] +fn cpu() -> Option { + let info = std::fs::read_to_string("/proc/cpuinfo").ok()?; + // x86 names the CPU per core; ARM boards name the machine once. + key_value(&info, "model name", ':') + .or_else(|| key_value(&info, "Model", ':')) + .map(str::to_owned) +} + +#[cfg(target_os = "linux")] +fn ram_bytes() -> Option { + let info = std::fs::read_to_string("/proc/meminfo").ok()?; + let kb = key_value(&info, "MemTotal", ':')? + .trim_end_matches("kB") + .trim(); + kb.parse::().ok().map(|kb| kb * 1024) +} + +#[cfg(target_os = "linux")] +fn key_value<'a>(text: &'a str, key: &str, sep: char) -> Option<&'a str> { + text.lines().find_map(|line| { + let (k, v) = line.split_once(sep)?; + (k.trim() == key).then(|| v.trim()) + }) +} + +#[cfg(target_os = "windows")] +fn os_version() -> Option { + output("cmd", &["/C", "ver"]) +} + +#[cfg(target_os = "windows")] +fn cpu() -> Option { + std::env::var("PROCESSOR_IDENTIFIER").ok() +} + +#[cfg(target_os = "windows")] +fn ram_bytes() -> Option { + let out = output( + "powershell", + &[ + "-NoProfile", + "-Command", + "(Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory", + ], + )?; + out.parse().ok() +} + +#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))] +fn os_version() -> Option { + None +} + +#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))] +fn cpu() -> Option { + None +} + +#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))] +fn ram_bytes() -> Option { + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn detects_this_machine() { + let hw = Hardware::detect(); + assert_eq!(hw.os, std::env::consts::OS); + assert!(hw.cpu_threads.unwrap() >= 1); + if cfg!(any(target_os = "macos", target_os = "linux")) { + assert!(hw.cpu.is_some(), "{hw:?}"); + assert!(hw.ram_mb.unwrap() > 256, "{hw:?}"); + assert!(hw.os_version.is_some(), "{hw:?}"); + assert!(load_average().is_some()); + assert!(rss_bytes(std::process::id()).unwrap() > 1 << 20); + assert!(cpu_seconds(std::process::id()).unwrap() >= 0.0); + } + } +} diff --git a/crates/horizon-bench/src/lib.rs b/crates/horizon-bench/src/lib.rs new file mode 100644 index 000000000..bdc885af1 --- /dev/null +++ b/crates/horizon-bench/src/lib.rs @@ -0,0 +1,457 @@ +//! The benchmark report format, version 1 (docs/benchmark-report.md). +//! +//! One JSON file per run, the same for the game, the launcher and `tools/perf_bench.py`: the local log +//! a player can attach, and, with consent, what the telemetry upload sends ([`Report::for_upload`]). +//! It holds summaries and fixed-edge histogram counts, never raw frame streams. + +use std::collections::BTreeMap; +use std::io; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; + +mod hardware; + +pub use hardware::{cpu_seconds, load_average, power_source, rss_bytes, Display, Gpu, Hardware}; + +pub const FORMAT: &str = "horizon-benchmark-report"; +pub const VERSION: u32 = 1; + +/// Lower edges of the frame-time histogram buckets, in milliseconds; the last bucket is 1000 ms and +/// over. Fixed by the format version so histograms from any number of reports add up. +pub const HISTOGRAM_EDGES_MS: [f64; 24] = [ + 0.0, 1.0, 2.0, 3.0, 4.17, 5.0, 6.0, 7.0, 8.33, 10.0, 12.0, 14.0, 16.67, 20.0, 25.0, 33.33, + 40.0, 50.0, 66.67, 100.0, 150.0, 250.0, 500.0, 1000.0, +]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Kind { + Game, + Launcher, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct App { + pub name: String, + pub version: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub commit: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub mods: Vec, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Mod { + pub name: String, + pub version: String, +} + +/// What has to match for two reports to be compared. Every field is optional. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Conditions { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scenario: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub seed: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub render_distance: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub simulation_distance: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub window: Option<[u32; 2]>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub vsync: Option, + /// Absent: unlimited. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fps_cap: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub offscreen: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub repeats: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub warmup_s: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub power: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub load_avg_1m: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub backend: Option, +} + +/// A measurement over a run's repeats. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Summary { + pub n: usize, + pub mean: f64, + /// Sample standard deviation; `None` for a single value. + pub stdev: Option, + pub min: f64, + pub max: f64, + /// Half-width of the 95% confidence interval of the mean (Student's t); `None` for a single value. + pub ci95: Option, +} + +impl Summary { + /// `None` for no values. + pub fn of(values: &[f64]) -> Option { + let n = values.len(); + if n == 0 { + return None; + } + let mean = values.iter().sum::() / n as f64; + let (stdev, ci95) = if n > 1 { + let var = values.iter().map(|v| (v - mean).powi(2)).sum::() / (n - 1) as f64; + let sd = var.sqrt(); + (Some(sd), Some(t95(n - 1) * sd / (n as f64).sqrt())) + } else { + (None, None) + }; + Some(Summary { + n, + mean: round(mean), + stdev: stdev.map(round), + min: round(values.iter().copied().fold(f64::INFINITY, f64::min)), + max: round(values.iter().copied().fold(f64::NEG_INFINITY, f64::max)), + ci95: ci95.map(round), + }) + } +} + +/// Two-sided 95% critical value of Student's t for `df` degrees of freedom. +fn t95(df: usize) -> f64 { + const TABLE: [f64; 30] = [ + 12.706, 4.303, 3.182, 2.776, 2.571, 2.447, 2.365, 2.306, 2.262, 2.228, 2.201, 2.179, 2.160, + 2.145, 2.131, 2.120, 2.110, 2.101, 2.093, 2.086, 2.080, 2.074, 2.069, 2.064, 2.060, 2.056, + 2.052, 2.048, 2.045, 2.042, + ]; + TABLE.get(df.wrapping_sub(1)).copied().unwrap_or(1.96) +} + +/// One measured phase of one repeat. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Frames { + pub phase: String, + pub repeat: u32, + pub frames: usize, + pub seconds: f64, + pub avg_fps: f64, + pub low_1pct_fps: f64, + pub low_01pct_fps: f64, + pub p50_ms: f64, + pub p95_ms: f64, + pub p99_ms: f64, + pub p999_ms: f64, + pub max_ms: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cpu_p50_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub gpu_p50_ms: Option, + /// Frame counts per bucket of [`HISTOGRAM_EDGES_MS`]. + pub histogram: Vec, +} + +impl Frames { + /// The figures of a phase from its frame times in milliseconds (time between the starts of + /// consecutive frames); `None` for no frames. CPU and GPU times are per frame too, when measured. + pub fn of( + phase: &str, + repeat: u32, + frame_ms: &[f32], + cpu_ms: &[f32], + gpu_ms: &[f32], + ) -> Option { + let times = sorted(frame_ms); + let n = times.len(); + if n == 0 { + return None; + } + let total: f64 = times.iter().sum(); + // The average frame time of the slowest `share` of frames, as frames per second. + let low = |share: f64| { + let slowest = ×[n - ((n as f64 * share).ceil() as usize).max(1)..]; + 1000.0 * slowest.len() as f64 / slowest.iter().sum::() + }; + let mut histogram = vec![0; HISTOGRAM_EDGES_MS.len()]; + for &t in × { + histogram[HISTOGRAM_EDGES_MS.partition_point(|&edge| edge <= t).max(1) - 1] += 1; + } + Some(Frames { + phase: phase.to_owned(), + repeat, + frames: n, + seconds: round(total / 1000.0), + avg_fps: round(n as f64 * 1000.0 / total), + low_1pct_fps: round(low(0.01)), + low_01pct_fps: round(low(0.001)), + p50_ms: round(percentile(×, 0.5)), + p95_ms: round(percentile(×, 0.95)), + p99_ms: round(percentile(×, 0.99)), + p999_ms: round(percentile(×, 0.999)), + max_ms: round(times[n - 1]), + cpu_p50_ms: (!cpu_ms.is_empty()).then(|| round(percentile(&sorted(cpu_ms), 0.5))), + gpu_p50_ms: (!gpu_ms.is_empty()).then(|| round(percentile(&sorted(gpu_ms), 0.5))), + histogram, + }) + } +} + +fn sorted(ms: &[f32]) -> Vec { + let mut v: Vec = ms + .iter() + .map(|&m| f64::from(m)) + .filter(|m| m.is_finite()) + .collect(); + v.sort_by(f64::total_cmp); + v +} + +/// Three decimals: plenty for milliseconds and FPS, short in JSON, and parsed back exactly. +fn round(v: f64) -> f64 { + (v * 1000.0).round() / 1000.0 +} + +/// Nearest-rank percentile of sorted, non-empty values. +fn percentile(sorted: &[f64], p: f64) -> f64 { + let n = sorted.len(); + sorted[((n as f64 * p).ceil() as usize).clamp(1, n) - 1] +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Report { + pub format: String, + pub version: u32, + pub kind: Kind, + /// When the run ended, UTC, `YYYY-MM-DDTHH:MM:SSZ`. + pub created: String, + pub app: App, + pub hardware: Hardware, + #[serde(default)] + pub conditions: Conditions, + /// Scalar measurements by name; the unit is the name's suffix (`_ms`, `_mb`...). + #[serde(default)] + pub metrics: BTreeMap, + #[serde(default)] + pub frames: Vec, + /// Local only: a name the person running it chose. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option, + /// Local only: logs the run wrote next to the report. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub local: Vec, +} + +impl Report { + /// An empty report for this machine, created now. + pub fn new(kind: Kind, app: App) -> Report { + Report { + format: FORMAT.to_owned(), + version: VERSION, + kind, + created: utc_now(), + app, + hardware: Hardware::detect(), + conditions: Conditions::default(), + metrics: BTreeMap::new(), + frames: Vec::new(), + label: None, + local: Vec::new(), + } + } + + /// Records a measurement over the repeats; no values records nothing. + pub fn metric(&mut self, name: &str, values: &[f64]) { + if let Some(summary) = Summary::of(values) { + self.metrics.insert(name.to_owned(), summary); + } + } + + /// Reads a report, rejecting other formats and newer versions. + pub fn parse(json: &str) -> Result { + let report: Report = serde_json::from_str(json).map_err(|e| e.to_string())?; + if report.format != FORMAT { + return Err(format!( + "not a benchmark report: format {:?}", + report.format + )); + } + if report.version > VERSION { + return Err(format!( + "report version {} is newer than {VERSION}", + report.version + )); + } + Ok(report) + } + + /// The report without its local-only fields, dated to the day: what an upload sends. + pub fn for_upload(&self) -> Report { + let day = self.created.get(..10).unwrap_or_default(); + Report { + label: None, + local: Vec::new(), + created: format!("{day}T00:00:00Z"), + ..self.clone() + } + } + + pub fn to_json(&self) -> String { + serde_json::to_string_pretty(self).expect("a report always serializes") + } + + /// Writes `/--.json` and returns its path. + pub fn write_to(&self, dir: &Path) -> io::Result { + std::fs::create_dir_all(dir)?; + let kind = match self.kind { + Kind::Game => "game", + Kind::Launcher => "launcher", + }; + let stamp: String = self.created.chars().filter(char::is_ascii_digit).collect(); + let scenario: String = self + .conditions + .scenario + .as_deref() + .unwrap_or("run") + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '-' { + c + } else { + '_' + } + }) + .collect(); + let path = dir.join(format!("{kind}-{stamp}-{scenario}.json")); + std::fs::write(&path, self.to_json() + "\n")?; + Ok(path) + } +} + +/// The current time, UTC, `YYYY-MM-DDTHH:MM:SSZ`. +pub fn utc_now() -> String { + let secs = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); + utc(secs) +} + +fn utc(secs: u64) -> String { + let (days, rem) = (secs / 86_400, secs % 86_400); + // Civil date from days since 1970-01-01 (Howard Hinnant's algorithm). + let z = days as i64 + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!( + "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", + rem / 3600, + rem / 60 % 60, + rem % 60 + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn utc_dates() { + assert_eq!(utc(0), "1970-01-01T00:00:00Z"); + assert_eq!(utc(951_782_400), "2000-02-29T00:00:00Z"); + assert_eq!(utc(1_791_983_007), "2026-10-14T13:03:27Z"); + } + + #[test] + fn summary_of_repeats() { + assert_eq!(Summary::of(&[]), None); + let one = Summary::of(&[5.0]).unwrap(); + assert_eq!((one.n, one.mean, one.stdev, one.ci95), (1, 5.0, None, None)); + let s = Summary::of(&[2.0, 4.0, 6.0]).unwrap(); + assert_eq!((s.mean, s.min, s.max), (4.0, 2.0, 6.0)); + assert_eq!(s.stdev, Some(2.0)); + assert_eq!(s.ci95, Some(4.969), "4.303 * 2 / sqrt(3)"); + } + + #[test] + fn frame_figures_and_histogram() { + // 998 frames of 2 ms, one of 20 ms, one of 1500 ms. + let mut ms = vec![2.0f32; 998]; + ms.extend([20.0, 1500.0]); + let f = Frames::of("flight", 0, &ms, &[], &[]).unwrap(); + assert_eq!(f.frames, 1000); + assert_eq!(f.seconds, 3.516); + assert_eq!((f.p50_ms, f.p999_ms, f.max_ms), (2.0, 20.0, 1500.0)); + // Slowest 1% = 10 frames: 8 of 2 ms, 20 ms, 1500 ms. + assert_eq!(f.low_1pct_fps, 6.51, "1000 * 10 / 1536"); + // Slowest 0.1% = the 1500 ms frame. + assert_eq!(f.low_01pct_fps, 0.667); + assert_eq!(f.histogram.len(), HISTOGRAM_EDGES_MS.len()); + assert_eq!(f.histogram[2], 998, "2 ms falls in [2, 3)"); + assert_eq!(f.histogram[13], 1, "20 ms falls in [20, 25)"); + assert_eq!(f.histogram[23], 1, "1500 ms falls in [1000, inf)"); + assert_eq!(f.histogram.iter().sum::(), 1000); + assert_eq!((f.cpu_p50_ms, f.gpu_p50_ms), (None, None)); + assert_eq!(Frames::of("x", 0, &[], &[], &[]), None); + } + + #[test] + fn round_trip_and_upload_strips_local_fields() { + let mut r = Report::new( + Kind::Game, + App { + name: "horizon-client".into(), + version: "0.1.0".into(), + ..App::default() + }, + ); + r.conditions.scenario = Some("flight".into()); + r.metric("startup.title_ms", &[800.0, 820.0]); + r.frames + .extend(Frames::of("village", 0, &[2.0, 3.0], &[1.0], &[])); + r.label = Some("my run".into()); + r.local.push("/home/someone/logs/latest.log".into()); + let back = Report::parse(&r.to_json()).unwrap(); + assert_eq!(back, r); + r.created = "2026-10-15T14:03:27Z".into(); + let upload = r.for_upload(); + assert_eq!(upload.created, "2026-10-15T00:00:00Z", "the day only"); + let upload = upload.to_json(); + assert!( + !upload.contains("my run") && !upload.contains("someone"), + "{upload}" + ); + } + + #[test] + fn rejects_other_formats_and_newer_versions() { + let r = Report::new(Kind::Launcher, App::default()); + let newer = r.to_json().replace("\"version\": 1", "\"version\": 2"); + assert!(Report::parse(&newer).unwrap_err().contains("newer")); + let other = r.to_json().replace(FORMAT, "something-else"); + assert!(Report::parse(&other).is_err()); + } + + #[test] + fn writes_into_a_folder() { + let dir = std::env::temp_dir().join(format!("horizon-bench-test-{}", std::process::id())); + let mut r = Report::new(Kind::Launcher, App::default()); + r.created = "2026-10-15T14:03:27Z".into(); + r.conditions.scenario = Some("cold start".into()); + let path = r.write_to(&dir).unwrap(); + assert_eq!( + path.file_name().unwrap(), + "launcher-20261015140327-cold_start.json" + ); + assert_eq!( + Report::parse(&std::fs::read_to_string(&path).unwrap()).unwrap(), + r + ); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 12aeaae4a..7609b6f78 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -12,12 +12,15 @@ horizon-assets = { path = "../horizon-assets" } horizon-core = { path = "../horizon-core" } horizon-world = { path = "../horizon-world" } horizon-protocol = { path = "../horizon-protocol" } +horizon-friends = { path = "../horizon-friends" } wgpu = { version = "30.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "metal", "wgsl"] } winit = "0.30.13" pollster = "0.4" bytemuck = { version = "1.24", features = ["derive"] } glam = "0.30" png = "0.18" +sha2 = "0.10.9" +serde = { version = "1", features = ["derive"] } serde_json = { version = "1.0.151", features = ["raw_value"] } cpal = "0.16" symphonia = { version = "0.5", default-features = false, features = ["ogg", "vorbis"] } @@ -27,6 +30,9 @@ log = "0.4" chrono = { version = "0.4.42", default-features = false, features = ["clock", "std"] } flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] } horizon-theme = { path = "../horizon-theme" } +# Opt-in data collection: the game keeps, the launcher sends (docs/telemetry.md). +horizon-telemetry = { path = "../horizon-telemetry", default-features = false } +horizon-bench = { path = "../horizon-bench" } arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] } zip = { version = "2", default-features = false, features = ["deflate"] } # Controllers (evdev + libudev on Linux, IOKit on macOS, Windows.Gaming.Input). diff --git a/crates/horizon-client/examples/arrow_probe.rs b/crates/horizon-client/examples/arrow_probe.rs index c8aed6a46..545d7ae4d 100644 --- a/crates/horizon-client/examples/arrow_probe.rs +++ b/crates/horizon-client/examples/arrow_probe.rs @@ -262,7 +262,7 @@ fn main() -> Result<()> { let a = arrow.arrow.as_ref().unwrap(); writeln!( out, - "arrow {} {} {:08x} {:08x} {} {} {} {} {} {} {} {} {} {:016x} {:016x} {} {} {:016x}", + "arrow {} {} {:08x} {:08x} {} {} {} {} {} {} {} {} {} {:016x} {:016x} {} {} {:016x} {}", bits(arrow.position), bits(arrow.velocity), arrow.pitch.to_bits(), @@ -280,7 +280,8 @@ fn main() -> Result<()> { a.fluids.fluid_height(&Tags, LAVA).to_bits(), a.removed, arrow.critical(), - a.fall_distance.to_bits() + a.fall_distance.to_bits(), + bits(arrow.previous) )?; writeln!(out, "events {}", events.join(" | "))?; let a = arrow.arrow.as_ref().unwrap(); diff --git a/crates/horizon-client/examples/chunk_bench.rs b/crates/horizon-client/examples/chunk_bench.rs index be60496f0..0d4a71ce6 100644 --- a/crates/horizon-client/examples/chunk_bench.rs +++ b/crates/horizon-client/examples/chunk_bench.rs @@ -9,7 +9,7 @@ use horizon_client::{ biome::Biomes, blocks::BlockFacts, chunk::{Chunk, MIN_Y, SECTIONS}, - light::{LightTables, light_chunk}, + light::{LightTables, apply_lighting, light_chunk}, mesher::{MeshTables, Mesher}, models, streaming::{ChunkGenerator, Proto}, @@ -105,7 +105,7 @@ fn main() -> Result<()> { ); let mut chunks: Vec = chunks.iter().map(|c| (**c).clone()).collect(); for ((x, z), sections) in lit { - chunks[((z - 1) * inner + x - 1) as usize].sections = sections; + apply_lighting(&mut chunks[((z - 1) * inner + x - 1) as usize], sections); } let chunks: Vec> = chunks.into_iter().map(Arc::new).collect(); let at = |x: i32, z: i32| chunks[((z - 1) * inner + x - 1) as usize].clone(); diff --git a/crates/horizon-client/examples/light_parity.rs b/crates/horizon-client/examples/light_parity.rs index 2307c6da1..afc3e3156 100644 --- a/crates/horizon-client/examples/light_parity.rs +++ b/crates/horizon-client/examples/light_parity.rs @@ -9,7 +9,7 @@ use horizon_client::{ biome::Biomes, blocks::BlockFacts, chunk::{Chunk, MIN_Y, SECTIONS, index}, - light::{LightTables, light_chunk}, + light::{LightTables, apply_lighting, light_chunk}, save, }; use horizon_core::position::ChunkPos; @@ -101,7 +101,7 @@ fn main() -> horizon_client::Result<()> { .unwrap_or((None, None)); let nib = |a: &Option>| a.as_ref().map(|a| (a[i >> 1] >> ((i & 1) * 4)) & 15); let id = chunks[&(x, z)].get(wx & 15, wy, wz & 15); - let packed = lit[si].light(i); + let packed = lit[si].get(i); println!( "{wy}: {} horizon sky {} block {} vanilla sky {:?} block {:?}", facts.states[id as usize].name, @@ -157,7 +157,7 @@ fn main() -> horizon_client::Result<()> { .map_or(15, |a| (a[(i & 255) >> 1] >> ((i & 1) * 4)) & 15), }; let vb = nibble(&block, 0); - let packed = section.light(i); + let packed = section.get(i); let (hs, hb) = (packed >> 4, packed & 15); total += 1; if hs != vs { @@ -228,7 +228,7 @@ fn incremental( std::array::from_fn(|dx| chunks.get(&(x + dx as i32 - 1, z + dz as i32 - 1))) }); let mut c = chunks[&(x, z)].clone(); - c.sections = light_chunk(®ion, tables, sky_light); + apply_lighting(&mut c, light_chunk(®ion, tables, sky_light)); c.lit = true; world.insert((x, z), Arc::new(c)); } @@ -299,7 +299,7 @@ fn incremental( let full = light_chunk(®ion, tables, sky_light); for (si, s) in full.iter().enumerate() { for i in 0..4096 { - let (a, b) = (s.light(i), world[&(kx, kz)].sections[si].light(i)); + let (a, b) = (s.get(i), world[&(kx, kz)].sections[si].light(i)); if a != b { bad += 1; if bad < 20 { diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 1645bc01c..5762abcd6 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -5,13 +5,14 @@ //! usage: mob_ai_probe RESOURCES SCENARIOS OUTPUT use horizon_client::{ assets::Assets, + beehive::HiveHost, biome::Biomes, blocks::BlockFacts, chunk::{Chunk, HEIGHT, MIN_Y}, collisions, containers::{BlockEntity, CreakingHeart}, items::{ItemStack, Items}, - light::{LightTables, light_chunk}, + light::{LightTables, apply_lighting, light_chunk}, mobs::{ Damage, MobType, creaking, creaking_heart::{self, HeartEvent, HeartHost}, @@ -27,7 +28,13 @@ use horizon_core::{ random::LegacyRandom, }; use horizon_world::{chunk::BlockState, registry::BlockRegistry, registry::BlockStateId}; -use std::{collections::BTreeMap, fmt::Write as _, fs, path::Path, sync::Arc}; +use std::{ + collections::{BTreeMap, HashMap}, + fmt::Write as _, + fs, + path::Path, + sync::Arc, +}; struct MobSpec { kind: String, @@ -54,6 +61,8 @@ struct Scenario { hearts: Vec>, /// `ServerLevel.isSpawningMonsters`. spawning: bool, + /// The day time moves on with every tick. + daycycle: bool, /// The player hits a mob for 1 at the start of a tick: (tick, mob index). hurts: Vec<(i32, usize)>, /// The player feeds an animal at the start of a tick (Animal.mobInteract): @@ -85,6 +94,7 @@ fn parse(text: &str) -> Vec { "thunder" => s.thunder = true, "levelseed" => {} "spawning" => s.spawning = true, + "daycycle" => s.daycycle = true, _ => panic!("unknown scenario option {kv}"), } } @@ -407,6 +417,65 @@ impl HeartHost for Host<'_> { self.spawning } } +/// A scenario's beehives as `BeehiveBlockEntity.serverTick` sees the level: +/// the bees let out are newcomers seeded as the oracle seeds them. +struct ProbeHive<'a, 'w> { + w: &'a MobWorld<'w>, + random: &'a mut LegacyRandom, + types: &'a HashMap>, + /// The index of the first newcomer of this tick. + first: usize, + added: &'a mut Vec, + honey: &'a mut Vec<([i32; 3], i32)>, + events: &'a mut Vec, +} +impl HiveHost for ProbeHive<'_, '_> { + fn random(&mut self) -> &mut LegacyRandom { + self.random + } + fn bees_stay_in_hive(&self, _at: [i32; 3]) -> bool { + horizon_client::mobs::bee::bees_stay_in_hive(self.w) + } + fn blocked(&self, at: [i32; 3]) -> bool { + !self.w.block_collision_boxes(at[0], at[1], at[2]).is_empty() + } + fn set_honey_level(&mut self, at: [i32; 3], level: i32) { + self.honey.push((at, level)); + } + fn load(&mut self, tag: &horizon_world::nbt::Tag) -> Option { + let index = self.first + self.added.len(); + let mut m = + horizon_client::entity_nbt::mob_from_nbt(tag, self.types, 100_000 + index as u32)?; + if m.species() != Species::Bee { + return None; + } + m.random = LegacyRandom::new(spawn_seed(index)); + horizon_client::mobs::bee::draw_cooldowns(&mut m); + Some(m) + } + fn add(&mut self, m: Mob) -> bool { + self.added.push(m); + true + } + fn sound(&mut self, name: &'static str, at: [f64; 3]) { + self.events.push(MobEvent::Sound(name, at, 1.0, 1.0)); + } +} +/// The hive's honey level and front from its block state. +fn hive_state(registry: &BlockRegistry, world: &World, at: [i32; 3]) -> (Option, [i32; 2]) { + let props = registry + .state(world.block(at[0], at[1], at[2])) + .map(|s| s.properties.clone()) + .unwrap_or_default(); + let honey = props.get("honey_level").and_then(|v| v.parse().ok()); + let facing = horizon_client::beehive::facing_step(props.get("facing").map(String::as_str)); + (honey, facing) +} +fn is_hive(b: &[String]) -> bool { + b[0] == "block" + && (b[4].starts_with("minecraft:beehive") || b[4].starts_with("minecraft:bee_nest")) +} + /// The heart's state, block entity and the level random, as the oracle /// prints them. fn print_heart( @@ -470,7 +539,7 @@ fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool { /// `player_down`: the scenario's player is no valid target (creative, or /// killed this tick). -fn print(out: &mut String, t: i32, i: usize, m: &Mob, player_down: bool) { +fn print(out: &mut String, t: i32, i: usize, m: &Mob, player_down: bool, now: i64) { let _ = write!(out, "{t} {i}"); if m.removed { // Entity.RemovalReason: the end of the death animation, else a discard. @@ -589,6 +658,21 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob, player_down: bool) { .map_or("-".into(), |p| format!("{},{},{}", p[0], p[1], p[2])); let _ = write!(out, "\tcg {} {held} {opened}", m.extra.variant3); } + if let Some(b) = horizon_client::mobs::bee::get(m) { + let anger = if b.anger_end > 0 { + b.anger_end - now + } else { + -1 + }; + let flower = b + .flower + .map_or("-".into(), |p| format!("{},{},{}", p[0], p[1], p[2])); + let _ = write!( + out, + "\tbee {} {anger} {} {} {flower}", + b.flags, b.ticks_without_nectar, b.flower_cooldown + ); + } out.push('\n'); } @@ -687,6 +771,12 @@ fn main() -> horizon_client::Result<()> { let motion = horizon_client::motion::MotionResources::load(root, &assets)?; let data = MobData::load(root, &facts); let types = MobTypes::load(root)?; + // The types a bee leaving its hive is loaded with (EntityType.loadEntityRecursive). + let arc_types: HashMap> = types + .types + .iter() + .map(|(k, v)| (k.clone(), Arc::new(v.clone()))) + .collect(); let biomes = Biomes::load(root)?; let items = Items::load(root, registry, &facts)?; let tables = LightTables::load(root, registry, &facts)?; @@ -729,6 +819,11 @@ fn main() -> horizon_client::Result<()> { let n = |i: usize| b[i].parse::().unwrap(); if b[0] == "block" || b[0] == "chest" { world.set(n(1), n(2), n(3), state(registry, &b[4]))?; + if is_hive(b) { + world + .block_entities + .insert((n(1), n(2), n(3)), BlockEntity::Beehive(Box::default())); + } if b[0] == "chest" { // chest X Y Z STATE SLOTS: item*count or - per slot. let mut slots = vec![None; 27]; @@ -779,7 +874,7 @@ fn main() -> horizon_client::Result<()> { }) }); let mut c = (*world.chunks[&(x, z)]).clone(); - c.sections = light_chunk(®ion, &tables, true); + apply_lighting(&mut c, light_chunk(®ion, &tables, true)); c.lit = true; ((x, z), c) }) @@ -815,6 +910,7 @@ fn main() -> horizon_client::Result<()> { &mut Vec::new(), ), "inlove" => m.extra.in_love = 600, + "nectar" => horizon_client::mobs::bee::set_has_nectar(&mut m, true), "tame" => m.extra.tame = true, x if x.starts_with("age=") => m.extra.age = x[4..].parse().unwrap(), x if x.starts_with("strength=") => m.extra.variant2 = x[9..].parse().unwrap(), @@ -835,6 +931,10 @@ fn main() -> horizon_client::Result<()> { } } m.random = LegacyRandom::new(spec.seed); + if m.species() == Species::Bee { + // The oracle draws the constructor's cooldowns again once seeded. + horizon_client::mobs::bee::draw_cooldowns(&mut m); + } if horizon_client::mobs::monster_brain::has_brain(m.species()) { // The oracle delays the sensors again with the seeded random // and seeds RunOne's shuffles with the mob's seed. @@ -902,7 +1002,7 @@ fn main() -> horizon_client::Result<()> { // from it, and the scenarios feed neither. let mut level_random = LegacyRandom::new(0); for (i, m) in mobs.iter().enumerate() { - print(&mut out, 0, i, m, s.creative); + print(&mut out, 0, i, m, s.creative, world.game_time); } // The MobWorld every step sees, over a snapshot of the mobs. macro_rules! mob_world { @@ -917,7 +1017,7 @@ fn main() -> horizon_client::Result<()> { data: &data, player: player.clone(), others: $snapshot, - daylight: (s.time.rem_euclid(24000)) < 12000, + daylight: (world.day_time.rem_euclid(24000)) < 12000, game_time: world.game_time, day_time: world.day_time, raining: s.rain, @@ -937,6 +1037,9 @@ fn main() -> horizon_client::Result<()> { } for t in 1..=s.ticks { world.game_time += 1; + if s.daycycle { + world.day_time = s.time + i64::from(t); + } let mut heart_events_later: Vec = Vec::new(); // Creaking.tick reads the heart's block entity. for (at, h) in &hearts { @@ -1102,6 +1205,41 @@ fn main() -> horizon_client::Result<()> { _ => {} } } + // BeeEnterHiveGoal.start: BeehiveBlockEntity.addOccupant. + let entering: Vec<[i32; 3]> = events[from.min(events.len())..] + .iter() + .filter_map(|e| match e { + MobEvent::EnterHive { hive, .. } => Some(*hive), + _ => None, + }) + .collect(); + for at in entering { + let key = (at[0], at[1], at[2]); + let Some(BlockEntity::Beehive(mut hive)) = world.block_entities.remove(&key) + else { + continue; + }; + let tag = horizon_client::entity_nbt::mob_to_nbt(&mobs[i], [0; 4], None); + let flower = horizon_client::mobs::bee::get(&mobs[i]).and_then(|b| b.flower); + let mut honey = Vec::new(); + let stored = { + let w = mob_world!(&snapshot); + let mut host = ProbeHive { + w: &w, + random: &mut scratch, + types: &arc_types, + first: 0, + added: &mut Vec::new(), + honey: &mut honey, + events: &mut events, + }; + hive.add_occupant(at, tag, flower, &mut host) + }; + world.block_entities.insert(key, BlockEntity::Beehive(hive)); + if stored { + mobs[i].removed = true; + } + } // 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) { @@ -1134,6 +1272,43 @@ fn main() -> horizon_client::Result<()> { added.append(&mut host.added); } drop(w); + // Then the hives (BeehiveBlockEntity.serverTick). + let mut hive_keys: Vec<(i32, i32, i32)> = world + .block_entities + .iter() + .filter(|(_, e)| matches!(e, BlockEntity::Beehive(_))) + .map(|(k, _)| *k) + .collect(); + hive_keys.sort_unstable(); + let mut honey = Vec::new(); + for key in hive_keys { + let at = [key.0, key.1, key.2]; + let (level, facing) = hive_state(registry, &world, at); + let Some(BlockEntity::Beehive(mut hive)) = world.block_entities.remove(&key) else { + continue; + }; + { + let w = mob_world!(&snapshot); + let mut host = ProbeHive { + w: &w, + random: &mut scratch, + types: &arc_types, + first: mobs.len() + born.len(), + added: &mut added, + honey: &mut honey, + events: &mut events, + }; + hive.server_tick(at, facing, level, &mut host); + } + world.block_entities.insert(key, BlockEntity::Beehive(hive)); + } + for (at, level) in honey { + if let Some(mut st) = registry.state(world.block(at[0], at[1], at[2])).cloned() { + st.properties + .insert("honey_level".to_owned(), level.to_string()); + world.set(at[0], at[1], at[2], registry.resolve(&st)?)?; + } + } mobs.append(&mut born); mobs.append(&mut added); for e in &heart_events { @@ -1152,7 +1327,14 @@ fn main() -> horizon_client::Result<()> { .iter() .any(|e| player_hurt(player.as_ref(), e) && player_damage(e) >= 20.0); for (i, m) in mobs.iter().enumerate() { - print(&mut out, t, i, m, s.creative || player_killed); + print( + &mut out, + t, + i, + m, + s.creative || player_killed, + world.game_time, + ); } for e in &events { if let MobEvent::Sound(name, _, volume, pitch) = e { @@ -1209,6 +1391,35 @@ fn main() -> horizon_client::Result<()> { } ); } + for b in s.blocks.iter().filter(|b| is_hive(b)) { + let n = |i: usize| b[i].parse::().unwrap(); + let Some(BlockEntity::Beehive(hive)) = + world.block_entities.get(&(n(1), n(2), n(3))) + else { + continue; + }; + let (level, _) = hive_state(registry, &world, [n(1), n(2), n(3)]); + let bees: Vec = hive + .bees + .iter() + .map(|b| format!("{}/{}", b.ticks_in_hive, b.min_ticks_in_hive)) + .collect(); + let _ = writeln!( + out, + "{t} hive {},{},{} honey {} bees {} flower {}", + b[1], + b[2], + b[3], + level.unwrap_or(-1), + if bees.is_empty() { + "-".into() + } else { + bees.join(",") + }, + hive.flower + .map_or("-".into(), |f| format!("{},{},{}", f[0], f[1], f[2])) + ); + } for line in traces { let _ = writeln!(out, "{line}"); } diff --git a/crates/horizon-client/examples/model_states_bench.rs b/crates/horizon-client/examples/model_states_bench.rs new file mode 100644 index 000000000..577ff649e --- /dev/null +++ b/crates/horizon-client/examples/model_states_bench.rs @@ -0,0 +1,291 @@ +//! Compare the old two-parse loading path with catalog construction from shared facts. +//! Run: cargo run -p horizon-client --profile fast --example model_states_bench -- 15 +use horizon_client::{Result, models::StateModels, sprites::Sprites}; +use horizon_core::position::BlockPos; +use horizon_world::{ + DATA_VERSION, + chunk::BlockState, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, +}; +use serde_json::{Value, json}; +use std::{collections::BTreeMap, fs, hint::black_box, path::PathBuf, time::Instant}; + +struct Fixture { + root: PathBuf, + registry: BlockRegistry, + bytes: usize, + blocks: usize, +} +impl Fixture { + fn new(target_bytes: usize) -> Result { + let root = + std::env::temp_dir().join(format!("horizon-model-states-{}", std::process::id())); + fs::create_dir_all(root.join("assets/minecraft/blockstates"))?; + fs::create_dir_all(root.join("assets/minecraft/models/block"))?; + let mut possible = Vec::new(); + for age in 0..8 { + for facing in ["north", "south", "east", "west"] { + for waterlogged in ["false", "true"] { + possible.push( + json!({"age":age.to_string(), "facing":facing, "waterlogged":waterlogged}), + ); + } + } + } + let fact = json!({"schema":{ + "age":{"integer":[0,7]}, + "facing":{"named":["north","south","east","west"]}, + "waterlogged":{"named":["false","true"]} + },"states":possible}); + let blocks = (target_bytes / (serde_json::to_vec(&fact)?.len() + 26)).max(1); + let mut facts = BTreeMap::new(); + let mut states = Vec::new(); + let mut defaults = BTreeMap::new(); + for i in 0..blocks { + let block = format!("fixture_{i:04}"); + let name = format!("minecraft:{block}"); + defaults.insert(name.as_str().into(), Tag::Int(states.len() as i32)); + for properties in &possible { + let state = BlockState { + name: name.clone(), + properties: serde_json::from_value(properties.clone())?, + }; + states.push(state.to_nbt()); + } + facts.insert(name, fact.clone()); + fs::write( + root.join(format!("assets/minecraft/blockstates/{block}.json")), + r#"{"multipart":[{"apply":[{"model":"minecraft:block/fixture","weight":2},{"model":"minecraft:block/fixture","y":90,"weight":1}]},{"when":{"waterlogged":"true"},"apply":{"model":"minecraft:block/fixture","y":180,"uvlock":true}}]}"#, + )?; + } + fs::write( + root.join("assets/minecraft/models/block/fixture.json"), + r##"{"textures":{"all":"minecraft:block/fixture"},"elements":[{"from":[0,0,0],"to":[16,16,16],"faces":{"north":{"texture":"#all","cullface":"north"}}}]}"##, + )?; + let document = serde_json::to_vec(&facts)?; + let bytes = document.len(); + fs::write(root.join("model-states.json"), document)?; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("states", Tag::List(states)), + ("defaults", Tag::Compound(defaults)), + ]))?; + Ok(Self { + root, + registry, + bytes, + blocks, + }) + } + fn facts(&self) -> Result> { + Ok(serde_json::from_slice(&fs::read( + self.root.join("model-states.json"), + )?)?) + } + fn block_names<'a>(&self, names: impl Iterator) -> Vec<&'a str> { + names + .filter(|name| self.registry.default_state(name).is_some()) + .filter_map(|name| name.strip_prefix("minecraft:")) + .collect() + } + fn load(&self, reuse: bool) -> Result<(StateModels, Sprites)> { + // The first parse and block filtering match models::prepare in both paths. + let mut sprites = Sprites::default(); + let catalog = if reuse { + let facts = self.facts()?; + let blocks = self.block_names(facts.keys()); + StateModels::from_facts(&self.root, &self.registry, &blocks, &mut sprites, &facts)? + } else { + let facts: serde_json::Map = + serde_json::from_slice(&fs::read(self.root.join("model-states.json"))?)?; + let blocks = self.block_names(facts.keys()); + StateModels::load(&self.root, &self.registry, &blocks, &mut sprites)? + }; + Ok((catalog, sprites)) + } + fn verify(&self) -> Result<()> { + let (before, before_sprites) = self.load(false)?; + let (after, after_sprites) = self.load(true)?; + assert_eq!(before_sprites.layers, after_sprites.layers); + assert_eq!(before_sprites.opaque, after_sprites.opaque); + assert_eq!(before_sprites.translucent, after_sprites.translucent); + for id in 0..self.registry.len() { + for position in [ + BlockPos::new(0, 0, 0), + BlockPos::new(12, -4, 7), + BlockPos::new(42, 9, -19), + ] { + let a = before.collect(BlockStateId(id as u32), position)?; + let b = after.collect(BlockStateId(id as u32), position)?; + assert_eq!(a.len(), b.len()); + for ((av, am), (bv, bm)) in a.into_iter().zip(b) { + assert_eq!(av, bv); + assert_eq!(am.ambient_occlusion, bm.ambient_occlusion); + assert_eq!(am.cube, bm.cube); + assert_eq!(am.faces.len(), bm.faces.len()); + for (af, bf) in am.faces.iter().zip(&bm.faces) { + assert_eq!(af.quad, bf.quad); + assert_eq!( + (af.layer, af.opaque, af.translucent), + (bf.layer, bf.opaque, bf.translucent) + ); + } + } + } + } + Ok(()) + } +} +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.root); + } +} +fn median(values: &mut [f64]) -> f64 { + values.sort_by(f64::total_cmp); + values[values.len() / 2] +} +fn main() -> Result<()> { + let repetitions: usize = std::env::args() + .nth(1) + .map(|s| s.parse()) + .transpose()? + .unwrap_or(15); + if repetitions == 0 { + return Err("repetitions must be positive".into()); + } + let fixture = Fixture::new(2_840_000)?; + fixture.verify()?; + for _ in 0..2 { + for reuse in [false, true] { + drop(black_box(fixture.load(reuse)?)); + } + } + let mut before = Vec::new(); + let mut after = Vec::new(); + for iteration in 0..repetitions { + // Alternate order to limit cache/order bias. Both paths use slice parsing. + for reuse in if iteration % 2 == 0 { + [false, true] + } else { + [true, false] + } { + let started = Instant::now(); + drop(black_box(fixture.load(black_box(reuse))?)); + let ms = started.elapsed().as_secs_f64() * 1000.0; + if reuse { + after.push(ms); + } else { + before.push(ms); + } + } + } + let before = median(&mut before); + let after = median(&mut after); + println!( + "fixture: {} bytes, {} blocks, {} states; equality: all states at 3 positions", + fixture.bytes, + fixture.blocks, + fixture.registry.len() + ); + println!( + "2 warmups/path, {repetitions} samples/path; median before {before:.3} ms, after {after:.3} ms; {:.3}x speedup ({:.2}% less time)", + before / after, + (1.0 - after / before) * 100.0 + ); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn shared_facts_match_load_and_preserve_errors() -> Result<()> { + let fixture = Fixture::new(1)?; + fixture.verify()?; + let mut facts = fixture.facts()?; + let blocks = ["fixture_0000"]; + let load_error = |facts: &BTreeMap| -> Result { + fs::write( + fixture.root.join("model-states.json"), + serde_json::to_vec(facts)?, + )?; + let a = StateModels::load( + &fixture.root, + &fixture.registry, + &blocks, + &mut Sprites::default(), + ) + .err() + .ok_or("expected load error")? + .to_string(); + let b = StateModels::from_facts( + &fixture.root, + &fixture.registry, + &blocks, + &mut Sprites::default(), + facts, + ) + .err() + .ok_or("expected shared facts error")? + .to_string(); + assert_eq!(a, b); + Ok(a) + }; + let good = facts.clone(); + facts.clear(); + assert_eq!(load_error(&facts)?, "missing block model state schema"); + facts = good.clone(); + facts.get_mut("minecraft:fixture_0000").unwrap()["schema"] = Value::Null; + assert_eq!(load_error(&facts)?, "invalid model schema"); + facts = good.clone(); + facts.get_mut("minecraft:fixture_0000").unwrap()["states"] + .as_array_mut() + .unwrap() + .reverse(); + assert_eq!( + load_error(&facts)?, + "model state definitions disagree with the imported block registry" + ); + fs::remove_file(fixture.root.join("model-states.json"))?; + // A parsed document remains usable without reopening its source file. + StateModels::from_facts( + &fixture.root, + &fixture.registry, + &blocks, + &mut Sprites::default(), + &good, + )?; + assert!( + StateModels::load( + &fixture.root, + &fixture.registry, + &blocks, + &mut Sprites::default() + ) + .is_err() + ); + fs::write(fixture.root.join("model-states.json"), b"null")?; + assert!( + StateModels::load( + &fixture.root, + &fixture.registry, + &blocks, + &mut Sprites::default() + ) + .is_err() + ); + fs::write(fixture.root.join("model-states.json"), b"{")?; + assert!( + StateModels::load( + &fixture.root, + &fixture.registry, + &blocks, + &mut Sprites::default() + ) + .is_err() + ); + Ok(()) + } +} diff --git a/crates/horizon-client/examples/save_parity.rs b/crates/horizon-client/examples/save_parity.rs index 017f60294..ba2c4b0fa 100644 --- a/crates/horizon-client/examples/save_parity.rs +++ b/crates/horizon-client/examples/save_parity.rs @@ -10,7 +10,7 @@ use horizon_client::{ biome::Biomes, blocks::BlockFacts, chunk::{Chunk, MIN_Y, SECTIONS}, - light::{LightTables, light_chunk}, + light::{LightTables, apply_lighting, light_chunk}, save::{self, SaveTables}, }; use horizon_core::position::ChunkPos; @@ -157,7 +157,7 @@ fn main() -> horizon_client::Result<()> { std::array::from_fn(|dx| chunks.get(&(x + dx as i32 - 1, z + dz as i32 - 1))) }); let mut chunk = chunks[&(x, z)].clone(); - chunk.sections = light_chunk(®ion, &lights, sky_light); + apply_lighting(&mut chunk, light_chunk(®ion, &lights, sky_light)); chunk.lit = true; let ours = save::encode_with(&chunk, assets.registry, &biomes, Some(&tables), sky_light); let theirs = &originals[&(x, z)]; diff --git a/crates/horizon-client/examples/scene_motion_probe.rs b/crates/horizon-client/examples/scene_motion_probe.rs index d5ef55d37..726ac278b 100644 --- a/crates/horizon-client/examples/scene_motion_probe.rs +++ b/crates/horizon-client/examples/scene_motion_probe.rs @@ -199,6 +199,28 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> { velocity.z.to_bits() )), MotionEvent::SplashEvent => Some("splash-event".into()), + MotionEvent::Swim { volume, pitch } => Some(format!( + "sound swim entity {:08x} {:08x}", + volume.to_bits(), + pitch.to_bits() + )), + MotionEvent::Emission { + state, + in_water: true, + .. + } => Some(format!("muffled-step {}", state.0)), + MotionEvent::BubbleColumnParticle { bubble, position } => Some(format!( + "column-particle {} {:016x},{:016x},{:016x} 1 {:016x},{:016x},{:016x} {:016x}", + if *bubble { "bubble" } else { "splash" }, + position.x.to_bits(), + position.y.to_bits(), + position.z.to_bits(), + 0f64.to_bits(), + if *bubble { 0.01f64 } else { 0.0 }.to_bits(), + 0f64.to_bits(), + if *bubble { 0.2f64 } else { 1.0 }.to_bits() + )), + MotionEvent::Drown => Some("broadcast 67".into()), // The oracle marks every getAdvancements call (ENTER_BLOCK.trigger) so. MotionEvent::EnterBlock { .. } => Some("hurt-criterion".into()), MotionEvent::Waypoint { receiver, enabled } => Some(format!( @@ -399,7 +421,8 @@ fn main() -> Result<()> { Some(vector(&op["value"])) }, ), - "block" => { + // A block, or every block of the box from position to "to". + "block" | "fill" => { let p = &op["position"]; let mut state = assets .registry @@ -417,12 +440,15 @@ fn main() -> Result<()> { .id(&definition) .ok_or("missing fixture state")?; } - world.scene.set( - p[0].as_i64().unwrap() as i32, - p[1].as_i64().unwrap() as i32, - p[2].as_i64().unwrap() as i32, - state, - )?; + let at = |v: &Value, i: usize| v[i].as_i64().unwrap() as i32; + let to = if op["to"].is_array() { &op["to"] } else { p }; + for x in at(p, 0)..=at(to, 0) { + for y in at(p, 1)..=at(to, 1) { + for z in at(p, 2)..=at(to, 2) { + world.scene.set(x, y, z, state)?; + } + } + } } "landing" => { let p = &op["position"]; @@ -443,6 +469,23 @@ fn main() -> Result<()> { // Entity.baseTick's fluid phase alone (wasEyeInWater, // updateFluidInteraction, lava fall halving, firstTick). "fluid_tick" => world.fluid_base_tick()?, + // LivingEntity.baseTick's air supply alone. + "air_tick" => world.tick_environment_damage()?, + "air" => world.player.air = op["value"].as_i64().unwrap() as i32, + "pitch" => world.player.pitch = single(&op["value"]), + "swimming" => world.player.swimming = op["value"].as_bool().unwrap(), + "effect" => { + let on = op["value"].as_bool().unwrap(); + let status = &mut world.player.status; + match op["name"].as_str().unwrap() { + "minecraft:dolphins_grace" => status.dolphins_grace = on, + "minecraft:water_breathing" | "minecraft:conduit_power" => { + status.water_breathing = on + } + "minecraft:breath_of_the_nautilus" => status.breath_of_the_nautilus = on, + other => return Err(format!("unknown fixture effect {other}").into()), + } + } "travel" => world.travel_in_air(vector(&op["value"]))?, "tick" => { let v = vector(&op["value"]); @@ -569,7 +612,7 @@ fn main() -> Result<()> { let stuck = player.stuck_multiplier; writeln!( out, - "block {} frozen {} {} {} {:016x},{:016x},{:016x} fluid {} {} {} {} {:016x} {:016x}", + "block {} frozen {} {} {} {:016x},{:016x},{:016x} fluid {} {} {} {} {:016x} {:016x} swim {} {} air {}", check_block.0, player.ticks_frozen, player.in_powder_snow, @@ -582,7 +625,10 @@ fn main() -> Result<()> { player.is_eye_in_fluid(WATER), player.fluids.first_tick, player.fluid_height(WATER).to_bits(), - player.fluid_height(LAVA).to_bits() + player.fluid_height(LAVA).to_bits(), + player.swimming, + player.fluids.was_eye_in_water, + player.air )?; writeln!( out, diff --git a/crates/horizon-client/examples/tick_chunk_membership_bench.rs b/crates/horizon-client/examples/tick_chunk_membership_bench.rs new file mode 100644 index 000000000..6b9cb8a0a --- /dev/null +++ b/crates/horizon-client/examples/tick_chunk_membership_bench.rs @@ -0,0 +1,143 @@ +//! Resident-key synchronization used by Game (registration callback work excluded). +//! Run: CARGO_INCREMENTAL=0 cargo run -p horizon-client --profile fast --example tick_chunk_membership_bench +use horizon_client::{ + chunk::Chunk, chunk_map::ChunkMap, tick_chunk_membership::TickChunkMembership, +}; +use std::{collections::HashSet, hint::black_box, sync::Arc, time::Instant}; + +type Key = (i32, i32); +#[derive(Default)] +struct Old { + keys: HashSet, +} +impl Old { + fn sync(&mut self, map: &ChunkMap) -> (usize, usize) { + let loaded: HashSet<_> = map.keys().copied().collect(); + let mut counts = (0, 0); + for key in loaded.difference(&self.keys.clone()) { + black_box(key); + counts.0 += 1; + } + for key in self.keys.difference(&loaded) { + black_box(key); + counts.1 += 1; + } + self.keys = loaded; + counts + } +} +fn new_sync(cache: &mut TickChunkMembership, map: &ChunkMap) -> (usize, usize) { + if !cache.synchronize(map) { + return (0, 0); + } + let added = cache.take_added(); + for key in &added { + black_box(key); + } + for key in cache.removed() { + black_box(key); + } + let counts = (added.len(), cache.removed().len()); + cache.recycle_added(added); + counts +} +fn map(offset: i32) -> ChunkMap { + let mut map = ChunkMap::default(); + // Share a payload: the synchronization path reads only keys, not block data. + let chunk = Arc::new(Chunk::empty(0, 0)); + for x in -16..=16 { + for z in -16..=16 { + map.insert((x + offset, z), chunk.clone()); + } + } + map +} +fn run(new: bool, scenario: usize, iterations: usize) -> (f64, (usize, usize)) { + let mut a = map(0); + let b = map(33); + let chunk = Arc::new(Chunk::empty(0, 0)); + let mut old = Old::default(); + let mut cache = TickChunkMembership::default(); + for _ in 0..64 { + if new { + black_box(new_sync(&mut cache, &a)); + } else { + black_box(old.sync(&a)); + } + } + let mut total = (0, 0); + let start = Instant::now(); + for i in 0..iterations { + let resident = match scenario { + 0 => &a, + 1 => { + let (previous, next) = if i % 2 == 0 { + ((-16, -16), (-17, -16)) + } else { + ((-17, -16), (-16, -16)) + }; + a.remove(&previous); + a.insert(next, chunk.clone()); + &a + } + 2 => { + if i % 2 == 0 { + &b + } else { + &a + } + } + _ => unreachable!(), + }; + let counts = if new { + new_sync(black_box(&mut cache), black_box(resident)) + } else { + old.sync(black_box(resident)) + }; + total.0 += counts.0; + total.1 += counts.1; + } + ( + start.elapsed().as_secs_f64() * 1e9 / iterations as f64, + black_box(total), + ) +} +fn main() { + println!("1089 keys, 64 warmup calls, 9 samples; ns/sync, median"); + for (scenario, name, iterations) in [ + (0, "stable", 10_000), + (1, "one-key same-count replacement", 2_000), + (2, "whole-map replacement", 1_000), + ] { + let mut before = Vec::new(); + let mut after = Vec::new(); + for sample in 0..9 { + let (old, new) = if sample % 2 == 0 { + ( + run(false, scenario, iterations), + run(true, scenario, iterations), + ) + } else { + let new = run(true, scenario, iterations); + (run(false, scenario, iterations), new) + }; + assert_eq!(old.1, new.1); + let expected = match scenario { + 0 => (0, 0), + 1 => (iterations, iterations), + _ => (1089 * iterations, 1089 * iterations), + }; + assert_eq!(new.1, expected); + before.push(old.0); + after.push(new.0); + } + before.sort_by(f64::total_cmp); + after.sort_by(f64::total_cmp); + println!( + "{name}: {:.1} -> {:.1} ns, {:.2}x; {iterations} iterations/sample", + before[4], + after[4], + before[4] / after[4] + ); + } +} diff --git a/crates/horizon-client/src/arrows.rs b/crates/horizon-client/src/arrows.rs index 1520ee7ca..d89d82161 100644 --- a/crates/horizon-client/src/arrows.rs +++ b/crates/horizon-client/src/arrows.rs @@ -387,6 +387,9 @@ pub fn tick(p: &mut Projectile, scene: &ArrowScene, targets: &[(Who, Aabb)]) -> let Some(mut st) = p.arrow.take() else { return (false, Hit::None); }; + // Entity.setOldPosAndRot: the renderer interpolates from here, in flight + // and stuck alike. + p.previous = p.position; let hit = Ticker { p, st: &mut st, diff --git a/crates/horizon-client/src/beehive.rs b/crates/horizon-client/src/beehive.rs new file mode 100644 index 000000000..26aa87cfc --- /dev/null +++ b/crates/horizon-client/src/beehive.rs @@ -0,0 +1,438 @@ +//! Beehives and bee nests (`BeehiveBlockEntity`): up to three bees stored as +//! entity tags, let out when their time inside is up (never at night or in +//! the rain, nor through a blocked front, unless the hive is emptied in an +//! emergency), honey for every bee coming home with nectar. The host (the game +//! or the mob AI probe) loads and adds the bees through [`HiveHost`]. +use crate::mobs::{Mob, Species, bee}; +use horizon_core::random::{LegacyRandom, RandomSource}; +use horizon_world::nbt::{Compound, Tag}; + +pub const MAX_OCCUPANTS: usize = 3; +/// `BeehiveBlockEntity.IGNORED_BEE_TAGS`: dropped from a bee going in, and +/// again from the tag it comes out with. +const IGNORED_BEE_TAGS: [&str; 25] = [ + "Air", + "drop_chances", + "equipment", + "Brain", + "CanPickUpLoot", + "DeathTime", + "fall_distance", + "FallFlying", + "Fire", + "HurtTime", + "LeftHanded", + "Motion", + "NoGravity", + "OnGround", + "PortalCooldown", + "Pos", + "Rotation", + "sleeping_pos", + "CannotEnterHiveTicks", + "TicksSincePollination", + "CropsGrownSincePollination", + "hive_pos", + "Passengers", + "leash", + "UUID", +]; + +/// `BeehiveBlockEntity`: the bees inside and the flower one of them knew. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Beehive { + pub bees: Vec, + pub flower: Option<[i32; 3]>, +} +/// `BeehiveBlockEntity.Occupant`: a bee's tag (with its `id`), its time in +/// the hive and the time it stays at least. +#[derive(Clone, Debug, PartialEq)] +pub struct Occupant { + pub entity_data: Tag, + pub ticks_in_hive: i32, + pub min_ticks_in_hive: i32, +} +/// `BeehiveBlockEntity.BeeReleaseStatus`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Release { + HoneyDelivered, + BeeReleased, + Emergency, +} + +/// What a hive needs from the level it is in. +pub trait HiveHost { + /// `level.getRandom()`. + fn random(&mut self) -> &mut LegacyRandom; + /// `EnvironmentAttributes.BEES_STAY_IN_HIVE` at a position. + fn bees_stay_in_hive(&self, at: [i32; 3]) -> bool; + /// A non-empty collision shape at a block. + fn blocked(&self, at: [i32; 3]) -> bool; + /// `BlockState.setValue(HONEY_LEVEL, level)` on the hive. + fn set_honey_level(&mut self, at: [i32; 3], level: i32); + /// `EntityType.loadEntityRecursive` (the tag has its `id` and a `Pos`): + /// a new entity, or `None` for anything but a `#beehive_inhabitors`. + fn load(&mut self, tag: &Tag) -> Option; + /// `Level.addFreshEntity`. + fn add(&mut self, m: Mob) -> bool; + fn sound(&mut self, name: &'static str, at: [f64; 3]); +} + +fn strip_ignored(c: &mut Compound) { + for key in IGNORED_BEE_TAGS { + c.remove(&key.into()); + } +} +fn int(tag: Option<&Tag>) -> Option { + match tag { + Some(Tag::Int(v)) => Some(*v), + _ => None, + } +} +fn pos(tag: Option<&Tag>) -> Option<[i32; 3]> { + match tag { + Some(Tag::IntArray(p)) if p.len() == 3 => Some([p[0], p[1], p[2]]), + _ => None, + } +} + +impl Occupant { + /// `Occupant.of`: the bee's saved tag without the ignored tags, staying + /// 2400 ticks with nectar, else 600. + pub fn of(mut tag: Tag) -> Self { + if let Tag::Compound(c) = &mut tag { + strip_ignored(c); + } + let nectar = matches!(tag.get("HasNectar"), Some(Tag::Byte(v)) if *v != 0); + Self { + entity_data: tag, + ticks_in_hive: 0, + min_ticks_in_hive: if nectar { 2400 } else { 600 }, + } + } + /// `Occupant.create`: a worldgen nest's bee, a bare bee tag. + pub fn create(ticks_in_hive: i32) -> Self { + Self { + entity_data: Tag::compound([("id", Tag::String("minecraft:bee".into()))]), + ticks_in_hive, + min_ticks_in_hive: 600, + } + } + fn has_nectar(&self) -> bool { + matches!(self.entity_data.get("HasNectar"), Some(Tag::Byte(v)) if *v != 0) + } + fn from_nbt(tag: &Tag) -> Option { + let data = tag.get("entity_data")?; + if !matches!(data, Tag::Compound(c) if c.contains_key(&"id".into())) { + return None; + } + Some(Self { + entity_data: data.clone(), + ticks_in_hive: int(tag.get("ticks_in_hive"))?, + min_ticks_in_hive: int(tag.get("min_ticks_in_hive"))?, + }) + } + fn to_nbt(&self) -> Tag { + Tag::compound([ + ("entity_data", self.entity_data.clone()), + ("ticks_in_hive", Tag::Int(self.ticks_in_hive)), + ("min_ticks_in_hive", Tag::Int(self.min_ticks_in_hive)), + ]) + } +} + +impl Beehive { + pub fn full(&self) -> bool { + self.bees.len() == MAX_OCCUPANTS + } + /// `loadAdditional`: `bees` (all or none, as the list codec reads them) + /// and `flower_pos`. + pub fn from_nbt(tag: &Tag) -> Self { + let bees = match tag.get("bees") { + Some(Tag::List(list)) => list + .iter() + .map(Occupant::from_nbt) + .collect::>>() + .unwrap_or_default(), + _ => Vec::new(), + }; + Self { + bees, + flower: pos(tag.get("flower_pos")), + } + } + /// `saveAdditional`. + pub fn to_nbt(&self) -> Vec<(&'static str, Tag)> { + let mut out = vec![( + "bees", + Tag::List(self.bees.iter().map(Occupant::to_nbt).collect()), + )]; + if let Some(f) = self.flower { + out.push(("flower_pos", Tag::IntArray(f.to_vec()))); + } + out + } + /// `addOccupant` (the bee's own tag, saved by the host): the hive keeps + /// the bee's flower, or now and then swaps its own for it. The host then + /// discards the bee. + pub fn add_occupant( + &mut self, + at: [i32; 3], + tag: Tag, + bee_flower: Option<[i32; 3]>, + host: &mut impl HiveHost, + ) -> bool { + if self.bees.len() >= MAX_OCCUPANTS { + return false; + } + self.bees.push(Occupant::of(tag)); + if let Some(f) = bee_flower + && (self.flower.is_none() || host.random().next_boolean()) + { + self.flower = Some(f); + } + let corner = at.map(f64::from); + host.sound("block.beehive.enter", corner); + true + } + /// `serverTick`: the bees whose time is up come out, then the hive + /// hums now and then while it holds any. `honey` is the hive state's + /// honey level as the tick starts (`None` without the property); + /// `facing` its front. + pub fn server_tick( + &mut self, + at: [i32; 3], + facing: [i32; 2], + honey: Option, + host: &mut impl HiveHost, + ) { + let flower = self.flower; + let mut i = 0; + while i < self.bees.len() { + // BeeData.tick: ticksInHive++ > minTicksInHive. + let b = &mut self.bees[i]; + let up = b.ticks_in_hive > b.min_ticks_in_hive; + b.ticks_in_hive += 1; + if up { + let status = if b.has_nectar() { + Release::HoneyDelivered + } else { + Release::BeeReleased + }; + let occupant = b.clone(); + if release(host, at, facing, honey, &occupant, status, flower).is_some() { + self.bees.remove(i); + continue; + } + } + i += 1; + } + if !self.bees.is_empty() && host.random().next_double() < 0.005 { + let hum = [ + f64::from(at[0]) + 0.5, + f64::from(at[1]), + f64::from(at[2]) + 0.5, + ]; + host.sound("block.beehive.work", hum); + } + } + /// `releaseAllOccupants`: the ids of the bees let out. + pub fn release_all( + &mut self, + at: [i32; 3], + facing: [i32; 2], + honey: Option, + status: Release, + host: &mut impl HiveHost, + ) -> Vec { + let flower = self.flower; + let mut out = Vec::new(); + self.bees.retain( + |b| match release(host, at, facing, honey, b, status, flower) { + Some(id) => { + out.extend(id); + false + } + None => true, + }, + ); + out + } +} + +/// `releaseOccupant`: `None` while the bee stays in, else the id of the bee +/// let out (`Some(None)` when the level refused it). +fn release( + host: &mut impl HiveHost, + at: [i32; 3], + facing: [i32; 2], + honey: Option, + occupant: &Occupant, + status: Release, + flower: Option<[i32; 3]>, +) -> Option> { + let emergency = status == Release::Emergency; + if host.bees_stay_in_hive(at) && !emergency { + return None; + } + let blocked = host.blocked([at[0] + facing[0], at[1], at[2] + facing[1]]); + if blocked && !emergency { + return None; + } + // Occupant.createEntity: the tag without the ignored tags. + let mut tag = occupant.entity_data.clone(); + if let Tag::Compound(c) = &mut tag { + strip_ignored(c); + let center = [at[0], at[1], at[2]].map(|v| Tag::Double((f64::from(v) + 0.5).to_bits())); + c.insert("Pos".into(), Tag::List(center.to_vec())); + } + let mut m = host.load(&tag)?; + m.no_gravity = true; + if m.species() == Species::Bee { + bee::set_hive(&mut m, Some(at)); + // setBeeReleaseData: the time inside counts towards growing up and + // away from love. + let ticks = occupant.ticks_in_hive; + if !m.extra.age_locked { + let age = m.extra.age; + m.extra.age = if age < 0 { + (age + ticks).min(0) + } else if age > 0 { + (age - ticks).max(0) + } else { + age + }; + } + m.extra.in_love = (m.extra.in_love - ticks).max(0); + if let Some(f) = flower + && bee::get(&m).is_none_or(|b| b.flower.is_none()) + && host.random().next_float() < 0.9 + { + bee::set_flower(&mut m, Some(f)); + } + if status == Release::HoneyDelivered { + bee::drop_off_nectar(&mut m); + if let Some(level) = honey.filter(|&l| l < 5) { + let mut increase = if host.random().next_int_bound(100).unwrap_or(1) == 0 { + 2 + } else { + 1 + }; + if level + increase > 5 { + increase -= 1; + } + host.set_honey_level(at, level + increase); + } + } + let delta = if blocked { + 0.0 + } else { + 0.55 + f64::from(m.width() / 2.0) + }; + let p = horizon_core::geometry::Vec3::new( + f64::from(at[0]) + 0.5 + delta * f64::from(facing[0]), + f64::from(at[1]) + 0.5 - f64::from(m.height() / 2.0), + f64::from(at[2]) + 0.5 + delta * f64::from(facing[1]), + ); + m.position = p; + m.previous = p; + } + host.sound( + "block.beehive.exit", + [ + f64::from(at[0]) + 0.5, + f64::from(at[1]) + 0.5, + f64::from(at[2]) + 0.5, + ], + ); + let id = m.id; + Some(host.add(m).then_some(id)) +} + +/// `CampfireBlock.isSmokeyPos`: a lit campfire up to five blocks below, +/// unless a block whose collision crosses the smoke's centre post comes +/// first (a lit campfire right under that block still counts). +pub fn smokey(w: &crate::mobs::MobWorld, at: [i32; 3]) -> bool { + let lit = |y: i32| { + w.has_tag("minecraft:campfires", w.block_name(at[0], y, at[2])) + && w.prop(at[0], y, at[2], "lit") == Some("true") + }; + for i in 1..=5 { + let y = at[1] - i; + if lit(y) { + return true; + } + // SHAPE_VIRTUAL_POST: Block.column(4, 0, 16), the middle quarter. + let (x0, z0) = (f64::from(at[0]), f64::from(at[2])); + let blocked = w.block_collision_boxes(at[0], y, at[2]).iter().any(|b| { + let (min, max) = (b.min_position(), b.max_position()); + min.x < x0 + 0.625 && max.x > x0 + 0.375 && min.z < z0 + 0.625 && max.z > z0 + 0.375 + }); + if blocked { + return lit(y - 1); + } + } + false +} + +/// `HorizontalDirectionalBlock.FACING` as an x/z step. +pub fn facing_step(facing: Option<&str>) -> [i32; 2] { + match facing { + Some("south") => [0, 1], + Some("west") => [-1, 0], + Some("east") => [1, 0], + _ => [0, -1], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nbt_round_trips_in_vanilla_order() { + let tag = Tag::compound([ + ( + "bees", + Tag::List(vec![ + Occupant::create(37).to_nbt(), + Occupant::create(0).to_nbt(), + ]), + ), + ("flower_pos", Tag::IntArray(vec![1, -60, 3])), + ]); + let hive = Beehive::from_nbt(&tag); + assert_eq!(hive.bees.len(), 2); + assert_eq!(hive.bees[0].ticks_in_hive, 37); + assert_eq!(hive.flower, Some([1, -60, 3])); + assert_eq!(Tag::compound(hive.to_nbt()), tag); + } + + #[test] + fn a_bad_bee_drops_the_whole_list() { + let tag = Tag::compound([( + "bees", + Tag::List(vec![ + Occupant::create(1).to_nbt(), + Tag::compound([("ticks_in_hive", Tag::Int(3))]), + ]), + )]); + assert!(Beehive::from_nbt(&tag).bees.is_empty()); + } + + #[test] + fn going_in_strips_the_ignored_tags() { + let tag = Tag::compound([ + ("id", Tag::String("minecraft:bee".into())), + ("UUID", Tag::IntArray(vec![1, 2, 3, 4])), + ("Health", Tag::Float(10.0_f32.to_bits())), + ("HasNectar", Tag::Byte(1)), + ("hive_pos", Tag::IntArray(vec![0, 0, 0])), + ]); + let o = Occupant::of(tag); + assert_eq!(o.min_ticks_in_hive, 2400); + assert!(o.entity_data.get("UUID").is_none()); + assert!(o.entity_data.get("hive_pos").is_none()); + assert!(o.entity_data.get("Health").is_some()); + } +} diff --git a/crates/horizon-client/src/benchmark.rs b/crates/horizon-client/src/benchmark.rs new file mode 100644 index 000000000..09989b8c9 --- /dev/null +++ b/crates/horizon-client/src/benchmark.rs @@ -0,0 +1,427 @@ +//! `horizon-client --benchmark SCENARIO`: the run `tools/perf_bench.py` drives from outside, driven +//! from inside, so anyone can measure their machine with nothing but the game. A thread sends the +//! same control commands `horizon-ctl` would, through the game's own command queue, and writes a +//! report (docs/benchmark-report.md) to `benchmarks/` in the game folder. +//! +//! The scenes, the world (seed 1234, creative) and every step and figure match `tools/perf_bench.py`, +//! so reports from the two can be compared. + +use std::path::{Path, PathBuf}; +use std::sync::mpsc::{self, Sender}; +use std::thread; +use std::time::{Duration, Instant}; + +use horizon_bench::{App, Frames, Kind, Report}; +use serde_json::Value; + +use crate::control::Request; + +pub const SEED: i64 = 1234; +/// The world the benchmark creates under `saves/`, replaced on every run. +pub const WORLD: &str = "horizon-benchmark"; +/// Written into the world so a later run only ever replaces its own world. +const MARKER: &str = "horizon-benchmark.txt"; + +/// A straight flight over terrain: name, start, end, pitch (`tools/graphics_bench.py`'s paths). +type Scene = (&'static str, [f64; 3], [f64; 3], f64); +pub const SCENES: [Scene; 4] = [ + ( + "village", + [-960.0, 125.0, 80.0], + [-960.0, 125.0, 272.0], + 35.0, + ), + ( + "forest", + [-1100.0, 120.0, -560.0], + [-1100.0, 120.0, -368.0], + 25.0, + ), + ( + "ocean", + [-300.0, 85.0, -420.0], + [-300.0, 85.0, -228.0], + 10.0, + ), + ( + "mountain", + [560.0, 260.0, 860.0], + [752.0, 260.0, 860.0], + 30.0, + ), +]; +const FLIGHT_SECONDS: f64 = 12.0; +const SETTLE: Duration = Duration::from_secs(2); +const LOAD_LIMIT: Duration = Duration::from_secs(600); + +/// `standard` flies every scene; a scene's name flies only that one. +pub fn scenes(scenario: &str) -> Option> { + match scenario { + "standard" => Some(SCENES.to_vec()), + name => SCENES.iter().find(|s| s.0 == name).map(|s| vec![*s]), + } +} + +/// What the game knows about the run before it starts. +pub struct Setup { + pub scenario: String, + pub started: Instant, + pub app: App, + pub simulation_distance: u32, + pub vsync: bool, + /// `None`: unlimited. + pub fps_cap: Option, + pub offscreen: bool, + pub game_dir: PathBuf, +} + +/// Starts the driver; the game quits when it is done, and the report's path is printed. +pub fn start(requests: Sender, setup: Setup) { + thread::Builder::new() + .name("horizon-benchmark".into()) + .spawn(move || { + let control = Control(requests); + match run(&control, setup) { + Ok(path) => println!("Horizon: benchmark report {}", path.display()), + Err(e) => eprintln!("Horizon: benchmark failed: {e}"), + } + let _ = control.call("quit"); + }) + .expect("spawn the benchmark thread"); +} + +struct Control(Sender); + +impl Control { + fn call(&self, line: &str) -> Result { + let (reply, response) = mpsc::channel(); + self.0 + .send(Request { + line: line.to_owned(), + reply, + }) + .map_err(|_| "the game has exited".to_owned())?; + // Flights and loads reply when they finish. + let text = response + .recv_timeout(LOAD_LIMIT) + .map_err(|_| format!("{line}: no reply"))?; + let value: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?; + match value.get("error").and_then(Value::as_str) { + Some(e) => Err(format!("{line}: {e}")), + None => Ok(value), + } + } + fn status(&self) -> Value { + self.call("status").unwrap_or(Value::Null) + } +} + +fn run(control: &Control, setup: Setup) -> Result { + let scenes = + scenes(&setup.scenario).ok_or_else(|| format!("unknown scenario {}", setup.scenario))?; + let mut report = Report::new(Kind::Game, setup.app.clone()); + let pid = std::process::id(); + report.conditions.load_avg_1m = horizon_bench::load_average(); + report.conditions.power = horizon_bench::power_source().map(str::to_owned); + let rss = RssSampler::start(pid); + + let title = poll(control, LOAD_LIMIT, |s| { + s["screen"] == "title" && !s["renderer"].is_null() + })?; + report.metric("startup.title_ms", &[ms(setup.started.elapsed())]); + let renderer = &title["renderer"]; + report.hardware.gpu = Some(horizon_bench::Gpu { + name: text(&renderer["gpu"]), + vendor: match text(&renderer["vendor"]) { + // Metal reports no vendor ID. + v if v.is_empty() && text(&renderer["gpu"]).starts_with("Apple") => "apple".into(), + v => v, + }, + driver: text(&renderer["driver"]), + backend: text(&renderer["backend"]).to_lowercase(), + kind: text(&renderer["device_type"]), + }); + report.hardware.display = serde_json::from_value(title["display"].clone()).ok(); + + replace_world(&setup.game_dir)?; + control.call(&format!("open {WORLD} {SEED} creative"))?; + std::fs::write( + setup.game_dir.join("saves").join(WORLD).join(MARKER), + "Created by horizon-client --benchmark; replaced by the next run.\n", + ) + .map_err(|e| e.to_string())?; + let loaded = wait_loaded(control, |_| true)?; + report.metric("startup.world_ms", &[ms(loaded - setup.started)]); + + let mut steady = Vec::new(); + for (name, start, end, pitch) in scenes { + control.call("time 6000")?; + let meshed = control.status()["meshed_sections"].as_f64().unwrap_or(0.0); + let generated = control.status()["generated_chunks"].as_f64().unwrap_or(0.0); + let [x, y, z] = start; + control.call(&format!("tp {x} {y} {z}"))?; + let teleported = Instant::now(); + // A zero-length flight holds the player at the start, flying. + control.call(&format!("fly {x} {y} {z} {x} {y} {z} 0.1 {pitch}"))?; + control.call(&format!("look {:.3} {pitch}", yaw(start, end)))?; + let near = |p: &Value| { + let p: Vec = p + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_f64) + .collect(); + p.len() == 3 && (0..3).map(|i| (p[i] - start[i]).powi(2)).sum::() < 4.0 + }; + let loaded = wait_loaded(control, near)?; + let load = loaded - teleported; + report.metric(&format!("chunks.{name}.load_ms"), &[ms(load)]); + let status = control.status(); + let meshes = status["meshed_sections"].as_f64().unwrap_or(0.0) - meshed; + let chunks = status["generated_chunks"].as_f64().unwrap_or(0.0) - generated; + report.metric(&format!("chunks.{name}.meshed_count"), &[meshes]); + report.metric(&format!("chunks.{name}.generated_count"), &[chunks]); + if load.as_secs_f64() > 0.0 { + report.metric( + &format!("chunks.{name}.generated_per_s"), + &[chunks / load.as_secs_f64()], + ); + } + thread::sleep(SETTLE); + let [ex, ey, ez] = end; + let begin = Instant::now(); + let flight = control.call(&format!( + "fly {x} {y} {z} {ex} {ey} {ez} {FLIGHT_SECONDS} {pitch} raw" + ))?; + steady.push((begin, Instant::now())); + let series = |key: &str| -> Vec { + flight[key] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_f64) + .map(|v| v as f32) + .collect() + }; + let frames = Frames::of( + name, + 0, + &series("frame_ms"), + &series("cpu_ms"), + &series("gpu_ms"), + ) + .ok_or("the flight drew no frames")?; + report.metric(&format!("fps.{name}.avg_fps"), &[frames.avg_fps]); + report.metric(&format!("fps.{name}.low_1pct_fps"), &[frames.low_1pct_fps]); + report.metric( + &format!("fps.{name}.low_01pct_fps"), + &[frames.low_01pct_fps], + ); + report.frames.push(frames); + } + + let status = control.status(); + let renderer = &status["renderer"]; + let c = &mut report.conditions; + c.scenario = Some(setup.scenario.clone()); + c.seed = Some(SEED.to_string()); + c.render_distance = status["render_distance"].as_u64().map(|d| d as u32); + c.simulation_distance = Some(setup.simulation_distance); + c.window = serde_json::from_value(renderer["size"].clone()).ok(); + c.vsync = Some(setup.vsync); + c.fps_cap = setup.fps_cap; + c.offscreen = Some(setup.offscreen); + c.repeats = Some(1); + c.warmup_s = Some(SETTLE.as_secs_f64()); + if let Some(bytes) = renderer["gpu_allocated_bytes"].as_f64() { + report.metric("memory.gpu_mb", &[bytes / f64::from(1 << 20)]); + } + let samples = rss.stop(); + if let Some(peak) = samples.iter().map(|s| s.1).max() { + report.metric("memory.rss_peak_mb", &[peak as f64 / f64::from(1 << 20)]); + } + let mut during: Vec = samples + .iter() + .filter(|(t, _)| steady.iter().any(|(a, b)| a <= t && t <= b)) + .map(|s| s.1) + .collect(); + during.sort_unstable(); + if let Some(&median) = during.get(during.len() / 2) { + report.metric( + "memory.rss_steady_mb", + &[median as f64 / f64::from(1 << 20)], + ); + } + if let Ok(meta) = std::env::current_exe().and_then(std::fs::metadata) { + report.metric("game.binary_bytes", &[meta.len() as f64]); + } + crate::telemetry::keep_benchmark(&crate::logging::game_home(), &report); + report + .write_to(&setup.game_dir.join("benchmarks")) + .map_err(|e| e.to_string()) +} + +/// Removes the previous run's world, never one the benchmark didn't create. +fn replace_world(game_dir: &Path) -> Result<(), String> { + let world = game_dir.join("saves").join(WORLD); + if !world.exists() { + return Ok(()); + } + if !world.join(MARKER).exists() { + return Err(format!( + "{} exists and was not created by the benchmark: rename it", + world.display() + )); + } + std::fs::remove_dir_all(&world).map_err(|e| e.to_string()) +} + +fn poll( + control: &Control, + limit: Duration, + ready: impl Fn(&Value) -> bool, +) -> Result { + let deadline = Instant::now() + limit; + while Instant::now() < deadline { + let status = control.status(); + if ready(&status) { + return Ok(status); + } + thread::sleep(Duration::from_millis(50)); + } + Err(format!("not ready after {} s", limit.as_secs())) +} + +/// Fewer section meshes than this in a second is the game remeshing blocks that change (random +/// ticks), not loading. +const QUIET_MESHES_PER_S: f64 = 100.0; + +/// Waits until the player is spawned where `near` says, nothing is queued, the resident and +/// generated chunk counts have not changed for a second and the last sections are drawn (they wait +/// for their neighbours' light, so after the counts settle); returns when the last of these +/// happened (`tools/perf_bench.py`'s `wait_loaded`). With `status.streaming`, the sections are +/// drawn once no stage has held work for half a second: blocks changing after the load (fluids +/// settling, random ticks) only remesh in bursts. Without it, meshing has to go quiet. +fn wait_loaded(control: &Control, near: impl Fn(&Value) -> bool) -> Result { + let deadline = Instant::now() + LOAD_LIMIT; + let (mut last, mut changed, mut meshing) = (None, Instant::now(), Instant::now()); + let mut previous: Option<(Instant, f64)> = None; + while Instant::now() < deadline { + let s = control.status(); + let now = Instant::now(); + let position = &s["player"]["position"]; + if position.is_null() + || !near(position) + || s["pending_chunks"] != 0 + || s["screen"] == "title" + { + (last, changed, previous, meshing) = (None, now, None, now); + } else { + let counts = (s["chunks"].as_u64(), s["generated_chunks"].as_u64()); + if last != Some(counts) { + (last, changed) = (Some(counts), now); + } + let meshed = s["meshed_sections"].as_f64().unwrap_or(0.0); + let quiet = if let Some(stages) = s["streaming"].as_object() { + // Protos outside the view distance wait for neighbours that are never generated. + if stages + .iter() + .any(|(k, v)| k != "protos" && v.as_u64().unwrap_or(0) > 0) + { + meshing = now; + } + Duration::from_millis(500) + } else { + if let Some((at, before)) = previous + && meshed - before > QUIET_MESHES_PER_S * (now - at).as_secs_f64() + { + meshing = now; + } + Duration::from_secs(1) + }; + previous = Some((now, meshed)); + if now - changed >= Duration::from_secs(1) && now - meshing >= quiet { + return Ok(changed.max(meshing)); + } + } + thread::sleep(Duration::from_millis(50)); + } + Err(format!("not loaded after {} s", LOAD_LIMIT.as_secs())) +} + +/// Vanilla's yaw facing from `start` to `end`. +fn yaw(start: [f64; 3], end: [f64; 3]) -> f64 { + (-(end[0] - start[0])).atan2(end[2] - start[2]).to_degrees() +} + +fn ms(d: Duration) -> f64 { + d.as_secs_f64() * 1000.0 +} + +fn text(v: &Value) -> String { + v.as_str().unwrap_or_default().to_owned() +} + +/// Samples the process's resident memory four times a second, as `tools/perf_bench.py` does. +struct RssSampler { + stop: Sender<()>, + thread: thread::JoinHandle>, +} + +impl RssSampler { + fn start(pid: u32) -> Self { + let (stop, stopped) = mpsc::channel(); + let thread = thread::spawn(move || { + let mut samples = Vec::new(); + while let Err(mpsc::RecvTimeoutError::Timeout) = + stopped.recv_timeout(Duration::from_millis(250)) + { + samples.extend(horizon_bench::rss_bytes(pid).map(|b| (Instant::now(), b))); + } + samples + }); + Self { stop, thread } + } + fn stop(self) -> Vec<(Instant, u64)> { + let _ = self.stop.send(()); + self.thread.join().unwrap_or_default() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn scenarios() { + assert_eq!(scenes("standard").unwrap().len(), 4); + assert_eq!(scenes("ocean").unwrap()[0].0, "ocean"); + assert!(scenes("nether").is_none()); + } + + #[test] + fn yaw_matches_vanilla() { + // South (+Z) is 0, west (-X) 90, east (+X) -90. + assert!((yaw([0.0; 3], [0.0, 0.0, 10.0])).abs() < 1e-9); + assert!((yaw([0.0; 3], [-10.0, 0.0, 0.0]) - 90.0).abs() < 1e-9); + assert!((yaw([0.0; 3], [10.0, 0.0, 0.0]) + 90.0).abs() < 1e-9); + } + + #[test] + fn only_replaces_its_own_world() { + let dir = + std::env::temp_dir().join(format!("horizon-benchmark-test-{}", std::process::id())); + let world = dir.join("saves").join(WORLD); + std::fs::create_dir_all(&world).unwrap(); + assert!( + replace_world(&dir).is_err(), + "a player's world of that name stays" + ); + assert!(world.exists()); + std::fs::write(world.join(MARKER), "").unwrap(); + replace_world(&dir).unwrap(); + assert!(!world.exists()); + replace_world(&dir).unwrap(); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/horizon-client/src/bin/horizon-ctl/commands.rs b/crates/horizon-client/src/bin/horizon-ctl/commands.rs index 655609d5c..c6beb4ab8 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/commands.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/commands.rs @@ -305,7 +305,8 @@ pub const COMMANDS: &[Cmd] = &[ ["horizon-ctl mcp"], &[], mcp: false, local: true), cmd!("bench", Scripting, "bench SECONDS", "reset frame stats, wait, reply with the summary", "", ["horizon-ctl bench 10"], &[], mcp: false, local: false), cmd!("stats", Scripting, "stats [reset]", "frame-time summary since the last reset", "", ["horizon-ctl stats"], &[], mcp: false, local: false), - cmd!("fly", Scripting, "fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH]", "fly the camera along a line, then reply with the frame summary", "", + cmd!("fly", Scripting, "fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH [raw]]", "fly the camera along a line, then reply with the frame summary", + "With raw, the reply also lists every frame time in milliseconds (frame_ms).", ["horizon-ctl fly 0 100 0 500 100 0 20"], &[], mcp: false, local: false), ]; diff --git a/crates/horizon-client/src/camera.rs b/crates/horizon-client/src/camera.rs index 17b68ccb9..7da08f2c8 100644 --- a/crates/horizon-client/src/camera.rs +++ b/crates/horizon-client/src/camera.rs @@ -598,8 +598,8 @@ pub fn depth_far(render_distance_chunks: i32, cloud_range_chunks: i32) -> f32 { /// `Projection.getMatrix` for a perspective set up by `setupPerspective`: /// JOML's `Matrix4f.setPerspective(fov * DEG_TO_RAD, width / height, near, -/// far, zZeroToOne)`, column-major. Vanilla passes its planes reversed -/// (`near` is `zFar`); the hand pass here keeps them in order. +/// far, zZeroToOne)`, column-major. Vanilla's `Projection` passes its planes +/// reversed (`near` is `zFar`) for reversed depth. pub fn perspective( fov_degrees: f32, width: f32, @@ -632,7 +632,7 @@ pub fn perspective( /// death and fluids), never the FOV option or the sprint, speed and bow /// modifier. pub fn hand_projection(hud_fov: f32, width: f32, height: f32, far: f32) -> [f32; 16] { - perspective(hud_fov, width, height, 0.05, far, true) + perspective(hud_fov, width, height, far, 0.05, true) } /// `Camera.modifyFovBasedOnDeathOrFluid`. `dead` is the camera entity's /// `deathTime` while it is a living entity that is dead or dying. diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs index 01147dea5..4e0936a05 100644 --- a/crates/horizon-client/src/chunk.rs +++ b/crates/horizon-client/src/chunk.rs @@ -20,6 +20,15 @@ pub enum Light { Uniform(u8), Full(Box<[u8; 4096]>), } +impl Light { + #[inline] + pub fn get(&self, i: usize) -> u8 { + match self { + Self::Uniform(v) => *v, + Self::Full(a) => a[i], + } + } +} #[inline] pub fn index(x: i32, y: i32, z: i32) -> usize { ((y & 15) << 8 | (z & 15) << 4 | (x & 15)) as usize @@ -59,10 +68,7 @@ impl Section { } #[inline] pub fn light(&self, i: usize) -> u8 { - match &self.light { - Light::Uniform(v) => *v, - Light::Full(a) => a[i], - } + self.light.get(i) } pub fn is_uniform(&self, v: u16) -> bool { self.blocks.is_uniform(u32::from(v)) diff --git a/crates/horizon-client/src/chunk_map.rs b/crates/horizon-client/src/chunk_map.rs new file mode 100644 index 000000000..81e06f020 --- /dev/null +++ b/crates/horizon-client/src/chunk_map.rs @@ -0,0 +1,122 @@ +//! Resident chunk membership, with a token for consumers that cache its keys. +use crate::{chunk::Chunk, fast_hash::FxHashMap}; +use std::{ + collections::hash_map::{Iter, ValuesMut}, + ops::Deref, + sync::{ + Arc, + atomic::{AtomicU64, Ordering}, + }, +}; + +type Key = (i32, i32); +type Columns = FxHashMap>; +static NEXT_REVISION: AtomicU64 = AtomicU64::new(1); +fn next_revision() -> u64 { + NEXT_REVISION.fetch_add(1, Ordering::Relaxed) +} + +/// Read access behaves like a map. Structural writes are explicit so edits to +/// blocks or light don't invalidate consumers of the loaded chunk key set. +/// Tokens are process-wide: replacing the entire map also invalidates caches. +pub struct ChunkMap { + columns: Columns, + revision: u64, +} +impl Default for ChunkMap { + fn default() -> Self { + Self { + columns: Columns::default(), + revision: next_revision(), + } + } +} +impl ChunkMap { + pub fn membership_revision(&self) -> u64 { + self.revision + } + pub fn insert(&mut self, key: Key, chunk: Arc) -> Option> { + let previous = self.columns.insert(key, chunk); + if previous.is_none() { + self.revision = next_revision(); + } + previous + } + pub fn remove(&mut self, key: &Key) -> Option> { + let previous = self.columns.remove(key); + if previous.is_some() { + self.revision = next_revision(); + } + previous + } + pub fn clear(&mut self) { + if !self.columns.is_empty() { + self.columns.clear(); + self.revision = next_revision(); + } + } + pub fn get_mut(&mut self, key: &Key) -> Option<&mut Arc> { + self.columns.get_mut(key) + } + pub fn values_mut(&mut self) -> ValuesMut<'_, Key, Arc> { + self.columns.values_mut() + } +} +impl Deref for ChunkMap { + type Target = Columns; + fn deref(&self) -> &Columns { + &self.columns + } +} +impl<'a> IntoIterator for &'a ChunkMap { + type Item = (&'a Key, &'a Arc); + type IntoIter = Iter<'a, Key, Arc>; + fn into_iter(self) -> Self::IntoIter { + self.columns.iter() + } +} +impl crate::light::LightWorld for ChunkMap { + fn state(&self, x: i32, y: i32, z: i32) -> Option { + self.columns.state(x, y, z) + } + fn light(&self, x: i32, y: i32, z: i32) -> Option { + self.columns.light(x, y, z) + } + fn set_light(&mut self, x: i32, y: i32, z: i32, packed: u8) { + self.columns.set_light(x, y, z, packed); + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn membership_tokens_track_keys_and_map_replacement_only() { + let mut map = ChunkMap::default(); + let empty = map.membership_revision(); + map.clear(); + map.remove(&(0, 0)); + assert_eq!(empty, map.membership_revision()); + let chunk = Arc::new(Chunk::empty(0, 0)); + map.insert((0, 0), chunk.clone()); + let inserted = map.membership_revision(); + assert_ne!(empty, inserted); + map.insert((0, 0), chunk.clone()); + Arc::make_mut(map.get_mut(&(0, 0)).unwrap()).lit = true; + for column in map.values_mut() { + Arc::make_mut(column).light_loaded = true; + } + crate::light::LightWorld::set_light(&mut map, 0, 0, 0, 0); + assert_eq!(inserted, map.membership_revision()); + map.remove(&(0, 0)); + map.insert((1, 0), chunk); + assert_eq!(map.len(), 1); + assert_ne!(inserted, map.membership_revision()); + let replaced = map.membership_revision(); + map.clear(); + assert_ne!(replaced, map.membership_revision()); + let cleared = map.membership_revision(); + map = ChunkMap::default(); + assert_ne!(cleared, map.membership_revision()); + } +} diff --git a/crates/horizon-client/src/clouds.rs b/crates/horizon-client/src/clouds.rs index b29fdf7ee..67223f7cb 100644 --- a/crates/horizon-client/src/clouds.rs +++ b/crates/horizon-client/src/clouds.rs @@ -1,4 +1,20 @@ -//! Fancy cloud face selection (`CloudRenderer.buildExtrudedCell`). +//! Cloud visibility and flat/fancy cell geometry (`CloudRenderer`). +/// `LevelRenderer`: skip OFF clouds and colors with no packed alpha. +pub fn visible(mode: &str, alpha: f32) -> bool { + mode != "false" && (alpha.clamp(0.0, 1.0) * 255.0) as u8 > 0 +} + +/// `buildFlatCell`: bottom plane, in both windings for the culled cloud pipeline. +pub fn flat_cell(x: f32, z: f32, bottom: f32) -> [[[f32; 3]; 4]; 2] { + let p = [ + [x + 12.0, bottom, z], + [x + 12.0, bottom, z + 12.0], + [x, bottom, z + 12.0], + [x, bottom, z], + ]; + [p, [p[3], p[2], p[1], p[0]]] +} + /// Direction order is DOWN, UP, NORTH, SOUTH, WEST, EAST; inward faces use bits 6..12. pub fn face_mask(x: i32, z: i32, bottom: f32, empty: [bool; 4]) -> u16 { let mut mask = 0; @@ -55,6 +71,37 @@ pub fn cells(radius: i32) -> impl Iterator { #[cfg(test)] mod tests { use super::*; + #[test] + fn settings_and_packed_alpha_gate_clouds() { + for mode in ["false", "fast", "true"] { + assert_eq!(visible(mode, 1.0), mode != "false"); + assert!(!visible(mode, 0.0)); + assert!(!visible(mode, 0.5 / 255.0)); + } + assert!(visible("fast", 1.0 / 255.0)); + } + + #[test] + fn fast_cells_are_flat_at_the_bottom_and_visible_from_both_sides() { + for bottom in [-10.0, 0.0, 10.0] { + let [down, up] = flat_cell(-3.0, 7.0, bottom); + assert_eq!( + down, + [ + [9.0, bottom, 7.0], + [9.0, bottom, 19.0], + [-3.0, bottom, 19.0], + [-3.0, bottom, 7.0], + ] + ); + assert_eq!(up, [down[3], down[2], down[1], down[0]]); + for (quad, sign) in [(down, -1.0), (up, 1.0)] { + let [a, b, c] = [quad[0], quad[1], quad[2]].map(glam::Vec3::from_array); + assert!((b - a).cross(c - a).y * sign > 0.0); + } + } + } + #[test] fn cells_are_nearest_first_and_unique() { let cells: Vec<_> = cells(2).collect(); diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index 1f84a1e29..b7d5be320 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -10,10 +10,10 @@ use horizon_world::{ block_collision::{BlockCollisionRegistry, DynamicCollisionWorld, ShulkerCollisionState}, block_collision_scan::{BlockCollisionWorld, CollisionBlock}, collision::CachedCollisionRegistry, - collision_context::CollisionContext, + collision_context::{CollisionContext, CollisionEntity, CollisionItem}, dynamic_support::DynamicSupportWorld, entity_obstruction::EntityIdentity, - fluid::FluidState, + fluid::{FluidKind, FluidState}, liquid_collision::LiquidCollisionWorld, nbt::{self, Limits}, powder_snow_collision::{PowderSnowEntity, PowderSnowWorld}, @@ -39,8 +39,8 @@ pub fn load<'r>(root: &Path, registry: &'r BlockRegistry) -> Result VoxelShape { + VoxelShape::from_cube([1, 2, 1], &[true, false]).expect("a valid half-block column") } pub struct SceneCollisions<'w, 'r> { @@ -60,7 +67,8 @@ pub struct SceneCollisions<'w, 'r> { } impl SceneCollisions<'_, '_> { /// Position contexts permit geometric movement probes without inventing a - /// player, inventory, effects or fluid-standing behavior. + /// player, inventory, effects or fluid-standing behavior; a lava walker + /// collides as the living entity it is, empty-handed. pub fn resolve( &mut self, bounds: Aabb, @@ -72,7 +80,7 @@ impl SceneCollisions<'_, '_> { self, MovementRequest { entity: EntityIdentity(0), - context: CollisionContext::position(bounds.min_position().y), + context: self.context(bounds), bounds, movement, max_step, @@ -81,6 +89,21 @@ impl SceneCollisions<'_, '_> { }, )?) } + fn context(&self, bounds: Aabb) -> CollisionContext<'static> { + let y = bounds.min_position().y; + if !self.subject.is_some_and(|s| s.lava_walker) { + return CollisionContext::position(y); + } + CollisionContext::for_entity( + CollisionEntity { + identity: EntityIdentity(0), + y, + descending: false, + main_hand: Some(CollisionItem::EMPTY), + }, + false, + ) + } pub fn unobstructed(&mut self, bounds: Aabb) -> Result { Ok(no_world_collision( self, @@ -180,9 +203,13 @@ impl DynamicCollisionWorld for SceneCollisions<'_, '_> { } impl LiquidCollisionWorld for SceneCollisions<'_, '_> { type Error = io::Error; - /// Players and the supported mobs cannot stand on fluids (no striders). + /// Only striders stand on fluids. fn entity_liquid_shape(&mut self, _: EntityIdentity) -> io::Result { - Ok(VoxelShape::empty()) + Ok(if self.subject.is_some_and(|s| s.lava_walker) { + strider_liquid_shape() + } else { + VoxelShape::empty() + }) } fn fluid(&mut self, p: BlockPos) -> io::Result { FluidState::from_block( @@ -192,8 +219,10 @@ impl LiquidCollisionWorld for SceneCollisions<'_, '_> { .ok_or_else(|| io::Error::other("scene fluid state outside registry"))?, ) } - fn entity_can_stand(&mut self, _: EntityIdentity, _: FluidState) -> io::Result { - Ok(false) + /// `Strider.canStandOnFluid`: lava. + fn entity_can_stand(&mut self, _: EntityIdentity, fluid: FluidState) -> io::Result { + Ok(self.subject.is_some_and(|s| s.lava_walker) + && matches!(fluid.kind(), FluidKind::Lava | FluidKind::FlowingLava)) } } impl PowderSnowWorld for SceneCollisions<'_, '_> { diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 70c71d7fc..4870216cd 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -68,6 +68,8 @@ pub enum BlockEntity { Crafter(Crafter), /// `SpawnerBlockEntity` (`crate::mobs::spawner`). Spawner(Box), + /// `BeehiveBlockEntity` of beehives and bee nests (`crate::beehive`). + Beehive(Box), } /// `CrafterBlockEntity`: nine slots that can be disabled, the powered flag /// and the ticks left in the crafting animation. @@ -185,6 +187,9 @@ impl BlockEntity { if name == "minecraft:spawner" { return Some(Self::Spawner(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())); } @@ -261,6 +266,7 @@ impl BlockEntity { Self::Crafter(_) => "minecraft:crafter", Self::CreakingHeart(_) => "minecraft:creaking_heart", Self::Spawner(_) => "minecraft:mob_spawner", + Self::Beehive(_) => "minecraft:beehive", } } pub fn contents(&self) -> Vec { @@ -270,7 +276,9 @@ impl BlockEntity { Self::Brewing(b) => b.items.iter().flatten().cloned().collect(), Self::Sign(_) => Vec::new(), Self::Jukebox(j) => j.record.iter().cloned().collect(), - Self::Beacon(_) | Self::CreakingHeart(_) | Self::Spawner(_) => Vec::new(), + Self::Beacon(_) | Self::CreakingHeart(_) | Self::Spawner(_) | Self::Beehive(_) => { + Vec::new() + } Self::Lectern(l) => l.book.iter().cloned().collect(), Self::Sculk(_) => Vec::new(), Self::Banner(_) => Vec::new(), @@ -289,7 +297,7 @@ impl BlockEntity { | Self::Sculk(_) | Self::Banner(_) => &[], Self::Crafter(c) => &c.items, - Self::CreakingHeart(_) | Self::Spawner(_) => &[], + Self::CreakingHeart(_) | Self::Spawner(_) | Self::Beehive(_) => &[], } } pub fn slots_mut(&mut self) -> &mut [Option] { @@ -304,7 +312,7 @@ impl BlockEntity { | Self::Sculk(_) | Self::Banner(_) => &mut [], Self::Crafter(c) => &mut c.items, - Self::CreakingHeart(_) | Self::Spawner(_) => &mut [], + Self::CreakingHeart(_) | Self::Spawner(_) | Self::Beehive(_) => &mut [], } } } diff --git a/crates/horizon-client/src/control.rs b/crates/horizon-client/src/control.rs index 9a670b90b..3019d8dfa 100644 --- a/crates/horizon-client/src/control.rs +++ b/crates/horizon-client/src/control.rs @@ -150,6 +150,7 @@ pub struct Request { pub struct Server { path: PathBuf, requests: mpsc::Receiver, + sender: mpsc::Sender, } /// `$HORIZON_CONTROL`, else `horizon-control.sock` in the user's runtime @@ -172,6 +173,7 @@ impl Server { std::fs::remove_file(path)?; } let (sender, requests) = mpsc::channel(); + let local = sender.clone(); if uses_tcp(path) { let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?; let token = random_token(); @@ -204,8 +206,22 @@ impl Server { Ok(Self { path: path.to_owned(), requests, + sender: local, }) } + /// Commands from inside the process only (`--benchmark` without `--control`). + pub fn local() -> Self { + let (sender, requests) = mpsc::channel(); + Self { + path: PathBuf::new(), + requests, + sender, + } + } + /// Sends commands as a socket client would, from another thread. + pub fn sender(&self) -> mpsc::Sender { + self.sender.clone() + } pub fn path(&self) -> &Path { &self.path } @@ -424,6 +440,18 @@ impl FrameStats { self.gpu.extend_from_slice(millis); } } + /// Every recorded frame time, in milliseconds, in order. + pub fn frame_millis(&self) -> &[f32] { + &self.millis + } + /// CPU time of every recorded frame, in milliseconds. + pub fn cpu_millis(&self) -> &[f32] { + &self.cpu + } + /// GPU time of every frame the GPU timed, in milliseconds. + pub fn gpu_millis(&self) -> &[f32] { + &self.gpu + } pub fn reset(&mut self) { self.millis.clear(); self.cpu.clear(); diff --git a/crates/horizon-client/src/crash.rs b/crates/horizon-client/src/crash.rs index 7e57355f2..a0b68260d 100644 --- a/crates/horizon-client/src/crash.rs +++ b/crates/horizon-client/src/crash.rs @@ -1,7 +1,8 @@ //! Crash reports, laid out like vanilla's CrashReport.getFriendlyReport: a comment, the time, //! a description, the error with its stack, then the details of the game and the machine. //! Written to `crash-reports/crash--client.txt` in the game folder when -//! the main thread panics or `main` gets an error back. Nothing is sent anywhere. +//! the main thread panics or `main` gets an error back. It leaves the machine only scrubbed, and +//! only if the player allows crash reports (`telemetry`). use std::fmt::Write as _; use std::path::{Path, PathBuf}; use std::sync::Mutex; @@ -104,8 +105,18 @@ impl Report { } } +/// The release tag (the launcher installs each build in a folder named after it) and the client's +/// own version, or just the latter. +pub fn version() -> String { + let version = env!("CARGO_PKG_VERSION"); + match release_tag() { + Some(tag) => format!("{tag} (client {version})"), + None => version.to_owned(), + } +} + /// The release this binary came with: launcher installs live in a folder named after the tag. -fn release_tag() -> Option { +pub fn release_tag() -> Option { let exe = std::env::current_exe().ok()?; let folder = exe.parent()?.file_name()?.to_str()?; (folder.starts_with('v') && folder[1..].starts_with(|c: char| c.is_ascii_digit())) @@ -227,12 +238,8 @@ fn memory() -> String { /// The report's details: Horizon's and the machine's, then what the game set as it ran. pub fn system_details() -> Vec<(String, String)> { - let mut version = env!("CARGO_PKG_VERSION").to_owned(); - if let Some(tag) = release_tag() { - version = format!("{tag} (client {version})"); - } let mut out = vec![ - ("Horizon Version".to_owned(), version), + ("Horizon Version".to_owned(), version()), ("Minecraft Version".to_owned(), "26.3".to_owned()), ("Operating System".to_owned(), operating_system()), ("CPU".to_owned(), cpu()), @@ -270,6 +277,7 @@ fn deliver(home: &Path, report: Report) -> Option { ), ); crate::logging::flush(); + crate::telemetry::keep_crash(home, &report); match report.save(home) { Ok(path) => { eprintln!("Horizon: crash report saved to {}", path.display()); diff --git a/crates/horizon-client/src/debug_chart.rs b/crates/horizon-client/src/debug_chart.rs new file mode 100644 index 000000000..68a469415 --- /dev/null +++ b/crates/horizon-client/src/debug_chart.rs @@ -0,0 +1,579 @@ +//! The debug charts (26.3 `debugchart`): F3+2 shows the frame times and, in +//! single player, the integrated server's tick times; F3+3 the ping and, on a +//! remote server, the bandwidth. Each chart keeps the last 240 samples +//! (`LocalSampleLogger`) and draws one bar per sample over a 60 pixel high +//! box (`AbstractDebugChart`). +use crate::{ + font::Font, + hud_layout::{GuiDraw, argb, fill}, + text::Text, +}; +use std::{ + collections::VecDeque, + time::{Duration, Instant}, +}; + +/// `LocalSampleLogger.CAPACITY`. +pub const CAPACITY: usize = 240; +/// `AbstractDebugChart.CHART_HEIGHT`. +pub const CHART_HEIGHT: i32 = 60; +/// `TpsDebugDimensions`: a tick sample's values. +pub const FULL_TICK: usize = 0; +pub const TICK_SERVER_METHOD: usize = 1; +pub const SCHEDULED_TASKS: usize = 2; +pub const IDLE: usize = 3; + +/// `LocalSampleLogger`: the last [`CAPACITY`] samples, oldest first; a +/// sample has up to four values (`TpsDebugDimensions`), the first the main. +#[derive(Clone, Debug, Default)] +pub struct SampleLogger { + samples: VecDeque<[i64; 4]>, +} +impl SampleLogger { + /// `logSample`. + pub fn log(&mut self, value: i64) { + self.log_full([value, 0, 0, 0]); + } + /// `logFullSample`. + pub fn log_full(&mut self, sample: [i64; 4]) { + if self.samples.len() == CAPACITY { + self.samples.pop_front(); + } + self.samples.push_back(sample); + } + pub fn len(&self) -> usize { + self.samples.len() + } + pub fn is_empty(&self) -> bool { + self.samples.is_empty() + } + pub fn reset(&mut self) { + self.samples.clear(); + } + fn get(&self, index: usize, dimension: usize) -> i64 { + self.samples[index][dimension] + } +} + +/// `DebugScreenOverlay`'s chart switches and the samples behind them. +#[derive(Clone, Debug, Default)] +pub struct DebugCharts { + /// `renderFpsCharts` (F3+2). + pub fps: bool, + /// `renderNetworkCharts` (F3+3). + pub network: bool, + /// `renderLightmapTexture` (F3+4). + pub lightmap: bool, + /// `frameTimeLogger`: nanoseconds between frames. + pub frame_times: SampleLogger, + /// `tickTimeLogger`: the integrated server's ticks. + pub tick_times: SampleLogger, + /// `pingLogger`: milliseconds. + pub ping: SampleLogger, + /// `bandwidthLogger`: bytes received per tick. + pub bandwidth: SampleLogger, + previous_tick: Option, + bytes_seen: Option, +} +impl DebugCharts { + /// `toggleFpsCharts`; `overlay` is the debug overlay's visibility. + pub fn toggle_fps(&mut self, overlay: &mut bool) { + self.fps = !*overlay || !self.fps; + if self.fps { + *overlay = true; + self.network = false; + self.lightmap = false; + } + } + /// `toggleNetworkCharts`. + pub fn toggle_network(&mut self, overlay: &mut bool) { + self.network = !*overlay || !self.network; + if self.network { + *overlay = true; + self.fps = false; + self.lightmap = false; + } + } + /// `toggleLightmapTexture`. + pub fn toggle_lightmap(&mut self, overlay: &mut bool) { + self.lightmap = !*overlay || !self.lightmap; + if self.lightmap { + *overlay = true; + self.fps = false; + self.network = false; + } + } + /// `reset`: leaving a world. + pub fn reset(&mut self) { + self.tick_times.reset(); + self.ping.reset(); + self.bandwidth.reset(); + self.previous_tick = None; + self.bytes_seen = None; + } + /// One integrated server tick that started at `started` and ran its + /// tick method for `method` (`MinecraftServer.logFullTickTime` and + /// `logTickMethodTime`): the full tick runs from one start to the next, + /// and what the tick method leaves of it is idle. + pub fn log_tick(&mut self, started: Instant, method: Duration) { + let method = method.as_nanos() as i64; + let full = self + .previous_tick + .map_or(method, |p| (started - p).as_nanos() as i64) + .max(method); + self.previous_tick = Some(started); + self.tick_times.log_full([full, method, 0, full - method]); + } + /// `BandwidthDebugMonitor.tick`: the bytes received since the last + /// tick, from the connection's running total. + pub fn log_bandwidth(&mut self, total: i64) { + if let Some(seen) = self.bytes_seen { + self.bandwidth.log(total - seen); + } + self.bytes_seen = Some(total); + } + /// The charts along the bottom of the screen (`extractRenderState`): + /// frame times left and tick times right, or bandwidth left (remote + /// servers only) and ping right. `mspt` is the level's milliseconds + /// per tick. + pub fn draw( + &self, + font: &Font, + width: i32, + height: i32, + framerate_limit: u32, + mspt: f32, + remote: bool, + ) -> Vec { + let mut out = Vec::new(); + let max_width = width / 2; + let chart_width = Chart::width(max_width); + if self.fps { + let fps = Chart::Fps { framerate_limit }; + out.extend(fps.draw(font, &self.frame_times, 0, chart_width, height)); + if !self.tick_times.is_empty() { + let tps = Chart::Tps { mspt }; + out.extend(tps.draw( + font, + &self.tick_times, + width - chart_width, + chart_width, + height, + )); + } + } + if self.network { + if remote { + out.extend(Chart::Bandwidth.draw(font, &self.bandwidth, 0, chart_width, height)); + } + out.extend(Chart::Ping.draw( + font, + &self.ping, + width - chart_width, + chart_width, + height, + )); + } + out + } +} + +/// The lightmap view (`showLightmapTexture`): the 16 by 16 texture at 64 +/// by 64 in the bottom right corner on a black border, sky light up and +/// block light right (the blit flips the texture's rows). `pixels` are RGBA +/// rows of sky level by block level. +pub fn lightmap(pixels: &[u8; 16 * 16 * 4], width: i32, height: i32) -> Vec { + let (x, y) = (width - 64 - 2, height - 64 - 2); + let mut out = vec![fill(x - 1, y - 1, x + 64 + 1, y + 64 + 1, 0xFF00_0000)]; + for (i, p) in pixels.as_chunks::<4>().0.iter().enumerate() { + let (sky, block) = ((i / 16) as i32, (i % 16) as i32); + let color = argb(255, u32::from(p[0]), u32::from(p[1]), u32::from(p[2])); + let (cx, cy) = (x + block * 4, y + (15 - sky) * 4); + out.push(fill(cx, cy, cx + 4, cy + 4, color)); + } + out +} + +/// The four charts and what each needs to scale its bars. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Chart { + /// `FpsDebugChart`: frame durations in nanoseconds; the frame rate limit + /// option (`maxFps`). + Fps { framerate_limit: u32 }, + /// `TpsDebugChart`: tick samples in nanoseconds; the level's + /// milliseconds per tick. + Tps { mspt: f32 }, + /// `PingDebugChart`: round trips in milliseconds. + Ping, + /// `BandwidthDebugChart`: bytes received per tick. + Bandwidth, +} + +/// The labels' colour and the backdrop of the box and shaded labels. +const LABEL: u32 = 0xFFE0_E0E0; +const BACKDROP: u32 = 0x9050_5050; +const WHITE: u32 = 0xFFFF_FFFF; +const GREEN: u32 = 0xFF00_FF00; +const YELLOW: u32 = 0xFFFF_FF00; +const RED: u32 = 0xFFFF_0000; +const CYAN: u32 = 0xFF00_FFFF; +/// `BandwidthDebugChart.MID_COLOR`. +const LAVENDER: u32 = 0xFFA0_A0FF; +/// `TpsDebugChart`'s bar parts. +const TICK_METHOD_COLOR: u32 = 0xFF99_1111; +const TASK_COLOR: u32 = 0xFFBA_995F; +const OTHER_COLOR: u32 = 0xFF5F_0E8C; +const MEGABYTE: f64 = 1_048_576.0; + +impl Chart { + /// `AbstractDebugChart.getWidth`. + pub fn width(max_width: i32) -> i32 { + (CAPACITY as i32 + 2).min(max_width) + } + /// `getFullHeight`: the box and the min/avg/max line above it. + pub fn full_height() -> i32 { + CHART_HEIGHT + 9 + } + /// `AbstractDebugChart.extractRenderState`. + pub fn draw( + self, + font: &Font, + samples: &SampleLogger, + left: i32, + width: i32, + bottom: i32, + ) -> Vec { + let mut out = vec![fill( + left, + bottom - CHART_HEIGHT, + left + width, + bottom, + BACKDROP, + )]; + let (mut sum, mut min, mut max) = (0i64, i64::from(i32::MAX), i64::from(i32::MIN)); + let start = CAPACITY.saturating_sub((width - 2).max(0) as usize); + let count = samples.len().saturating_sub(start); + for i in 0..count { + let x = left + i as i32 + 1; + let index = start + i; + let value = self.aggregated(samples, index); + min = min.min(value); + max = max.max(value); + sum += value; + self.bars(&mut out, samples, bottom, x, index); + } + horizontal_line( + &mut out, + left, + left + width - 1, + bottom - CHART_HEIGHT, + WHITE, + ); + horizontal_line(&mut out, left, left + width - 1, bottom - 1, WHITE); + vertical_line(&mut out, left, bottom - CHART_HEIGHT, bottom, WHITE); + vertical_line( + &mut out, + left + width - 1, + bottom - CHART_HEIGHT, + bottom, + WHITE, + ); + if count > 0 { + let y = bottom - CHART_HEIGHT - 9; + let min_text = format!("{} min", self.display(min as f64)); + let avg_text = format!("{} avg", self.display(sum as f64 / count as f64)); + let max_text = format!("{} max", self.display(max as f64)); + text(&mut out, min_text, left + 2, y, LABEL, true); + let avg_x = left + width / 2 - font.width(&avg_text) as i32 / 2; + text(&mut out, avg_text, avg_x, y, LABEL, true); + let max_x = left + width - font.width(&max_text) as i32 - 2; + text(&mut out, max_text, max_x, y, LABEL, true); + } + self.lines_and_labels(&mut out, font, left, width, bottom); + out + } + fn bars( + self, + out: &mut Vec, + samples: &SampleLogger, + bottom: i32, + x: i32, + index: usize, + ) { + let value = samples.get(index, 0); + let height = self.height(value as f64); + out.push(fill(x, bottom - height, x + 1, bottom, self.color(value))); + if let Chart::Tps { .. } = self { + let method = samples.get(index, TICK_SERVER_METHOD); + let method_h = self.height(method as f64); + out.push(fill(x, bottom - method_h, x + 1, bottom, TICK_METHOD_COLOR)); + let tasks = samples.get(index, SCHEDULED_TASKS); + let tasks_h = self.height(tasks as f64); + out.push(fill( + x, + bottom - method_h - tasks_h, + x + 1, + bottom - method_h, + TASK_COLOR, + )); + let other = value - samples.get(index, IDLE) - method - tasks; + let other_h = self.height(other as f64); + out.push(fill( + x, + bottom - other_h - tasks_h - method_h, + x + 1, + bottom - tasks_h - method_h, + OTHER_COLOR, + )); + } + } + /// `getValueForAggregation`: a tick's time without its idle part. + fn aggregated(self, samples: &SampleLogger, index: usize) -> i64 { + match self { + Chart::Tps { .. } => samples.get(index, 0) - samples.get(index, IDLE), + _ => samples.get(index, 0), + } + } + /// `extractAdditionalLinesAndLabels`. + fn lines_and_labels( + self, + out: &mut Vec, + font: &Font, + left: i32, + width: i32, + bottom: i32, + ) { + match self { + Chart::Fps { framerate_limit } => { + shaded(out, font, "30 fps", left + 1, bottom - CHART_HEIGHT + 1); + shaded(out, font, "60 fps", left + 1, bottom - 30 + 1); + horizontal_line(out, left, left + width - 1, bottom - 30, WHITE); + if framerate_limit > 0 && framerate_limit <= 250 { + let y = bottom - self.height(1.0e9 / f64::from(framerate_limit)) - 1; + horizontal_line(out, left, left + width - 1, y, CYAN); + } + } + Chart::Tps { mspt } => { + let tps = 1000.0 / mspt; + shaded( + out, + font, + &format!("{tps:.1} tps"), + left + 1, + bottom - CHART_HEIGHT + 1, + ); + } + Chart::Ping => shaded(out, font, "500 ms", left + 1, bottom - CHART_HEIGHT + 1), + Chart::Bandwidth => { + for bytes in [64.0, 1024.0, 16384.0] { + let y = bottom - bandwidth_height(bytes); + shaded(out, font, &bandwidth_display(bytes), left + 1, y + 1); + horizontal_line(out, left, left + width - 1, y, WHITE); + } + let y = bottom - bandwidth_height(MEGABYTE) + 1; + shaded(out, font, &bandwidth_display(MEGABYTE), left + 1, y); + } + } + } + /// `toDisplayString`. + fn display(self, sample: f64) -> String { + match self { + Chart::Fps { .. } | Chart::Tps { .. } => format!("{} ms", java_round(sample / 1.0e6)), + Chart::Ping => format!("{} ms", java_round(sample)), + Chart::Bandwidth => bandwidth_display(sample * 20.0), + } + } + /// `getSampleHeight`. + fn height(self, sample: f64) -> i32 { + match self { + Chart::Fps { .. } => java_round(sample / 1.0e6 * 60.0 / 33.333333333333336) as i32, + Chart::Tps { mspt } => java_round(sample / 1.0e6 * 60.0 / f64::from(mspt)) as i32, + Chart::Ping => java_round(sample * 60.0 / 500.0) as i32, + Chart::Bandwidth => bandwidth_height(sample * 20.0), + } + } + /// `getSampleColor`. + fn color(self, sample: i64) -> u32 { + let s = sample as f64; + match self { + Chart::Fps { .. } => gradient(s / 1.0e6, 0.0, GREEN, 28.0, YELLOW, 56.0, RED), + Chart::Tps { mspt } => { + let m = f64::from(mspt); + gradient(s / 1.0e6, m, GREEN, m * 1.125, YELLOW, m * 1.25, RED) + } + Chart::Ping => gradient(s, 0.0, GREEN, 250.0, YELLOW, 500.0, RED), + Chart::Bandwidth => gradient(s * 20.0, 0.0, CYAN, 8192.0, LAVENDER, 1.048576e7, RED), + } + } +} + +/// `BandwidthDebugChart.toDisplayStringInternal`. +fn bandwidth_display(bytes_per_second: f64) -> String { + if bytes_per_second >= MEGABYTE { + format!("{:.1} MiB/s", bytes_per_second / MEGABYTE) + } else if bytes_per_second >= 1024.0 { + format!("{:.1} KiB/s", bytes_per_second / 1024.0) + } else { + format!("{} B/s", bytes_per_second.floor() as i64) + } +} +/// `BandwidthDebugChart.getSampleHeightInternal`: logarithmic, 1 MiB/s at +/// the top. +fn bandwidth_height(bytes_per_second: f64) -> i32 { + java_round((bytes_per_second + 1.0).ln() * 60.0 / MEGABYTE.ln()) as i32 +} +/// `Math.round(double)`: halves round up. +fn java_round(v: f64) -> i64 { + (v + 0.5).floor() as i64 +} +/// `AbstractDebugChart.getSampleColor(sample, min, minColor, mid, ...)`. +fn gradient( + sample: f64, + min: f64, + min_color: u32, + mid: f64, + mid_color: u32, + max: f64, + max_color: u32, +) -> u32 { + let sample = sample.clamp(min, max); + if sample < mid { + srgb_lerp(((sample - min) / (mid - min)) as f32, min_color, mid_color) + } else { + srgb_lerp(((sample - mid) / (max - mid)) as f32, mid_color, max_color) + } +} +/// `ARGB.srgbLerp`: each channel by `Mth.lerpInt`. +fn srgb_lerp(alpha: f32, p0: u32, p1: u32) -> u32 { + let channel = |shift: u32| { + let (a, b) = (((p0 >> shift) & 255) as i32, ((p1 >> shift) & 255) as i32); + (a + (alpha * (b - a) as f32).floor() as i32) as u32 + }; + argb(channel(24), channel(16), channel(8), channel(0)) +} +/// `GuiGraphicsExtractor.horizontalLine`. +fn horizontal_line(out: &mut Vec, x0: i32, x1: i32, y: i32, color: u32) { + out.push(fill(x0.min(x1), y, x0.max(x1) + 1, y + 1, color)); +} +/// `GuiGraphicsExtractor.verticalLine`. +fn vertical_line(out: &mut Vec, x: i32, y0: i32, y1: i32, color: u32) { + out.push(fill(x, y0.min(y1) + 1, x + 1, y0.max(y1), color)); +} +fn text(out: &mut Vec, s: String, x: i32, y: i32, color: u32, shadow: bool) { + out.push(GuiDraw::Text { + text: Text::literal(s), + x, + y, + color, + shadow, + }); +} +/// `extractStringWithShade`: a label on a dark backdrop, without shadow. +fn shaded(out: &mut Vec, font: &Font, s: &str, x: i32, y: i32) { + out.push(fill(x, y, x + font.width(s) as i32 + 1, y + 9, BACKDROP)); + text(out, s.to_owned(), x + 1, y + 1, LABEL, false); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_logger_keeps_the_last_240_samples() { + let mut l = SampleLogger::default(); + for i in 0..300 { + l.log(i); + } + assert_eq!(l.len(), CAPACITY); + assert_eq!(l.get(0, 0), 60); + assert_eq!(l.get(CAPACITY - 1, 0), 299); + } + + #[test] + fn chart_toggles_show_the_overlay_and_exclude_each_other() { + let mut c = DebugCharts::default(); + let mut overlay = false; + c.toggle_fps(&mut overlay); + assert!(overlay && c.fps); + c.toggle_network(&mut overlay); + assert!(c.network && !c.fps); + c.toggle_network(&mut overlay); + assert!(!c.network && overlay); + c.toggle_lightmap(&mut overlay); + c.toggle_fps(&mut overlay); + assert!(c.fps && !c.lightmap); + // With the overlay hidden, the key shows it again with the chart on. + c.toggle_fps(&mut overlay); + overlay = false; + c.toggle_fps(&mut overlay); + assert!(overlay && c.fps); + } + + #[test] + fn the_lightmap_puts_full_sky_light_at_the_top_left() { + let mut pixels = [0u8; 16 * 16 * 4]; + // Sky 15, block 0: the last row's first texel. + pixels[15 * 64..15 * 64 + 4].copy_from_slice(&[10, 20, 30, 255]); + let draws = lightmap(&pixels, 427, 240); + assert_eq!(draws[0], fill(360, 173, 426, 239, 0xFF00_0000)); + assert_eq!(draws.len(), 257); + assert!(draws.contains(&fill(361, 174, 365, 178, 0xFF0A_141E))); + } + + #[test] + fn ticks_and_bandwidth_log_their_differences() { + let mut c = DebugCharts::default(); + let t0 = Instant::now(); + c.log_tick(t0, Duration::from_millis(5)); + c.log_tick(t0 + Duration::from_millis(50), Duration::from_millis(7)); + assert_eq!( + c.tick_times.samples[1], + [50_000_000, 7_000_000, 0, 43_000_000] + ); + c.log_bandwidth(1000); + c.log_bandwidth(1600); + assert_eq!(c.bandwidth.len(), 1); + assert_eq!(c.bandwidth.get(0, 0), 600); + } + + #[test] + fn heights_match_vanilla_scales() { + let fps = Chart::Fps { + framerate_limit: 260, + }; + // 33.3 ms (30 fps) fills the chart; 16.7 ms half of it. + assert_eq!(fps.height(33_333_333.0), 60); + assert_eq!(fps.height(16_666_667.0), 30); + let tps = Chart::Tps { mspt: 50.0 }; + assert_eq!(tps.height(25e6), 30); + assert_eq!(Chart::Ping.height(250.0), 30); + // 1 MiB/s at the top; 52 bytes per tick is 1 KiB/s. + assert_eq!(bandwidth_height(MEGABYTE), 60); + assert_eq!(Chart::Bandwidth.height(51.2), 30); + } + + #[test] + fn labels_match_vanilla_formats() { + assert_eq!( + Chart::Fps { framerate_limit: 0 }.display(16_500_000.0), + "17 ms" + ); + assert_eq!(Chart::Ping.display(12.4), "12 ms"); + assert_eq!(Chart::Bandwidth.display(3.0), "60 B/s"); + assert_eq!(Chart::Bandwidth.display(100.0), "2.0 KiB/s"); + assert_eq!(bandwidth_display(MEGABYTE), "1.0 MiB/s"); + } + + #[test] + fn colours_go_green_yellow_red() { + let fps = Chart::Fps { framerate_limit: 0 }; + assert_eq!(fps.color(0), GREEN); + assert_eq!(fps.color(28_000_000), YELLOW); + assert_eq!(fps.color(100_000_000), RED); + // Halfway between green and yellow: Mth.lerpInt floors. + assert_eq!(fps.color(14_000_000), 0xFF7F_FF00); + let tps = Chart::Tps { mspt: 50.0 }; + assert_eq!(tps.color(10_000_000), GREEN); + assert_eq!(Chart::Bandwidth.color(0), CYAN); + } +} diff --git a/crates/horizon-client/src/debug_keys.rs b/crates/horizon-client/src/debug_keys.rs index 43e9c10bf..8f37174c2 100644 --- a/crates/horizon-client/src/debug_keys.rs +++ b/crates/horizon-client/src/debug_keys.rs @@ -433,6 +433,23 @@ mod tests { assert_eq!(h.overlay, 0); } + #[test] + fn switcher_modifier_release_does_not_toggle_the_debug_overlay() { + let (mut k, mut h, mut b) = (DebugKeys::default(), Host::default(), KeyBinds::default()); + // Screen release handling must also work with rebound debug keys. + b.set("key.debug.modifier", "key.keyboard.f7"); + b.set("key.debug.overlay", "key.keyboard.f7"); + b.set("key.debug.switchGameMode", "key.keyboard.f8"); + press(&mut k, &mut h, &b, "key.keyboard.f7", 0); + assert!(!press(&mut k, &mut h, &b, "key.keyboard.f8", 1)); + assert_eq!(h.actions, [(DebugAction::SwitchGameMode, false)]); + h.screen = Some(OpenScreen::GameModeSwitcher); + release(&mut k, &mut h, &b, "key.keyboard.f8"); + release(&mut k, &mut h, &b, "key.keyboard.f7"); + assert!(!k.modifier_down); + assert_eq!(h.overlay, 0); + } + #[test] fn a_separate_overlay_key_toggles_on_press() { let (mut k, mut h, mut b) = (DebugKeys::default(), Host::default(), KeyBinds::default()); diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 8428a9410..11601db78 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -309,6 +309,9 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } map.insert("equipment".into(), Tag::Compound(equipment)); } + "minecraft:bat" => { + map.insert("BatFlags".into(), Tag::Byte(i8::from(m.extra.flag))); + } "minecraft:creaking" => { // home_pos: the heart it is bound to. if let Some(home) = m.extra.home { @@ -386,6 +389,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { crate::mobs::nautilus::to_nbt(m, map); } "minecraft:sulfur_cube" => crate::mobs::sulfur_cube::to_nbt(m, map), + "minecraft:bee" => crate::mobs::bee::to_nbt(m, map), "minecraft:sniffer" => crate::mobs::sniffer::to_nbt(m, map), "minecraft:wither" => { map.insert("Invul".into(), Tag::Int(m.extra.counter)); @@ -597,7 +601,9 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.main_hand = None; } m.death_time = number(tag.get("DeathTime")).unwrap_or(0) as i32; - m.persistent |= flag(tag, "PersistenceRequired"); + // Mob.readAdditionalSaveData overrides what the constructor set (copper + // golems and elder guardians start persistent). + m.persistent = flag(tag, "PersistenceRequired"); m.extra.pick_up_loot = flag(tag, "CanPickUpLoot"); m.custom_name = custom_name(tag); if m.kind.category == "creature" { @@ -612,6 +618,10 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.ticks_frozen = number(tag.get("TicksFrozen")).unwrap_or(0) as i32; m.silent = flag(tag, "Silent"); m.invulnerable_flag = flag(tag, "Invulnerable"); + if m.species() == crate::mobs::Species::Bat { + // Bat.readAdditionalSaveData: BatFlags bit 0, resting. + m.extra.flag = number(tag.get("BatFlags")).unwrap_or(0) & 1 != 0; + } if m.species() == crate::mobs::Species::Creeper { m.extra.charged = flag(tag, "powered"); // Creeper.readAdditionalSaveData: `ignited` lights the fuse. @@ -761,6 +771,9 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - if m.species() == crate::mobs::Species::SulfurCube { crate::mobs::sulfur_cube::from_nbt(&mut m, tag); } + if m.species() == crate::mobs::Species::Bee { + crate::mobs::bee::from_nbt(&mut m, tag); + } if m.species() == crate::mobs::Species::Creaking && let Some(Tag::IntArray(home)) = tag.get("home_pos") && home.len() == 3 diff --git a/crates/horizon-client/src/front.rs b/crates/horizon-client/src/front.rs index 64a27d5ac..e6224683f 100644 --- a/crates/horizon-client/src/front.rs +++ b/crates/horizon-client/src/front.rs @@ -33,6 +33,7 @@ const MAKE: u64 = id("create.make", 0); const SERVER: u64 = id("mp.row", 0); const JOIN: u64 = id("mp.join", 0); const DIRECT: u64 = id("mp.direct", 0); +const FRIEND: u64 = id("mp.friend", 0); const ADD: u64 = id("mp.add", 0); const EDIT: u64 = id("mp.edit", 0); const DELETE: u64 = id("mp.delete", 0); @@ -108,7 +109,7 @@ impl Title { /// live backdrop is visible (0 shows the plain cold background). pub fn draw_horizon(&self, ui: &mut Ui, backdrop: f32) { if classic(&self.mode) { - self.draw(ui.atlas, ui.batch, ui.cursor); + self.draw(ui.atlas, ui.batch, ui.cursor, false); return; } let reveal = self.opening_phase(backdrop >= 1.0); @@ -153,6 +154,7 @@ impl Title { seed, creative, focus, + .. } => { let caret = (self.started.elapsed().as_millis() / 500).is_multiple_of(2); create_page(ui, x, w, name, seed, *creative, *focus, caret); @@ -378,14 +380,7 @@ impl Title { }; } } - CREATE => { - self.mode = Mode::Create { - name: "New World".into(), - seed: String::new(), - creative: false, - focus: 0, - } - } + CREATE => self.mode = Title::new_world(), DELETE_WORLD => { if let Some(world) = selected.and_then(|i| worlds.get(i)).cloned() { self.mode = Mode::Delete { world }; @@ -435,6 +430,7 @@ impl Title { let id = match hit { JOIN => Some(40), DIRECT => Some(41), + FRIEND => Some(47), ADD => Some(42), EDIT => Some(43), DELETE => Some(44), @@ -443,15 +439,17 @@ impl Title { Screen::List { .. } => 46, Screen::Edit { .. } => 51, Screen::Direct { .. } => 53, + Screen::Friend { .. } => 57, Screen::Disconnected { .. } => 54, }), CANCEL_RETRY => Some(55), DONE => Some(match screen { Screen::Direct { .. } => 52, + Screen::Friend { .. } => 56, _ => 50, }), FIELD_A | FIELD_B => { - if let Screen::Edit { focus, .. } = screen { + if let Screen::Edit { focus, .. } | Screen::Friend { focus, .. } = screen { *focus = u8::from(hit == FIELD_B); } None @@ -484,6 +482,25 @@ impl Title { } } +/// The end of `text` that fits `width`, led by an ellipsis when cut. +fn tail_fit(ui: &Ui, text: &str, width: f32) -> String { + if ui.measure(Face::Regular, BODY, text) <= width { + return text.to_owned(); + } + let chars: Vec = text.chars().collect(); + let mut start = 0; + while start < chars.len() { + let tail: String = std::iter::once('…') + .chain(chars[start..].iter().copied()) + .collect(); + if ui.measure(Face::Regular, BODY, &tail) <= width { + return tail; + } + start += 1; + } + String::new() +} + /// The page header plus a row of actions under it; returns the y below. fn header(ui: &mut Ui, x: f32, title: &str, description: &str) -> f32 { let y = 36.0; @@ -791,6 +808,7 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) { selected, pings, lan, + .. } => { let games = lan.games(); let sub = match servers.len() { @@ -803,6 +821,7 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) { let saved = selected.is_some_and(|i| i < servers.len()); let mut items = vec![ (JOIN, "Join", Kind::Primary, has), + (FRIEND, "Join a friend", Kind::Secondary, true), (ADD, "Add server", Kind::Secondary, true), (DIRECT, "Direct connect", Kind::Secondary, true), (REFRESH, "Refresh", Kind::Ghost, true), @@ -955,6 +974,67 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) { ); ui.divider(x, y + rh, w); } + Screen::Friend { code, relay, focus } => { + let y = header( + ui, + x, + "Join a friend", + "Paste the invite code your friend sees in their pause menu.", + ); + let parsed = horizon_friends::invite::parse_detailed(code); + let ok = parsed.is_ok(); + actions_right( + ui, + x + w, + y - 24.0 - 58.0, + &[ + (DONE, "Join", Kind::Primary, ok), + (BACK, "Cancel", Kind::Ghost, true), + ], + ); + ui.divider(x, y, w); + let rh = 12.0 + CONTROL + 12.0; + let fx = x + t::ROW_LABEL + 16.0; + let fw = w - t::ROW_LABEL - 16.0; + let rows = [ + (FIELD_A, "Invite code", code, "Paste the code here", fw), + ( + FIELD_B, + "Relay (optional)", + relay, + "host:port, for short codes", + fw.min(360.0), + ), + ]; + let mut ry = y; + for (i, (fid, label, value, hint, width)) in rows.into_iter().enumerate() { + ui.text_line(Face::Regular, BODY, rh, x, ry, color::MUTED, label); + // A long code shows its end, where the typing is. + let shown = tail_fit(ui, value, width - 28.0); + ui.field( + fid, + [fx, ry + 12.0, width, CONTROL], + &shown, + hint, + usize::from(*focus) == i, + caret, + ); + ry += rh; + ui.divider(x, ry, w); + } + let note = match parsed { + _ if code.trim().is_empty() => None, + Err(e) => Some(e.to_string()), + Ok(horizon_friends::invite::Parsed::Short(_)) if relay.trim().is_empty() => Some( + "This is a relay's short code: fill in your friend's relay above, or ask for the full code." + .to_owned(), + ), + Ok(_) => None, + }; + if let Some(note) = note { + ui.text(Face::Regular, SMALL, x, ry + 12.0, color::MUTED, ¬e); + } + } Screen::Disconnected { reason, retry } => { let mut y = header( ui, @@ -1018,12 +1098,39 @@ pub fn wrap(ui: &Ui, text: &str, width: f32) -> Vec { /// blurred world, with the game's actions as a page. Ids match /// `game/screens.rs`'s PauseScreen actions: 0 back to game, 1 options, /// 2 save and quit, 3 statistics, 4 advancements, 9 world options. +/// Play with friends as the pause menu shows it (game/friends.rs fills it). +#[derive(Clone, Debug, Default)] +pub struct FriendsView { + /// A singleplayer world (not a server): the button is offered. + pub shown: bool, + pub sharing: bool, + pub code: Option, + /// Who can join and what to do when friends on the internet can't (or, + /// before the code, what the game is doing). + pub status: String, + /// Friends on the internet can reach the host. + pub reachable: bool, + /// Where the troubleshooting is, when they can't. + pub help: Option, + /// The players in the world besides the host. + pub guests: Vec, + pub notice: Option, + /// The code was just copied. + pub copied: bool, +} + pub mod pause { use super::*; fn act(a: u8) -> u64 { id("pause", u64::from(a)) } - pub fn draw(ui: &mut Ui, world: &str, quit_label: &str, opened: Instant) { + pub fn draw( + ui: &mut Ui, + world: &str, + quit_label: &str, + opened: Instant, + friends: &FriendsView, + ) { let (w, h) = (ui.w, ui.h); let p = t::ease_out_quint(opened.elapsed().as_secs_f32() / t::move_()); ui.opacity = p; @@ -1065,8 +1172,21 @@ pub mod pause { Kind::Secondary, true, ); + if friends.shown { + let iw = ui.button_width("Invite friends", true); + ui.button( + act(10), + [x + bw + lw + 16.0, y, iw, CONTROL_LARGE], + "Invite friends", + Kind::Secondary, + !friends.sharing, + ); + } y += CONTROL_LARGE + 32.0; ui.row_index = 0; + if friends.sharing { + y = invite(ui, x, y, cw, friends); + } ui.divider(x, y, cw); let rh = ui.row( x, @@ -1088,6 +1208,109 @@ pub mod pause { ui.opacity = 1.0; ui.offset = (0.0, 0.0); } + /// The invite section while sharing: the code with Copy and Stop + /// sharing, who is here, and what changed. Returns the y below it. + /// The code's groups packed into lines of at most `width`. + fn code_lines(ui: &Ui, code: &str, width: f32) -> Vec { + let mut lines: Vec = Vec::new(); + for group in code.split('-') { + match lines.last_mut() { + Some(l) if ui.measure(Face::Mono, BODY, &format!("{l}-{group}")) <= width => { + l.push('-'); + l.push_str(group); + } + _ => lines.push(group.to_owned()), + } + } + lines + } + fn invite(ui: &mut Ui, x: f32, mut y: f32, cw: f32, f: &FriendsView) -> f32 { + ui.divider(x, y, cw); + let top = y + 12.0; + ui.text( + Face::Regular, + BODY, + x, + top + 6.0, + color::MUTED, + "Invite code", + ); + let vx = x + t::ROW_LABEL + 16.0; + let stop = "Stop sharing"; + let sw = ui.button_width(stop, false); + ui.button( + act(12), + [x + cw - sw, top, sw, CONTROL], + stop, + Kind::Danger, + true, + ); + let copy = if f.copied { "Copied" } else { "Copy" }; + let copy_w = ui.button_width("Copied", false); + let buttons = sw + 8.0 + copy_w; + ui.button( + act(11), + [x + cw - buttons, top, copy_w, CONTROL], + copy, + Kind::Secondary, + f.code.is_some(), + ); + let line = (BODY * 1.45).round(); + let value_w = (cw - t::ROW_LABEL - 16.0 - buttons - 16.0).max(120.0); + y = top + 6.0; + match &f.code { + Some(code) => { + for l in code_lines(ui, code, value_w) { + ui.text(Face::Mono, BODY, vx, y, color::TEXT, &l); + y += line; + } + } + None => { + for l in wrap(ui, &f.status, value_w) { + ui.text(Face::Regular, BODY, vx, y, color::MUTED, &l); + y += line; + } + } + } + y = y.max(top + CONTROL) + 10.0; + let small = (SMALL * 1.45).round(); + if f.code.is_some() { + // Who can join: plain when friends anywhere can, in the text + // colour (it asks for something) when only the LAN and VPNs can. + let tint = if f.reachable { + color::MUTED + } else { + color::TEXT + }; + for l in wrap(ui, &f.status, cw) { + ui.text(Face::Regular, SMALL, x, y, tint, &l); + y += small; + } + if let Some(help) = &f.help { + let l = ui.fit(Face::Regular, SMALL, &format!("Help: {help}"), cw); + ui.text(Face::Regular, SMALL, x, y, color::FAINT, &l); + y += small; + } + } + let here = if f.guests.is_empty() { + "No friends here yet.".to_owned() + } else { + format!("Here now: {}", f.guests.join(", ")) + }; + let hint = + "Friends paste the code in Multiplayer, Join a friend, or on the launcher's Play page."; + let lines = [ + Some((here, color::MUTED)), + f.notice.clone().map(|n| (n, color::MUTED)), + Some((hint.to_owned(), color::FAINT)), + ]; + for (line, tint) in lines.into_iter().flatten() { + let line = ui.fit(Face::Regular, SMALL, &line, cw); + ui.text(Face::Regular, SMALL, x, y, tint, &line); + y += small; + } + y + 12.0 + } /// The PauseScreen action under a click, if any. pub fn click( atlas: &HudAtlas, @@ -1096,6 +1319,7 @@ pub mod pause { y: f32, world: &str, quit_label: &str, + friends: &FriendsView, ) -> Option { let mut ui = Ui::dry(atlas, batch, (x, y)); draw( @@ -1103,6 +1327,7 @@ pub mod pause { world, quit_label, Instant::now() - std::time::Duration::from_secs(5), + friends, ); let hit = ui.hit((x, y))?; let nav = id("pause.nav", 0); @@ -1111,7 +1336,9 @@ pub mod pause { h if h == nav + 1 => Some(4), h if h == nav + 2 => Some(3), h if h == nav + 3 => Some(1), - h => [0u8, 1, 2, 3, 4, 9].into_iter().find(|&a| act(a) == h), + h => [0u8, 1, 2, 3, 4, 9, 10, 11, 12] + .into_iter() + .find(|&a| act(a) == h), } } } @@ -1173,7 +1400,7 @@ mod tests { for (i, folder) in ["C", "B", "A"].iter().enumerate() { world(&saves, folder, 1000 * (i as i64 + 1)); } - let mut title = Title::new(saves.clone()); + let mut title = Title::new(saves.clone(), &saves); title.mode = Mode::Select { worlds: list_worlds(&saves), selected: None, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f56b41a3f..11ab140ea 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -8,6 +8,7 @@ mod armor_stands; mod backdrop; mod banners; mod beacon; +mod beehives; mod block_entity_anims; mod blockctl; mod boats; @@ -40,8 +41,10 @@ mod fireworks; mod fishing; mod fov; mod frames; +mod friends; mod functions; mod game_mode; +mod gamemode_switcher; mod ghasts; mod golems; mod growth; @@ -215,6 +218,8 @@ struct Options { /// `--dedicated`: run as a dedicated server; vanilla's server arguments /// (`--nogui`, `--port`, `--world`, `--universe`, `--initSettings`) follow. dedicated: Option>, + /// `--benchmark SCENARIO`: run the benchmark, write its report and quit. + benchmark: Option, } impl Options { /// The name to join servers with: the one given, else the offline name kept @@ -263,6 +268,7 @@ impl Options { .ok() .filter(|n| !n.is_empty()), dedicated: None, + benchmark: None, }; let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok(); let mut args = std::env::args().skip(1); @@ -270,7 +276,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 --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\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 --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\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); } @@ -312,6 +318,15 @@ impl Options { "--smoke-report" => o.report = Some(value.into()), "--screenshot-after" => o.screenshot_after = Some(value.parse()?), "--world" => o.world = Some(value), + "--benchmark" => { + if horizon_client::benchmark::scenes(&value).is_none() { + return Err(format!( + "unknown benchmark {value}: standard, village, forest, ocean or mountain" + ) + .into()); + } + o.benchmark = Some(value); + } "--server" => o.server = Some(value), "--name" => o.player_name = Some(value), "--session-file" => session_file = Some(value), @@ -351,6 +366,7 @@ impl Options { #[derive(Clone, Copy, PartialEq, Eq)] enum Screen { Playing, + GameModeSwitcher, Paused, Options, Chat, @@ -837,7 +853,7 @@ struct Game<'a> { end_portal_travel: bool, end: end::EndState, block_ticks: Ticks, - tick_chunks: HashSet<(i32, i32)>, + tick_chunks: horizon_client::tick_chunk_membership::TickChunkMembership, random_tick_sections: horizon_client::random_tick_sections::RandomTickSections, level_events: Vec, falling: Vec, @@ -904,6 +920,8 @@ struct Game<'a> { creative_screen: Creative, control: Option, frame_stats: horizon_client::control::FrameStats, + /// This play session's frame and tick times, for opt-in performance statistics. + perf: horizon_client::telemetry::Session, /// Control replies waiting for a rendered frame or a benchmark deadline. pending_screenshot: Option>, pending_bench: Option<(Instant, std::sync::mpsc::Sender)>, @@ -926,16 +944,21 @@ struct Game<'a> { remote: Option, /// This world is open to the network (game/lan.rs). lan: Option, + /// The open world is shared behind an invite code (game/friends.rs). + friends: Option, world_options: 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, + /// The F3 overlay's charts (F3+2, F3+3). + debug_charts: horizon_client::debug_chart::DebugCharts, show_hitboxes: bool, show_chunk_borders: bool, /// PauseScreen.showPauseMenu (false after F3+Escape). pause_menu: bool, /// MultiPlayerGameMode.previousLocalPlayerMode (F3+N goes back to it). previous_mode: Option, + gamemode_switcher: Option, /// The system clipboard (`KeyboardHandler.clipboardManager`). clipboard: horizon_client::clipboard::SystemClipboard, /// Select All in the append-only text fields. @@ -1550,16 +1573,20 @@ impl Game<'_> { } /// Track which chunks are ticking (Ticks needs chunk load/unload). fn sync_tick_chunks(&mut self) { - let loaded: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect(); - for k in loaded.difference(&self.tick_chunks.clone()) { - self.register_chunk_ticks(*k); + if !self.tick_chunks.synchronize(&self.world.chunks) { + return; } - for k in self.tick_chunks.difference(&loaded) { - self.random_tick_sections.remove(k); + // Move only the added keys out so registration can borrow all of Game. + let added = self.tick_chunks.take_added(); + for &key in &added { + self.register_chunk_ticks(key); + } + for &key in self.tick_chunks.removed() { + self.random_tick_sections.remove(&key); self.block_ticks - .remove_chunk(horizon_core::position::ChunkPos::new(k.0, k.1)); + .remove_chunk(horizon_core::position::ChunkPos::new(key.0, key.1)); } - self.tick_chunks = loaded; + self.tick_chunks.recycle_added(added); } /// ServerLevel.tick block phases: scheduled ticks, random ticks within the /// simulation distance, block events and moving pistons. @@ -2119,6 +2146,10 @@ impl Game<'_> { self.pending.record_saved(pos, &tag); } self.creaking_heart_broken(pos); + let hive = match self.world.block_entities.get(&key) { + Some(BlockEntity::Beehive(h)) => self.hive_state(pos).map(|s| ((**h).clone(), s)), + _ => None, + }; // playerWillDestroy and Level.removeBlock through the vanilla behaviour // library: the block entity's side effects (containers spill), neighbour // and shape updates, and the destroy event (particles, sound). @@ -2168,6 +2199,12 @@ impl Game<'_> { self.pop_resource(pos, d); } } + // BeehiveBlock.playerDestroy: silk touch keeps the bees in. + if let Some((hive, (honey, facing))) = hive + && !silk + { + self.hive_broken_by_player(pos, hive, honey, facing); + } // SpawnerBlock.spawnAfterBreak pops its experience whatever the tool. let xp = if silk && &*facts.name != "minecraft:spawner" { 0 @@ -2214,11 +2251,17 @@ impl Game<'_> { { return Ok(()); } + // An EntityHitResult may fall through to Item.use, never to useItemOn. + let block_hit = if self.entity_targeted() { + None + } else { + self.pick() + }; let sneaking = self.keys.contains(&KeyCode::ShiftLeft); let mut anchor_passed = None; // MultiPlayerGameMode.useItemOn: blocks react first unless sneaking with an item. if !(sneaking && self.held().is_some()) - && let Some(hit) = self.pick() + && let Some(hit) = block_hit.as_ref() { let held = self.held().cloned(); if self.use_lectern(hit.pos, held.as_ref()) { @@ -2297,12 +2340,12 @@ impl Game<'_> { let Some(info) = self.res.items.get(&stack.item).cloned() else { return Ok(()); }; - if self.use_bone_meal(&stack)? || self.ignite_tnt(&stack)? { + if block_hit.is_some() && (self.use_bone_meal(&stack)? || self.ignite_tnt(&stack)?) { return Ok(()); } use horizon_client::first_person::UseResult; let swings = self.swings_started; - match self.use_tool(&stack)? { + match self.use_tool(&stack, block_hit.is_some())? { UseResult::Success { swing } => { if (UseResult::Success { swing }).should_swing(swings, self.swings_started) { self.swing_arm(); @@ -2312,7 +2355,10 @@ impl Game<'_> { UseResult::Fail => return Ok(()), UseResult::Pass => {} } - if self.use_potion_item(&stack)? || self.throw_item(&stack)? { + if self.use_potion_item(&stack)? + || ((block_hit.is_some() || !stack.item.ends_with("_spawn_egg")) + && self.throw_item(&stack)?) + { return Ok(()); } if self.raise_shield(self.selected) @@ -2324,7 +2370,7 @@ impl Game<'_> { || self.use_book(&stack) // Block items (heads, carved pumpkins) aimed at a block are // placed first (useItemOn before useItem). - || (!(info.block.is_some() && self.pick().is_some()) && self.equip_from_hand(&stack)) + || (!(info.block.is_some() && block_hit.is_some()) && self.equip_from_hand(&stack)) { return Ok(()); } @@ -2339,26 +2385,28 @@ impl Game<'_> { return Ok(()); } // Block foods attempt placement before starting consumption. - if !(info.block.is_some() && self.pick().is_some()) && self.start_eating(&info) { + if !(info.block.is_some() && block_hit.is_some()) && self.start_eating(&info) { return Ok(()); } + // BoatItem.use also performs its own fluid/block raycast. if self.place_boat(&stack) { return Ok(()); } - if let Some(hit) = self.pick() - && (self.launch_firework(&hit, &stack) - || self.place_minecart(&hit, &stack) - || self.place_painting(&hit, &stack) - || self.place_item_frame(&hit, &stack) - || self.place_armor_stand(&hit, &stack) - || self.place_end_crystal(&hit, &stack)) + if let Some(hit) = block_hit.as_ref() + && (self.launch_firework(hit, &stack) + || self.place_minecart(hit, &stack) + || self.place_painting(hit, &stack) + || self.place_item_frame(hit, &stack) + || self.place_armor_stand(hit, &stack) + || self.place_end_crystal(hit, &stack)) { return Ok(()); } - if self.use_ender_eye(&stack)? { + if self.use_ender_eye(&stack, block_hit.is_some())? { return Ok(()); } - let Some(hit) = self.pick() else { + let Some(hit) = block_hit else { + self.use_offhand(); return Ok(()); }; if info.block.is_none() { @@ -2813,6 +2861,7 @@ impl Game<'_> { } fn tick(&mut self) -> Result<()> { self.tick_debug_keys()?; + self.tick_debug_charts(); if self.remote.is_some() { return self.tick_remote(); } @@ -2827,7 +2876,7 @@ impl Game<'_> { self.tick_weather_effects(); } if self.ticks.is_multiple_of(6000) { - self.save_game()?; + self.save_game_with(false)?; } if running { self.advance_clock(); @@ -2963,6 +3012,7 @@ impl Game<'_> { elytra.damage += glider_wear; } let feet = [player.position.x, player.position.y, player.position.z]; + let player_velocity = [player.velocity.x, player.velocity.y, player.velocity.z]; self.previous_eye = self.eye; self.eye += (camera_eye.unwrap_or(player.dimensions.eye_height) - self.eye) * 0.5; let crouching = player.pose == horizon_client::pose::Pose::Crouching; @@ -2972,13 +3022,59 @@ impl Game<'_> { match event { MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, feet), MotionEvent::Emission { - position, state, .. + state, in_water, .. } if !crouching => { - // Entity.playStepSound: the block's step sound at 0.15 volume. let sounds = self.res.facts.get(state).sounds.clone(); + // Entity.playStepSound: the block's step sound at 0.15 volume, + // muffled under the swim sound in water. + let (volume, pitch) = if in_water { + (sounds.volume * 0.05, sounds.pitch * 0.8) + } else { + (sounds.volume * 0.15, sounds.pitch) + }; + self.audio.play(&sounds.step, Some(feet), volume, pitch); + } + MotionEvent::Swim { volume, pitch } => { self.audio - .play(&sounds.step, Some(feet), sounds.volume * 0.15, sounds.pitch); - let _ = position; + .play("minecraft:entity.player.swim", Some(feet), volume, pitch); + } + MotionEvent::Drown => { + // LivingEntity.makeDrownParticles: eight bubbles moving + // with the player. + use horizon_client::particles::{ParticleOptions, ParticleType}; + for _ in 0..8 { + let mut triangle = || { + let r = self.particles.random(); + r.next_double() - r.next_double() + }; + let p = [ + feet[0] + triangle(), + feet[1] + triangle(), + feet[2] + triangle(), + ]; + self.particles.add( + &ParticleOptions::simple(ParticleType::Bubble), + p, + player_velocity, + ); + } + } + MotionEvent::BubbleColumnParticle { bubble, position } => { + // ServerLevel.sendParticles: SPLASH (speed 1) or BUBBLE + // (y spread 0.01, speed 0.2), one each. + use horizon_client::particles::{ParticleOptions, ParticleType}; + let (kind, spread, speed) = if bubble { + (ParticleType::Bubble, [0.0, 0.01, 0.0], 0.2) + } else { + (ParticleType::Splash, [0.0; 3], 1.0) + }; + self.particles.send_particles( + &ParticleOptions::simple(kind), + [position.x, position.y, position.z], + spread, + speed, + 1, + ); } MotionEvent::Fall(horizon_client::landing::FallEvent::Sound { sound, @@ -3152,6 +3248,7 @@ impl Game<'_> { }); } horizon_client::spans::time("tick_lan", || self.tick_lan()); + self.tick_friends(); horizon_client::spans::time("tick_hand", || self.tick_hand()); horizon_client::spans::time("tick_sleep", || self.tick_sleep()); horizon_client::spans::time("tick_portal", || self.tick_nether_portal())?; @@ -3372,7 +3469,12 @@ impl Game<'_> { title.draw_horizon(&mut ui, fade); ui.finish(); } else { - title.draw(&self.res.atlas, &mut batch, self.cursor); + title.draw( + &self.res.atlas, + &mut batch, + self.cursor, + self.settings.file.bool("hideSplashTexts"), + ); } return batch; } @@ -3550,7 +3652,7 @@ impl Game<'_> { 2 => "north (Towards negative Z)", _ => "east (Towards positive X)", }; - let lines = [ + let mut lines = vec![ format!("Horizon 26.3 (Rust) {:.0} fps", self.fps), format!( "C: {} chunks, {} sections drawn / {}", @@ -3593,7 +3695,9 @@ impl Game<'_> { self.world.day_time / 24000, self.world.day_time % 24000 ), + String::new(), ]; + lines.extend(self.debug_chart_lines()); for (i, line) in lines.iter().enumerate() { if line.is_empty() { continue; @@ -3616,6 +3720,22 @@ impl Game<'_> { false, ); } + let charts = self.debug_charts.draw( + &atlas.font, + w as i32, + h as i32, + self.settings.max_fps, + 1000.0 / self.clock.rate(), + self.remote.is_some(), + ); + hud_layout::paint(&mut batch, atlas, &charts); + if self.debug_charts.lightmap + && let Some(r) = &self.renderer + { + let view = + horizon_client::debug_chart::lightmap(&r.lightmap_pixels, w as i32, h as i32); + hud_layout::paint(&mut batch, atlas, &view); + } } if !self.ui.hide_gui && let Some((text, at)) = &self.message @@ -3641,6 +3761,7 @@ impl Game<'_> { true, ); } + Screen::GameModeSwitcher => self.draw_gamemode_switcher(&mut batch), Screen::Dead => self.draw_death_screen(&mut batch), Screen::Stats => self.draw_stats(&mut batch), Screen::Advancements => self.draw_advancements(&mut batch), @@ -3697,7 +3818,8 @@ impl Game<'_> { | BlockEntity::Sculk(_) | BlockEntity::Banner(_) | BlockEntity::CreakingHeart(_) - | BlockEntity::Spawner(_), + | BlockEntity::Spawner(_) + | BlockEntity::Beehive(_), ) => {} None => { v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); @@ -3946,7 +4068,8 @@ impl Game<'_> { | BlockEntity::Sculk(_) | BlockEntity::Banner(_) | BlockEntity::CreakingHeart(_) - | BlockEntity::Spawner(_), + | BlockEntity::Spawner(_) + | BlockEntity::Beehive(_), ) => {} None if self.mount_active() => self.draw_mount_background(batch, ox, oy), None => { @@ -3995,6 +4118,9 @@ impl Game<'_> { self.draw_item(batch, &stack, self.cursor.0 - 8.0, self.cursor.1 - 8.0); } self.draw_slot_tooltip(batch); + if self.container.is_none() && self.craft_size == 2 && !self.mount_active() { + self.draw_inventory_effects(batch, (ox, oy), 176); + } } pub(super) fn close_container(&mut self) { self.close_station(); @@ -4856,6 +4982,22 @@ impl Game<'_> { f.input_clicked(&self.res.recipes, before); } } + /// `Camera.setRotation`: the camera's orientation, turned round in + /// third-person front view. + pub(super) fn camera_orientation(&self) -> glam::Quat { + let (view_yaw, view_pitch) = + if self.camera_type == perspective::CameraType::ThirdPersonFront { + (self.yaw + 180.0, -self.pitch) + } else { + (self.yaw, self.pitch) + }; + glam::Quat::from_euler( + glam::EulerRot::YXZ, + std::f32::consts::PI - view_yaw.to_radians(), + -view_pitch.to_radians(), + 0.0, + ) + } /// ItemEntityRenderer: items bob and spin; blocks render as small cubes. fn entity_geometry( &mut self, @@ -5006,21 +5148,9 @@ impl Game<'_> { if let Some(r) = &self.renderer { let lid = |p: [i32; 3]| self.chest_lid(p, alpha as f32); let anim = |p: [i32; 3]| self.block_anim(p, alpha as f32); - let (view_yaw, view_pitch) = - if self.camera_type == perspective::CameraType::ThirdPersonFront { - (self.yaw + 180.0, -self.pitch) - } else { - (self.yaw, self.pitch) - }; let scene = horizon_client::block_entity_render::Scene { camera, - // Camera.setRotation. - orientation: glam::Quat::from_euler( - glam::EulerRot::YXZ, - std::f32::consts::PI - view_yaw.to_radians(), - -view_pitch.to_radians(), - 0.0, - ), + orientation: self.camera_orientation(), anim: &anim, texts: None, partial: alpha as f32, @@ -5450,6 +5580,7 @@ impl Game<'_> { self.tick_beacons(); self.tick_creaking_hearts()?; self.tick_spawners()?; + self.tick_beehives(); let mut lit_changes = Vec::new(); for (pos, entity) in self.world.block_entities.iter_mut() { if let BlockEntity::Furnace(f) = entity @@ -5593,7 +5724,7 @@ impl Game<'_> { } out } - /// CloudRenderer (fancy): 12x4x12 cells from clouds.png drifting east. + /// CloudRenderer: flat or 12x4x12 extruded cells drifting east. fn cloud_geometry( &self, sky: &horizon_client::environment::Sky, @@ -5650,6 +5781,12 @@ impl Game<'_> { }); } }; + 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]], @@ -5700,7 +5837,9 @@ impl Game<'_> { name: Option<&str>, seed: Option, creative: bool, + create: Option<&horizon_client::title::WorldOptions>, ) -> Result<()> { + self.perf.world_opening(); let save_root = std::env::current_dir()?.join("saves").join(folder); horizon_client::save::upgrade_older_world(&save_root)?; horizon_client::save::migrate_legacy(&save_root)?; @@ -5719,7 +5858,9 @@ impl Game<'_> { .map(|d| horizon_client::random_sequences::RandomSequences::from_nbt(&d)) .unwrap_or_default(); self.border = Default::default(); - let level = Level::read(&save_root).unwrap_or_else(|| Level { + let existing = Level::read(&save_root); + let created = existing.is_none(); + let level = existing.unwrap_or_else(|| Level { name: name.unwrap_or(folder).to_owned(), // WorldOptions.randomSeed when no seed was given. seed: seed.unwrap_or_else(|| { @@ -5736,6 +5877,13 @@ impl Game<'_> { ..Level::default() }); let mut level = level; + // CreateWorldScreen's choices, before streaming reads the generator. + if created && let Some(o) = create { + level.hardcore = o.hardcore; + level.difficulty = horizon_client::title::DIFFICULTIES[o.difficulty()].into(); + level.allow_commands = Some(o.commands(creative)); + horizon_client::save::write_world_gen_settings(&save_root, level.seed, o.world_gen())?; + } horizon_client::crash::set_detail("World", format!("{} (saves/{folder})", level.name)); if let Some(d) = &self.options.dimension { level.dimension = d.clone(); @@ -5966,6 +6114,7 @@ impl Game<'_> { return Ok(()); }; // Save the departing dimension's changed chunks. + self.streaming.save(&mut self.world, true); 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 @@ -6125,6 +6274,27 @@ impl Game<'_> { /// Leaving the game with a world open (window closed, Quit, `quit`): /// menu items go back (Player.closeContainer), then the world is saved, /// once. + /// Keeps this play session's performance summary for the launcher to send, if the player + /// allows performance statistics (`horizon_client::telemetry`), and starts the next one. + pub(super) fn finish_perf(&mut self) { + let s = &self.settings; + let settings = horizon_telemetry::payload::Settings { + render_distance: s.render_distance.clamp(0, 255) as u8, + simulation_distance: s.simulation_distance.clamp(0, 255) as u8, + // 260 is the slider's "unlimited". + max_fps: if s.max_fps >= 260 { + 0 + } else { + s.max_fps.min(u32::from(u16::MAX)) as u16 + }, + vsync: s.vsync, + fullscreen: s.fullscreen, + graphics: s.graphics_preset.clone(), + }; + self.perf + .finish(&horizon_client::logging::game_home(), settings); + } + pub(super) fn save_for_exit(&mut self) -> Result<()> { if self.title.is_some() || self.saved_for_exit { return Ok(()); @@ -6146,6 +6316,7 @@ impl Game<'_> { if self.remote.is_some() { return self.leave_server(None); } + self.finish_perf(); self.stats.custom("leave_game", 1); self.save_game()?; self.lan_close(false); @@ -6154,6 +6325,7 @@ impl Game<'_> { self.save.flush(); self.session_lock = None; horizon_client::crash::clear_detail("World"); + self.debug_charts.reset(); self.streaming.paused = true; self.world = World::new(self.res.facts.air, 0); self.player = None; @@ -6166,7 +6338,10 @@ impl Game<'_> { if let Some(r) = self.renderer.as_mut() { r.clear_sections(); } - self.title = Some(Title::new(std::env::current_dir()?.join("saves"))); + self.title = Some(Title::new( + std::env::current_dir()?.join("saves"), + &self.options.resources, + )); self.capture(false); Ok(()) } @@ -6500,7 +6675,11 @@ impl Game<'_> { } } /// Block tool use: distinguish success, failure and fall-through for hand feedback. - fn use_tool(&mut self, stack: &ItemStack) -> Result { + fn use_tool( + &mut self, + stack: &ItemStack, + allow_block_actions: bool, + ) -> Result { use horizon_client::first_person::UseResult; let item = stack.item.trim_start_matches("minecraft:").to_owned(); let at = |p: [i32; 3]| { @@ -6510,7 +6689,8 @@ impl Game<'_> { f64::from(p[2]) + 0.5, ] }; - if let Some(hit) = self.pick() + if allow_block_actions + && let Some(hit) = self.pick() && self.use_on_cauldron(hit.pos)? { return Ok(UseResult::Success { swing: true }); @@ -6572,11 +6752,16 @@ impl Game<'_> { } return Ok(UseResult::Success { swing: true }); } + // BucketItem.use has its own ray, even when the crosshair hits an entity. + let bucket = horizon_client::items::bucket_contents(&stack.item); + if !allow_block_actions && bucket.is_none() { + return Ok(UseResult::Pass); + } let Some(hit) = self.pick() else { return Ok(UseResult::Pass); }; let clicked = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); - if let Some((content, sound, mob)) = horizon_client::items::bucket_contents(&stack.item) { + if let Some((content, sound, mob)) = bucket { if !self.may_build() { return Ok(UseResult::Fail); } @@ -7127,9 +7312,17 @@ impl Game<'_> { .clamp_gui_scale([r.config.width as i32, r.config.height as i32]); } self.streaming.radius = self.settings.render_distance; + // Options.biomeBlendRadius, ambientOcclusion and cutoutLeaves: + // LevelExtractor.allChanged when they change. + let (s, st) = (&self.settings, &self.streaming); + let remesh = (s.biome_blend, s.smooth_lighting, s.cutout_leaves) + != (st.biome_blend, st.smooth_lighting, st.cutout_leaves); self.streaming.biome_blend = self.settings.biome_blend; self.streaming.smooth_lighting = self.settings.smooth_lighting; self.streaming.cutout_leaves = self.settings.cutout_leaves; + if remesh { + self.all_sections_changed(); + } self.audio.master = self.settings.master_volume; horizon_client::hud::GUI_SCALE.store( self.settings.gui_scale, @@ -7137,6 +7330,14 @@ impl Game<'_> { ); self.apply_ui_settings(); } + /// `LevelExtractor.allChanged`: every loaded section is rebuilt. + fn all_sections_changed(&mut self) { + for &(x, z) in self.world.chunks.keys() { + for sy in 0..horizon_client::chunk::HEIGHT / 16 { + self.world.dirty_sections.insert((x, sy, z)); + } + } + } /// Whether precipitation at a column is snow (Biome.coldEnoughToSnow: /// base temperature lowered above y 80) or none (no precipitation). fn precipitation(&self, x: i32, y: i32, z: i32) -> Option { @@ -7582,6 +7783,7 @@ impl Game<'_> { let name = self.res.names.item(&item); self.tooltip(batch, &name, self.cursor.0, self.cursor.1); } + self.draw_inventory_effects(batch, (ox, oy), Creative::WIDTH as i32); } fn creative_trash_hovered(batch: &HudBatch, cursor: (f32, f32)) -> bool { let (ox, oy) = Self::creative_origin(batch); @@ -7777,14 +7979,24 @@ impl Game<'_> { .collect(); } fn save_game(&mut self) -> Result<()> { + self.save_game_with(true) + } + /// The autosave doesn't `wait` for the chunks to be on disk: every + /// generated chunk is saved, hundreds at a time, encoded and written on + /// the region writer meanwhile. + fn save_game_with(&mut self, wait: bool) -> Result<()> { if self.remote.is_some() { return Ok(()); } + self.streaming.save(&mut self.world, wait); 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)?; - self.save_entities()?; + .save_later(&chunks, self.res.assets.registry, &self.res.biomes)?; + if wait { + self.save.flush(); + } + self.save_entities(wait)?; self.save_maps(); self.save_random_sequences(); self.save_raids(); @@ -7973,9 +8185,11 @@ impl Game<'_> { self.end_geometry(camera, &mut entities); } if (!title || live) && self.dim == Dim::Overworld { - horizon_client::spans::time("clouds", || { - self.cloud_geometry(&sky, camera, alpha, &mut entities) - }); + 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) @@ -8071,6 +8285,7 @@ impl Game<'_> { } else { None }, + menu_blur: self.menu_blur(), }; let result = match self.renderer.as_mut() { Some(renderer) => horizon_client::spans::time("renderer", || renderer.render(&frame)), @@ -8080,6 +8295,18 @@ impl Game<'_> { self.entity_vertices = entities; result } + /// `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 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) + }); + let radius = self.settings.menu_blur as f32; + (blurred && radius >= 1.0).then_some(radius) + } /// `LevelExtractor` / `LevelRenderer`: the world border wall this frame. fn border_draw( &mut self, @@ -8138,6 +8365,7 @@ impl Game<'_> { self.pause_menu = true; self.capture(true); } + Screen::GameModeSwitcher => self.close_gamemode_switcher(false), Screen::Dead => {} Screen::Stats => self.screen = Screen::Paused, Screen::Advancements => self.close_advancements(), @@ -8504,6 +8732,11 @@ impl ApplicationHandler for Game<'_> { if self.screen == Screen::Inventory || self.creative_inventory_open() { self.inventory_drag_move(); } + if let Some(title) = &mut self.title + && !horizon_client::ui_theme::horizon() + { + title.drag(self.cursor, (b.width, b.height)); + } if self.dragging && self.screen == Screen::Options { let _ = b; self.options_drag()?; @@ -8579,6 +8812,15 @@ impl ApplicationHandler for Game<'_> { )?; } } + WindowEvent::MouseInput { + state: ElementState::Released, + button: MouseButton::Left, + .. + } if self.title.is_some() && self.screen != Screen::Options => { + if let Some(title) = &mut self.title { + title.release(); + } + } WindowEvent::MouseInput { state, button: MouseButton::Left, @@ -8607,13 +8849,23 @@ impl ApplicationHandler for Game<'_> { match action { Action::Quit => event_loop.exit(), Action::Options => self.open_options(true), - Action::Play { folder } => self.open_world(&folder, None, None, false)?, + Action::Accessibility => self + .open_options_at(true, horizon_client::options_ui::Page::Accessibility), + Action::Language => { + self.open_options_at(true, horizon_client::options_ui::Page::Language) + } + Action::Play { folder } => { + self.open_world(&folder, None, None, false, None)? + } Action::Create { folder, name, seed, creative, - } => self.open_world(&folder, Some(&name), seed, creative)?, + options, + } => { + self.open_world(&folder, Some(&name), seed, creative, Some(&options))? + } Action::Connect { address } => { self.connect_server(&address, &self.options.player_name())? } @@ -8870,7 +9122,13 @@ impl ApplicationHandler for Game<'_> { for _ in 0..steps { let started = Instant::now(); if self.title.is_none() && !self.pause { + let tick = Instant::now(); horizon_client::spans::time("tick", || self.tick())?; + // In single player the tick is the integrated server's. + if self.remote.is_none() { + self.perf.tick(tick.elapsed().as_secs_f32() * 1000.0); + self.debug_charts.log_tick(tick, tick.elapsed()); + } self.tick_ambience(); self.tick_fov(); } else if self.title.is_some() { @@ -8956,6 +9214,19 @@ impl ApplicationHandler for Game<'_> { } if rendered { self.frame_stats.record(elapsed.as_secs_f32() * 1000.0); + self.debug_charts.frame_times.log(elapsed.as_nanos() as i64); + if self.frames == 0 { + // The launcher times Play to this line (launcher/src/perf.rs). + log::info!( + "Horizon: first frame after {} ms", + self.started.elapsed().as_millis() + ); + } + if self.title.is_some() { + self.perf.title_shown(); + } else if self.screen == Screen::Playing && self.player.is_some() { + self.perf.frame(elapsed.as_secs_f32() * 1000.0); + } self.frames += 1; self.fps_frames += 1; horizon_client::crash::debug_crash_tick(); @@ -8999,7 +9270,14 @@ impl ApplicationHandler for Game<'_> { return; } if let Some(w) = &self.window { - w.request_redraw(); + if self.options.offscreen { + // Offscreen frames don't wait for the window to be drawn: an + // occluded window (a locked macOS session) gets no redraws. + let id = w.id(); + self.window_event(event_loop, id, WindowEvent::RedrawRequested); + } else { + w.request_redraw(); + } } event_loop.set_control_flow(ControlFlow::Poll); } @@ -9010,6 +9288,7 @@ impl ApplicationHandler for Game<'_> { if let Err(e) = self.save_for_exit() { log::warn!("Horizon: failed to save the world on exit: {e}"); } + self.finish_perf(); } } /// clouds.png as filled cells (`CloudRenderer.prepare`: alpha 10 or more). @@ -9177,6 +9456,15 @@ pub fn run() -> Result<()> { 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(); @@ -9336,7 +9624,7 @@ pub fn run() -> Result<()> { end_portal_travel: false, end: Default::default(), block_ticks: Ticks::new(0), - tick_chunks: HashSet::new(), + tick_chunks: Default::default(), random_tick_sections: Default::default(), level_events: Vec::new(), falling: Vec::new(), @@ -9349,9 +9637,9 @@ pub fn run() -> Result<()> { glow_map_frame_model: frames::bake_frame(&root, "glow_item_frame_map"), armor_stands: Vec::new(), others: Vec::new(), - armor_stand_assets: armor_stands::ArmorStandAssets::load(&root), + armor_stand_assets, boats: Vec::new(), - boat_models: boats::BoatModels::load(&root), + boat_models, crystal_model: horizon_client::mobs::load_model(&root, "minecraft:end_crystal#main"), carts: Vec::new(), jukebox_sounds: HashMap::new(), @@ -9370,7 +9658,7 @@ pub fn run() -> Result<()> { .join("assets/skins"), ), skin_slots: Vec::new(), - cart_models: minecarts::CartModels::load(&root), + cart_models, riding: None, ender_items: vec![None; 27], ender_open: None, @@ -9390,6 +9678,7 @@ pub fn run() -> Result<()> { creative_screen: Creative::load(&game_root)?, control: None, frame_stats: Default::default(), + perf: Default::default(), pending_screenshot: None, pending_bench: None, flight: None, @@ -9403,11 +9692,14 @@ pub fn run() -> Result<()> { 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, @@ -9442,6 +9734,14 @@ pub fn run() -> Result<()> { player_model: None, }; game.ui.vanilla_root = vanilla_root; + if game.options.benchmark.is_some() { + // The same conditions on every machine: no VSync, no frame cap, no + // pause or idle limit without focus. In memory only, never saved. + game.settings.vsync = false; + game.settings.max_fps = 260; + game.settings.inactivity_fps_limit = "minimized".into(); + game.options.no_pause = true; + } game.apply_settings(); if let Some(path) = &game.options.control { let server = horizon_client::control::Server::start(path) @@ -9449,6 +9749,29 @@ pub fn run() -> Result<()> { log::info!("Horizon: control socket {}", server.path().display()); game.control = Some(server); } + if let Some(scenario) = game.options.benchmark.clone() { + let control = game + .control + .get_or_insert_with(horizon_client::control::Server::local); + horizon_client::benchmark::start( + control.sender(), + horizon_client::benchmark::Setup { + scenario, + started, + app: horizon_bench::App { + name: "horizon-client".into(), + version: horizon_client::crash::version(), + commit: option_env!("HORIZON_COMMIT").map(str::to_owned), + mods: Vec::new(), + }, + simulation_distance: game.settings.simulation_distance as u32, + vsync: false, + fps_cap: None, + offscreen: game.options.offscreen, + game_dir: std::env::current_dir()?, + }, + ); + } if let Ok(spec) = std::env::var("HORIZON_DISPENSE_FIXTURE") { return game.dispense_fixture(&spec); } @@ -9471,10 +9794,13 @@ pub fn run() -> Result<()> { } Some(folder) => { let (seed, creative) = (game.options.seed, game.options.creative); - game.open_world(&folder, None, Some(seed), creative)?; + game.open_world(&folder, None, Some(seed), creative, None)?; } None => { - let title = Title::new(std::env::current_dir()?.join("saves")); + let title = Title::new( + std::env::current_dir()?.join("saves"), + &game.options.resources, + ); // The launcher's opening, once per session and only in Horizon's style. if horizon_client::ui_theme::horizon() && game.options.frames.is_none() { title @@ -9534,6 +9860,9 @@ mod runtime_reset_tests { } } +#[cfg(test)] +mod entity_model_loading_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 02638f64f..4c5c0fbbe 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -19,27 +19,99 @@ pub(super) struct Toast { icon: String, frame: Frame, title: Text, - shown: Option, - /// A `RecipeToast`: the icon is a recipe result. - recipe: bool, + slide: Slide, + /// A `RecipeToast`: the crafting station and result of each display + /// unlocked while it lasts (`recipeItems`); empty for an advancement. + recipes: Vec<(String, ItemStack)>, + /// `RecipeToast.changed` and `lastChanged`. + changed: bool, + last_changed: i64, } impl Toast { - pub(super) fn is_recipe(&self) -> bool { - self.recipe - } - pub(super) fn was_shown(&self) -> bool { - self.shown.is_some() - } - /// `RecipeToast`: "New Recipe(s) Unlocked!" with the recipe's result. - pub(super) fn recipe(icon: &str) -> Self { + /// `RecipeToast.addOrUpdate` on a new toast. + pub(super) fn recipe(items: Vec<(String, ItemStack)>) -> Self { Self { - icon: icon.to_owned(), + icon: String::new(), frame: Frame::Task, title: Text::literal(""), - shown: None, - recipe: true, + slide: Slide::default(), + recipes: items, + changed: true, + last_changed: 0, } } + pub(super) fn is_recipe(&self) -> bool { + !self.recipes.is_empty() + } + /// `RecipeToast.addItem`: more displays on a toast still queued or shown. + pub(super) fn add_recipes(&mut self, items: Vec<(String, ItemStack)>) { + self.recipes.extend(items); + self.changed = true; + } + /// `Toast.update` with `fullyVisibleForMs`: whether it wants to be shown. + fn wants_show(&mut self, fully_for: i64, multiplier: f64) -> bool { + let time = 5000.0 * multiplier; + if self.recipes.is_empty() { + // AdvancementToast. + return (fully_for as f64) < time; + } + if self.changed { + self.last_changed = fully_for; + self.changed = false; + } + ((fully_for - self.last_changed) as f64) < time + } + /// `RecipeToast.displayedRecipeIndex`: the displays take turns over the + /// toast's display time. + fn displayed_recipe(&self, fully_for: i64, multiplier: f64) -> usize { + let n = self.recipes.len() as f64; + (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 { @@ -430,8 +502,10 @@ impl Game<'_> { icon: d.icon.clone(), frame: d.frame, title: text_of(&d.title), - shown: None, - recipe: false, + slide: Slide::default(), + recipes: Vec::new(), + changed: false, + last_changed: 0, }); } if d.announce && self.ui.rules.bool("show_advancement_messages") { @@ -679,45 +753,57 @@ impl Game<'_> { c["from"].as_str().is_none_or(|f| f == from) && c["to"].as_str().is_none_or(|t| t == to) }); } - /// `ToastManager` with the `AdvancementToast`. + /// `ToastManager` with the `AdvancementToast` and the `RecipeToast`, + /// one at a time. pub(super) fn draw_toasts(&mut self, batch: &mut HudBatch) { + let multiplier = f64::from(self.settings.notification_display_time); let Some(t) = self.adv.toasts.front_mut() else { return; }; - let shown = *t.shown.get_or_insert_with(Instant::now); - let ms = shown.elapsed().as_millis() as f32; - // AdvancementToast.DISPLAY_TIME: 5 s, sliding 600 ms in and out. - if ms > 5600.0 { + let first = t.slide.origin.is_none(); + let origin = *t.slide.origin.get_or_insert_with(Instant::now); + let now = origin.elapsed().as_millis() as i64; + let mut slide = std::mem::take(&mut t.slide); + let (sound, finished) = slide.update(now, |fully| t.wants_show(fully, multiplier)); + t.slide = slide; + if finished { self.adv.toasts.pop_front(); return; } - let slide = if ms < 600.0 { - ms / 600.0 - } else if ms > 5000.0 { - 1.0 - (ms - 5000.0) / 600.0 - } else { - 1.0 - }; - let (title, frame, icon, recipe) = (t.title.clone(), t.frame, t.icon.clone(), t.recipe); - if recipe { - // RecipeToast: black description under a purple title. + let x = batch.width - 160.0 * t.slide.portion; + let fully_for = t.slide.fully_for; + let (title, frame, icon) = (t.title.clone(), t.frame, t.icon.clone()); + let recipe = t + .is_recipe() + .then(|| t.recipes[t.displayed_recipe(fully_for, multiplier)].clone()); + // ToastManager.update: the sound of the new visibility, and a + // challenge's own sound as it leaves the queue. + if let Some(show) = sound { + let event = if show { "ui.toast.in" } else { "ui.toast.out" }; + self.audio + .play(&format!("minecraft:{event}"), None, 1.0, 1.0); + } + if first && recipe.is_none() && frame == Frame::Challenge { + self.audio + .play("minecraft:ui.toast.challenge_complete", None, 1.0, 1.0); + } + 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 x = batch.width - 160.0 * slide; 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; batch.text(atlas, &title, x + 30.0, 7.0, 0xFF50_0050, false); batch.text(atlas, &description, x + 30.0, 18.0, 0xFF00_0000, false); - self.draw_item(batch, &ItemStack::new(&icon, 1), x + 8.0, 8.0); + let start = batch.vertices.len(); + self.draw_item_model(batch, &ItemStack::new(&station, 1), x + 3.0, 3.0); + batch.scale_since(start, x, 0.0, 0.6, 0.6); + self.draw_item_model(batch, &item, x + 8.0, 8.0); return; } - if frame == Frame::Challenge && ms < 50.0 { - self.audio - .play("minecraft:ui.toast.challenge_complete", None, 1.0, 1.0); - } let atlas = &self.res.atlas; - let x = batch.width - 160.0 * slide; batch.sprite(atlas, "gui/sprites/toast/advancement", x, 0.0); let (key, color) = match frame { Frame::Task => ("advancements.toast.task", 0xFF00_FFFF), @@ -813,3 +899,94 @@ pub(super) fn text_of(v: &Value) -> Text { Text::empty() } } + +#[cfg(test)] +mod tests { + use super::*; + + fn recipes(n: usize) -> Toast { + Toast::recipe( + (0..n) + .map(|i| { + let item = ItemStack::new(&format!("minecraft:item_{i}"), 1); + ("minecraft:crafting_table".to_owned(), item) + }) + .collect(), + ) + } + /// Drives a toast frame by frame (every `step` ms) and returns the slide + /// portions at the given times and when it finished. + fn run(toast: &mut Toast, step: i64, until: i64, at: &[i64]) -> (Vec, Option) { + let mut slide = Slide::default(); + let mut seen = Vec::new(); + for now in (0..=until).step_by(step as usize) { + let (_, finished) = slide.update(now, |f| toast.wants_show(f, 1.0)); + if finished { + return (seen, Some(now)); + } + if at.contains(&now) { + seen.push(slide.portion); + } + } + (seen, None) + } + + #[test] + fn toasts_slide_in_squared_and_out_after_five_seconds() { + let mut toast = recipes(1); + let (portions, finished) = run(&mut toast, 10, 10_000, &[0, 300, 600, 3000]); + // (300 / 600)² = 0.25: ToastInstance.calculateVisiblePortion. + assert_eq!(portions, [0.0, 0.25, 1.0, 1.0]); + // Fully in at 600, shown 5000 ms, out over 600 more. + assert!( + finished.is_some_and(|t| (6200..=6220).contains(&t)), + "{finished:?}" + ); + } + + #[test] + fn the_first_update_plays_the_show_sound_and_the_hide_sound_follows() { + let mut toast = recipes(1); + let mut slide = Slide::default(); + assert_eq!(slide.update(0, |f| toast.wants_show(f, 1.0)).0, Some(true)); + assert_eq!(slide.update(100, |f| toast.wants_show(f, 1.0)).0, None); + assert_eq!( + slide.update(5600, |f| toast.wants_show(f, 1.0)).0, + Some(false) + ); + } + + #[test] + fn recipe_toasts_cycle_through_their_displays_over_the_display_time() { + let toast = recipes(4); + let shown: Vec = [0, 1249, 1250, 2500, 3750, 4999, 5000] + .iter() + .map(|&t| toast.displayed_recipe(t, 1.0)) + .collect(); + assert_eq!(shown, [0, 0, 1, 2, 3, 3, 0]); + // notificationDisplayTime doubles each turn. + assert_eq!(toast.displayed_recipe(2500, 2.0), 1); + } + + #[test] + fn unlocking_more_recipes_keeps_the_toast_up_five_more_seconds() { + let mut toast = recipes(1); + let mut slide = Slide::default(); + let mut finished = None; + for now in (0..=20_000).step_by(10) { + if now == 4000 { + toast.add_recipes(recipes(1).recipes); + } + if slide.update(now, |f| toast.wants_show(f, 1.0)).1 { + finished = Some(now); + break; + } + } + assert_eq!(toast.recipes.len(), 2); + // lastChanged moved to 3400 ms fully shown: hidden at 8400 + 600. + assert!( + finished.is_some_and(|t| (9600..=9620).contains(&t)), + "{finished:?}" + ); + } +} diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index e554cd520..243351af6 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -368,6 +368,7 @@ impl Game<'_> { } match self.screen { Screen::Playing => "playing", + Screen::GameModeSwitcher => "gamemode-switcher", Screen::Paused => "paused", Screen::Options => "options", Screen::Inventory if self.station.is_some() => "station", @@ -484,11 +485,19 @@ impl Game<'_> { seed, creative, focus, + options, } => json!({ "mode": "create-world", + "tab": (["game", "world", "more"][options.tab.min(2)]), "fields": { "name": name, "seed": seed }, "focus": match focus { 0 => "name", 1 => "seed", _ => "none" }, "creative": creative, + "hardcore": options.hardcore, + "difficulty": horizon_client::title::DIFFICULTIES[options.difficulty()], + "allow_commands": options.commands(*creative), + "superflat": options.flat, + "generate_structures": options.structures, + "bonus_chest": options.bonus_chest(), }), Mode::Edit { world, @@ -1321,10 +1330,17 @@ impl Game<'_> { let title = self.title.as_mut().ok_or("no title screen")?; if let Some(field) = &field { match &mut title.mode { - horizon_client::title::Mode::Create { focus, .. } => { + horizon_client::title::Mode::Create { focus, options, .. } => { + // Each box is on its own tab. *focus = match field.as_str() { - "name" => 0, - "seed" => 1, + "name" => { + options.tab = 0; + 0 + } + "seed" => { + options.tab = 1; + 1 + } other => { return Err(format!( "the create-world fields are name and seed, not {other}" diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index dfc6adfd8..94e9422ed 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -27,8 +27,11 @@ pub(super) struct ArmorStandAssets { pub equipment: HashMap)>>, } impl ArmorStandAssets { - pub fn load(root: &std::path::Path) -> Self { - let load = |key: &str| horizon_client::mobs::load_model(root, key); + pub fn load( + root: &std::path::Path, + document: Option<&horizon_client::mobs::EntityModelDocument>, + ) -> Self { + let load = |key: &str| document.and_then(|document| document.model(key)); let mut layers = HashMap::new(); let mut player = HashMap::new(); for slot in ["helmet", "chestplate", "leggings", "boots"] { diff --git a/crates/horizon-client/src/game/beacon.rs b/crates/horizon-client/src/game/beacon.rs index 943fb9e9d..fafb2787d 100644 --- a/crates/horizon-client/src/game/beacon.rs +++ b/crates/horizon-client/src/game/beacon.rs @@ -274,6 +274,17 @@ impl Game<'_> { } } /// Clicks on the power, confirm and cancel buttons. + /// The effect, upgrade, confirm and cancel buttons a controller can + /// focus (GUI origin relative). + pub(super) fn beacon_targets(&self) -> Vec<[f32; 4]> { + let (ux, uy) = upgrade_button(); + buttons() + .into_iter() + .map(|(_, x, y, _)| (x, y)) + .chain([(ux, uy), (164.0, 107.0), (190.0, 107.0)]) + .map(|(x, y)| [x + SHIFT, y, 22.0, 22.0]) + .collect() + } pub(super) fn beacon_click(&mut self, local: (f32, f32)) -> bool { let l = (local.0 - SHIFT, local.1); let levels = self.beacon_levels(); diff --git a/crates/horizon-client/src/game/beehives.rs b/crates/horizon-client/src/game/beehives.rs new file mode 100644 index 000000000..eb74becc7 --- /dev/null +++ b/crates/horizon-client/src/game/beehives.rs @@ -0,0 +1,238 @@ +//! Beehives and bee nests in the game (`crate::beehive` holds their logic): +//! their server tick, bees going in, and the bees let out, angry, when a +//! player breaks the hive or fire reaches it. +use super::Game; +use horizon_client::{ + beehive::{self, Beehive, HiveHost, Release}, + containers::BlockEntity, + mobs::{Mob, Who, bee}, +}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::{LegacyRandom, RandomSource}, +}; +use horizon_world::{nbt::Tag, registry::BlockStateId}; + +struct GameHive<'g, 'a> { + game: &'g mut Game<'a>, +} +impl HiveHost for GameHive<'_, '_> { + fn random(&mut self) -> &mut LegacyRandom { + &mut self.game.world.random + } + fn bees_stay_in_hive(&self, _at: [i32; 3]) -> bool { + bee::bees_stay_in_hive(&self.game.mob_world_base(&[])) + } + fn blocked(&self, at: [i32; 3]) -> bool { + !self + .game + .mob_world_base(&[]) + .block_collision_boxes(at[0], at[1], at[2]) + .is_empty() + } + fn set_honey_level(&mut self, at: [i32; 3], level: i32) { + let state = self.game.world.block(at[0], at[1], at[2]); + if let Some(state) = self.game.hive_with_honey(state, level) { + let _ = self.game.level_set(at, state); + } + } + fn load(&mut self, tag: &Tag) -> Option { + let kind = horizon_client::entity_nbt::kind(tag)?; + if !self + .game + .res + .mob_data + .entity_has("minecraft:beehive_inhabitors", &kind) + { + return None; + } + let id = self.game.load_mob(tag.clone(), None)?; + let i = self.game.mobs.iter().position(|m| m.id == id)?; + Some(self.game.mobs.remove(i)) + } + fn add(&mut self, m: Mob) -> bool { + self.game.mobs.push(m); + true + } + fn sound(&mut self, name: &'static str, at: [f64; 3]) { + self.game + .audio + .play(&format!("minecraft:{name}"), Some(at), 1.0, 1.0); + } +} + +impl Game<'_> { + fn hive_with_honey(&self, state: BlockStateId, level: i32) -> Option { + let registry = self.res.assets.registry; + let mut s = registry.state(state)?.clone(); + s.properties + .insert("honey_level".to_owned(), level.to_string()); + registry.resolve(&s).ok() + } + /// The hive's honey level and front, from its block state. + pub(super) fn hive_state(&self, at: [i32; 3]) -> Option<(Option, [i32; 2])> { + let state = self.world.block(at[0], at[1], at[2]); + let name = &self.res.facts.get(state).name; + if !self + .res + .items + .block_tags + .get("minecraft:beehives") + .is_some_and(|t| t.contains(&**name)) + { + return None; + } + let props = &self.res.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)) + } + /// `BeehiveBlockEntity.serverTick` for every hive, after an emergency + /// exit for those with fire beside them (`BeehiveBlock.updateShape`). + pub(super) fn tick_beehives(&mut self) { + let mut keys: Vec<(i32, i32, i32)> = self + .world + .block_entities + .iter() + .filter(|(_, e)| matches!(e, BlockEntity::Beehive(_))) + .map(|(k, _)| *k) + .collect(); + keys.sort_unstable(); + for key in keys { + let at = [key.0, key.1, key.2]; + let Some((honey, facing)) = self.hive_state(at) else { + continue; + }; + let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key) + else { + continue; + }; + let fire = [ + [1, 0, 0], + [-1, 0, 0], + [0, 1, 0], + [0, -1, 0], + [0, 0, 1], + [0, 0, -1], + ] + .iter() + .any(|d| { + let state = self.world.block(at[0] + d[0], at[1] + d[1], at[2] + d[2]); + &*self.res.facts.get(state).name == "minecraft:fire" + }); + let mut host = GameHive { game: self }; + if fire && !hive.bees.is_empty() { + hive.release_all(at, facing, honey, Release::Emergency, &mut host); + } + hive.server_tick(at, facing, honey, &mut host); + self.world + .block_entities + .insert(key, BlockEntity::Beehive(hive)); + } + } + /// `BeehiveBlockEntity.addOccupant` for a bee its `BeeEnterHiveGoal` + /// sent in: off its lead, its tag stored, the bee gone. + pub(super) fn bee_enter_hive(&mut self, mob: u32, at: [i32; 3]) { + let key = (at[0], at[1], at[2]); + let Some(i) = self + .mobs + .iter() + .position(|m| m.id == mob && m.alive() && !m.removed) + else { + return; + }; + if !matches!(self.world.block_entities.get(&key), Some(BlockEntity::Beehive(h)) if !h.full()) + { + return; + } + if self.mobs[i].extra.leash.is_some() { + self.break_leash(mob, true, false); + self.mobs[i].extra.leash = None; + } + self.mobs[i].extra.mount = None; + let tag = self.mob_tree_nbt(i); + let flower = bee::get(&self.mobs[i]).and_then(|b| b.flower); + let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key) else { + return; + }; + let stored = hive.add_occupant(at, tag, flower, &mut GameHive { game: self }); + self.world + .block_entities + .insert(key, BlockEntity::Beehive(hive)); + if stored && let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { + m.removed = true; + } + } + /// `BeehiveBlockEntity.emptyAllLivingFromHive` with no player about. + pub(super) fn empty_hive(&mut self, at: [i32; 3], facing: [i32; 2], status: Release) { + let key = (at[0], at[1], at[2]); + let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key) else { + return; + }; + hive.release_all(at, facing, None, status, &mut GameHive { game: self }); + self.world + .block_entities + .insert(key, BlockEntity::Beehive(hive)); + } + /// `BeehiveBlock.playerDestroy` without silk touch: the bees come out + /// angry at the player unless smoke calms them, then + /// `angerNearbyBees`. + pub(super) fn hive_broken_by_player( + &mut self, + at: [i32; 3], + mut hive: Beehive, + honey: Option, + facing: [i32; 2], + ) { + let released = hive.release_all( + at, + facing, + honey, + Release::Emergency, + &mut GameHive { game: self }, + ); + let sedated = beehive::smokey(&self.mob_world_base(&[]), at); + if let Some(p) = self.player_view().map(|p| p.position) { + for m in self.mobs.iter_mut().filter(|m| released.contains(&m.id)) { + if m.distance_sqr(p) <= 16.0 { + if sedated { + bee::set_stay_out_of_hive_countdown(m); + } else { + m.ai.target = Some(Who::Player); + } + } + } + } + self.anger_nearby_bees(at); + } + /// `BeehiveBlock.angerNearbyBees`: bees within 8 blocks (6 up and down) + /// without a target go for a player in the same box. + fn anger_nearby_bees(&mut self, at: [i32; 3]) { + let min = Vec3::new( + f64::from(at[0]) - 8.0, + f64::from(at[1]) - 6.0, + f64::from(at[2]) - 8.0, + ); + let area = Aabb::new(min, Vec3::new(min.x + 17.0, min.y + 13.0, min.z + 17.0)); + if !self + .player_view() + .is_some_and(|p| p.bounds.intersects(area)) + { + return; + } + let mut bees: Vec = (0..self.mobs.len()) + .filter(|&i| { + let m = &self.mobs[i]; + m.species() == horizon_client::mobs::Species::Bee + && !m.removed + && m.bounds().intersects(area) + }) + .collect(); + bees.retain(|&i| self.mobs[i].ai.target.is_none()); + for i in bees { + // Util.getRandom over the one player. + let _ = self.world.random.next_int_bound(1); + self.mobs[i].ai.target = Some(Who::Player); + } + } +} diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index b31127e1e..5f2897c67 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -151,25 +151,22 @@ impl BoatModels { self.models.contains_key(wood) } } - pub fn load(root: &std::path::Path) -> Self { + pub fn load(document: Option<&horizon_client::mobs::EntityModelDocument>) -> Self { let mut models = HashMap::new(); let mut chest_models = HashMap::new(); - if let Ok(bytes) = std::fs::read(root.join("entity-models.json")) - && let Ok(serde_json::Value::Object(all)) = - serde_json::from_slice::(&bytes) - { - for key in all.keys() { + if let Some(document) = document { + for key in document.keys() { if let Some(wood) = key .strip_prefix("minecraft:boat/") .and_then(|k| k.strip_suffix("#main")) - && let Some(part) = horizon_client::mobs::load_model(root, key) + && let Some(part) = document.model(key) { models.insert(wood.to_owned(), part); } if let Some(wood) = key .strip_prefix("minecraft:chest_boat/") .and_then(|k| k.strip_suffix("#main")) - && let Some(part) = horizon_client::mobs::load_model(root, key) + && let Some(part) = document.model(key) { chest_models.insert(wood.to_owned(), part); } diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index dc5c7cdf1..7bf687899 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -139,6 +139,11 @@ impl Game<'_> { PhysicalKey::Code(k) => Some(k), _ => None, }; + self.book_input(key, event.text.as_deref()); + } + /// A key and the text it typed in the open book (the keyboard, or a + /// controller's on-screen keyboard). + pub(super) fn book_input(&mut self, key: Option, text: Option<&str>) { match self.book.as_mut() { Some(BookScreen::View { .. }) => match key { Some(KeyCode::Escape) => self.close_book(), @@ -167,7 +172,7 @@ impl Game<'_> { } } _ => { - if let Some(typed) = event.text.as_ref() { + if let Some(typed) = text { self.text_selection.take(BOOK_TITLE, title); for c in typed.chars().filter(|c| !c.is_control()) { if title.chars().count() < 15 { @@ -193,7 +198,7 @@ impl Game<'_> { self.type_into_page("\n") } _ => { - if let Some(typed) = event.text.as_ref().map(|t| t.to_string()) { + if let Some(typed) = text { let typed: String = typed.chars().filter(|c| !c.is_control()).collect(); if !typed.is_empty() { self.take_page_selection(); diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 61c0cce0a..af981b798 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -32,7 +32,7 @@ const HELP: &[&str] = &[ "options [PAGE] open the options (video sound controls keybinds mouse chat accessibility language font packs graphics graphics-advanced)", "stats [reset] frame-time summary since the last reset", "bench SECONDS reset stats, wait, then reply with the summary", - "fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH] fly the camera along a line at constant speed, then reply with the frame summary", + "fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH [raw]] fly the camera along a line at constant speed, then reply with the frame summary (raw: every frame time too)", "open WORLD [SEED] [creative] open or create a world from the title screen", "save save the world", "save-all save the world, rewriting every resident chunk", @@ -51,6 +51,8 @@ pub struct Flight { pitch: f32, started: Instant, seconds: f64, + /// Reply with every frame time too (`fly ... PITCH raw`). + raw: bool, reply: Sender, } @@ -76,7 +78,13 @@ impl Game<'_> { if t >= 1.0 && let Some(flight) = self.flight.take() { - let _ = flight.reply.send(self.frame_stats.summary().to_string()); + let mut summary = self.frame_stats.summary(); + if flight.raw { + summary["frame_ms"] = self.frame_stats.frame_millis().into(); + summary["cpu_ms"] = self.frame_stats.cpu_millis().into(); + summary["gpu_ms"] = self.frame_stats.gpu_millis().into(); + } + let _ = flight.reply.send(summary.to_string()); } } pub(super) fn poll_control(&mut self, event_loop: &ActiveEventLoop) { @@ -120,6 +128,9 @@ impl Game<'_> { if let Some(value) = self.lan_control(&words)? { return Ok(Some(value)); } + if let Some(value) = self.friends_control(&words)? { + return Ok(Some(value)); + } match self.agent_command(&words, line, reply, event_loop)? { super::agent::Handled::Reply(value) => return Ok(Some(value)), super::agent::Handled::Deferred => return Ok(None), @@ -131,6 +142,7 @@ impl Game<'_> { .chain(super::station_control::HELP) .chain(super::blockctl::HELP) .chain(super::lan::HELP) + .chain(super::friends::HELP) .chain(super::render_control::HELP) .chain(super::sculk::HELP) .chain(super::agent::HELP) @@ -464,6 +476,7 @@ impl Game<'_> { pitch, started: Instant::now(), seconds: n(7)?.max(0.1), + raw: words.get(9) == Some(&"raw"), reply: reply.clone(), }); Ok(None) @@ -475,7 +488,7 @@ impl Game<'_> { let folder = arg(1)?; let seed = words.get(2).map(|s| s.parse::()).transpose()?; let creative = words.get(3) == Some(&"creative"); - self.open_world(folder, Some(folder), seed, creative)?; + self.open_world(folder, Some(folder), seed, creative, None)?; ok() } "connect" => { @@ -562,6 +575,7 @@ impl Game<'_> { } match self.screen { Screen::Playing => "playing", + Screen::GameModeSwitcher => "gamemode-switcher", Screen::Paused => "paused", Screen::Options => "options", Screen::Inventory => "inventory", @@ -594,6 +608,15 @@ impl Game<'_> { let memory = r.device.generate_allocator_report(); json!({ "gpu": r.info.name, + "vendor": vendor_name(r.info.vendor), + "driver": format!("{} {}", r.info.driver, r.info.driver_info).trim(), + "device_type": match r.info.device_type { + wgpu::DeviceType::IntegratedGpu => "integrated", + wgpu::DeviceType::DiscreteGpu => "discrete", + wgpu::DeviceType::VirtualGpu => "virtual", + wgpu::DeviceType::Cpu => "cpu", + wgpu::DeviceType::Other => "other", + }, "backend": format!("{:?}", r.info.backend), "size": [r.config.width, r.config.height], "present_mode": format!("{:?}", r.config.present_mode), @@ -647,13 +670,36 @@ impl Game<'_> { "pending_chunks": self.streaming.pending() + self.pending_uploads.len(), "generated_chunks": self.streaming.generated_total, "meshed_sections": self.streaming.meshed_total, + "streaming": self.streaming.stages().into_iter().map(|(k, v)| (k.to_string(), v.into())).collect::>(), + "dirty_light": self.world.dirty_light.len(), "renderer": renderer, + "display": self.window.as_ref().and_then(|w| w.current_monitor()).map(|m| json!({ + "width": m.size().width, + "height": m.size().height, + "scale": m.scale_factor(), + "refresh_hz": m.refresh_rate_millihertz().map(|r| r.div_ceil(1000)), + })), "uptime_seconds": self.started.elapsed().as_secs_f64(), "server": self.remote_status(), }) } } +/// PCI vendor IDs of the GPU makers players have (Apple's is wgpu's Metal value). +fn vendor_name(id: u32) -> String { + match id { + 0x10de => "nvidia".into(), + 0x1002 | 0x1022 => "amd".into(), + 0x8086 => "intel".into(), + 0x106b => "apple".into(), + 0x5143 => "qualcomm".into(), + 0x13b5 => "arm".into(), + 0x10005 => "mesa".into(), + 0 => String::new(), + other => format!("{other:#06x}"), + } +} + fn key_code(name: &str) -> Option { let name = name.to_ascii_lowercase(); let letters = [ @@ -713,6 +759,7 @@ fn key_code(name: &str) -> Option { "f1" => KeyCode::F1, "f2" => KeyCode::F2, "f3" => KeyCode::F3, + "f4" => KeyCode::F4, "f5" => KeyCode::F5, "f11" => KeyCode::F11, "slash" | "/" => KeyCode::Slash, diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 6ba1d81e2..f9f102e93 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -884,6 +884,7 @@ impl Game<'_> { self.golem_chest_slot(chest, slot, stack) } MobEvent::BecomeStatue { mob } => self.golem_become_statue(mob), + MobEvent::EnterHive { mob, hive } => self.bee_enter_hive(mob, hive), MobEvent::Gift { target, item } => { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == target) && m.saddle_item().is_none() @@ -2441,7 +2442,9 @@ impl Game<'_> { consume = true; eat = sound; } - None => handled = false, + // Animal.mobInteract still consumes the client click when + // an adult cannot breed, without swinging or taking food. + None => return Ok(true), } } _ => handled = false, diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index 20d71ae85..05380d980 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -49,6 +49,7 @@ impl DebugHost for Host<'_, '_> { impl Game<'_> { fn open_screen(&self) -> OpenScreen { match self.screen { + Screen::GameModeSwitcher => OpenScreen::GameModeSwitcher, Screen::Playing if self.book.is_none() && self.sign_edit.is_none() => OpenScreen::None, Screen::Paused if !self.pause_menu => OpenScreen::PauseWithoutMenu, _ => OpenScreen::Other, @@ -62,6 +63,19 @@ impl Game<'_> { return false; }; let pressed = action != KeyAction::Release; + let switcher_open = self.screen == Screen::GameModeSwitcher; + if switcher_open && pressed { + if name == self.settings.keys.get("key.debug.switchGameMode") { + if let Some(switcher) = &mut self.gamemode_switcher { + switcher.cycle(); + } + } else if key == KeyCode::Escape { + self.close_gamemode_switcher(false); + } else if matches!(key, KeyCode::F2 | KeyCode::F11) { + return false; + } + return true; + } // Screens with a text box take every key press first // (EditBox.keyPressed); releases still reach KeyboardHandler. let typing = matches!( @@ -116,6 +130,13 @@ impl Game<'_> { now, ); self.debug_keys = keys; + if switcher_open { + if name == binds.get("key.debug.modifier") { + self.close_gamemode_switcher(true); + return true; + } + return false; + } if !pressed { return false; } @@ -130,7 +151,7 @@ impl Game<'_> { } } /// `Util.getMillis` (positive: KeyboardHandler treats 0 as unset). - fn debug_millis(&self) -> i64 { + pub(super) fn debug_millis(&self) -> i64 { self.started.elapsed().as_millis() as i64 + 1_000_000 } /// `KeyboardHandler.tick`: the debug crash countdown. @@ -159,6 +180,79 @@ impl Game<'_> { } Ok(()) } + /// The network charts' samples each tick: `PingDebugMonitor.tick` while + /// they show, `BandwidthDebugMonitor.tick` always. + pub(super) fn tick_debug_charts(&mut self) { + let shown = self.debug && self.debug_charts.network; + let Some(r) = &self.remote else { + // The integrated server answers within the tick. + if shown { + self.debug_charts.ping.log(0); + } + return; + }; + let received = r + .session + .counters + .lock() + .unwrap() + .as_ref() + .map(|c| c.bytes_in.load(std::sync::atomic::Ordering::Relaxed)); + if let Some(total) = received { + self.debug_charts.log_bandwidth(total); + } + if shown { + use horizon_protocol::packets::{play::Serverbound, status::Ping}; + let time = self.debug_millis(); + self.send(Serverbound::PingRequest(Ping { time })); + } + } + /// The overlay's chart lines (`DebugScreenOverlay`'s "Debug charts"). + pub(super) fn debug_chart_lines(&self) -> [String; 3] { + let keys = &self.settings.keys; + let modifier = keys.get("key.debug.modifier"); + let key = |mapping: &str| { + let prefix = if modifier == "key.keyboard.unknown" { + String::new() + } else { + format!("{}+", keybinds::display_name(modifier).plain()) + }; + format!( + "[{prefix}{}]", + keybinds::display_name(keys.get(mapping)).plain() + ) + }; + let chart = |mapping: &str, name: &str, on: bool| { + format!( + "{} {name} {}", + key(mapping), + if on { "visible" } else { "hidden" } + ) + }; + let remote = self.remote.is_some(); + let c = &self.debug_charts; + [ + format!( + "Debug charts: {}; {};", + chart("key.debug.profilingChart", "Profiler", false), + chart( + "key.debug.fpsCharts", + if remote { "fps" } else { "fps + tps" }, + c.fps + ), + ), + format!( + "{}; {}", + chart( + "key.debug.networkCharts", + if remote { "Bandwidth + Ping" } else { "Ping" }, + c.network + ), + chart("key.debug.lightmapTexture", "Lightmap", c.lightmap), + ), + format!("To edit: press {}", key("key.debug.debugOptions")), + ] + } /// `KeyMapping.getTranslatedKeyMessage`. fn key_text(&self, mapping: &str) -> Text { keybinds::display_name(self.settings.keys.get(mapping)) @@ -190,7 +284,7 @@ impl Game<'_> { self.settings.reduced_debug_info || self.ui.rules.bool("reduced_debug_info") } /// `Permissions.COMMANDS_GAMEMASTER` (`GameModeCommand.PERMISSION_CHECK`). - fn gamemaster(&self) -> bool { + pub(super) fn gamemaster(&self) -> bool { self.ui.registries.permission >= 2 } fn toggle_option(&mut self, key: &str) -> bool { @@ -206,13 +300,7 @@ impl Game<'_> { let player = self.player.is_some() && !self.reduced_debug_info(); match action { DebugAction::ReloadChunks => { - // LevelExtractor.allChanged: every section is rebuilt. - let keys: Vec<(i32, i32)> = self.world.chunks.keys().copied().collect(); - for (x, z) in keys { - for sy in 0..horizon_client::chunk::HEIGHT / 16 { - self.world.dirty_sections.insert((x, sy, z)); - } - } + self.all_sections_changed(); self.debug_translated("debug.reload_chunks.message"); true } @@ -268,10 +356,10 @@ impl Game<'_> { true } DebugAction::SwitchGameMode if self.open_screen() == OpenScreen::None => { - // Minecraft.canSwitchGameMode and the permission; the - // GameModeSwitcherScreen itself is not drawn yet. if self.player.is_none() || !self.gamemaster() { self.debug_translated("debug.gamemodes.error"); + } else { + self.open_gamemode_switcher(); } true } @@ -324,16 +412,25 @@ impl Game<'_> { }); true } + DebugAction::FpsCharts => { + self.debug_charts.toggle_fps(&mut self.debug); + true + } + DebugAction::NetworkCharts => { + self.debug_charts.toggle_network(&mut self.debug); + true + } + DebugAction::LightmapTexture => { + self.debug_charts.toggle_lightmap(&mut self.debug); + true + } // Screens and overlays Horizon does not draw yet (the debug - // options screen, the profiler and its charts, the lightmap, the - // texture dump): the keys are used up as in vanilla. + // options screen, the profiler and its chart, the texture dump): + // the keys are used up as in vanilla. DebugAction::DebugOptions | DebugAction::DumpDynamicTextures | DebugAction::Profiling - | DebugAction::ProfilingChart - | DebugAction::FpsCharts - | DebugAction::NetworkCharts - | DebugAction::LightmapTexture => true, + | DebugAction::ProfilingChart => true, DebugAction::ShowHitboxes | DebugAction::ShowChunkBorders | DebugAction::SwitchGameMode @@ -343,8 +440,15 @@ impl Game<'_> { /// `ServerboundChangeGameModePacket` handled by the integrated server: /// `GameModeCommand.setGameMode` with its feedback. pub(super) fn change_game_mode(&mut self, mode: GameMode) { - // On a server the packet decides; Horizon's client does not send it yet. if self.remote.is_some() { + use horizon_protocol::packets::play::{ChangeGameMode, Serverbound}; + let mode = match mode { + GameMode::Survival => 0, + GameMode::Creative => 1, + GameMode::Adventure => 2, + GameMode::Spectator => 3, + }; + self.send(Serverbound::ChangeGameMode(ChangeGameMode { mode })); return; } if self.set_game_mode(mode) { diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index f4e410e2f..e73de6988 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -372,7 +372,13 @@ impl Game<'_> { let world_dir = std::env::current_dir()?.join(&universe).join(&level_name); let folder = world_dir.to_string_lossy().into_owned(); let new_world = !world_dir.join("level.dat").exists(); - self.open_world(&folder, Some(&level_name), Some(props.seed), game_mode == 1)?; + self.open_world( + &folder, + Some(&level_name), + Some(props.seed), + game_mode == 1, + None, + )?; if new_world { self.level.hardcore = props.hardcore; } diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index 6c50b80ae..e8ceb5be3 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -1552,10 +1552,11 @@ impl Game<'_> { && let Some(level) = honey && level >= 5 { - // releaseBeesAndResetHoneyLevel (the bees themselves are not modelled). + // releaseBeesAndResetHoneyLevel. if let Some(reset) = self.with_props(state, &[("honey_level", "0")]) { self.level_set([target.0, target.1, target.2], reset)?; } + self.dispenser_empty_hive(target, state); let bottle = ItemStack::new("minecraft:honey_bottle", 1); self.post_block_game_event("minecraft:fluid_pickup", [pos.0, pos.1, pos.2], None, None); return Ok(( @@ -1624,6 +1625,16 @@ impl Game<'_> { } Ok((Some(stack), FAIL)) } + /// The bees of a hive a dispenser harvested come out (`BEE_RELEASED`: + /// not at night nor in the rain), through the front of its old state. + fn dispenser_empty_hive(&mut self, target: Pos, old: BlockStateId) { + let facing = self.prop(old, "facing"); + self.empty_hive( + [target.0, target.1, target.2], + horizon_client::beehive::facing_step(facing.as_deref()), + horizon_client::beehive::Release::BeeReleased, + ); + } fn shear_beehive(&mut self, target: Pos) -> Result { let state = self.block_at(target); let name = self.dispenser_block_name(target); @@ -1652,6 +1663,7 @@ impl Game<'_> { if let Some(reset) = self.with_props(state, &[("honey_level", "0")]) { self.level_set(p, reset)?; } + self.dispenser_empty_hive(target, state); self.post_block_game_event("minecraft:shear", p, None, None); Ok(true) } diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index 5ac4b5c45..4bebc8d9b 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -233,7 +233,7 @@ impl Game<'_> { /// EnderEyeItem.useOn: fill an empty End portal frame, then light the /// portal when the ring of twelve filled frames is complete. - pub(super) fn use_ender_eye(&mut self, stack: &ItemStack) -> Result { + pub(super) fn use_ender_eye(&mut self, stack: &ItemStack, use_on_block: bool) -> Result { if &*stack.item != "minecraft:ender_eye" { return Ok(false); } @@ -247,6 +247,10 @@ impl Game<'_> { self.throw_ender_eye(); return Ok(true); }; + if !use_on_block { + // EnderEyeItem.use passes on a frame; only useOn can insert an eye. + return Ok(false); + } if state.properties.get("eye").map(String::as_str) == Some("true") { // Both useOn and use pass on a filled frame. return Ok(true); diff --git a/crates/horizon-client/src/game/entity_model_loading_tests.rs b/crates/horizon-client/src/game/entity_model_loading_tests.rs new file mode 100644 index 000000000..61ed81491 --- /dev/null +++ b/crates/horizon-client/src/game/entity_model_loading_tests.rs @@ -0,0 +1,272 @@ +//! Model-batch equivalence tests and an opt-in benchmark of the actual loaders. +use super::{armor_stands::ArmorStandAssets, boats::BoatModels, minecarts::CartModels}; +use horizon_client::mobs::{EntityModelDocument, Part, load_model}; +use serde_json::{Value, json}; +use std::{collections::BTreeMap, fs, hint::black_box, path::Path, time::Instant}; + +const WOODS: [&str; 11] = [ + "oak", + "spruce", + "birch", + "jungle", + "acacia", + "dark_oak", + "mangrove", + "cherry", + "bamboo", + "pale_oak", + "test_wood", +]; +const CARTS: [&str; 6] = [ + "minecart", + "chest_minecart", + "hopper_minecart", + "furnace_minecart", + "tnt_minecart", + "command_block_minecart", +]; + +fn fixture() -> Value { + let mut all = serde_json::Map::new(); + let part = json!({ + "pose": [1,2,3,0.25,-0.5,0.75,1,2,0.5], + "polygons": [[[0,0,0,0,0],[1,0,0,1,0],[1,1,0,1,1],[0,1,0,0,1]]], + "normals": [[0,0,1]], + "children": {"root": {"children": {"bone": {"pose": [4,5,6]}}}, "other": {}} + }); + for wood in WOODS { + for prefix in ["boat", "chest_boat"] { + all.insert(format!("minecraft:{prefix}/{wood}#main"), part.clone()); + } + } + for cart in CARTS { + all.insert(format!("minecraft:{cart}#main"), part.clone()); + } + for model in ["player", "armor_stand", "armor_stand_small"] { + for layer in ["helmet", "chestplate", "leggings", "boots"] { + all.insert(format!("minecraft:{model}#{layer}"), part.clone()); + } + } + for model in ["armor_stand", "armor_stand_small"] { + all.insert(format!("minecraft:{model}#main"), part.clone()); + } + // Discovery must exclude other models and non-main boat layers. + all.insert("minecraft:boat/oak#water_patch".into(), part.clone()); + all.insert("minecraft:unrelated#main".into(), part); + Value::Object(all) +} + +struct FixtureRoot(std::path::PathBuf); +impl FixtureRoot { + fn new() -> Self { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let next = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let root = std::env::temp_dir().join(format!( + "horizon-entity-models-{}-{next}", + std::process::id() + )); + fs::create_dir(&root).unwrap(); + Self(root) + } +} +impl Drop for FixtureRoot { + fn drop(&mut self) { + fs::remove_dir_all(&self.0).unwrap(); + } +} + +// Preserve the previous production algorithm: one discovery parse, then a full +// file read/parse through load_model for each of the 42 selected layers. +fn baseline(root: &Path) -> BTreeMap { + let mut models = BTreeMap::new(); + if let Ok(bytes) = fs::read(root.join("entity-models.json")) + && let Ok(Value::Object(all)) = serde_json::from_slice::(&bytes) + { + for key in all.keys() { + for (prefix, label) in [ + ("minecraft:boat/", "boat"), + ("minecraft:chest_boat/", "chest_boat"), + ] { + if let Some(wood) = key + .strip_prefix(prefix) + .and_then(|k| k.strip_suffix("#main")) + && let Some(part) = load_model(root, key) + { + models.insert(format!("{label}/{wood}"), part); + } + } + } + } + for cart in CARTS { + if let Some(part) = load_model(root, &format!("minecraft:{cart}#main")) { + models.insert(format!("cart/{cart}"), part); + } + } + for slot in ["helmet", "chestplate", "leggings", "boots"] { + for model in ["player", "armor_stand", "armor_stand_small"] { + if let Some(part) = load_model(root, &format!("minecraft:{model}#{slot}")) { + models.insert(format!("{model}/{slot}"), part); + } + } + } + // The fixture contains only entity-models.json; armor equipment is absent. + let _ = fs::read_dir(root.join("assets/minecraft/equipment")); + for model in ["armor_stand", "armor_stand_small"] { + if let Some(part) = load_model(root, &format!("minecraft:{model}#main")) { + models.insert(format!("{model}/main"), part); + } + } + models +} + +fn optimized(root: &Path) -> BTreeMap { + let document = EntityModelDocument::load(root).ok(); + let boats = BoatModels::load(document.as_ref()); + let carts = CartModels::load(document.as_ref()); + let armor = ArmorStandAssets::load(root, document.as_ref()); + let mut models = BTreeMap::new(); + for (label, group) in [("boat", boats.models), ("chest_boat", boats.chest_models)] { + for (wood, part) in group { + models.insert(format!("{label}/{wood}"), part); + } + } + for (kind, part) in carts.models { + models.insert( + format!("cart/{}", kind.id().trim_start_matches("minecraft:")), + part, + ); + } + for ((slot, small), part) in armor.layers { + let model = if small { + "armor_stand_small" + } else { + "armor_stand" + }; + models.insert(format!("{model}/{slot}"), part); + } + for (slot, part) in armor.player { + models.insert(format!("player/{slot}"), part); + } + for (model, part) in [ + ("armor_stand", armor.main), + ("armor_stand_small", armor.small), + ] { + if let Some(part) = part { + models.insert(format!("{model}/main"), part); + } + } + models +} + +fn assert_equivalent(root: &Path) { + // Debug includes every part name, pose, polygon normal/vertex and child. + assert_eq!( + format!("{:?}", baseline(root)), + format!("{:?}", optimized(root)) + ); +} + +#[test] +fn entity_model_batches_preserve_parts_missing_layers_and_load_failures() { + let root = FixtureRoot::new(); + assert_equivalent(&root.0); // missing file + let file = root.0.join("entity-models.json"); + for bytes in [b"{".as_slice(), b"null", b"[]", b"{}"] { + fs::write(&file, bytes).unwrap(); + assert_equivalent(&root.0); + } + let mut all = fixture(); + fs::write(&file, serde_json::to_vec(&all).unwrap()).unwrap(); + assert_equivalent(&root.0); + assert_eq!(optimized(&root.0).len(), 42); + all.as_object_mut() + .unwrap() + .remove("minecraft:armor_stand_small#main"); + all.as_object_mut() + .unwrap() + .remove("minecraft:boat/oak#main"); + fs::write(&file, serde_json::to_vec(&all).unwrap()).unwrap(); + assert_equivalent(&root.0); + assert_eq!(optimized(&root.0).len(), 40); + let document = EntityModelDocument::load(&root.0).unwrap(); + let mut first = document.model("minecraft:armor_stand#main").unwrap(); + first.children.clear(); + assert!( + !document + .model("minecraft:armor_stand#main") + .unwrap() + .children + .is_empty() + ); +} + +#[test] +fn armor_equipment_loads_without_an_entity_model_document() { + let root = FixtureRoot::new(); + let equipment = root.0.join("assets/minecraft/equipment"); + fs::create_dir_all(&equipment).unwrap(); + fs::write( + equipment.join("leather.json"), + serde_json::to_vec(&json!({"layers": {"humanoid": [{ + "texture": "minecraft:leather", "dyeable": {"color_when_undyed": 0x123456} + }]}})) + .unwrap(), + ) + .unwrap(); + fs::write(equipment.join("invalid.json"), b"{").unwrap(); + let assets = ArmorStandAssets::load(&root.0, None); + assert!(assets.main.is_none()); + assert!(assets.layers.is_empty()); + assert_eq!( + assets.equipment["minecraft:leather"]["humanoid"], + ("entity/equipment/humanoid/leather".into(), Some(0x123456)) + ); + assert!(!assets.equipment.contains_key("minecraft:invalid")); +} + +#[test] +#[ignore = "opt-in benchmark; requires ENTITY_MODEL_BENCH_DOCUMENT"] +fn entity_model_document_benchmark() { + let input = std::env::var("ENTITY_MODEL_BENCH_DOCUMENT").unwrap(); + let root = FixtureRoot::new(); + let bytes = fs::read(&input).unwrap(); + fs::write(root.0.join("entity-models.json"), &bytes).unwrap(); + assert_equivalent(&root.0); + let model_count = optimized(&root.0).len(); + let repetitions: usize = std::env::var("ENTITY_MODEL_BENCH_REPETITIONS") + .unwrap_or_else(|_| "15".into()) + .parse() + .unwrap(); + assert!(repetitions > 0); + for _ in 0..3 { + black_box(baseline(black_box(&root.0))); + black_box(optimized(black_box(&root.0))); + } + let mut before = Vec::new(); + let mut after = Vec::new(); + for i in 0..repetitions { + for optimized_first in [i % 2 == 0, i % 2 != 0] { + let started = Instant::now(); + if optimized_first { + black_box(optimized(black_box(&root.0))); + after.push(started.elapsed().as_secs_f64() * 1000.0); + } else { + black_box(baseline(black_box(&root.0))); + before.push(started.elapsed().as_secs_f64() * 1000.0); + } + } + } + before.sort_by(f64::total_cmp); + after.sort_by(f64::total_cmp); + let old = before[repetitions / 2]; + let new = after[repetitions / 2]; + println!( + "{}", + json!({ + "document_bytes": bytes.len(), "selected_models": model_count, + "warmup_pairs": 3, "repetitions": repetitions, + "baseline_ms": before, "optimized_ms": after, + "baseline_median_ms": old, "optimized_median_ms": new, "speedup": old / new + }) + ); +} diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index b934f8279..9fd42d5ff 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -123,7 +123,7 @@ impl Game<'_> { { log::info!( "Horizon: reconnecting to {} in {} s", - retry.address, + horizon_client::net::shown_address(&retry.address), retry.seconds_left(std::time::Instant::now()) ); *slot = Some(retry); diff --git a/crates/horizon-client/src/game/fireworks.rs b/crates/horizon-client/src/game/fireworks.rs index 79ddd562a..cd4e01a16 100644 --- a/crates/horizon-client/src/game/fireworks.rs +++ b/crates/horizon-client/src/game/fireworks.rs @@ -2,8 +2,10 @@ //! from a block face, boosting a gliding player, the 1.15 horizontal //! acceleration and 0.04 lift, the flight-duration lifetime, explosion //! damage with line of sight, and the client explosion (`createFireworks`). -use super::{Game, Hit, view_vector}; +use super::{Game, Hit, item_draw::owner_at, view_vector}; +use horizon_assets::item_model::DisplayContext; use horizon_client::{ + block_entity_render::vertex_light, collisions::SceneCollisions, items::ItemStack, mesher::Vertex, @@ -27,7 +29,8 @@ pub(super) struct Rocket { /// `DATA_SHOT_AT_ANGLE` (dispensers): constant velocity, exploding on /// the first block it hits. angled: bool, - icon: Option, + /// `DATA_ID_FIREWORKS_ITEM`: the stack it was launched from. + item: ItemStack, } impl Rocket { /// Position and motion (the dispenser parity fixture). @@ -61,7 +64,7 @@ impl Game<'_> { explosions, attached, angled: false, - icon: Some("item/firework_rocket".into()), + item: stack.clone(), } } /// `FireworkRocketItem.useOn`: launch from the clicked point. @@ -244,44 +247,35 @@ impl Game<'_> { self.particles .fireworks(at, v, r.explosions.clone(), camera); } + /// `FireworkEntityRenderer.submit`: the item (GROUND) facing the camera, + /// lit at the rocket's light probe. pub(super) fn rocket_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { - let forward = glam::DVec3::from_array(view_vector(self.yaw, self.pitch)); - let right = forward.cross(glam::DVec3::Y).normalize_or_zero(); - let up = right.cross(forward).normalize_or_zero(); + let orientation = glam::Mat4::from_quat(self.camera_orientation()); for r in self.rockets.iter().filter(|r| !r.attached) { - let Some(s) = r - .icon - .as_ref() - .and_then(|n| self.res.atlas.sprites.get(n)) - .copied() - else { - continue; - }; let p = glam::DVec3::new( r.previous.x + (r.position.x - r.previous.x) * alpha, r.previous.y + (r.position.y - r.previous.y) * alpha, r.previous.z + (r.position.z - r.previous.z) * alpha, - ) - camera; - let h = 0.25; - let c = [ - p - right * h - up * h, - p + right * h - up * h, - p + right * h + up * h, - p - right * h + up * h, - ]; - for (v, uv) in c - .iter() - .zip([[s.u0, s.v1], [s.u1, s.v1], [s.u1, s.v0], [s.u0, s.v0]]) - { - out.push(Vertex { - normal: [0; 4], - pos: v.as_vec3().to_array(), - uv, - layer: 0, - color: 0xFFFF_FFFF, - light: 240 | 240 << 8, - }); + ); + // `updateForNonLiving`: GROUND, owned by the rocket. + let owner = owner_at(p.to_array(), 0.0, "minecraft:firework_rocket"); + let state = self.resolve_item(&r.item, DisplayContext::Ground, Some(&owner), 0); + if state.is_empty() { + continue; } + let mut pose = glam::Mat4::from_translation((p - camera).as_vec3()) * orientation; + if r.angled { + pose *= glam::Mat4::from_rotation_z(std::f32::consts::PI) + * glam::Mat4::from_rotation_y(std::f32::consts::PI) + * glam::Mat4::from_rotation_x(std::f32::consts::FRAC_PI_2); + } + // getLightProbePosition: the eye, 0.85 of its 0.25 height. + let light = self.world.light( + p.x.floor() as i32, + (p.y + 0.2125).floor() as i32, + p.z.floor() as i32, + ); + self.submit_item_world(&state, pose, vertex_light(light), out); } } } diff --git a/crates/horizon-client/src/game/friends.rs b/crates/horizon-client/src/game/friends.rs new file mode 100644 index 000000000..51dfe3fbf --- /dev/null +++ b/crates/horizon-client/src/game/friends.rs @@ -0,0 +1,254 @@ +//! Play with friends, host side: "Invite friends" opens the world to LAN if +//! it isn't (with Open to LAN's defaults) and shares that port behind an +//! invite code (horizon-friends). The code holds this computer's addresses +//! and the key, so friends join with no server of ours; a relay the player +//! configured adds a short code and a fallback. The integrated server is the +//! LAN one, unchanged: tunnelled guests are LAN guests that connect from the +//! loopback address. +use super::{Game, lan::LanSettings}; +use horizon_client::{Result, front::FriendsView, text::Text}; +use horizon_friends::{Host, HostConfig, HostEvent, PathMode, host::DEFAULT_PORT, reach, stun}; +use horizon_protocol::{GAME_VERSION, PROTOCOL_VERSION}; +use std::time::{Duration, Instant}; + +pub(super) struct Sharing { + host: Host, + /// Sharing opened the world to LAN, so stopping closes it again. + opened_lan: bool, + code: Option, + /// Wrong codes tried so far. + wrong: u32, + notice: Option, + copied: Option, + /// Sessions carried directly and through the relay so far. + paths: (u32, u32), +} + +pub const HELP: &[&str] = &[ + "friends host share the open world behind an invite code", + "friends stop stop sharing", + "friends status the code, how friends reach this host, the guests", +]; + +/// `HORIZON_STUN_SERVERS`, else `friendsStun` in horizon.txt, else the defaults. +fn stun_servers() -> Vec { + if std::env::var_os("HORIZON_STUN_SERVERS").is_some() { + return stun::servers_from_env(); + } + let dir = std::env::current_dir().unwrap_or_default(); + match horizon_client::ui_theme::preference(&dir, "friendsStun") { + Some(list) => stun::parse_servers(&list), + None => stun::servers_from_env(), + } +} + +fn env_flag(name: &str, default: bool) -> bool { + std::env::var(name).map_or(default, |v| v != "0") +} + +impl Game<'_> { + /// Start sharing the open world. + pub(super) fn friends_start(&mut self) -> Result<()> { + if self.friends.is_some() { + return Ok(()); + } + if self.remote.is_some() || self.title.is_some() { + return Err("open a singleplayer world first".into()); + } + let opened_lan = self.lan.is_none(); + if opened_lan { + // ShareToLanScreen's defaults, as the world options screen offers them. + self.lan_open(LanSettings { + port: horizon_client::lan::available_port(), + guest_commands: false, + force_game_mode: true, + })?; + } + let port = self.lan_port().ok_or("the world isn't open to LAN")?; + let host = match Host::start(HostConfig { + lan: std::net::SocketAddr::from(([127, 0, 0, 1], port)), + protocol: PROTOCOL_VERSION, + game: GAME_VERSION.to_owned(), + relay: horizon_client::net::friends_relay_setting(), + path: PathMode::from_env(), + port: std::env::var("HORIZON_FRIENDS_PORT") + .ok() + .and_then(|p| p.parse().ok()) + .unwrap_or(DEFAULT_PORT), + reach: reach::Options { + // HORIZON_FRIENDS_UPNP=0 leaves the router alone. + map_port: env_flag("HORIZON_FRIENDS_UPNP", true), + stun: stun_servers(), + // Both ends on one machine (tests). + loopback: env_flag("HORIZON_FRIENDS_LOOPBACK", false), + }, + }) { + Ok(h) => h, + Err(e) => { + if opened_lan { + self.lan_close(true); + } + return Err(e.into()); + } + }; + self.friends = Some(Sharing { + host, + opened_lan, + code: None, + wrong: 0, + notice: None, + copied: None, + paths: (0, 0), + }); + Ok(()) + } + + /// Stop sharing: the code ends (direct port closed, router mapping + /// deleted); the world closes to LAN again if sharing opened it. + pub(super) fn friends_stop(&mut self) { + let Some(mut sharing) = self.friends.take() else { + return; + }; + sharing.host.stop(); + if sharing.opened_lan { + self.lan_close(true); + } else { + self.system_message(Text::literal("Stopped sharing the invite code.")); + } + } + + /// The LAN server is closing: the code goes with it. + pub(super) fn friends_lan_closed(&mut self) { + if let Some(mut sharing) = self.friends.take() { + sharing.host.stop(); + } + } + + /// New codes and sessions, once a tick and while the pause menu is drawn. + pub(super) fn tick_friends(&mut self) { + let Some(sharing) = self.friends.as_mut() else { + return; + }; + let mut announce = false; + for event in sharing.host.poll() { + match event { + HostEvent::Code(code) => { + if sharing.code.is_some() && sharing.wrong >= horizon_friends::host::MAX_WRONG { + sharing.notice = Some( + "Someone kept trying a wrong short code, so it changed.".to_owned(), + ); + sharing.wrong = 0; + } + announce = sharing.code.is_none(); + sharing.code = Some(code); + } + HostEvent::WrongCode { count } => { + sharing.wrong = count; + sharing.notice = Some("Someone tried a wrong code.".to_owned()); + } + HostEvent::Connected { direct: true, .. } => sharing.paths.0 += 1, + HostEvent::Connected { direct: false, .. } => sharing.paths.1 += 1, + HostEvent::Disconnected { .. } => {} + } + } + if announce { + self.system_message(Text::literal( + "Your invite code is ready in the pause menu: copy it and send it to your friends.", + )); + } + } + + pub(super) fn friends_copy(&mut self) { + let Some(code) = self.friends.as_ref().and_then(|s| s.code.clone()) else { + return; + }; + use horizon_client::clipboard::Clipboard; + self.clipboard.set(&code); + if let Some(s) = self.friends.as_mut() { + s.copied = Some(Instant::now()); + } + } + + /// What the pause menu shows. + pub(super) fn friends_view(&self) -> FriendsView { + let guests = self + .lan + .as_ref() + .map(|h| h.hub.guests.iter().map(|g| g.name.clone()).collect()) + .unwrap_or_default(); + let Some(s) = &self.friends else { + return FriendsView { + shown: self.remote.is_none(), + ..FriendsView::default() + }; + }; + let state = s.host.state(); + let mut status = if s.code.is_none() { + "Finding how friends can reach you…".to_owned() + } else { + state.summary.clone() + }; + if let Some(short) = &state.short { + status.push_str(&format!(" Short code for the relay: {short}.")); + } + if let Some(problem) = &state.relay_problem { + status.push(' '); + status.push_str(problem); + } + let reachable = matches!( + state.verdict, + Some(reach::Verdict::Mapped(_) | reach::Verdict::Public) + ) || state.short.is_some(); + FriendsView { + shown: true, + sharing: true, + code: s.code.clone(), + status, + reachable, + help: (!reachable && s.code.is_some()).then(|| reach::HELP_URL.to_owned()), + guests, + notice: s.notice.clone(), + copied: s + .copied + .is_some_and(|t| t.elapsed() < Duration::from_secs(2)), + } + } + + /// `horizon-ctl friends ...`. + pub(super) fn friends_control(&mut self, words: &[&str]) -> Result> { + use serde_json::json; + if words[0] != "friends" { + return Ok(None); + } + match words.get(1).copied() { + Some("host") => { + self.friends_start()?; + Ok(Some(json!({ "ok": true, "lan_port": self.lan_port() }))) + } + Some("stop") => { + self.friends_stop(); + Ok(Some(json!({ "ok": true }))) + } + Some("status") => { + self.tick_friends(); + let view = self.friends_view(); + let state = self.friends.as_ref().map(|s| s.host.state()); + Ok(Some(json!({ + "sharing": view.sharing, + "code": view.code, + "short": state.as_ref().and_then(|s| s.short.as_ref().map(ToString::to_string)), + "summary": view.status, + "reachable": view.reachable, + "verdict": state.as_ref().and_then(|s| s.verdict.as_ref().map(|v| format!("{v:?}"))), + "direct_port": state.as_ref().map(|s| s.port), + "sessions": self.friends.as_ref().map_or(0, |s| s.host.sessions()), + "direct": self.friends.as_ref().map_or(0, |s| s.paths.0), + "relayed": self.friends.as_ref().map_or(0, |s| s.paths.1), + "guests": view.guests, + "lan_port": self.lan_port(), + }))) + } + _ => Err("friends host|stop|status".into()), + } + } +} diff --git a/crates/horizon-client/src/game/gamemode_switcher.rs b/crates/horizon-client/src/game/gamemode_switcher.rs new file mode 100644 index 000000000..e7826ba22 --- /dev/null +++ b/crates/horizon-client/src/game/gamemode_switcher.rs @@ -0,0 +1,86 @@ +//! The non-pausing F3+F4 screen (`GameModeSwitcherScreen`). +use super::{Game, ItemStack, Screen}; +use horizon_client::{ + game_mode_switcher::{GameModeSwitcher, ICONS, MODES, slot_origin}, + hud::HudBatch, + keybinds, + text::Text, +}; + +impl Game<'_> { + pub(super) fn open_gamemode_switcher(&mut self) { + self.gamemode_switcher = Some(GameModeSwitcher::new(self.mode, self.previous_mode)); + self.screen = Screen::GameModeSwitcher; + self.keys.clear(); + self.left = false; + self.right = false; + self.mining = None; + self.capture(false); + } + + pub(super) fn close_gamemode_switcher(&mut self, apply: bool) { + let selected = self.gamemode_switcher.take().map(|s| s.selected); + self.screen = Screen::Playing; + self.capture(true); + if apply + && self.player.is_some() + && self.gamemaster() + && let Some(mode) = selected + && mode != self.mode + { + self.change_game_mode(mode); + } + } + + pub(super) fn draw_gamemode_switcher(&mut self, batch: &mut HudBatch) { + let (w, h) = (batch.width as i32, batch.height as i32); + let Some(switcher) = &mut self.gamemode_switcher else { + return; + }; + switcher.hover(w, h, (self.cursor.0 as i32, self.cursor.1 as i32)); + let selected = switcher.selected; + let atlas = &self.res.atlas; + batch.sprite_region( + atlas, + "gui/container/gamemode_switcher", + [(w / 2 - 62) as f32, (h / 2 - 58) as f32, 125.0, 75.0], + 128.0, + 128.0, + ); + let title = Text::translate(&format!("gameMode.{}", selected.name()), &[]); + let help = Text::translate( + "debug.gamemodes.select_next", + &[ + keybinds::display_name(self.settings.keys.get("key.debug.switchGameMode")) + .with_color(0x55FFFF), + ], + ); + for (text, y) in [(title, h / 2 - 51), (help, h / 2 + 5)] { + let x = w / 2 - (HudBatch::text_width(atlas, &text.plain()) / 2.0) as i32; + batch.text_styled(atlas, &text, x as f32, y as f32, u32::MAX, true); + } + for (index, mode) in MODES.into_iter().enumerate() { + let (x, y) = slot_origin(w, h, index); + batch.sprite( + &self.res.atlas, + "gui/sprites/gamemode_switcher/slot", + x as f32, + y as f32, + ); + if mode == selected { + batch.sprite( + &self.res.atlas, + "gui/sprites/gamemode_switcher/selection", + x as f32, + y as f32, + ); + } + self.draw_item_model( + batch, + &ItemStack::new(ICONS[index], 1), + (x + 5) as f32, + (y + 5) as f32, + ); + } + } +} diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index ed29d0305..1bce62bb8 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -450,6 +450,7 @@ impl Game<'_> { /// IntegratedServer.unpublishServer: the guests are sent away. pub(super) fn lan_close(&mut self, announce: bool) { + self.friends_lan_closed(); let Some(mut host) = self.lan.take() else { return; }; diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 293afdcdd..7faba7f6c 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -412,6 +412,32 @@ impl Game<'_> { } } S::ChatCommand(c) => self.guest_command(host, conn, &c.command), + S::ChangeGameMode(p) if host.hub.guests[gi].permission >= 2 => { + if let Some(mode) = usize::try_from(p.mode) + .ok() + .and_then(|index| horizon_client::command::args::GameMode::ALL.get(index)) + { + let lines = self.as_guest(host, conn, |g| { + g.chat_capture = Some(Vec::new()); + g.change_game_mode(*mode); + g.chat_capture + .take() + .unwrap_or_default() + .iter() + .map(|t| horizon_client::lan::data::component_nbt(&t.component())) + .collect::>() + }); + for content in lines.unwrap_or_default() { + host.hub.send_to( + conn, + &C::SystemChat(play::SystemChat { + content, + overlay: false, + }), + ); + } + } + } S::Unknown(8, payload) => { // A signed command: the text comes first. if let Ok(text) = horizon_protocol::buf::Reader::new(&payload).string(32767) { diff --git a/crates/horizon-client/src/game/lan_screen.rs b/crates/horizon-client/src/game/lan_screen.rs index c36ce5d84..f0eb57b3e 100644 --- a/crates/horizon-client/src/game/lan_screen.rs +++ b/crates/horizon-client/src/game/lan_screen.rs @@ -333,13 +333,26 @@ impl Game<'_> { o.port.shortcut(shortcut, &mut self.clipboard); return; } - if !o.port.key(key, ctrl, false) - && !ctrl - && let Some(text) = &event.text - { - let digits: String = text.chars().filter(char::is_ascii_digit).collect(); - if !digits.is_empty() { - o.port.insert_text(&digits); + if !o.port.key(key, ctrl, false) && !ctrl { + self.world_options_text(event.text.as_deref()); + } + } + /// Digits typed into the port field (the keyboard, or a controller's + /// on-screen keyboard), and its backspace. + pub(super) fn world_options_text(&mut self, text: Option<&str>) { + let Some(o) = self.world_options.as_mut().filter(|o| o.port.focused) else { + return; + }; + match text { + Some(text) => { + let digits: String = text.chars().filter(char::is_ascii_digit).collect(); + if !digits.is_empty() { + o.port.insert_text(&digits); + } + } + None => { + o.port + .key(winit::keyboard::KeyCode::Backspace, false, false); } } } diff --git a/crates/horizon-client/src/game/loom.rs b/crates/horizon-client/src/game/loom.rs index f6648c43b..c0827b9a6 100644 --- a/crates/horizon-client/src/game/loom.rs +++ b/crates/horizon-client/src/game/loom.rs @@ -128,6 +128,24 @@ impl Game<'_> { } false } + /// The pattern buttons a controller can focus (GUI origin relative). + pub(super) fn loom_targets(&self) -> Vec<[f32; 4]> { + let Some(loom) = self.station.as_ref().map(|s| &s.loom).filter(|l| l.display) else { + return Vec::new(); + }; + (0..16) + .filter(|i| (i / 4 + loom.start_row) * 4 + i % 4 < loom.patterns.len()) + .map(|i| { + let (row, column) = (i / 4, i % 4); + [ + 60.0 + column as f32 * BUTTON, + 13.0 + row as f32 * BUTTON, + BUTTON, + BUTTON, + ] + }) + .collect() + } /// `LoomScreen.mouseDragged` on the scroller. pub(super) fn loom_drag(&mut self) { let Some(size) = self diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index 31affaa3f..1afc5638a 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -159,6 +159,10 @@ impl Containers<'_> { }); } let entity = self.world.block_entities.get(&pos)?; + // A beehive keeps bees, not items: it is no `Container`. + if matches!(entity, BlockEntity::Beehive(_)) { + return None; + } let kind = match (entity, name) { (BlockEntity::Furnace(_), _) => Kind::Furnace, (BlockEntity::Crafter(_), _) => Kind::Crafter, diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index b81d09325..47b1ab053 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -191,7 +191,7 @@ pub(super) struct CartModels { pub models: HashMap, } impl CartModels { - pub fn load(root: &std::path::Path) -> Self { + pub fn load(document: Option<&horizon_client::mobs::EntityModelDocument>) -> Self { let kinds = [ CartKind::Rideable, CartKind::Chest, @@ -202,9 +202,7 @@ impl CartModels { ]; let models = kinds .into_iter() - .filter_map(|k| { - horizon_client::mobs::load_model(root, &format!("{}#main", k.id())).map(|m| (k, m)) - }) + .filter_map(|k| document?.model(&format!("{}#main", k.id())).map(|m| (k, m))) .collect(); Self { models } } diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index fa631e114..cdeb68d0a 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -26,13 +26,16 @@ impl Game<'_> { } /// Open the options screens (OptionsScreen) from the title or pause menu. pub(super) fn open_options(&mut self, from_title: bool) { + self.open_options_at(from_title, Page::Main); + } + pub(super) fn open_options_at(&mut self, from_title: bool, page: Page) { // Gameplay keys must not stay held behind the options screen, where // bindings can also change before the physical key is released. self.keys.clear(); self.screen = Screen::Options; self.options_from_title = from_title; let ui = &mut self.ui.options; - ui.open(!from_title && self.title.is_none()); + ui.open_at(!from_title && self.title.is_none(), page); let root = self.options.resources.clone(); ui.languages = lang::available(&[&root]); self.refresh_pack_lists(); @@ -240,7 +243,10 @@ impl Game<'_> { has_screen: self.title.is_some() || self.screen != super::Screen::Playing, has_overlay: false, }; - framerate_limit(self.settings.max_fps as i32, context) + let limit = framerate_limit(self.settings.max_fps as i32, context); + self.settings + .horizon + .battery_limit(limit, self.title.is_none(), self.focused) } /// `Minecraft.runTick`'s frame limiter: `FramerateLimiter.limitDisplayFPS` /// below 260 frames per second, sleeping then spin-waiting until the diff --git a/crates/horizon-client/src/game/pad.rs b/crates/horizon-client/src/game/pad.rs index 2f050fdec..a9009db35 100644 --- a/crates/horizon-client/src/game/pad.rs +++ b/crates/horizon-client/src/game/pad.rs @@ -255,7 +255,7 @@ impl Game<'_> { if down && !self.pad_focused() { return Ok(()); } - let playing = self.title.is_none() && self.screen == Screen::Playing; + let playing = !self.pad_in_menu(); if down && playing && !self.captured && self.focused { // Like a click into the window: take the pointer. self.capture(true); @@ -315,6 +315,11 @@ impl Game<'_> { /// B and Start: what Escape does where the pad is. pub(super) fn pad_back(&mut self) -> Result<()> { + // The options open over the title screen too: they come first, as + // for the keyboard's Escape. + if self.screen == Screen::Options { + return self.options_key(KeyCode::Escape, None); + } if let Some(title) = self.title.as_mut() { title.escape(); return Ok(()); @@ -340,11 +345,7 @@ impl Game<'_> { /// The left stick as the move vector, while playing. pub(super) fn pad_move(&self) -> Option<[f32; 2]> { let settings = &self.settings.controller; - if !settings.enabled - || self.title.is_some() - || self.screen != Screen::Playing - || !self.pad_focused() - { + if !settings.enabled || self.pad_in_menu() || !self.pad_focused() { return None; } gamepad::move_vector(self.pad.state.left, settings.move_deadzone) @@ -353,12 +354,7 @@ impl Game<'_> { /// The right stick turns the view, once per frame (`Entity.turn`). pub(super) fn pad_look(&mut self, seconds: f32) { let settings = &self.settings.controller; - if !settings.enabled - || self.title.is_some() - || self.screen != Screen::Playing - || self.player.is_none() - || !self.pad_focused() - { + if !settings.enabled || self.pad_in_menu() || self.player.is_none() || !self.pad_focused() { return; } // A long frame (a hitch) must not spin the view. @@ -478,6 +474,7 @@ impl Game<'_> { "reason": why, "strong": p.strong, "weak": p.weak, "ms": p.millis, })), "in_use": self.pad.in_use, + "menu": self.pad_menu_status(), "held": held, "left": s.left, "right": s.right, diff --git a/crates/horizon-client/src/game/pad_menu.rs b/crates/horizon-client/src/game/pad_menu.rs index 8047e889a..46a6d66b1 100644 --- a/crates/horizon-client/src/game/pad_menu.rs +++ b/crates/horizon-client/src/game/pad_menu.rs @@ -1,17 +1,29 @@ //! A controller in menus, screens and inventories (Horizon's own; -//! docs/controllers.md): a virtual cursor the left stick moves and the -//! D-pad steps between slots and buttons, with A, X and the stick feeding -//! the screens the same pointer events a mouse sends. Every screen keeps -//! its mouse behaviour (drags, sliders, scrollbars) with no pad code of its -//! own. +//! docs/controllers.md). Two ways to drive them, picked in the controller +//! options: +//! +//! - **Focus** (console-style): a highlight steps between the widgets, list +//! rows, fields and slots each screen registers (`widgets::target_as`) +//! with vanilla's arrow-key navigation; A presses the focused one, the +//! bumpers switch tabs, left/right move a focused slider, A on a text field +//! opens the on-screen keyboard (`osk`). +//! - **Pointer**: a virtual cursor the left stick moves and the D-pad steps +//! between slots and buttons. +//! +//! Both feed the screens the same pointer events a mouse sends (the pointer +//! sits on the focused widget, hidden), so every screen keeps its mouse +//! behaviour (drags, sliders, scrollbars, hover highlights) with no pad code +//! of its own. A screen with nothing registered falls back to the pointer, +//! and a right stick click swaps modes for the open screen. use super::{Game, Screen}; use horizon_client::{ Result, creative::Creative, - gamepad::{self, Button}, + gamepad::{self, Button, MenuNav, Rect}, hud::{HudBatch, rgba}, options_ui::{Event, Page}, - widgets, + osk::{self, Keyboard}, + widgets::{self, Kind, Target}, }; use std::time::Instant; use winit::{ @@ -19,7 +31,7 @@ use winit::{ dpi::PhysicalPosition, event::{DeviceId, ElementState, MouseButton, MouseScrollDelta, TouchPhase, WindowEvent}, event_loop::ActiveEventLoop, - keyboard::KeyCode, + keyboard::{KeyCode, NamedKey}, }; /// D-pad auto-repeat: the first step at once, the next after a pause. @@ -27,6 +39,23 @@ const REPEAT_DELAY: f32 = 0.35; const REPEAT_EVERY: f32 = 0.09; /// Lines per second the right stick scrolls at full tilt. const SCROLL_SPEED: f32 = 12.0; +/// How far the stick must lean to step focus. +const STICK_STEP: f32 = 0.55; +/// Scrolls a step may try to reveal the next row of a list. +const SCROLL_TRIES: u8 = 4; + +/// A focus step that ran off the visible part of a list: the list was +/// scrolled and the step runs again once a new frame is drawn. When the +/// targets didn't move (nothing scrolled), the step takes vanilla's vague +/// pass instead. +#[derive(Clone)] +struct Pending { + button: Button, + from: Rect, + generation: u64, + tries: u8, + before: Vec, +} #[derive(Default)] pub(super) struct MenuCursor { @@ -45,12 +74,31 @@ pub(super) struct MenuCursor { os_hidden: bool, /// Polls since a menu opened (its widgets are drawn after one frame). open_polls: u32, + /// Focus mode: the focused target as last drawn. + focus: Option, + /// The left stick's step direction last poll. + stick: Option