diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index 2ab491207..c902acf32 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -1,7 +1,6 @@ name: launcher # Builds the launcher on Linux, macOS and Windows, and releases it by itself (docs/release-flow.md): after a -# push to main that changes the launcher or what it builds in (crates/horizon-prepare, crates/horizon-theme, -# crates/horizon-telemetry), +# push to main that changes the launcher or a crate it builds in (the paths below), # every 10 minutes (a release waiting for merges to settle goes out) and by hand, tools/release_train.py decides as # for the game. # A release is launcher-vX.Y.Z: the patch after the last launcher tag, or the next minor when a merged pull @@ -14,10 +13,15 @@ on: push: branches: [main, launcher, 'launcher-*'] paths: + # Every crate the launcher builds in, as tools/release_train.py's LAUNCHER_PATHS. - 'launcher/**' + - 'crates/horizon-bench/**' + - 'crates/horizon-friends/**' + - 'crates/horizon-mods/**' + - 'crates/horizon-port-pack/**' - 'crates/horizon-prepare/**' - - 'crates/horizon-theme/**' - 'crates/horizon-telemetry/**' + - 'crates/horizon-theme/**' - '.github/workflows/launcher.yml' schedule: - cron: '7-59/10 * * * *' @@ -138,7 +142,8 @@ jobs: echo "::notice::No Metal toolchain on this runner: GPUI compiles its shaders at run time" echo "LAUNCHER_FEATURES=gpui/runtime_shaders" >> "$GITHUB_ENV" fi - - run: cargo test --release --locked --lib ${LAUNCHER_FEATURES:+--features "$LAUNCHER_FEATURES"} + # Every test target (the library, the binary, tests/), on each system the launcher ships for. + - run: cargo test --release --locked ${LAUNCHER_FEATURES:+--features "$LAUNCHER_FEATURES"} - run: cargo build --release --locked ${LAUNCHER_FEATURES:+--features "$LAUNCHER_FEATURES"} - name: The version is the release's run: | diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 27636b0eb..a4780c85b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -174,7 +174,14 @@ jobs: case "${{ matrix.asset }}" in *.tar.gz) tar czf "${{ matrix.asset }}" "${{ matrix.dir }}" ;; *) if [[ "$RUNNER_OS" == Windows ]]; then 7z a -tzip "${{ matrix.asset }}" "${{ matrix.dir }}" > /dev/null - else ditto -c -k --keepParent "${{ matrix.dir }}" "${{ matrix.asset }}"; fi ;; + else + # Without resource forks and extended attributes: plain ditto adds an + # AppleDouble `._` file beside every file that has any. + ditto -c -k --norsrc --noextattr --noqtn --keepParent "${{ matrix.dir }}" "${{ matrix.asset }}" + if unzip -Z1 "${{ matrix.asset }}" | grep -E '(^|/)(\._|__MACOSX/)'; then + echo "::error::macOS metadata files in ${{ matrix.asset }}"; exit 1 + fi + fi ;; esac ls -l "${{ matrix.asset }}" - uses: actions/upload-artifact@v4 diff --git a/README.md b/README.md index f4f3094ae..0efae1088 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ Captured in the Rust client itself, with vanilla assets and no mods or shaders. Horizon's title screen: the mark and the pages on the left, the Horizon title, Singleplayer and Multiplayer, and the last world played and the faint wordmark, over a veiled snowy landscape - The Singleplayer page: three worlds with their dates and game modes, and Create world and Play buttons + The Singleplayer page: two worlds with their dates and game modes, and Create world and Play buttons The Video settings in their Simple view: a preset, render distance, field of view, framerate, VSync and GUI scale, each with what it costs @@ -79,17 +79,17 @@ The vanilla menus are one setting away: Options → Interface → Menu style → Sunset over a savanna river valley and a plains village - A plains village with farms, an iron golem and animals - Survival at dusk: a zombie attacks near the village + A plains village among savanna hills, with farms, villagers and an iron golem + Survival at dusk: a zombie walks up, with the hotbar, health, hunger and experience A crimson forest in the Nether with a zombified piglin Moonrise over a torch-lit village and river - Salmon swimming in a river + Tropical fish over a warm-ocean coral reef - Vanilla world generation ported to Rust (terrain, aquifers, carvers, features, villages and the Nether), every block model with smooth lighting and biome tints, the vanilla sky and fog, mobs, the HUD, chat and advancements: everything in these frames is drawn by Horizon. + Vanilla world generation ported to Rust (terrain, aquifers, carvers, features, villages and the Nether), every block model with smooth lighting and biome tints, the vanilla sky and fog, mobs and the HUD: everything in these frames is drawn by Horizon. diff --git a/benchmarks/server-2026-10-17/README.md b/benchmarks/server-2026-10-17/README.md new file mode 100644 index 000000000..4a3cd3dcc --- /dev/null +++ b/benchmarks/server-2026-10-17/README.md @@ -0,0 +1,174 @@ +# Dedicated server against vanilla 26.3, with bots (2026-10-17) + +`horizon-client --dedicated` (run by `horizon-server`) against the pinned vanilla 26.3 `server.jar`, on `main` +at `7bbbf6e9` (in release v2026.10.17.17). That build has the movement checks and chunk pacing of #586, the +equal-work method of #670, and the server performance PRs #701–#707 and #713. + +This replaces the data first published here, which came from a Mac mini overloaded by other work (load 55–141 on +14 threads). An earlier run of this method, on `main` at `002f14ce`, is kept in `earlier-002f14ce/` and compared +at the end. + +## Setup + +- **Server machine:** ThinkPad, Intel i7-7500U (2 cores, 4 threads), 32 GB, NixOS. Nothing else heavy ran on it: + its load average was 0.4 when idle. Both servers ran under `nice -n 19`. +- **Bots:** `horizon-bots` on another machine (Mac mini M4 Pro), over the tailnet. That machine was shared with + other work (load 36–170 on 14 threads, mean 78). The bots need little CPU, but a busy bot host can answer later. + Both servers saw the same conditions, since they took turns at each bot count. +- **Horizon:** release build of `7bbbf6e9` (`horizon-server`, `horizon-client`). +- **Vanilla:** the pinned 26.3 `server.jar` on OpenJDK 25.0.4.1, with `-Xms4g -Xmx4g`. +- **Properties:** + - `level-seed=12345`, view and simulation distance 10, creative (forced); + - `online-mode=false`, `difficulty=easy`, `max-players=200`; + - default game rules on both (the locator bar is on). +- **Each run:** a fresh server, bots joining one per second, a 60 s warm-up, then 180 s measured. +- **Commands** (on the server machine): + ``` + python3 tools/server_bench.py --servers horizon,vanilla --nice 19 --warmup 60 --seconds 180 \ + --bots-via "ssh " --bots-bin --connect \ + --bots 1,10,25,50,100 --behaviour walk,explore + python3 tools/server_bench.py ...same... --bots 1,10,25,50 --behaviour explore --explore-speed 0.8 + ``` +- **Columns:** + - **MSPT** (mean) and **P95** come from `/tick query`, in ms. **TPS** is the tick rate. + - **RSS** is the mean over the run. **CPU** is the whole process tree, as a percentage of one core. + - **Chunks/s** is what the bots received. **New chunks/s** counts each chunk once per bot. + - **Pulled back** counts the times the server moved a bot back (vanilla's "moved too quickly" and similar). + - **Load** is the mean load average during that run: the server machine (which includes the server's own + threads) and the bot host. + +## Results + +### Equal work: bots explore at the same pace (`--explore-speed 0.8`) + +Each bot flies outwards at 0.8 blocks a second, which both servers keep up with. They send the same chunks, so +the tick times compare the same work. + +| Bots | Server | MSPT | P95 | TPS | RSS | CPU | Chunks/s | New chunks/s | Pulled back | Load (server / bots) | +|---:|---|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| 1 | Horizon | 3.16 | 5.78 | 20.0 | 0.76 GB | 22 % | 2 | 1.27 | 0 | 2.8 / 63 | +| 1 | Vanilla | 16.82 | 27.3 | 20.0 | 3.37 GB | 69 % | 2 | 1.35 | 0 | 1.8 / 94 | +| 10 | Horizon | 9.83 | 19.01 | 20.0 | 0.86 GB | 77 % | 14 | 12.31 | 1051 | 2.2 / 74 | +| 10 | Vanilla | 24.38 | 39.58 | 20.0 | 3.57 GB | 132 % | 14 | 12.32 | 1027 | 2.5 / 64 | +| 25 | Horizon | 16.87 | 30.88 | 20.0 | 0.89 GB | 111 % | 34 | 29.92 | 3770 | 5.1 / 51 | +| 25 | Vanilla | 30.29 | 43.47 | 20.0 | 3.61 GB | 176 % | 33 | 29.29 | 5139 | 5.2 / 55 | +| 50 | Horizon | 23.57 | 47.53 | 20.0 | 0.92 GB | 127 % | 67 | 59.42 | 7434 | 8.5 / 64 | +| 50 | Vanilla | 42.44 | 54.84 | 20.0 | 3.67 GB | 201 % | 65 | 58.11 | 10604 | 5.1 / 59 | + +### `walk`: bots walk around the spawn + +| Bots | Server | MSPT | P95 | TPS | RSS | CPU | Chunks/s | New chunks/s | Pulled back | Load (server / bots) | +|---:|---|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| 1 | Horizon | 4.01 | 8.19 | 20.0 | 0.78 GB | 59 % | 10 | 0.43 | 0 | 1.4 / 70 | +| 1 | Vanilla | 18.22 | 29.34 | 20.0 | 3.43 GB | 69 % | 10 | 0.47 | 0 | 1.9 / 63 | +| 10 | Horizon | 8.79 | 17.35 | 20.0 | 0.78 GB | 119 % | 95 | 3.58 | 0 | 2.9 / 69 | +| 10 | Vanilla | 18.67 | 38.26 | 20.0 | 3.50 GB | 101 % | 101 | 4.38 | 5 | 3.2 / 59 | +| 25 | Horizon | 15.01 | 31.12 | 20.0 | 0.80 GB | 161 % | 234 | 8.49 | 0 | 6.3 / 43 | +| 25 | Vanilla | 18.78 | 28.16 | 20.0 | 3.52 GB | 155 % | 252 | 11.89 | 10 | 6.7 / 57 | +| 50 | Horizon | 22.72 | 60.19 | 20.0 | 0.81 GB | 180 % | 465 | 16.94 | 0 | 14.7 / 50 | +| 50 | Vanilla | 34.3 | 55.55 | 20.0 | 3.58 GB | 267 % | 497 | 26.74 | 39 | 9.5 / 56 | +| 100 | Horizon | 63.33 | 125.04 | 15.79 | 0.87 GB | 246 % | 678 | 31.8 | 0 | 32.9 / 95 | +| 100 | Vanilla | stopped by its watchdog (a 60 s tick) | | | | | | | | 15.1 / 120 | + +Both servers sent each walking bot the same number of distinct chunks over the whole run (680–690). Horizon's +"new chunks/s" inside the measured window is lower, so compare the totals, not that column. + +### `explore` at full speed: unequal work + +Bots fly outwards as fast as chunks arrive (`horizon-bots`' default, up to 22 blocks a second). Both servers now pull them back ("moved too quickly"), but Horizon sends +more new terrain, so this pass doesn't compare equal work. The server-machine load of Horizon's 1-bot run is +estimated from the time between the runs around it: its log was overwritten before it was read. + +| Bots | Server | MSPT | P95 | TPS | RSS | CPU | Chunks/s | New chunks/s | Pulled back | Load (server / bots) | +|---:|---|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| 1 | Horizon | 9.73 | 20.99 | 20.0 | 0.84 GB | 330 % | 41 | 35.96 | 0 | 4.7 / 129 | +| 1 | Vanilla | 9.71 | 20.37 | 20.0 | 3.61 GB | 247 % | 35 | 33.61 | 0 | 4.3 / 156 | +| 10 | Horizon | 21.27 | 39.15 | 20.0 | 1.18 GB | 322 % | 46 | 46.11 | 9856 | 5.0 / 114 | +| 10 | Vanilla | 16.94 | 30.28 | 20.0 | 3.95 GB | 254 % | 25 | 25.01 | 11123 | 5.5 / 89 | +| 25 | Horizon | 25.76 | 45.01 | 20.0 | 1.17 GB | 314 % | 61 | 60.7 | 31264 | 6.6 / 82 | +| 25 | Vanilla | 24.93 | 37.09 | 20.0 | 4.04 GB | 305 % | 38 | 37.84 | 33467 | 6.1 / 91 | +| 50 | Horizon | 39.31 | 65.33 | 20.0 | 1.25 GB | 325 % | 115 | 112.25 | 64163 | 6.9 / 95 | +| 50 | Vanilla | stopped by its watchdog (a 60 s tick) | | | | | | | | 7.7 / 86 | +| 100 | Horizon | 52.7 | 85.73 | 18.97 | 1.36 GB | 328 % | 154 | 151.83 | 116161 | 13.4 / 79 | +| 100 | Vanilla | stopped by its watchdog (a 60 s tick) | | | | | | | | 10.0 / 72 | + +Vanilla's watchdog stopped it after a 60-second tick in three runs (walk 100, explore 50 and 100). Each time its +server thread was in entity tracking (`ChunkMap$TrackedEntity.updatePlayer`). + +## What it shows + +- **Same work, 1 to 50 players:** Horizon's mean tick is 44–81 % shorter than vanilla's, its 95th percentile is + lower, and its process uses 32–63 % of vanilla's CPU. +- **Walking, 1 to 50 players:** Horizon's mean tick is shorter at every count (4.0 against 18.2 ms with 1 bot, + 22.7 against 34.3 ms with 50). +- **Where vanilla wins:** + - With 25 and 50 walking bots, vanilla's 95th percentile is lower (28.2 against 31.1 ms, 55.6 against + 60.2 ms). Horizon's slow ticks are spikier. + - In the full-speed explore pass, vanilla's mean tick is shorter with 10 and 25 bots (16.9 against 21.3 ms, + 24.9 against 25.8 ms), while Horizon sends 1.6–1.8 times as many new chunks. + - With 50 walking bots, Horizon makes the server machine busier (load 14.7 against 9.5). Its connection + writer threads compress every packet (below). +- **100 players:** Horizon keeps 15.8 TPS walking and 19.0 TPS exploring at full speed. Vanilla's watchdog + stopped it in both. +- **Memory:** Horizon used 0.76–0.92 GB in every walk and equal-work run, and 1.36 GB at most when 100 bots + explored at full speed. Vanilla used 3.4–4.0 GB with its 4 GB heap. +- **Start:** Horizon's fresh world was ready in 9.2–9.9 s, vanilla's in 14.9–17.2 s. + +## Where Horizon's time goes (50 walking bots) + +`perf record -e cycles:u --call-graph lbr` on the engine for 30 s, during a separate 50-bot `walk` run on the same +build and machine (MSPT 21.7 ms, 178 % CPU). Shares of all the engine's CPU samples: + +| Thread | Share | Mostly | +|---|---:|---| +| Connection writers (`horizon-lan-out`) | 55 % | 53 % in `miniz_oxide` deflate, from `horizon_protocol::frame::encode` | +| World generation workers | 33 % | noise, surface rules, aquifers | +| Server thread (the tick) | 12 % | see below | + +Inside the tick: +- the locator bar (`Waypoints::tick`): a third of the tick; +- `Hub::tick`: a quarter; +- block entities, creatures, chunk encoding (`ChunkEncoder::encode_in`) and `Streaming::update`: 7–10 % each; +- SipHash of `u128` keys (the default `HashMap` hasher): about 10 % of the tick. + +**The next biggest cost is compressing packets.** Every chunk packet is compressed again for each player who gets +it, with `flate2`'s default `miniz_oxide` backend at level 6. On this 4-thread CPU that competes with the tick +and with world generation. Two fixes, which can be combined: +- the `zlib-rs` backend for `flate2`: 2.2–10 times faster than `miniz_oxide` at level 6 in a quick test, with + output about 3 % larger; +- compressing a chunk packet once and sending the same bytes to every player who needs it. + +## Before and after the performance PRs + +The earlier run, on `main` at `002f14ce` with #670's bench changes (build `a9ee56a8`), before #586, #701–#707 and +#713. Same machines and settings. MSPT mean / P95, in ms: + +Walk: + +| Bots | Horizon before | Horizon now | Vanilla before | Vanilla now | +|---:|---|---|---|---| +| 1 | 5.77 / 11.04 | 4.01 / 8.19 | 18.84 / 29.55 | 18.22 / 29.34 | +| 10 | 16.23 / 29.32 | 8.79 / 17.35 | 18.02 / 37.62 | 18.67 / 38.26 | +| 25 | 23.98 / 49.18 | 15.01 / 31.12 | 19.19 / 33.84 | 18.78 / 28.16 | +| 50 | 35.07 / 73.24 | 22.72 / 60.19 | 35.23 / 60.87 | 34.3 / 55.55 | +| 100 | 104.8 / 158.8 | 63.33 / 125.04 | watchdog | watchdog | + +Equal work: + +| Bots | Horizon before | Horizon now | Vanilla before | Vanilla now | +|---:|---|---|---|---| +| 1 | 4.78 / 7.3 | 3.16 / 5.78 | 16.63 / 26.23 | 16.82 / 27.3 | +| 10 | 15.19 / 25.66 | 9.83 / 19.01 | 24.65 / 40.81 | 24.38 / 39.58 | +| 25 | 23.37 / 42.59 | 16.87 / 30.88 | 30.28 / 44.81 | 30.29 / 43.47 | +| 50 | 30.59 / 67.94 | 23.57 / 47.53 | 43.52 / 56.18 | 42.44 / 54.84 | + +Vanilla's numbers repeat within a few percent, so the runs are comparable. In the earlier run, 25 walking bots +were faster on vanilla (19.2 against 24.0 ms). A profile then put a third of the tick in advancement updates, +which #701 fixed. + +## Files + +- `walk-explore.json`: the `walk` and full-speed `explore` passes. `explore-equal-rate.json`: the equal-work pass. +- `load.txt`: both machines' load averages every 30 s during the runs. +- `earlier-002f14ce/`: the same files for the earlier run. +- The server's tailnet address is replaced by `` in the JSON. diff --git a/benchmarks/server-2026-10-17/earlier-002f14ce/explore-equal-rate.json b/benchmarks/server-2026-10-17/earlier-002f14ce/explore-equal-rate.json new file mode 100644 index 000000000..404f8d032 --- /dev/null +++ b/benchmarks/server-2026-10-17/earlier-002f14ce/explore-equal-rate.json @@ -0,0 +1,341 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T15:37:03+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "a9ee56a8b143999c9bc7056850ffcd622a9214aa", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon,vanilla", + "bots": "1,10,25,50", + "behaviour": "explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 180, + "seed": 12345, + "explore_speed": 0.8, + "gamerule": "", + "heap": "4g", + "out": "/home/ludovic/code/horizon/.claude/worktrees/server-host-4/.local/bench-out/explore-equal-rate.json", + "nice": 19, + "bots_via": "ssh macmini", + "bots_bin": "/Users/ludovicmarie/code/horizon/.claude/worktrees/server-host-4/target/release/horizon-bots", + "connect": "", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "explore", + "start_seconds": 9.21, + "mspt": { + "average": 4.78, + "p50": 4.59, + "p95": 7.3, + "p99": 13.53 + }, + "mspt_worst_p99": 36.5, + "tps": 20.0, + "rss_mb": { + "mean": 759.91, + "max": 771.3 + }, + "cpu_percent": 24.49, + "chunks_per_second": 1.64, + "unique_per_second": 1.27, + "forgotten_per_second": 1.54, + "waited_ticks_per_second": 0.0, + "chunks_total": 841, + "chunks_per_bot": { + "explore": 841.0 + }, + "unique_chunks_per_bot": { + "explore": 781.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "explore", + "start_seconds": 14.35, + "mspt": { + "average": 16.63, + "p50": 16.73, + "p95": 26.23, + "p99": 35.39 + }, + "mspt_worst_p99": 68.5, + "tps": 20.0, + "rss_mb": { + "mean": 3431.12, + "max": 3459.2 + }, + "cpu_percent": 69.76, + "chunks_per_second": 1.66, + "unique_per_second": 1.37, + "forgotten_per_second": 1.67, + "waited_ticks_per_second": 0.0, + "chunks_total": 840, + "chunks_per_bot": { + "explore": 840.0 + }, + "unique_chunks_per_bot": { + "explore": 780.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "explore", + "start_seconds": 9.31, + "mspt": { + "average": 15.19, + "p50": 14.45, + "p95": 25.66, + "p99": 38.89 + }, + "mspt_worst_p99": 57.6, + "tps": 20.0, + "rss_mb": { + "mean": 859.86, + "max": 920.2 + }, + "cpu_percent": 84.95, + "chunks_per_second": 14.22, + "unique_per_second": 12.7, + "forgotten_per_second": 14.11, + "waited_ticks_per_second": 0.0, + "chunks_total": 7962, + "chunks_per_bot": { + "explore": 796.2 + }, + "unique_chunks_per_bot": { + "explore": 768.2 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "explore", + "start_seconds": 14.74, + "mspt": { + "average": 24.65, + "p50": 21.82, + "p95": 40.81, + "p99": 70.23 + }, + "mspt_worst_p99": 119.1, + "tps": 20.0, + "rss_mb": { + "mean": 3528.77, + "max": 3643.2 + }, + "cpu_percent": 133.1, + "chunks_per_second": 13.62, + "unique_per_second": 12.32, + "forgotten_per_second": 13.62, + "waited_ticks_per_second": 0.0, + "chunks_total": 7746, + "chunks_per_bot": { + "explore": 774.6 + }, + "unique_chunks_per_bot": { + "explore": 748.7 + }, + "resent": 0, + "pulled_back": 1150, + "moved_too_quickly": 5, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "explore", + "start_seconds": 9.42, + "mspt": { + "average": 23.37, + "p50": 21.61, + "p95": 42.59, + "p99": 60.21 + }, + "mspt_worst_p99": 102.1, + "tps": 20.0, + "rss_mb": { + "mean": 889.21, + "max": 950.7 + }, + "cpu_percent": 117.59, + "chunks_per_second": 35.34, + "unique_per_second": 31.62, + "forgotten_per_second": 35.12, + "waited_ticks_per_second": 0.0, + "chunks_total": 20137, + "chunks_per_bot": { + "explore": 805.48 + }, + "unique_chunks_per_bot": { + "explore": 774.52 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "explore", + "start_seconds": 15.14, + "mspt": { + "average": 30.28, + "p50": 28.17, + "p95": 44.81, + "p99": 71.77 + }, + "mspt_worst_p99": 158.1, + "tps": 20.0, + "rss_mb": { + "mean": 3574.32, + "max": 3692.7 + }, + "cpu_percent": 173.43, + "chunks_per_second": 32.76, + "unique_per_second": 29.38, + "forgotten_per_second": 33.02, + "waited_ticks_per_second": 0.0, + "chunks_total": 19417, + "chunks_per_bot": { + "explore": 776.68 + }, + "unique_chunks_per_bot": { + "explore": 747.36 + }, + "resent": 0, + "pulled_back": 4728, + "moved_too_quickly": 15, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "explore", + "start_seconds": 9.11, + "mspt": { + "average": 30.59, + "p50": 25.19, + "p95": 67.94, + "p99": 90.77 + }, + "mspt_worst_p99": 122.1, + "tps": 20.0, + "rss_mb": { + "mean": 915.93, + "max": 978.0 + }, + "cpu_percent": 132.13, + "chunks_per_second": 71.31, + "unique_per_second": 63.56, + "forgotten_per_second": 71.19, + "waited_ticks_per_second": 0.0, + "chunks_total": 41365, + "chunks_per_bot": { + "explore": 827.3 + }, + "unique_chunks_per_bot": { + "explore": 793.14 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "explore", + "start_seconds": 15.35, + "mspt": { + "average": 43.52, + "p50": 41.69, + "p95": 56.18, + "p99": 84.55 + }, + "mspt_worst_p99": 155.1, + "tps": 20.0, + "rss_mb": { + "mean": 3801.29, + "max": 3920.7 + }, + "cpu_percent": 198.97, + "chunks_per_second": 65.86, + "unique_per_second": 58.63, + "forgotten_per_second": 66.12, + "waited_ticks_per_second": 0.0, + "chunks_total": 39790, + "chunks_per_bot": { + "explore": 795.8 + }, + "unique_chunks_per_bot": { + "explore": 764.48 + }, + "resent": 0, + "pulled_back": 8392, + "moved_too_quickly": 38, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 35 + } + ] +} diff --git a/benchmarks/server-2026-10-17/earlier-002f14ce/load.txt b/benchmarks/server-2026-10-17/earlier-002f14ce/load.txt new file mode 100644 index 000000000..853252809 --- /dev/null +++ b/benchmarks/server-2026-10-17/earlier-002f14ce/load.txt @@ -0,0 +1,278 @@ +2026-10-17T13:17:13Z thinkpad: 2.76 2.26 2.04 | macmini (bots): { 73.08 70.73 75.98 } +2026-10-17T13:17:43Z thinkpad: 2.90 2.33 2.07 | macmini (bots): { 75.66 71.62 76.12 } +2026-10-17T13:18:13Z thinkpad: 3.02 2.43 2.11 | macmini (bots): { 65.77 69.61 75.24 } +2026-10-17T13:18:44Z thinkpad: 2.15 2.27 2.07 | macmini (bots): { 59.85 67.75 74.37 } +2026-10-17T13:19:14Z thinkpad: 1.45 2.09 2.02 | macmini (bots): { 63.86 67.87 74.17 } +2026-10-17T13:19:44Z thinkpad: 1.28 1.98 1.98 | macmini (bots): { 63.51 67.54 73.84 } +2026-10-17T13:20:14Z thinkpad: 1.14 1.89 1.95 | macmini (bots): { 65.82 67.85 73.71 } +2026-10-17T13:20:45Z thinkpad: 0.90 1.77 1.91 | macmini (bots): { 63.62 67.08 73.22 } +2026-10-17T13:21:15Z thinkpad: 0.55 1.60 1.85 | macmini (bots): { 62.45 66.37 72.75 } +2026-10-17T13:21:45Z thinkpad: 0.79 1.54 1.82 | macmini (bots): { 67.04 67.04 72.76 } +2026-10-17T13:22:15Z thinkpad: 1.96 1.75 1.88 | macmini (bots): { 65.53 66.60 72.40 } +2026-10-17T13:22:46Z thinkpad: 1.82 1.75 1.88 | macmini (bots): { 61.52 65.55 71.82 } +2026-10-17T13:23:16Z thinkpad: 1.29 1.63 1.83 | macmini (bots): { 62.36 65.36 71.53 } +2026-10-17T13:23:46Z thinkpad: 0.86 1.49 1.78 | macmini (bots): { 68.76 66.51 71.73 } +2026-10-17T13:24:16Z thinkpad: 1.29 1.52 1.78 | macmini (bots): { 77.68 68.77 72.36 } +2026-10-17T13:24:46Z thinkpad: 1.82 1.62 1.80 | macmini (bots): { 74.03 68.88 72.28 } +2026-10-17T13:25:17Z thinkpad: 1.50 1.56 1.78 | macmini (bots): { 71.53 68.76 72.12 } +2026-10-17T13:25:47Z thinkpad: 0.96 1.42 1.72 | macmini (bots): { 74.46 69.85 72.40 } +2026-10-17T13:26:17Z thinkpad: 0.87 1.35 1.69 | macmini (bots): { 80.85 71.79 73.01 } +2026-10-17T13:26:47Z thinkpad: 3.95 2.02 1.90 | macmini (bots): { 74.77 71.31 72.81 } +2026-10-17T13:27:18Z thinkpad: 2.98 1.97 1.89 | macmini (bots): { 70.52 70.52 72.46 } +2026-10-17T13:27:48Z thinkpad: 3.78 2.26 1.99 | macmini (bots): { 67.62 69.91 72.18 } +2026-10-17T13:28:18Z thinkpad: 3.05 2.23 1.99 | macmini (bots): { 72.51 70.83 72.43 } +2026-10-17T13:28:48Z thinkpad: 2.05 2.07 1.94 | macmini (bots): { 79.07 72.64 73.03 } +2026-10-17T13:29:19Z thinkpad: 2.09 2.11 1.96 | macmini (bots): { 90.42 75.94 74.21 } +2026-10-17T13:29:49Z thinkpad: 1.61 1.99 1.93 | macmini (bots): { 102.68 80.15 75.78 } +2026-10-17T13:30:19Z thinkpad: 2.31 2.12 1.97 | macmini (bots): { 111.15 84.19 77.39 } +2026-10-17T13:30:49Z thinkpad: 4.14 2.61 2.14 | macmini (bots): { 115.67 87.82 78.94 } +2026-10-17T13:31:20Z thinkpad: 4.84 2.92 2.26 | macmini (bots): { 122.95 92.31 80.88 } +2026-10-17T13:31:50Z thinkpad: 6.84 3.60 2.51 | macmini (bots): { 136.25 98.41 83.48 } +2026-10-17T13:32:20Z thinkpad: 4.85 3.43 2.49 | macmini (bots): { 128.59 100.39 84.73 } +2026-10-17T13:32:50Z thinkpad: 3.48 3.25 2.46 | macmini (bots): { 111.05 98.73 84.66 } +2026-10-17T13:33:20Z thinkpad: 3.09 3.15 2.45 | macmini (bots): { 102.40 98.03 84.98 } +2026-10-17T13:33:51Z thinkpad: 2.47 2.99 2.42 | macmini (bots): { 94.57 96.54 84.89 } +2026-10-17T13:34:21Z thinkpad: 2.42 2.94 2.42 | macmini (bots): { 86.26 94.36 84.50 } +2026-10-17T13:34:51Z thinkpad: 2.95 3.04 2.47 | macmini (bots): { 76.90 91.56 83.84 } +2026-10-17T13:35:21Z thinkpad: 2.66 2.96 2.46 | macmini (bots): { 65.57 87.42 82.61 } +2026-10-17T13:35:52Z thinkpad: 2.47 2.88 2.45 | macmini (bots): { 64.13 85.05 81.92 } +2026-10-17T13:36:22Z thinkpad: 3.89 3.17 2.56 | macmini (bots): { 58.65 81.74 80.83 } +2026-10-17T13:36:52Z thinkpad: 6.43 3.83 2.80 | macmini (bots): { 66.32 81.32 80.71 } +2026-10-17T13:37:22Z thinkpad: 8.73 4.60 3.09 | macmini (bots): { 67.30 80.14 80.30 } +2026-10-17T13:37:53Z thinkpad: 9.03 5.10 3.30 | macmini (bots): { 63.66 78.24 79.62 } +2026-10-17T13:38:23Z thinkpad: 9.49 5.57 3.52 | macmini (bots): { 61.25 76.23 78.84 } +2026-10-17T13:38:53Z thinkpad: 7.55 5.50 3.56 | macmini (bots): { 62.30 74.88 78.25 } +2026-10-17T13:39:23Z thinkpad: 8.62 5.99 3.79 | macmini (bots): { 57.34 72.56 77.29 } +2026-10-17T13:39:53Z thinkpad: 6.65 5.81 3.80 | macmini (bots): { 51.24 69.62 76.06 } +2026-10-17T13:40:24Z thinkpad: 5.55 5.62 3.80 | macmini (bots): { 48.87 67.26 74.98 } +2026-10-17T13:40:54Z thinkpad: 6.11 5.71 3.89 | macmini (bots): { 51.16 66.08 74.29 } +2026-10-17T13:41:24Z thinkpad: 8.93 6.43 4.19 | macmini (bots): { 48.67 64.00 73.24 } +2026-10-17T13:41:54Z thinkpad: 9.05 6.74 4.36 | macmini (bots): { 46.47 61.96 72.18 } +2026-10-17T13:42:25Z thinkpad: 7.70 6.65 4.41 | macmini (bots): { 44.24 60.05 71.14 } +2026-10-17T13:42:55Z thinkpad: 5.64 6.24 4.34 | macmini (bots): { 49.30 59.83 70.68 } +2026-10-17T13:43:25Z thinkpad: 4.83 6.02 4.33 | macmini (bots): { 47.39 58.24 69.72 } +2026-10-17T13:43:55Z thinkpad: 3.57 5.61 4.25 | macmini (bots): { 47.32 57.23 68.96 } +2026-10-17T13:44:25Z thinkpad: 3.41 5.40 4.23 | macmini (bots): { 47.86 56.49 68.28 } +2026-10-17T13:44:55Z thinkpad: 3.37 5.21 4.20 | macmini (bots): { 50.10 56.19 67.77 } +2026-10-17T13:45:26Z thinkpad: 3.78 5.16 4.22 | macmini (bots): { 51.91 55.98 67.28 } +2026-10-17T13:45:56Z thinkpad: 4.34 5.12 4.23 | macmini (bots): { 49.16 54.85 66.42 } +2026-10-17T13:46:26Z thinkpad: 10.04 6.46 4.71 | macmini (bots): { 45.01 53.33 65.47 } +2026-10-17T13:46:56Z thinkpad: 18.10 8.73 5.52 | macmini (bots): { 46.41 52.87 64.88 } +2026-10-17T13:47:27Z thinkpad: 14.99 8.91 5.68 | macmini (bots): { 51.12 53.21 64.57 } +2026-10-17T13:47:57Z thinkpad: 13.46 9.27 5.92 | macmini (bots): { 53.84 53.81 64.40 } +2026-10-17T13:48:27Z thinkpad: 12.76 9.41 6.07 | macmini (bots): { 51.94 53.27 63.84 } +2026-10-17T13:48:58Z thinkpad: 10.20 9.11 6.08 | macmini (bots): { 50.70 52.83 63.31 } +2026-10-17T13:49:28Z thinkpad: 9.95 9.25 6.23 | macmini (bots): { 51.51 52.89 62.97 } +2026-10-17T13:49:58Z thinkpad: 11.98 9.87 6.53 | macmini (bots): { 50.98 52.73 62.57 } +2026-10-17T13:50:29Z thinkpad: 14.96 10.76 6.94 | macmini (bots): { 49.68 52.31 62.08 } +2026-10-17T13:50:59Z thinkpad: 10.54 10.09 6.83 | macmini (bots): { 53.34 53.01 62.00 } +2026-10-17T13:51:29Z thinkpad: 10.21 10.01 6.91 | macmini (bots): { 51.61 52.69 61.57 } +2026-10-17T13:52:00Z thinkpad: 11.86 10.42 7.14 | macmini (bots): { 48.94 51.89 60.97 } +2026-10-17T13:52:30Z thinkpad: 10.88 10.33 7.22 | macmini (bots): { 48.46 51.44 60.49 } +2026-10-17T13:53:01Z thinkpad: 10.94 10.41 7.35 | macmini (bots): { 54.27 52.41 60.47 } +2026-10-17T13:53:31Z thinkpad: 10.77 10.42 7.45 | macmini (bots): { 57.13 53.30 60.51 } +2026-10-17T13:54:02Z thinkpad: 10.62 10.40 7.53 | macmini (bots): { 53.78 52.84 60.09 } +2026-10-17T13:54:32Z thinkpad: 10.85 10.48 7.66 | macmini (bots): { 52.01 52.51 59.73 } +2026-10-17T13:55:02Z thinkpad: 10.36 10.39 7.73 | macmini (bots): { 53.44 52.83 59.59 } +2026-10-17T13:55:32Z thinkpad: 8.58 9.95 7.67 | macmini (bots): { 58.66 54.12 59.82 } +2026-10-17T13:56:03Z thinkpad: 7.29 9.52 7.60 | macmini (bots): { 60.98 55.05 59.96 } +2026-10-17T13:56:33Z thinkpad: 5.02 8.75 7.40 | macmini (bots): { 65.14 56.71 60.39 } +2026-10-17T13:57:03Z thinkpad: 5.03 8.38 7.32 | macmini (bots): { 57.51 55.73 59.91 } +2026-10-17T13:57:34Z thinkpad: 7.39 8.66 7.45 | macmini (bots): { 52.57 54.73 59.41 } +2026-10-17T13:58:04Z thinkpad: 10.56 9.45 7.76 | macmini (bots): { 53.11 54.60 59.20 } +2026-10-17T13:58:34Z thinkpad: 28.87 14.20 9.41 | macmini (bots): { 54.53 54.93 59.16 } +2026-10-17T13:59:05Z thinkpad: 39.33 17.79 10.73 | macmini (bots): { 62.67 56.86 59.71 } +2026-10-17T13:59:35Z thinkpad: 34.07 18.33 11.12 | macmini (bots): { 61.78 57.22 59.75 } +2026-10-17T14:00:06Z thinkpad: 34.42 19.72 11.80 | macmini (bots): { 53.10 55.55 59.03 } +2026-10-17T14:00:36Z thinkpad: 33.60 20.94 12.46 | macmini (bots): { 48.70 54.23 58.43 } +2026-10-17T14:01:07Z thinkpad: 29.29 20.99 12.74 | macmini (bots): { 50.25 54.00 58.20 } +2026-10-17T14:01:37Z thinkpad: 20.83 19.79 12.61 | macmini (bots): { 50.48 53.74 57.96 } +2026-10-17T14:02:08Z thinkpad: 21.74 20.44 13.11 | macmini (bots): { 48.65 53.04 57.56 } +2026-10-17T14:02:38Z thinkpad: 17.68 19.67 13.09 | macmini (bots): { 54.17 53.85 57.69 } +2026-10-17T14:03:08Z thinkpad: 13.97 18.55 12.93 | macmini (bots): { 53.39 53.84 57.56 } +2026-10-17T14:03:39Z thinkpad: 14.10 18.17 12.98 | macmini (bots): { 50.71 53.09 57.16 } +2026-10-17T14:04:09Z thinkpad: 13.60 17.65 12.97 | macmini (bots): { 52.30 53.28 57.08 } +2026-10-17T14:04:39Z thinkpad: 12.09 16.91 12.88 | macmini (bots): { 51.52 53.03 56.87 } +2026-10-17T14:05:10Z thinkpad: 10.15 15.98 12.69 | macmini (bots): { 54.53 53.57 56.91 } +2026-10-17T14:05:42Z thinkpad: 7.77 14.86 12.42 | macmini (bots): { 63.58 55.55 57.49 } +2026-10-17T14:06:12Z thinkpad: 6.58 13.89 12.18 | macmini (bots): { 75.29 59.41 58.84 } +2026-10-17T14:06:42Z thinkpad: 5.96 13.02 11.94 | macmini (bots): { 78.06 61.64 59.67 } +2026-10-17T14:07:12Z thinkpad: 4.86 12.08 11.66 | macmini (bots): { 72.26 61.85 59.81 } +2026-10-17T14:07:42Z thinkpad: 4.49 11.18 11.38 | macmini (bots): { 67.84 61.73 59.84 } +2026-10-17T14:08:13Z thinkpad: 4.37 10.51 11.15 | macmini (bots): { 64.25 61.45 59.80 } +2026-10-17T14:08:43Z thinkpad: 4.57 9.97 10.94 | macmini (bots): { 57.86 60.14 59.38 } +2026-10-17T14:09:13Z thinkpad: 4.60 9.46 10.74 | macmini (bots): { 60.21 60.39 59.49 } +2026-10-17T14:09:43Z thinkpad: 4.20 8.89 10.51 | macmini (bots): { 57.11 59.57 59.22 } +2026-10-17T14:10:14Z thinkpad: 3.80 8.36 10.28 | macmini (bots): { 66.05 61.48 59.92 } +2026-10-17T14:10:44Z thinkpad: 4.19 8.00 10.10 | macmini (bots): { 78.51 64.91 61.22 } +2026-10-17T14:11:14Z thinkpad: 4.27 7.65 9.92 | macmini (bots): { 74.15 65.33 61.51 } +2026-10-17T14:11:44Z thinkpad: 4.35 7.35 9.74 | macmini (bots): { 62.47 63.48 60.98 } +2026-10-17T14:12:14Z thinkpad: 4.98 7.22 9.62 | macmini (bots): { 56.73 61.86 60.46 } +2026-10-17T14:12:45Z thinkpad: 4.60 6.91 9.44 | macmini (bots): { 57.78 61.49 60.37 } +2026-10-17T14:13:15Z thinkpad: 4.15 6.57 9.25 | macmini (bots): { 56.21 60.71 60.12 } +2026-10-17T14:13:45Z thinkpad: 3.87 6.25 9.05 | macmini (bots): { 54.75 60.00 59.89 } +2026-10-17T14:14:15Z thinkpad: 3.86 6.02 8.89 | macmini (bots): { 52.21 58.88 59.49 } +2026-10-17T14:14:46Z thinkpad: 3.14 5.64 8.67 | macmini (bots): { 58.81 59.59 59.71 } +2026-10-17T14:15:16Z thinkpad: 3.76 5.54 8.54 | macmini (bots): { 64.13 60.86 60.16 } +2026-10-17T14:15:46Z thinkpad: 3.91 5.41 8.40 | macmini (bots): { 59.02 59.97 59.87 } +2026-10-17T14:16:16Z thinkpad: 4.33 5.35 8.28 | macmini (bots): { 64.48 60.97 60.22 } +2026-10-17T14:16:46Z thinkpad: 5.20 5.44 8.21 | macmini (bots): { 79.56 64.98 61.70 } +2026-10-17T14:17:17Z thinkpad: 4.88 5.36 8.10 | macmini (bots): { 94.21 69.99 63.63 } +2026-10-17T14:17:47Z thinkpad: 4.80 5.30 8.00 | macmini (bots): { 85.75 70.51 64.08 } +2026-10-17T14:18:17Z thinkpad: 4.82 5.25 7.89 | macmini (bots): { 82.33 71.25 64.57 } +2026-10-17T14:18:48Z thinkpad: 4.50 5.12 7.75 | macmini (bots): { 77.67 71.11 64.75 } +2026-10-17T14:19:18Z thinkpad: 3.76 4.88 7.58 | macmini (bots): { 77.29 71.67 65.17 } +2026-10-17T14:19:48Z thinkpad: 3.68 4.75 7.45 | macmini (bots): { 71.16 70.71 65.05 } +2026-10-17T14:20:18Z thinkpad: 4.25 4.82 7.39 | macmini (bots): { 66.97 69.63 64.85 } +2026-10-17T14:20:49Z thinkpad: 4.72 4.89 7.33 | macmini (bots): { 59.23 67.50 64.24 } +2026-10-17T14:21:19Z thinkpad: 5.12 4.98 7.28 | macmini (bots): { 52.38 65.10 63.48 } +2026-10-17T14:21:49Z thinkpad: 5.69 5.13 7.26 | macmini (bots): { 59.43 65.53 63.69 } +2026-10-17T14:22:19Z thinkpad: 5.78 5.19 7.21 | macmini (bots): { 62.28 65.65 63.80 } +2026-10-17T14:22:50Z thinkpad: 5.34 5.14 7.13 | macmini (bots): { 57.40 64.12 63.30 } +2026-10-17T14:23:20Z thinkpad: 4.89 5.04 7.03 | macmini (bots): { 58.39 63.61 63.14 } +2026-10-17T14:23:50Z thinkpad: 5.00 5.07 6.98 | macmini (bots): { 64.88 64.63 63.52 } +2026-10-17T14:24:20Z thinkpad: 3.88 4.80 6.83 | macmini (bots): { 80.70 68.30 64.88 } +2026-10-17T14:24:51Z thinkpad: 2.90 4.47 6.65 | macmini (bots): { 94.09 72.75 66.61 } +2026-10-17T14:25:21Z thinkpad: 2.63 4.25 6.51 | macmini (bots): { 93.13 74.91 67.63 } +2026-10-17T14:25:51Z thinkpad: 6.66 5.07 6.71 | macmini (bots): { 72.87 71.72 66.72 } +2026-10-17T14:26:21Z thinkpad: 7.15 5.34 6.74 | macmini (bots): { 67.03 70.37 66.40 } +2026-10-17T14:26:51Z thinkpad: 6.20 5.29 6.68 | macmini (bots): { 58.68 68.08 65.71 } +2026-10-17T14:27:22Z thinkpad: 6.11 5.35 6.66 | macmini (bots): { 55.26 66.28 65.14 } +2026-10-17T14:27:52Z thinkpad: 5.45 5.26 6.59 | macmini (bots): { 56.51 65.74 64.99 } +2026-10-17T14:28:22Z thinkpad: 6.11 5.45 6.61 | macmini (bots): { 52.24 63.77 64.30 } +2026-10-17T14:28:52Z thinkpad: 6.06 5.50 6.59 | macmini (bots): { 55.56 63.38 64.13 } +2026-10-17T14:29:23Z thinkpad: 6.11 5.58 6.58 | macmini (bots): { 59.66 63.63 64.20 } +2026-10-17T14:29:53Z thinkpad: 5.52 5.54 6.53 | macmini (bots): { 63.71 64.30 64.42 } +2026-10-17T14:30:23Z thinkpad: 4.79 5.35 6.43 | macmini (bots): { 69.84 65.61 64.89 } +2026-10-17T14:30:53Z thinkpad: 6.21 5.63 6.49 | macmini (bots): { 62.76 64.46 64.50 } +2026-10-17T14:31:23Z thinkpad: 8.36 6.21 6.66 | macmini (bots): { 53.51 62.09 63.64 } +2026-10-17T14:31:54Z thinkpad: 8.49 6.45 6.72 | macmini (bots): { 52.80 60.98 63.18 } +2026-10-17T14:32:24Z thinkpad: 8.28 6.59 6.77 | macmini (bots): { 48.98 59.20 62.45 } +2026-10-17T14:32:54Z thinkpad: 8.02 6.70 6.79 | macmini (bots): { 48.95 58.30 62.02 } +2026-10-17T14:33:25Z thinkpad: 7.02 6.59 6.76 | macmini (bots): { 51.06 57.70 61.66 } +2026-10-17T14:33:55Z thinkpad: 7.09 6.62 6.76 | macmini (bots): { 70.89 61.81 63.00 } +2026-10-17T14:34:25Z thinkpad: 6.18 6.44 6.69 | macmini (bots): { 69.38 62.46 63.21 } +2026-10-17T14:34:55Z thinkpad: 6.67 6.52 6.72 | macmini (bots): { 76.87 64.84 64.04 } +2026-10-17T14:35:25Z thinkpad: 4.76 6.08 6.56 | macmini (bots): { 86.19 68.04 65.21 } +2026-10-17T14:35:56Z thinkpad: 3.47 5.64 6.40 | macmini (bots): { 101.03 73.28 67.21 } +2026-10-17T14:36:26Z thinkpad: 2.68 5.24 6.24 | macmini (bots): { 106.05 77.09 68.79 } +2026-10-17T14:36:56Z thinkpad: 2.41 4.91 6.10 | macmini (bots): { 107.57 80.20 70.20 } +2026-10-17T14:37:26Z thinkpad: 3.74 4.99 6.08 | macmini (bots): { 101.16 81.38 70.98 } +2026-10-17T14:37:57Z thinkpad: 5.96 5.39 6.18 | macmini (bots): { 86.51 79.61 70.70 } +2026-10-17T14:38:27Z thinkpad: 7.91 5.98 6.35 | macmini (bots): { 81.13 79.06 70.81 } +2026-10-17T14:38:57Z thinkpad: 8.45 6.25 6.43 | macmini (bots): { 79.56 79.01 71.08 } +2026-10-17T14:39:27Z thinkpad: 8.75 6.52 6.52 | macmini (bots): { 71.92 77.22 70.71 } +2026-10-17T14:39:58Z thinkpad: 8.86 6.76 6.60 | macmini (bots): { 71.38 76.58 70.70 } +2026-10-17T14:40:28Z thinkpad: 8.74 6.98 6.68 | macmini (bots): { 71.25 76.12 70.74 } +2026-10-17T14:40:58Z thinkpad: 7.99 6.96 6.68 | macmini (bots): { 70.49 75.51 70.71 } +2026-10-17T14:41:28Z thinkpad: 7.64 7.01 6.70 | macmini (bots): { 68.93 74.58 70.56 } +2026-10-17T14:41:59Z thinkpad: 6.57 6.84 6.66 | macmini (bots): { 68.35 73.75 70.39 } +2026-10-17T14:42:29Z thinkpad: 5.83 6.62 6.59 | macmini (bots): { 63.57 72.20 69.95 } +2026-10-17T14:42:59Z thinkpad: 7.40 6.91 6.69 | macmini (bots): { 56.77 69.69 69.12 } +2026-10-17T14:43:29Z thinkpad: 9.07 7.37 6.85 | macmini (bots): { 49.53 66.71 68.06 } +2026-10-17T14:44:00Z thinkpad: 9.39 7.63 6.96 | macmini (bots): { 43.53 63.68 66.91 } +2026-10-17T14:44:30Z thinkpad: 9.16 7.73 7.01 | macmini (bots): { 41.12 61.23 65.92 } +2026-10-17T14:45:00Z thinkpad: 7.96 7.57 6.98 | macmini (bots): { 40.62 59.23 65.03 } +2026-10-17T14:45:30Z thinkpad: 6.34 7.24 6.89 | macmini (bots): { 38.17 56.80 63.94 } +2026-10-17T14:46:01Z thinkpad: 6.39 7.18 6.88 | macmini (bots): { 40.35 55.54 63.24 } +2026-10-17T14:46:31Z thinkpad: 5.63 6.95 6.82 | macmini (bots): { 48.66 56.25 63.24 } +2026-10-17T14:47:01Z thinkpad: 4.73 6.60 6.70 | macmini (bots): { 46.68 55.20 62.62 } +2026-10-17T14:47:31Z thinkpad: 9.18 7.55 7.02 | macmini (bots): { 41.45 53.19 61.64 } +2026-10-17T14:48:01Z thinkpad: 10.40 8.02 7.19 | macmini (bots): { 40.76 51.87 60.87 } +2026-10-17T14:48:32Z thinkpad: 8.24 7.73 7.12 | macmini (bots): { 44.46 51.67 60.48 } +2026-10-17T14:49:02Z thinkpad: 9.60 8.09 7.26 | macmini (bots): { 38.75 49.66 59.45 } +2026-10-17T14:49:32Z thinkpad: 8.90 8.10 7.29 | macmini (bots): { 34.93 47.72 58.41 } +2026-10-17T14:50:02Z thinkpad: 11.17 8.66 7.50 | macmini (bots): { 35.70 46.68 57.66 } +2026-10-17T14:50:33Z thinkpad: 12.06 9.19 7.72 | macmini (bots): { 43.94 47.43 57.54 } +2026-10-17T14:51:03Z thinkpad: 12.50 9.49 7.87 | macmini (bots): { 40.76 46.36 56.80 } +2026-10-17T14:51:33Z thinkpad: 10.35 9.24 7.83 | macmini (bots): { 44.81 46.69 56.55 } +2026-10-17T14:52:03Z thinkpad: 9.32 9.09 7.83 | macmini (bots): { 54.94 48.97 57.04 } +2026-10-17T14:52:34Z thinkpad: 7.07 8.58 7.70 | macmini (bots): { 54.59 49.54 56.92 } +2026-10-17T14:53:04Z thinkpad: 5.33 8.01 7.54 | macmini (bots): { 67.48 53.27 58.02 } +2026-10-17T14:53:34Z thinkpad: 7.22 8.20 7.62 | macmini (bots): { 57.82 52.33 57.52 } +2026-10-17T14:54:04Z thinkpad: 9.69 8.73 7.81 | macmini (bots): { 46.67 50.20 56.57 } +2026-10-17T14:54:35Z thinkpad: 9.14 8.66 7.82 | macmini (bots): { 49.88 50.61 56.49 } +2026-10-17T14:55:05Z thinkpad: 9.75 8.87 7.91 | macmini (bots): { 46.88 49.95 56.06 } +2026-10-17T14:55:35Z thinkpad: 8.51 8.67 7.88 | macmini (bots): { 42.90 48.80 55.43 } +2026-10-17T14:56:06Z thinkpad: 8.46 8.62 7.89 | macmini (bots): { 49.23 49.72 55.53 } +2026-10-17T14:56:36Z thinkpad: 6.19 8.07 7.73 | macmini (bots): { 54.41 50.86 55.74 } +2026-10-17T14:57:06Z thinkpad: 4.69 7.53 7.56 | macmini (bots): { 60.26 52.69 56.24 } +2026-10-17T14:57:36Z thinkpad: 3.21 6.90 7.35 | macmini (bots): { 67.66 55.21 57.03 } +2026-10-17T14:58:06Z thinkpad: 1.94 6.24 7.11 | macmini (bots): { 75.73 58.41 58.13 } +2026-10-17T14:58:37Z thinkpad: 1.18 5.64 6.89 | macmini (bots): { 74.69 59.90 58.68 } +2026-10-17T14:59:07Z thinkpad: 0.78 5.12 6.67 | macmini (bots): { 77.10 61.82 59.42 } +2026-10-17T14:59:37Z thinkpad: 0.88 4.72 6.49 | macmini (bots): { 87.05 65.59 60.86 } +2026-10-17T15:00:07Z thinkpad: 0.53 4.27 6.28 | macmini (bots): { 78.18 65.51 60.99 } +2026-10-17T15:00:38Z thinkpad: 0.38 3.88 6.09 | macmini (bots): { 79.38 67.00 61.69 } +2026-10-17T15:01:08Z thinkpad: 1.50 3.80 5.99 | macmini (bots): { 78.36 67.86 62.18 } +2026-10-17T15:01:38Z thinkpad: 2.97 3.93 5.95 | macmini (bots): { 74.18 67.90 62.39 } +2026-10-17T15:02:08Z thinkpad: 2.61 3.77 5.83 | macmini (bots): { 68.63 67.00 62.25 } +2026-10-17T15:02:39Z thinkpad: 2.10 3.55 5.69 | macmini (bots): { 69.84 67.50 62.60 } +2026-10-17T15:03:09Z thinkpad: 1.44 3.25 5.53 | macmini (bots): { 67.10 67.06 62.61 } +2026-10-17T15:03:39Z thinkpad: 1.39 3.08 5.40 | macmini (bots): { 60.83 65.50 62.19 } +2026-10-17T15:04:09Z thinkpad: 1.28 2.88 5.26 | macmini (bots): { 75.40 68.61 63.46 } +2026-10-17T15:04:40Z thinkpad: 2.30 2.99 5.22 | macmini (bots): { 106.08 76.54 66.50 } +2026-10-17T15:05:10Z thinkpad: 2.65 3.02 5.15 | macmini (bots): { 111.96 81.09 68.52 } +2026-10-17T15:05:40Z thinkpad: 2.41 2.92 5.05 | macmini (bots): { 104.19 82.08 69.31 } +2026-10-17T15:06:10Z thinkpad: 2.71 2.95 4.99 | macmini (bots): { 116.20 87.04 71.54 } +2026-10-17T15:06:40Z thinkpad: 2.51 2.87 4.90 | macmini (bots): { 136.68 94.24 74.66 } +2026-10-17T15:07:11Z thinkpad: 3.68 3.11 4.91 | macmini (bots): { 132.76 97.43 76.50 } +2026-10-17T15:07:41Z thinkpad: 3.77 3.19 4.88 | macmini (bots): { 132.73 100.97 78.51 } +2026-10-17T15:08:11Z thinkpad: 3.00 3.06 4.79 | macmini (bots): { 116.92 100.33 79.07 } +2026-10-17T15:08:41Z thinkpad: 2.40 2.91 4.68 | macmini (bots): { 109.83 100.07 79.70 } +2026-10-17T15:09:12Z thinkpad: 2.18 2.81 4.59 | macmini (bots): { 113.21 101.71 81.00 } +2026-10-17T15:09:42Z thinkpad: 1.67 2.62 4.47 | macmini (bots): { 131.87 107.11 83.66 } +2026-10-17T15:10:12Z thinkpad: 1.90 2.58 4.39 | macmini (bots): { 133.45 109.92 85.49 } +2026-10-17T15:10:42Z thinkpad: 4.00 3.02 4.48 | macmini (bots): { 130.14 111.67 86.99 } +2026-10-17T15:11:13Z thinkpad: 4.77 3.32 4.54 | macmini (bots): { 118.78 110.28 87.32 } +2026-10-17T15:11:43Z thinkpad: 3.86 3.24 4.47 | macmini (bots): { 124.01 112.36 88.87 } +2026-10-17T15:12:13Z thinkpad: 3.61 3.26 4.44 | macmini (bots): { 122.21 112.94 89.88 } +2026-10-17T15:12:43Z thinkpad: 3.12 3.17 4.36 | macmini (bots): { 111.62 111.10 90.00 } +2026-10-17T15:13:14Z thinkpad: 3.07 3.14 4.31 | macmini (bots): { 122.97 113.95 91.77 } +2026-10-17T15:13:44Z thinkpad: 3.33 3.20 4.30 | macmini (bots): { 102.64 109.89 91.07 } +2026-10-17T15:14:14Z thinkpad: 2.85 3.10 4.23 | macmini (bots): { 94.46 107.15 90.72 } +2026-10-17T15:14:44Z thinkpad: 2.66 3.03 4.17 | macmini (bots): { 94.94 106.07 90.90 } +2026-10-17T15:15:14Z thinkpad: 2.54 2.96 4.11 | macmini (bots): { 94.52 104.93 91.01 } +2026-10-17T15:15:45Z thinkpad: 3.20 3.08 4.11 | macmini (bots): { 84.00 101.47 90.25 } +2026-10-17T15:16:15Z thinkpad: 5.56 3.61 4.25 | macmini (bots): { 83.16 99.76 90.02 } +2026-10-17T15:16:45Z thinkpad: 5.66 3.84 4.30 | macmini (bots): { 69.71 94.66 88.56 } +2026-10-17T15:17:15Z thinkpad: 5.04 3.90 4.31 | macmini (bots): { 59.31 89.78 87.00 } +2026-10-17T15:17:46Z thinkpad: 4.29 3.87 4.29 | macmini (bots): { 58.57 86.47 85.89 } +2026-10-17T15:18:16Z thinkpad: 4.16 3.91 4.29 | macmini (bots): { 56.43 83.29 84.75 } +2026-10-17T15:18:46Z thinkpad: 2.80 3.60 4.18 | macmini (bots): { 50.60 79.22 83.22 } +2026-10-17T15:19:16Z thinkpad: 1.85 3.28 4.05 | macmini (bots): { 54.97 77.50 82.46 } +2026-10-17T15:19:47Z thinkpad: 1.82 3.14 3.98 | macmini (bots): { 56.82 75.80 81.67 } +2026-10-17T15:20:17Z thinkpad: 2.19 3.10 3.94 | macmini (bots): { 59.30 74.46 80.97 } +2026-10-17T15:20:47Z thinkpad: 4.44 3.54 4.06 | macmini (bots): { 55.22 72.11 79.90 } +2026-10-17T15:21:17Z thinkpad: 5.99 4.03 4.21 | macmini (bots): { 49.41 69.01 78.50 } +2026-10-17T15:21:48Z thinkpad: 4.85 3.95 4.18 | macmini (bots): { 46.89 66.58 77.29 } +2026-10-17T15:22:18Z thinkpad: 4.31 3.92 4.16 | macmini (bots): { 45.13 64.31 76.10 } +2026-10-17T15:22:48Z thinkpad: 4.28 3.95 4.16 | macmini (bots): { 51.82 63.98 75.56 } +2026-10-17T15:23:18Z thinkpad: 4.75 4.11 4.21 | macmini (bots): { 50.35 62.51 74.63 } +2026-10-17T15:23:48Z thinkpad: 4.08 4.02 4.17 | macmini (bots): { 44.62 60.01 73.31 } +2026-10-17T15:24:19Z thinkpad: 3.93 4.00 4.16 | macmini (bots): { 46.02 58.72 72.37 } +2026-10-17T15:24:49Z thinkpad: 3.67 3.92 4.13 | macmini (bots): { 47.23 57.90 71.60 } +2026-10-17T15:25:19Z thinkpad: 2.79 3.68 4.04 | macmini (bots): { 50.80 57.78 71.09 } +2026-10-17T15:25:49Z thinkpad: 2.79 3.58 3.99 | macmini (bots): { 47.66 56.35 70.11 } +2026-10-17T15:26:19Z thinkpad: 5.04 3.97 4.11 | macmini (bots): { 45.15 54.84 69.08 } +2026-10-17T15:26:50Z thinkpad: 8.46 4.86 4.40 | macmini (bots): { 43.59 53.51 68.10 } +2026-10-17T15:27:20Z thinkpad: 6.84 4.81 4.39 | macmini (bots): { 42.38 52.39 67.19 } +2026-10-17T15:27:50Z thinkpad: 8.24 5.33 4.58 | macmini (bots): { 49.87 53.02 66.82 } +2026-10-17T15:28:21Z thinkpad: 7.11 5.34 4.61 | macmini (bots): { 61.30 55.60 67.28 } +2026-10-17T15:28:51Z thinkpad: 6.11 5.27 4.61 | macmini (bots): { 67.60 57.74 67.66 } +2026-10-17T15:29:21Z thinkpad: 5.33 5.17 4.59 | macmini (bots): { 63.72 57.79 67.33 } +2026-10-17T15:29:51Z thinkpad: 3.57 4.75 4.47 | macmini (bots): { 60.80 57.62 66.94 } +2026-10-17T15:30:22Z thinkpad: 4.74 4.88 4.52 | macmini (bots): { 59.69 57.64 66.62 } +2026-10-17T15:30:52Z thinkpad: 3.44 4.54 4.42 | macmini (bots): { 66.89 59.49 66.97 } +2026-10-17T15:31:22Z thinkpad: 4.57 4.69 4.47 | macmini (bots): { 83.43 64.16 68.40 } +2026-10-17T15:31:52Z thinkpad: 7.17 5.30 4.68 | macmini (bots): { 77.62 64.77 68.49 } +2026-10-17T15:32:23Z thinkpad: 8.55 5.82 4.88 | macmini (bots): { 74.20 65.09 68.47 } +2026-10-17T15:32:53Z thinkpad: 7.49 5.85 4.92 | macmini (bots): { 82.07 67.70 69.29 } +2026-10-17T15:33:23Z thinkpad: 5.65 5.59 4.86 | macmini (bots): { 79.44 68.47 69.51 } +2026-10-17T15:33:54Z thinkpad: 5.73 5.64 4.91 | macmini (bots): { 78.94 69.26 69.76 } +2026-10-17T15:34:24Z thinkpad: 6.84 5.92 5.02 | macmini (bots): { 76.33 69.71 69.91 } +2026-10-17T15:34:54Z thinkpad: 5.11 5.59 4.94 | macmini (bots): { 86.09 72.63 70.95 } +2026-10-17T15:35:24Z thinkpad: 6.68 5.93 5.08 | macmini (bots): { 72.77 70.70 70.31 } +2026-10-17T15:35:55Z thinkpad: 5.75 5.75 5.04 | macmini (bots): { 71.50 70.49 70.24 } +2026-10-17T15:36:25Z thinkpad: 4.31 5.41 4.95 | macmini (bots): { 80.75 72.67 71.03 } +2026-10-17T15:36:55Z thinkpad: 3.15 5.02 4.83 | macmini (bots): { 89.83 75.59 72.14 } diff --git a/benchmarks/server-2026-10-17/earlier-002f14ce/walk-explore.json b/benchmarks/server-2026-10-17/earlier-002f14ce/walk-explore.json new file mode 100644 index 000000000..39dcd268c --- /dev/null +++ b/benchmarks/server-2026-10-17/earlier-002f14ce/walk-explore.json @@ -0,0 +1,695 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T14:56:24+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "a9ee56a8b143999c9bc7056850ffcd622a9214aa", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon,vanilla", + "bots": "1,10,25,50,100", + "behaviour": "walk,explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 180, + "seed": 12345, + "explore_speed": 0, + "gamerule": "", + "heap": "4g", + "out": "/home/ludovic/code/horizon/.claude/worktrees/server-host-4/.local/bench-out/walk-explore.json", + "nice": 19, + "bots_via": "ssh macmini", + "bots_bin": "/Users/ludovicmarie/code/horizon/.claude/worktrees/server-host-4/target/release/horizon-bots", + "connect": "", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "walk", + "start_seconds": 9.51, + "mspt": { + "average": 5.77, + "p50": 5.15, + "p95": 11.04, + "p99": 28.99 + }, + "mspt_worst_p99": 45.9, + "tps": 20.0, + "rss_mb": { + "mean": 777.78, + "max": 779.8 + }, + "cpu_percent": 59.02, + "chunks_per_second": 9.94, + "unique_per_second": 0.45, + "forgotten_per_second": 9.99, + "waited_ticks_per_second": 0.0, + "chunks_total": 2763, + "chunks_per_bot": { + "walk": 2763.0 + }, + "unique_chunks_per_bot": { + "walk": 697.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "walk", + "start_seconds": 15.35, + "mspt": { + "average": 18.84, + "p50": 18.87, + "p95": 29.55, + "p99": 51.32 + }, + "mspt_worst_p99": 456.4, + "tps": 20.0, + "rss_mb": { + "mean": 3442.06, + "max": 3462.1 + }, + "cpu_percent": 70.63, + "chunks_per_second": 10.47, + "unique_per_second": 0.47, + "forgotten_per_second": 10.53, + "waited_ticks_per_second": 0.0, + "chunks_total": 2763, + "chunks_per_bot": { + "walk": 2763.0 + }, + "unique_chunks_per_bot": { + "walk": 697.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "walk", + "start_seconds": 9.31, + "mspt": { + "average": 16.23, + "p50": 15.6, + "p95": 29.32, + "p99": 44.43 + }, + "mspt_worst_p99": 100.6, + "tps": 20.0, + "rss_mb": { + "mean": 781.84, + "max": 782.6 + }, + "cpu_percent": 136.59, + "chunks_per_second": 93.82, + "unique_per_second": 3.33, + "forgotten_per_second": 93.61, + "waited_ticks_per_second": 0.0, + "chunks_total": 26481, + "chunks_per_bot": { + "walk": 2648.1 + }, + "unique_chunks_per_bot": { + "walk": 679.5 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "walk", + "start_seconds": 14.65, + "mspt": { + "average": 18.02, + "p50": 15.22, + "p95": 37.62, + "p99": 54.5 + }, + "mspt_worst_p99": 73.8, + "tps": 20.0, + "rss_mb": { + "mean": 3408.62, + "max": 3423.6 + }, + "cpu_percent": 100.57, + "chunks_per_second": 101.12, + "unique_per_second": 4.25, + "forgotten_per_second": 101.17, + "waited_ticks_per_second": 0.0, + "chunks_total": 26763, + "chunks_per_bot": { + "walk": 2676.3 + }, + "unique_chunks_per_bot": { + "walk": 687.8 + }, + "resent": 0, + "pulled_back": 7, + "moved_too_quickly": 7, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "walk", + "start_seconds": 9.31, + "mspt": { + "average": 23.98, + "p50": 20.89, + "p95": 49.18, + "p99": 65.87 + }, + "mspt_worst_p99": 109.8, + "tps": 20.0, + "rss_mb": { + "mean": 786.18, + "max": 786.5 + }, + "cpu_percent": 159.81, + "chunks_per_second": 235.75, + "unique_per_second": 7.84, + "forgotten_per_second": 235.72, + "waited_ticks_per_second": 0.0, + "chunks_total": 67251, + "chunks_per_bot": { + "walk": 2690.04 + }, + "unique_chunks_per_bot": { + "walk": 683.92 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "walk", + "start_seconds": 14.95, + "mspt": { + "average": 19.19, + "p50": 17.34, + "p95": 33.84, + "p99": 56.21 + }, + "mspt_worst_p99": 79.2, + "tps": 20.0, + "rss_mb": { + "mean": 3531.46, + "max": 3582.1 + }, + "cpu_percent": 153.78, + "chunks_per_second": 252.35, + "unique_per_second": 11.73, + "forgotten_per_second": 251.58, + "waited_ticks_per_second": 0.0, + "chunks_total": 66759, + "chunks_per_bot": { + "walk": 2670.36 + }, + "unique_chunks_per_bot": { + "walk": 689.76 + }, + "resent": 0, + "pulled_back": 12, + "moved_too_quickly": 12, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "walk", + "start_seconds": 9.21, + "mspt": { + "average": 35.07, + "p50": 30.55, + "p95": 73.24, + "p99": 99.38 + }, + "mspt_worst_p99": 117.2, + "tps": 20.0, + "rss_mb": { + "mean": 816.58, + "max": 818.5 + }, + "cpu_percent": 187.42, + "chunks_per_second": 469.11, + "unique_per_second": 15.92, + "forgotten_per_second": 468.62, + "waited_ticks_per_second": 0.0, + "chunks_total": 136962, + "chunks_per_bot": { + "walk": 2739.24 + }, + "unique_chunks_per_bot": { + "walk": 685.68 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "walk", + "start_seconds": 15.95, + "mspt": { + "average": 35.23, + "p50": 31.39, + "p95": 60.87, + "p99": 104.2 + }, + "mspt_worst_p99": 443.7, + "tps": 20.0, + "rss_mb": { + "mean": 3562.57, + "max": 3598.9 + }, + "cpu_percent": 263.27, + "chunks_per_second": 497.51, + "unique_per_second": 30.67, + "forgotten_per_second": 495.7, + "waited_ticks_per_second": 0.0, + "chunks_total": 131116, + "chunks_per_bot": { + "walk": 2622.32 + }, + "unique_chunks_per_bot": { + "walk": 687.78 + }, + "resent": 0, + "pulled_back": 96, + "moved_too_quickly": 96, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "walk", + "start_seconds": 9.21, + "mspt": { + "average": 104.8, + "p50": 100.6, + "p95": 158.8, + "p99": 198.61 + }, + "mspt_worst_p99": 259.8, + "tps": 9.54, + "rss_mb": { + "mean": 850.05, + "max": 851.2 + }, + "cpu_percent": 198.95, + "chunks_per_second": 371.72, + "unique_per_second": 26.27, + "forgotten_per_second": 365.57, + "waited_ticks_per_second": 0.0, + "chunks_total": 144465, + "chunks_per_bot": { + "walk": 1444.65 + }, + "unique_chunks_per_bot": { + "walk": 571.76 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 34 + }, + { + "server": "vanilla", + "bots": 100, + "behaviour": "walk", + "start_seconds": 15.25, + "error": "[Errno 32] Broken pipe" + }, + { + "server": "horizon", + "bots": 1, + "behaviour": "explore", + "start_seconds": 9.41, + "mspt": { + "average": 11.42, + "p50": 10.15, + "p95": 24.66, + "p99": 37.27 + }, + "mspt_worst_p99": 60.3, + "tps": 20.0, + "rss_mb": { + "mean": 838.61, + "max": 888.0 + }, + "cpu_percent": 326.85, + "chunks_per_second": 41.83, + "unique_per_second": 36.39, + "forgotten_per_second": 41.75, + "waited_ticks_per_second": 0.0, + "chunks_total": 9845, + "chunks_per_bot": { + "explore": 9845.0 + }, + "unique_chunks_per_bot": { + "explore": 8718.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "explore", + "start_seconds": 15.44, + "mspt": { + "average": 9.83, + "p50": 7.72, + "p95": 20.36, + "p99": 84.65 + }, + "mspt_worst_p99": 385.9, + "tps": 20.0, + "rss_mb": { + "mean": 3598.02, + "max": 3658.9 + }, + "cpu_percent": 244.86, + "chunks_per_second": 35.28, + "unique_per_second": 33.34, + "forgotten_per_second": 35.13, + "waited_ticks_per_second": 0.0, + "chunks_total": 7881, + "chunks_per_bot": { + "explore": 7881.0 + }, + "unique_chunks_per_bot": { + "explore": 7540.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "explore", + "start_seconds": 9.52, + "mspt": { + "average": 23.54, + "p50": 21.18, + "p95": 43.4, + "p99": 60.85 + }, + "mspt_worst_p99": 109.1, + "tps": 20.0, + "rss_mb": { + "mean": 1139.51, + "max": 1301.0 + }, + "cpu_percent": 331.74, + "chunks_per_second": 43.86, + "unique_per_second": 43.09, + "forgotten_per_second": 43.82, + "waited_ticks_per_second": 172.35, + "chunks_total": 14140, + "chunks_per_bot": { + "explore": 1414.0 + }, + "unique_chunks_per_bot": { + "explore": 1395.9 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "explore", + "start_seconds": 15.78, + "mspt": { + "average": 16.42, + "p50": 14.01, + "p95": 30.29, + "p99": 96.17 + }, + "mspt_worst_p99": 1144.3, + "tps": 20.0, + "rss_mb": { + "mean": 3964.49, + "max": 4248.3 + }, + "cpu_percent": 256.86, + "chunks_per_second": 25.43, + "unique_per_second": 25.33, + "forgotten_per_second": 25.96, + "waited_ticks_per_second": 76.05, + "chunks_total": 7991, + "chunks_per_bot": { + "explore": 799.1 + }, + "unique_chunks_per_bot": { + "explore": 797.7 + }, + "resent": 0, + "pulled_back": 11028, + "moved_too_quickly": 17, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "explore", + "start_seconds": 9.31, + "mspt": { + "average": 36.87, + "p50": 33.92, + "p95": 63.19, + "p99": 84.17 + }, + "mspt_worst_p99": 124.2, + "tps": 20.0, + "rss_mb": { + "mean": 1236.2, + "max": 1438.4 + }, + "cpu_percent": 345.03, + "chunks_per_second": 91.07, + "unique_per_second": 88.7, + "forgotten_per_second": 92.51, + "waited_ticks_per_second": 443.88, + "chunks_total": 30035, + "chunks_per_bot": { + "explore": 1201.4 + }, + "unique_chunks_per_bot": { + "explore": 1176.84 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "explore", + "start_seconds": 14.55, + "mspt": { + "average": 24.31, + "p50": 21.76, + "p95": 36.55, + "p99": 155.88 + }, + "mspt_worst_p99": 1535.8, + "tps": 20.0, + "rss_mb": { + "mean": 4047.76, + "max": 4459.2 + }, + "cpu_percent": 305.24, + "chunks_per_second": 37.94, + "unique_per_second": 37.82, + "forgotten_per_second": 38.87, + "waited_ticks_per_second": 261.79, + "chunks_total": 16604, + "chunks_per_bot": { + "explore": 664.16 + }, + "unique_chunks_per_bot": { + "explore": 660.92 + }, + "resent": 0, + "pulled_back": 33246, + "moved_too_quickly": 20, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "explore", + "start_seconds": 9.21, + "mspt": { + "average": 60.06, + "p50": 57.31, + "p95": 88.38, + "p99": 112.89 + }, + "mspt_worst_p99": 172.4, + "tps": 16.65, + "rss_mb": { + "mean": 1192.47, + "max": 1372.5 + }, + "cpu_percent": 362.42, + "chunks_per_second": 157.28, + "unique_per_second": 154.2, + "forgotten_per_second": 156.07, + "waited_ticks_per_second": 890.09, + "chunks_total": 54551, + "chunks_per_bot": { + "explore": 1091.02 + }, + "unique_chunks_per_bot": { + "explore": 1078.5 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "explore", + "start_seconds": 15.64, + "error": "[Errno 32] Broken pipe" + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "explore", + "start_seconds": 9.21, + "mspt": { + "average": 124.25, + "p50": 120.1, + "p95": 168.33, + "p99": 204.64 + }, + "mspt_worst_p99": 262.2, + "tps": 8.05, + "rss_mb": { + "mean": 1283.26, + "max": 1418.6 + }, + "cpu_percent": 334.14, + "chunks_per_second": 185.47, + "unique_per_second": 184.54, + "forgotten_per_second": 179.79, + "waited_ticks_per_second": 1864.45, + "chunks_total": 78556, + "chunks_per_bot": { + "explore": 785.56 + }, + "unique_chunks_per_bot": { + "explore": 784.88 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 100, + "behaviour": "explore", + "start_seconds": 15.44, + "error": "[Errno 32] Broken pipe" + } + ] +} diff --git a/benchmarks/server-2026-10-17/explore-equal-rate.json b/benchmarks/server-2026-10-17/explore-equal-rate.json new file mode 100644 index 000000000..1356529e3 --- /dev/null +++ b/benchmarks/server-2026-10-17/explore-equal-rate.json @@ -0,0 +1,341 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T18:12:19+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "7bbbf6e97fb53683eae0a01ce2c134e53cb649a7", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon,vanilla", + "bots": "1,10,25,50", + "behaviour": "explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 180, + "seed": 12345, + "explore_speed": 0.8, + "gamerule": "", + "heap": "4g", + "out": "/home/ludovic/code/horizon/.claude/worktrees/server-host-4/.local/bench-out/explore-equal-rate.json", + "nice": 19, + "bots_via": "ssh macmini", + "bots_bin": "/Users/ludovicmarie/code/horizon/.claude/worktrees/server-host-4/target/release/horizon-bots", + "connect": "", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "explore", + "start_seconds": 9.42, + "mspt": { + "average": 3.16, + "p50": 2.98, + "p95": 5.78, + "p99": 12.17 + }, + "mspt_worst_p99": 38.1, + "tps": 20.0, + "rss_mb": { + "mean": 759.26, + "max": 769.5 + }, + "cpu_percent": 21.74, + "chunks_per_second": 1.64, + "unique_per_second": 1.27, + "forgotten_per_second": 1.54, + "waited_ticks_per_second": 0.0, + "chunks_total": 841, + "chunks_per_bot": { + "explore": 841.0 + }, + "unique_chunks_per_bot": { + "explore": 781.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "explore", + "start_seconds": 17.17, + "mspt": { + "average": 16.82, + "p50": 16.67, + "p95": 27.3, + "p99": 52.16 + }, + "mspt_worst_p99": 453.4, + "tps": 20.0, + "rss_mb": { + "mean": 3373.16, + "max": 3405.9 + }, + "cpu_percent": 69.22, + "chunks_per_second": 1.66, + "unique_per_second": 1.35, + "forgotten_per_second": 1.54, + "waited_ticks_per_second": 0.0, + "chunks_total": 838, + "chunks_per_bot": { + "explore": 838.0 + }, + "unique_chunks_per_bot": { + "explore": 779.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "explore", + "start_seconds": 9.82, + "mspt": { + "average": 9.83, + "p50": 8.65, + "p95": 19.01, + "p99": 32.9 + }, + "mspt_worst_p99": 64.0, + "tps": 20.0, + "rss_mb": { + "mean": 861.49, + "max": 922.2 + }, + "cpu_percent": 77.43, + "chunks_per_second": 13.71, + "unique_per_second": 12.31, + "forgotten_per_second": 13.59, + "waited_ticks_per_second": 0.0, + "chunks_total": 7831, + "chunks_per_bot": { + "explore": 783.1 + }, + "unique_chunks_per_bot": { + "explore": 757.1 + }, + "resent": 0, + "pulled_back": 1051, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "explore", + "start_seconds": 15.06, + "mspt": { + "average": 24.38, + "p50": 21.55, + "p95": 39.58, + "p99": 66.64 + }, + "mspt_worst_p99": 107.1, + "tps": 20.0, + "rss_mb": { + "mean": 3569.41, + "max": 3685.1 + }, + "cpu_percent": 132.09, + "chunks_per_second": 13.54, + "unique_per_second": 12.32, + "forgotten_per_second": 13.62, + "waited_ticks_per_second": 0.0, + "chunks_total": 7753, + "chunks_per_bot": { + "explore": 775.3 + }, + "unique_chunks_per_bot": { + "explore": 749.2 + }, + "resent": 0, + "pulled_back": 1027, + "moved_too_quickly": 6, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "explore", + "start_seconds": 9.31, + "mspt": { + "average": 16.87, + "p50": 15.4, + "p95": 30.88, + "p99": 46.73 + }, + "mspt_worst_p99": 84.9, + "tps": 20.0, + "rss_mb": { + "mean": 887.11, + "max": 945.5 + }, + "cpu_percent": 111.2, + "chunks_per_second": 33.51, + "unique_per_second": 29.92, + "forgotten_per_second": 33.33, + "waited_ticks_per_second": 0.0, + "chunks_total": 19718, + "chunks_per_bot": { + "explore": 788.72 + }, + "unique_chunks_per_bot": { + "explore": 759.08 + }, + "resent": 0, + "pulled_back": 3770, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "explore", + "start_seconds": 14.94, + "mspt": { + "average": 30.29, + "p50": 28.25, + "p95": 43.47, + "p99": 68.56 + }, + "mspt_worst_p99": 165.2, + "tps": 20.0, + "rss_mb": { + "mean": 3608.97, + "max": 3732.0 + }, + "cpu_percent": 176.28, + "chunks_per_second": 32.98, + "unique_per_second": 29.29, + "forgotten_per_second": 32.84, + "waited_ticks_per_second": 0.0, + "chunks_total": 19442, + "chunks_per_bot": { + "explore": 777.68 + }, + "unique_chunks_per_bot": { + "explore": 748.24 + }, + "resent": 0, + "pulled_back": 5139, + "moved_too_quickly": 11, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "explore", + "start_seconds": 9.41, + "mspt": { + "average": 23.57, + "p50": 20.43, + "p95": 47.53, + "p99": 67.23 + }, + "mspt_worst_p99": 106.2, + "tps": 20.0, + "rss_mb": { + "mean": 924.41, + "max": 984.3 + }, + "cpu_percent": 127.14, + "chunks_per_second": 66.56, + "unique_per_second": 59.42, + "forgotten_per_second": 66.43, + "waited_ticks_per_second": 0.0, + "chunks_total": 39950, + "chunks_per_bot": { + "explore": 799.0 + }, + "unique_chunks_per_bot": { + "explore": 767.56 + }, + "resent": 0, + "pulled_back": 7434, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "explore", + "start_seconds": 15.04, + "mspt": { + "average": 42.44, + "p50": 40.71, + "p95": 54.84, + "p99": 94.23 + }, + "mspt_worst_p99": 212.3, + "tps": 20.0, + "rss_mb": { + "mean": 3667.85, + "max": 3780.8 + }, + "cpu_percent": 200.85, + "chunks_per_second": 65.17, + "unique_per_second": 58.11, + "forgotten_per_second": 65.22, + "waited_ticks_per_second": 0.0, + "chunks_total": 39772, + "chunks_per_bot": { + "explore": 795.44 + }, + "unique_chunks_per_bot": { + "explore": 764.02 + }, + "resent": 0, + "pulled_back": 10604, + "moved_too_quickly": 38, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 35 + } + ] +} diff --git a/benchmarks/server-2026-10-17/load.txt b/benchmarks/server-2026-10-17/load.txt new file mode 100644 index 000000000..33d8b191f --- /dev/null +++ b/benchmarks/server-2026-10-17/load.txt @@ -0,0 +1,279 @@ +2026-10-17T15:51:54Z thinkpad: 1.30 2.47 3.85 | macmini (bots): { 67.44 76.34 77.44 } +2026-10-17T15:52:25Z thinkpad: 2.07 2.54 3.83 | macmini (bots): { 64.78 74.76 76.82 } +2026-10-17T15:52:55Z thinkpad: 2.08 2.51 3.78 | macmini (bots): { 62.50 73.29 76.22 } +2026-10-17T15:53:25Z thinkpad: 1.46 2.31 3.67 | macmini (bots): { 63.70 72.67 75.90 } +2026-10-17T15:53:55Z thinkpad: 1.12 2.15 3.58 | macmini (bots): { 69.06 73.27 76.01 } +2026-10-17T15:54:26Z thinkpad: 1.34 2.09 3.51 | macmini (bots): { 72.55 73.63 76.04 } +2026-10-17T15:54:56Z thinkpad: 1.11 1.97 3.42 | macmini (bots): { 77.53 74.77 76.37 } +2026-10-17T15:55:26Z thinkpad: 1.02 1.87 3.34 | macmini (bots): { 77.61 74.90 76.36 } +2026-10-17T15:55:56Z thinkpad: 1.09 1.81 3.27 | macmini (bots): { 71.56 73.69 75.86 } +2026-10-17T15:56:26Z thinkpad: 2.23 1.99 3.29 | macmini (bots): { 65.21 71.93 75.15 } +2026-10-17T15:56:57Z thinkpad: 2.60 2.12 3.29 | macmini (bots): { 58.16 69.40 74.10 } +2026-10-17T15:57:27Z thinkpad: 2.57 2.18 3.27 | macmini (bots): { 57.54 68.26 73.52 } +2026-10-17T15:57:57Z thinkpad: 2.37 2.17 3.23 | macmini (bots): { 56.15 66.85 72.83 } +2026-10-17T15:58:27Z thinkpad: 1.90 2.08 3.17 | macmini (bots): { 59.28 66.57 72.52 } +2026-10-17T15:58:58Z thinkpad: 1.71 2.02 3.11 | macmini (bots): { 55.64 64.94 71.72 } +2026-10-17T15:59:28Z thinkpad: 1.66 1.97 3.06 | macmini (bots): { 66.06 66.49 72.04 } +2026-10-17T15:59:58Z thinkpad: 1.18 1.83 2.98 | macmini (bots): { 78.15 69.43 72.92 } +2026-10-17T16:00:28Z thinkpad: 0.83 1.68 2.89 | macmini (bots): { 70.77 68.57 72.49 } +2026-10-17T16:00:58Z thinkpad: 1.27 1.70 2.86 | macmini (bots): { 71.95 68.97 72.49 } +2026-10-17T16:01:29Z thinkpad: 1.85 1.79 2.85 | macmini (bots): { 83.43 72.22 73.56 } +2026-10-17T16:01:59Z thinkpad: 2.51 1.95 2.86 | macmini (bots): { 70.49 70.18 72.77 } +2026-10-17T16:02:29Z thinkpad: 1.98 1.87 2.81 | macmini (bots): { 64.00 68.64 72.12 } +2026-10-17T16:02:59Z thinkpad: 1.77 1.84 2.77 | macmini (bots): { 59.65 67.09 71.44 } +2026-10-17T16:03:30Z thinkpad: 4.04 2.35 2.91 | macmini (bots): { 62.67 67.15 71.31 } +2026-10-17T16:04:00Z thinkpad: 4.94 2.72 3.01 | macmini (bots): { 67.63 67.82 71.40 } +2026-10-17T16:04:30Z thinkpad: 4.22 2.78 3.02 | macmini (bots): { 70.41 68.39 71.48 } +2026-10-17T16:05:00Z thinkpad: 3.81 2.80 3.02 | macmini (bots): { 66.59 67.83 71.18 } +2026-10-17T16:05:31Z thinkpad: 3.20 2.75 3.00 | macmini (bots): { 72.53 69.01 71.48 } +2026-10-17T16:06:01Z thinkpad: 4.22 3.04 3.08 | macmini (bots): { 71.30 69.27 71.50 } +2026-10-17T16:06:31Z thinkpad: 5.43 3.47 3.23 | macmini (bots): { 68.37 68.63 71.19 } +2026-10-17T16:07:01Z thinkpad: 4.35 3.42 3.22 | macmini (bots): { 60.20 66.68 70.39 } +2026-10-17T16:07:31Z thinkpad: 3.47 3.31 3.19 | macmini (bots): { 58.03 65.51 69.84 } +2026-10-17T16:08:02Z thinkpad: 2.30 3.04 3.11 | macmini (bots): { 59.05 65.13 69.55 } +2026-10-17T16:08:32Z thinkpad: 1.88 2.86 3.04 | macmini (bots): { 51.77 62.75 68.53 } +2026-10-17T16:09:02Z thinkpad: 1.38 2.65 2.97 | macmini (bots): { 49.05 61.01 67.70 } +2026-10-17T16:09:32Z thinkpad: 3.10 2.95 3.06 | macmini (bots): { 48.91 59.82 67.03 } +2026-10-17T16:10:02Z thinkpad: 2.91 2.91 3.04 | macmini (bots): { 47.56 58.44 66.25 } +2026-10-17T16:10:33Z thinkpad: 2.58 2.83 3.01 | macmini (bots): { 49.23 57.69 65.70 } +2026-10-17T16:11:03Z thinkpad: 8.38 4.15 3.44 | macmini (bots): { 44.16 55.72 64.71 } +2026-10-17T16:11:33Z thinkpad: 9.94 4.92 3.72 | macmini (bots): { 44.50 54.71 64.03 } +2026-10-17T16:12:03Z thinkpad: 10.08 5.42 3.92 | macmini (bots): { 42.15 53.21 63.17 } +2026-10-17T16:12:33Z thinkpad: 6.79 5.06 3.85 | macmini (bots): { 36.13 50.73 61.92 } +2026-10-17T16:13:04Z thinkpad: 4.61 4.72 3.77 | macmini (bots): { 41.28 50.64 61.51 } +2026-10-17T16:13:34Z thinkpad: 3.81 4.50 3.73 | macmini (bots): { 42.92 50.15 60.95 } +2026-10-17T16:14:04Z thinkpad: 3.39 4.35 3.71 | macmini (bots): { 41.56 49.16 60.22 } +2026-10-17T16:14:35Z thinkpad: 7.53 5.17 4.00 | macmini (bots): { 47.48 49.82 60.07 } +2026-10-17T16:15:05Z thinkpad: 9.73 6.01 4.32 | macmini (bots): { 51.43 50.41 59.92 } +2026-10-17T16:15:35Z thinkpad: 8.07 5.94 4.35 | macmini (bots): { 69.31 54.81 61.18 } +2026-10-17T16:16:05Z thinkpad: 9.27 6.45 4.57 | macmini (bots): { 71.85 56.92 61.73 } +2026-10-17T16:16:35Z thinkpad: 8.69 6.59 4.68 | macmini (bots): { 64.77 56.72 61.50 } +2026-10-17T16:17:06Z thinkpad: 6.11 6.17 4.60 | macmini (bots): { 57.92 55.86 61.02 } +2026-10-17T16:17:36Z thinkpad: 6.79 6.33 4.70 | macmini (bots): { 51.44 54.51 60.36 } +2026-10-17T16:18:06Z thinkpad: 5.16 5.99 4.64 | macmini (bots): { 51.33 54.23 60.05 } +2026-10-17T16:18:36Z thinkpad: 5.30 5.93 4.66 | macmini (bots): { 55.22 54.87 60.08 } +2026-10-17T16:19:07Z thinkpad: 4.78 5.72 4.63 | macmini (bots): { 51.62 53.94 59.56 } +2026-10-17T16:19:37Z thinkpad: 5.25 5.78 4.69 | macmini (bots): { 48.77 53.04 59.04 } +2026-10-17T16:20:07Z thinkpad: 4.63 5.60 4.67 | macmini (bots): { 54.59 53.92 59.14 } +2026-10-17T16:20:37Z thinkpad: 5.46 5.67 4.72 | macmini (bots): { 59.07 55.03 59.36 } +2026-10-17T16:21:07Z thinkpad: 8.07 6.19 4.91 | macmini (bots): { 52.53 53.83 58.77 } +2026-10-17T16:21:38Z thinkpad: 15.01 8.05 5.57 | macmini (bots): { 48.85 52.78 58.19 } +2026-10-17T16:22:08Z thinkpad: 19.08 9.69 6.20 | macmini (bots): { 54.73 53.61 58.29 } +2026-10-17T16:22:39Z thinkpad: 27.72 12.63 7.29 | macmini (bots): { 54.23 53.61 58.13 } +2026-10-17T16:23:09Z thinkpad: 23.10 12.88 7.53 | macmini (bots): { 51.63 53.06 57.77 } +2026-10-17T16:23:39Z thinkpad: 20.51 13.53 7.96 | macmini (bots): { 45.29 51.38 57.00 } +2026-10-17T16:24:10Z thinkpad: 12.70 12.30 7.72 | macmini (bots): { 45.61 50.91 56.63 } +2026-10-17T16:24:40Z thinkpad: 8.67 11.35 7.55 | macmini (bots): { 45.18 50.35 56.23 } +2026-10-17T16:25:10Z thinkpad: 6.35 10.53 7.40 | macmini (bots): { 41.10 48.88 55.50 } +2026-10-17T16:25:40Z thinkpad: 6.26 10.16 7.38 | macmini (bots): { 49.86 50.24 55.76 } +2026-10-17T16:26:11Z thinkpad: 7.71 10.11 7.45 | macmini (bots): { 53.93 51.11 55.88 } +2026-10-17T16:26:41Z thinkpad: 9.50 10.32 7.61 | macmini (bots): { 47.61 49.86 55.26 } +2026-10-17T16:27:11Z thinkpad: 10.26 10.39 7.72 | macmini (bots): { 46.43 49.36 54.89 } +2026-10-17T16:27:42Z thinkpad: 10.61 10.48 7.83 | macmini (bots): { 48.88 49.66 54.80 } +2026-10-17T16:28:12Z thinkpad: 10.39 10.45 7.91 | macmini (bots): { 58.42 51.74 55.37 } +2026-10-17T16:28:42Z thinkpad: 10.36 10.44 7.99 | macmini (bots): { 59.59 52.67 55.58 } +2026-10-17T16:29:13Z thinkpad: 9.63 10.25 8.00 | macmini (bots): { 55.30 52.38 55.38 } +2026-10-17T16:29:43Z thinkpad: 10.33 10.37 8.12 | macmini (bots): { 57.79 53.13 55.52 } +2026-10-17T16:30:13Z thinkpad: 9.68 10.18 8.12 | macmini (bots): { 57.83 53.60 55.61 } +2026-10-17T16:30:43Z thinkpad: 9.72 10.17 8.19 | macmini (bots): { 78.94 59.18 57.56 } +2026-10-17T16:31:14Z thinkpad: 6.60 9.36 7.98 | macmini (bots): { 87.29 62.98 58.99 } +2026-10-17T16:31:44Z thinkpad: 6.77 9.08 7.93 | macmini (bots): { 81.82 64.16 59.57 } +2026-10-17T16:32:14Z thinkpad: 13.15 10.41 8.41 | macmini (bots): { 81.20 65.92 60.37 } +2026-10-17T16:32:45Z thinkpad: 27.80 14.12 9.71 | macmini (bots): { 75.41 66.22 60.69 } +2026-10-17T16:33:15Z thinkpad: 44.59 19.25 11.54 | macmini (bots): { 66.92 65.08 60.47 } +2026-10-17T16:33:46Z thinkpad: 44.87 21.89 12.67 | macmini (bots): { 61.47 63.94 60.22 } +2026-10-17T16:34:16Z thinkpad: 38.98 22.67 13.23 | macmini (bots): { 62.13 63.78 60.28 } +2026-10-17T16:34:47Z thinkpad: 47.64 26.08 14.65 | macmini (bots): { 81.23 68.06 61.94 } +2026-10-17T16:35:17Z thinkpad: 47.83 28.02 15.65 | macmini (bots): { 116.14 78.43 65.98 } +2026-10-17T16:35:48Z thinkpad: 40.43 28.18 16.10 | macmini (bots): { 125.61 84.41 68.58 } +2026-10-17T16:36:19Z thinkpad: 41.34 29.71 17.00 | macmini (bots): { 143.61 92.86 72.20 } +2026-10-17T16:36:49Z thinkpad: 34.40 29.19 17.29 | macmini (bots): { 156.05 100.88 75.83 } +2026-10-17T16:37:20Z thinkpad: 25.34 27.65 17.17 | macmini (bots): { 151.90 105.26 78.29 } +2026-10-17T16:37:50Z thinkpad: 18.36 25.71 16.85 | macmini (bots): { 141.10 107.25 79.96 } +2026-10-17T16:38:20Z thinkpad: 16.19 24.47 16.72 | macmini (bots): { 131.21 107.92 81.13 } +2026-10-17T16:38:51Z thinkpad: 13.36 23.00 16.48 | macmini (bots): { 122.08 107.78 82.00 } +2026-10-17T16:39:21Z thinkpad: 11.27 21.57 16.21 | macmini (bots): { 107.07 105.50 82.07 } +2026-10-17T16:39:51Z thinkpad: 11.19 20.56 16.04 | macmini (bots): { 96.38 103.12 82.02 } +2026-10-17T16:40:22Z thinkpad: 10.06 19.37 15.79 | macmini (bots): { 89.06 100.79 81.91 } +2026-10-17T16:40:52Z thinkpad: 7.38 17.86 15.40 | macmini (bots): { 79.35 97.41 81.34 } +2026-10-17T16:41:23Z thinkpad: 6.18 16.57 15.05 | macmini (bots): { 81.70 96.20 81.46 } +2026-10-17T16:41:53Z thinkpad: 5.56 15.44 14.72 | macmini (bots): { 86.51 95.88 81.84 } +2026-10-17T16:42:23Z thinkpad: 4.90 14.33 14.37 | macmini (bots): { 99.20 97.69 83.05 } +2026-10-17T16:42:53Z thinkpad: 5.01 13.47 14.08 | macmini (bots): { 116.29 101.87 85.07 } +2026-10-17T16:43:24Z thinkpad: 4.34 12.50 13.74 | macmini (bots): { 131.32 106.77 87.42 } +2026-10-17T16:43:54Z thinkpad: 4.08 11.65 13.42 | macmini (bots): { 155.44 114.77 90.98 } +2026-10-17T16:44:24Z thinkpad: 4.00 10.90 13.11 | macmini (bots): { 167.86 121.62 94.28 } +2026-10-17T16:44:54Z thinkpad: 3.98 10.13 12.77 | macmini (bots): { 160.36 124.31 96.20 } +2026-10-17T16:45:25Z thinkpad: 4.20 9.59 12.50 | macmini (bots): { 163.23 128.59 98.74 } +2026-10-17T16:45:55Z thinkpad: 4.54 9.15 12.27 | macmini (bots): { 169.93 133.73 101.65 } +2026-10-17T16:46:25Z thinkpad: 4.44 8.69 12.01 | macmini (bots): { 162.40 135.22 103.29 } +2026-10-17T16:46:55Z thinkpad: 4.06 8.20 11.74 | macmini (bots): { 164.16 138.31 105.52 } +2026-10-17T16:47:26Z thinkpad: 3.96 7.78 11.49 | macmini (bots): { 157.92 139.31 107.02 } +2026-10-17T16:47:56Z thinkpad: 3.71 7.35 11.23 | macmini (bots): { 155.72 140.55 108.59 } +2026-10-17T16:48:26Z thinkpad: 4.93 7.32 11.09 | macmini (bots): { 153.39 141.52 110.05 } +2026-10-17T16:48:56Z thinkpad: 4.61 7.03 10.88 | macmini (bots): { 137.54 138.87 110.18 } +2026-10-17T16:49:27Z thinkpad: 4.01 6.65 10.63 | macmini (bots): { 136.53 138.36 110.98 } +2026-10-17T16:49:57Z thinkpad: 3.19 6.19 10.35 | macmini (bots): { 141.12 139.18 112.22 } +2026-10-17T16:50:27Z thinkpad: 5.31 6.43 10.30 | macmini (bots): { 122.76 135.27 111.75 } +2026-10-17T16:50:57Z thinkpad: 5.95 6.48 10.19 | macmini (bots): { 114.26 132.02 111.39 } +2026-10-17T16:51:28Z thinkpad: 5.76 6.41 10.05 | macmini (bots): { 116.04 130.87 111.69 } +2026-10-17T16:51:58Z thinkpad: 5.11 6.18 9.86 | macmini (bots): { 115.06 129.17 111.74 } +2026-10-17T16:52:28Z thinkpad: 5.09 6.07 9.70 | macmini (bots): { 109.91 126.59 111.41 } +2026-10-17T16:52:58Z thinkpad: 4.74 5.90 9.53 | macmini (bots): { 101.90 123.11 110.67 } +2026-10-17T16:53:29Z thinkpad: 4.89 5.84 9.39 | macmini (bots): { 83.29 116.38 108.74 } +2026-10-17T16:53:59Z thinkpad: 5.10 5.82 9.27 | macmini (bots): { 119.16 122.10 111.09 } +2026-10-17T16:54:29Z thinkpad: 4.57 5.67 9.10 | macmini (bots): { 114.87 120.76 110.98 } +2026-10-17T16:55:00Z thinkpad: 4.74 5.58 8.96 | macmini (bots): { 129.84 123.74 112.39 } +2026-10-17T16:55:30Z thinkpad: 6.40 5.90 8.96 | macmini (bots): { 100.10 117.29 110.46 } +2026-10-17T16:56:00Z thinkpad: 6.96 6.08 8.92 | macmini (bots): { 80.18 110.75 108.32 } +2026-10-17T16:56:30Z thinkpad: 6.07 5.95 8.79 | macmini (bots): { 74.41 106.39 106.82 } +2026-10-17T16:57:01Z thinkpad: 6.63 6.13 8.75 | macmini (bots): { 81.71 104.99 106.29 } +2026-10-17T16:57:31Z thinkpad: 6.39 6.14 8.68 | macmini (bots): { 101.10 107.55 107.18 } +2026-10-17T16:58:01Z thinkpad: 6.32 6.16 8.60 | macmini (bots): { 94.45 105.66 106.52 } +2026-10-17T16:58:31Z thinkpad: 5.19 5.90 8.44 | macmini (bots): { 78.76 100.83 104.75 } +2026-10-17T16:59:02Z thinkpad: 5.24 5.83 8.33 | macmini (bots): { 78.19 98.42 103.73 } +2026-10-17T16:59:32Z thinkpad: 3.95 5.48 8.13 | macmini (bots): { 77.57 96.42 102.82 } +2026-10-17T17:00:02Z thinkpad: 3.12 5.13 7.93 | macmini (bots): { 85.23 96.29 102.54 } +2026-10-17T17:00:32Z thinkpad: 3.17 4.93 7.77 | macmini (bots): { 99.84 99.07 103.35 } +2026-10-17T17:01:02Z thinkpad: 6.09 5.50 7.88 | macmini (bots): { 80.56 94.49 101.54 } +2026-10-17T17:01:33Z thinkpad: 9.23 6.29 8.06 | macmini (bots): { 79.70 93.03 100.77 } +2026-10-17T17:02:03Z thinkpad: 9.09 6.54 8.09 | macmini (bots): { 76.63 90.94 99.74 } +2026-10-17T17:02:33Z thinkpad: 7.86 6.52 8.04 | macmini (bots): { 93.08 93.50 100.36 } +2026-10-17T17:03:03Z thinkpad: 7.81 6.67 8.04 | macmini (bots): { 83.14 91.09 99.25 } +2026-10-17T17:03:34Z thinkpad: 6.69 6.51 7.94 | macmini (bots): { 79.37 89.64 98.45 } +2026-10-17T17:04:04Z thinkpad: 5.63 6.27 7.81 | macmini (bots): { 73.68 87.23 97.27 } +2026-10-17T17:04:34Z thinkpad: 5.75 6.21 7.75 | macmini (bots): { 75.89 86.23 96.54 } +2026-10-17T17:05:04Z thinkpad: 5.05 6.01 7.63 | macmini (bots): { 79.29 86.13 96.10 } +2026-10-17T17:05:35Z thinkpad: 3.88 5.62 7.44 | macmini (bots): { 76.07 84.79 95.28 } +2026-10-17T17:06:05Z thinkpad: 6.47 6.07 7.53 | macmini (bots): { 70.59 82.62 94.13 } +2026-10-17T17:06:35Z thinkpad: 8.20 6.53 7.63 | macmini (bots): { 69.09 81.18 93.21 } +2026-10-17T17:07:05Z thinkpad: 7.59 6.54 7.60 | macmini (bots): { 77.55 82.11 93.13 } +2026-10-17T17:07:36Z thinkpad: 6.93 6.49 7.55 | macmini (bots): { 84.23 83.41 93.22 } +2026-10-17T17:08:06Z thinkpad: 7.21 6.61 7.56 | macmini (bots): { 84.31 83.68 92.99 } +2026-10-17T17:08:36Z thinkpad: 6.73 6.57 7.51 | macmini (bots): { 81.04 82.99 92.42 } +2026-10-17T17:09:06Z thinkpad: 6.12 6.43 7.44 | macmini (bots): { 86.55 83.77 92.35 } +2026-10-17T17:09:36Z thinkpad: 6.77 6.58 7.46 | macmini (bots): { 95.19 86.31 92.99 } +2026-10-17T17:10:07Z thinkpad: 7.13 6.68 7.46 | macmini (bots): { 111.30 91.11 94.50 } +2026-10-17T17:10:37Z thinkpad: 5.09 6.23 7.29 | macmini (bots): { 118.51 95.17 95.87 } +2026-10-17T17:11:07Z thinkpad: 4.00 5.86 7.13 | macmini (bots): { 121.12 98.01 96.88 } +2026-10-17T17:11:38Z thinkpad: 3.50 5.57 6.99 | macmini (bots): { 109.57 97.67 96.81 } +2026-10-17T17:12:08Z thinkpad: 2.92 5.22 6.83 | macmini (bots): { 108.43 98.44 97.11 } +2026-10-17T17:12:38Z thinkpad: 3.42 5.12 6.74 | macmini (bots): { 101.61 97.86 96.95 } +2026-10-17T17:13:09Z thinkpad: 5.64 5.51 6.82 | macmini (bots): { 101.66 98.17 97.09 } +2026-10-17T17:13:39Z thinkpad: 7.06 5.89 6.91 | macmini (bots): { 88.43 95.36 96.11 } +2026-10-17T17:14:09Z thinkpad: 7.61 6.13 6.96 | macmini (bots): { 79.03 92.54 95.07 } +2026-10-17T17:14:39Z thinkpad: 9.06 6.68 7.12 | macmini (bots): { 92.55 94.57 95.72 } +2026-10-17T17:15:10Z thinkpad: 9.81 7.06 7.22 | macmini (bots): { 93.71 94.49 95.64 } +2026-10-17T17:15:40Z thinkpad: 9.98 7.41 7.34 | macmini (bots): { 92.26 93.86 95.35 } +2026-10-17T17:16:10Z thinkpad: 7.60 7.08 7.23 | macmini (bots): { 88.61 92.91 94.96 } +2026-10-17T17:16:40Z thinkpad: 6.81 6.93 7.17 | macmini (bots): { 96.96 94.47 95.45 } +2026-10-17T17:17:11Z thinkpad: 6.31 6.81 7.12 | macmini (bots): { 102.92 96.14 96.02 } +2026-10-17T17:17:41Z thinkpad: 4.81 6.38 6.97 | macmini (bots): { 91.20 94.16 95.32 } +2026-10-17T17:18:11Z thinkpad: 7.36 6.81 7.09 | macmini (bots): { 93.60 94.31 95.32 } +2026-10-17T17:18:41Z thinkpad: 9.42 7.38 7.27 | macmini (bots): { 90.86 93.57 95.02 } +2026-10-17T17:19:11Z thinkpad: 9.95 7.72 7.39 | macmini (bots): { 88.94 92.94 94.75 } +2026-10-17T17:19:42Z thinkpad: 9.51 7.85 7.45 | macmini (bots): { 94.97 93.93 95.03 } +2026-10-17T17:20:12Z thinkpad: 8.97 7.90 7.48 | macmini (bots): { 80.46 90.39 93.71 } +2026-10-17T17:20:42Z thinkpad: 7.56 7.65 7.41 | macmini (bots): { 74.38 87.95 92.71 } +2026-10-17T17:21:12Z thinkpad: 6.39 7.36 7.32 | macmini (bots): { 77.48 87.26 92.28 } +2026-10-17T17:21:43Z thinkpad: 5.21 6.98 7.19 | macmini (bots): { 82.05 87.48 92.19 } +2026-10-17T17:22:13Z thinkpad: 3.87 6.49 7.02 | macmini (bots): { 88.15 88.45 92.38 } +2026-10-17T17:22:43Z thinkpad: 3.86 6.22 6.91 | macmini (bots): { 100.23 91.12 93.19 } +2026-10-17T17:23:13Z thinkpad: 8.32 7.05 7.16 | macmini (bots): { 84.55 88.39 92.15 } +2026-10-17T17:23:43Z thinkpad: 13.84 8.37 7.59 | macmini (bots): { 73.74 85.38 90.92 } +2026-10-17T17:24:14Z thinkpad: 21.02 10.71 8.40 | macmini (bots): { 71.36 83.72 90.13 } +2026-10-17T17:24:44Z thinkpad: 20.73 11.82 8.85 | macmini (bots): { 82.27 85.04 90.38 } +2026-10-17T17:25:14Z thinkpad: 16.80 11.77 8.94 | macmini (bots): { 78.63 83.92 89.78 } +2026-10-17T17:25:44Z thinkpad: 14.62 11.68 8.99 | macmini (bots): { 82.33 84.06 89.61 } +2026-10-17T17:26:15Z thinkpad: 14.51 11.94 9.17 | macmini (bots): { 74.13 81.89 88.63 } +2026-10-17T17:26:45Z thinkpad: 12.48 11.74 9.20 | macmini (bots): { 75.65 81.46 88.24 } +2026-10-17T17:27:15Z thinkpad: 15.24 12.56 9.56 | macmini (bots): { 71.35 79.78 87.35 } +2026-10-17T17:27:45Z thinkpad: 15.70 12.87 9.76 | macmini (bots): { 68.21 78.17 86.51 } +2026-10-17T17:28:16Z thinkpad: 12.80 12.47 9.72 | macmini (bots): { 79.74 80.10 86.92 } +2026-10-17T17:28:46Z thinkpad: 9.05 11.58 9.51 | macmini (bots): { 101.01 85.27 88.56 } +2026-10-17T17:29:16Z thinkpad: 9.38 11.41 9.53 | macmini (bots): { 93.76 85.18 88.43 } +2026-10-17T17:29:46Z thinkpad: 11.08 11.62 9.65 | macmini (bots): { 74.91 81.56 87.01 } +2026-10-17T17:30:17Z thinkpad: 10.98 11.53 9.69 | macmini (bots): { 61.10 77.50 85.34 } +2026-10-17T17:30:47Z thinkpad: 9.83 11.21 9.64 | macmini (bots): { 51.19 73.56 83.64 } +2026-10-17T17:31:18Z thinkpad: 9.65 11.03 9.63 | macmini (bots): { 49.64 71.03 82.37 } +2026-10-17T17:31:48Z thinkpad: 7.22 10.33 9.44 | macmini (bots): { 53.62 69.90 81.56 } +2026-10-17T17:32:18Z thinkpad: 5.79 9.68 9.25 | macmini (bots): { 61.07 70.36 81.34 } +2026-10-17T17:32:48Z thinkpad: 3.70 8.80 8.97 | macmini (bots): { 60.39 69.24 80.55 } +2026-10-17T17:33:19Z thinkpad: 2.72 8.08 8.73 | macmini (bots): { 57.06 67.51 79.53 } +2026-10-17T17:33:49Z thinkpad: 1.97 7.37 8.47 | macmini (bots): { 65.72 68.41 79.42 } +2026-10-17T17:34:19Z thinkpad: 1.25 6.68 8.20 | macmini (bots): { 62.60 67.40 78.67 } +2026-10-17T17:34:49Z thinkpad: 0.94 6.09 7.96 | macmini (bots): { 71.83 69.24 78.95 } +2026-10-17T17:35:20Z thinkpad: 0.72 5.54 7.71 | macmini (bots): { 66.16 68.07 78.19 } +2026-10-17T17:35:50Z thinkpad: 0.44 5.01 7.47 | macmini (bots): { 70.96 68.91 78.13 } +2026-10-17T17:36:20Z thinkpad: 1.70 4.79 7.30 | macmini (bots): { 79.74 71.45 78.74 } +2026-10-17T17:36:50Z thinkpad: 3.03 4.80 7.22 | macmini (bots): { 79.71 72.75 78.95 } +2026-10-17T17:37:21Z thinkpad: 3.07 4.67 7.10 | macmini (bots): { 85.13 74.60 79.40 } +2026-10-17T17:37:51Z thinkpad: 2.32 4.33 6.91 | macmini (bots): { 84.85 75.70 79.64 } +2026-10-17T17:38:21Z thinkpad: 1.83 4.03 6.73 | macmini (bots): { 86.47 76.79 79.88 } +2026-10-17T17:38:51Z thinkpad: 1.11 3.64 6.51 | macmini (bots): { 106.96 82.74 81.94 } +2026-10-17T17:39:22Z thinkpad: 1.03 3.37 6.33 | macmini (bots): { 114.52 87.01 83.52 } +2026-10-17T17:39:52Z thinkpad: 1.11 3.16 6.16 | macmini (bots): { 103.99 87.05 83.65 } +2026-10-17T17:40:22Z thinkpad: 1.31 3.02 6.02 | macmini (bots): { 100.27 87.59 83.95 } +2026-10-17T17:40:52Z thinkpad: 1.36 2.87 5.87 | macmini (bots): { 98.17 88.44 84.40 } +2026-10-17T17:41:22Z thinkpad: 2.01 2.88 5.78 | macmini (bots): { 96.27 88.67 84.60 } +2026-10-17T17:41:53Z thinkpad: 1.96 2.77 5.65 | macmini (bots): { 96.31 89.44 85.03 } +2026-10-17T17:42:23Z thinkpad: 3.06 2.97 5.62 | macmini (bots): { 80.49 86.30 84.04 } +2026-10-17T17:42:53Z thinkpad: 2.38 2.81 5.49 | macmini (bots): { 66.40 82.24 82.64 } +2026-10-17T17:43:24Z thinkpad: 2.44 2.81 5.40 | macmini (bots): { 56.70 78.37 81.22 } +2026-10-17T17:43:54Z thinkpad: 1.93 2.65 5.26 | macmini (bots): { 61.56 77.39 80.77 } +2026-10-17T17:44:24Z thinkpad: 1.96 2.59 5.16 | macmini (bots): { 58.25 75.14 79.83 } +2026-10-17T17:44:54Z thinkpad: 2.25 2.60 5.08 | macmini (bots): { 56.32 73.21 78.98 } +2026-10-17T17:45:24Z thinkpad: 1.79 2.46 4.95 | macmini (bots): { 62.87 73.14 78.75 } +2026-10-17T17:45:55Z thinkpad: 2.78 2.64 4.93 | macmini (bots): { 62.58 72.22 78.23 } +2026-10-17T17:46:25Z thinkpad: 4.82 3.14 5.03 | macmini (bots): { 58.89 70.44 77.38 } +2026-10-17T17:46:55Z thinkpad: 3.10 2.90 4.88 | macmini (bots): { 61.68 70.08 77.01 } +2026-10-17T17:47:25Z thinkpad: 2.27 2.71 4.75 | macmini (bots): { 70.43 71.40 77.25 } +2026-10-17T17:47:56Z thinkpad: 1.71 2.53 4.62 | macmini (bots): { 70.51 71.56 77.12 } +2026-10-17T17:48:26Z thinkpad: 1.59 2.42 4.52 | macmini (bots): { 68.98 70.98 76.71 } +2026-10-17T17:48:56Z thinkpad: 2.09 2.47 4.47 | macmini (bots): { 67.75 70.60 76.38 } +2026-10-17T17:49:26Z thinkpad: 2.14 2.44 4.39 | macmini (bots): { 61.53 69.01 75.58 } +2026-10-17T17:49:56Z thinkpad: 2.22 2.43 4.33 | macmini (bots): { 58.49 67.45 74.78 } +2026-10-17T17:50:27Z thinkpad: 1.98 2.36 4.24 | macmini (bots): { 66.15 68.33 74.84 } +2026-10-17T17:50:57Z thinkpad: 2.38 2.42 4.20 | macmini (bots): { 61.65 67.22 74.22 } +2026-10-17T17:51:27Z thinkpad: 3.62 2.72 4.24 | macmini (bots): { 54.05 64.88 73.13 } +2026-10-17T17:51:57Z thinkpad: 3.25 2.70 4.19 | macmini (bots): { 49.14 62.62 72.02 } +2026-10-17T17:52:28Z thinkpad: 2.45 2.55 4.09 | macmini (bots): { 43.72 60.06 70.77 } +2026-10-17T17:52:58Z thinkpad: 2.85 2.62 4.06 | macmini (bots): { 42.53 58.22 69.73 } +2026-10-17T17:53:28Z thinkpad: 8.44 3.97 4.46 | macmini (bots): { 45.21 57.34 69.01 } +2026-10-17T17:53:58Z thinkpad: 10.75 4.91 4.76 | macmini (bots): { 44.86 56.01 68.11 } +2026-10-17T17:54:29Z thinkpad: 8.36 4.90 4.76 | macmini (bots): { 51.73 56.60 67.91 } +2026-10-17T17:54:59Z thinkpad: 7.41 4.98 4.79 | macmini (bots): { 55.80 57.05 67.67 } +2026-10-17T17:55:29Z thinkpad: 5.45 4.73 4.71 | macmini (bots): { 50.40 55.67 66.81 } +2026-10-17T17:55:59Z thinkpad: 6.26 4.97 4.79 | macmini (bots): { 57.22 56.88 66.87 } +2026-10-17T17:56:30Z thinkpad: 8.22 5.52 4.98 | macmini (bots): { 48.94 54.86 65.78 } +2026-10-17T17:57:00Z thinkpad: 6.71 5.42 4.96 | macmini (bots): { 50.54 54.70 65.35 } +2026-10-17T17:57:30Z thinkpad: 4.94 5.14 4.89 | macmini (bots): { 58.02 56.25 65.55 } +2026-10-17T17:58:01Z thinkpad: 4.54 5.04 4.86 | macmini (bots): { 53.98 55.38 64.90 } +2026-10-17T17:58:31Z thinkpad: 4.65 5.04 4.87 | macmini (bots): { 49.96 54.23 64.16 } +2026-10-17T17:59:01Z thinkpad: 5.29 5.16 4.92 | macmini (bots): { 49.63 53.68 63.61 } +2026-10-17T17:59:31Z thinkpad: 4.23 4.94 4.85 | macmini (bots): { 57.15 55.10 63.78 } +2026-10-17T18:00:01Z thinkpad: 3.57 4.72 4.78 | macmini (bots): { 61.70 56.26 63.89 } +2026-10-17T18:00:32Z thinkpad: 3.16 4.52 4.71 | macmini (bots): { 62.10 56.86 63.79 } +2026-10-17T18:01:02Z thinkpad: 2.81 4.29 4.63 | macmini (bots): { 76.29 60.79 64.98 } +2026-10-17T18:01:32Z thinkpad: 7.77 5.26 4.93 | macmini (bots): { 75.36 62.16 65.34 } +2026-10-17T18:02:02Z thinkpad: 11.60 6.45 5.34 | macmini (bots): { 70.83 62.28 65.27 } +2026-10-17T18:02:33Z thinkpad: 11.54 6.97 5.56 | macmini (bots): { 65.66 61.87 65.01 } +2026-10-17T18:03:03Z thinkpad: 10.80 7.33 5.73 | macmini (bots): { 63.09 61.54 64.78 } +2026-10-17T18:03:33Z thinkpad: 10.52 7.56 5.85 | macmini (bots): { 60.31 61.12 64.52 } +2026-10-17T18:04:04Z thinkpad: 10.27 7.76 5.97 | macmini (bots): { 60.99 61.21 64.44 } +2026-10-17T18:04:34Z thinkpad: 8.77 7.69 6.01 | macmini (bots): { 56.72 60.19 63.96 } +2026-10-17T18:05:05Z thinkpad: 5.77 7.06 5.85 | macmini (bots): { 56.14 59.70 63.65 } +2026-10-17T18:05:35Z thinkpad: 5.16 6.79 5.80 | macmini (bots): { 51.25 58.17 62.95 } +2026-10-17T18:06:05Z thinkpad: 4.16 6.36 5.69 | macmini (bots): { 52.03 57.64 62.59 } +2026-10-17T18:06:35Z thinkpad: 4.28 6.18 5.65 | macmini (bots): { 64.66 60.00 63.27 } +2026-10-17T18:07:06Z thinkpad: 7.47 6.76 5.86 | macmini (bots): { 56.20 58.45 62.59 } +2026-10-17T18:07:36Z thinkpad: 6.95 6.74 5.89 | macmini (bots): { 51.92 57.20 62.00 } +2026-10-17T18:08:06Z thinkpad: 7.70 6.99 6.00 | macmini (bots): { 51.14 56.65 61.64 } +2026-10-17T18:08:36Z thinkpad: 5.83 6.60 5.90 | macmini (bots): { 48.08 55.33 60.98 } +2026-10-17T18:09:07Z thinkpad: 4.89 6.30 5.82 | macmini (bots): { 53.80 56.00 61.00 } +2026-10-17T18:09:37Z thinkpad: 4.93 6.19 5.80 | macmini (bots): { 60.49 57.24 61.27 } +2026-10-17T18:10:07Z thinkpad: 4.61 5.98 5.74 | macmini (bots): { 58.95 57.21 61.12 } +2026-10-17T18:10:37Z thinkpad: 4.74 5.91 5.73 | macmini (bots): { 60.84 57.65 61.13 } +2026-10-17T18:11:07Z thinkpad: 3.96 5.61 5.63 | macmini (bots): { 64.23 58.82 61.43 } +2026-10-17T18:11:38Z thinkpad: 4.16 5.53 5.61 | macmini (bots): { 75.59 62.26 62.60 } +2026-10-17T18:12:08Z thinkpad: 2.97 5.11 5.46 | macmini (bots): { 75.25 63.65 63.10 } diff --git a/benchmarks/server-2026-10-17/walk-explore.json b/benchmarks/server-2026-10-17/walk-explore.json new file mode 100644 index 000000000..a9479f455 --- /dev/null +++ b/benchmarks/server-2026-10-17/walk-explore.json @@ -0,0 +1,695 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T17:31:40+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "7bbbf6e97fb53683eae0a01ce2c134e53cb649a7", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon,vanilla", + "bots": "1,10,25,50,100", + "behaviour": "walk,explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 180, + "seed": 12345, + "explore_speed": 0, + "gamerule": "", + "heap": "4g", + "out": "/home/ludovic/code/horizon/.claude/worktrees/server-host-4/.local/bench-out/walk-explore.json", + "nice": 19, + "bots_via": "ssh macmini", + "bots_bin": "/Users/ludovicmarie/code/horizon/.claude/worktrees/server-host-4/target/release/horizon-bots", + "connect": "", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "walk", + "start_seconds": 9.62, + "mspt": { + "average": 4.01, + "p50": 3.54, + "p95": 8.19, + "p99": 25.59 + }, + "mspt_worst_p99": 47.5, + "tps": 20.0, + "rss_mb": { + "mean": 782.52, + "max": 785.3 + }, + "cpu_percent": 58.87, + "chunks_per_second": 9.6, + "unique_per_second": 0.43, + "forgotten_per_second": 9.65, + "waited_ticks_per_second": 0.0, + "chunks_total": 2697, + "chunks_per_bot": { + "walk": 2697.0 + }, + "unique_chunks_per_bot": { + "walk": 693.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "walk", + "start_seconds": 14.85, + "mspt": { + "average": 18.22, + "p50": 17.99, + "p95": 29.34, + "p99": 50.06 + }, + "mspt_worst_p99": 395.5, + "tps": 20.0, + "rss_mb": { + "mean": 3429.06, + "max": 3446.3 + }, + "cpu_percent": 68.81, + "chunks_per_second": 10.47, + "unique_per_second": 0.47, + "forgotten_per_second": 10.53, + "waited_ticks_per_second": 0.0, + "chunks_total": 2755, + "chunks_per_bot": { + "walk": 2755.0 + }, + "unique_chunks_per_bot": { + "walk": 697.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "walk", + "start_seconds": 9.21, + "mspt": { + "average": 8.79, + "p50": 8.05, + "p95": 17.35, + "p99": 30.47 + }, + "mspt_worst_p99": 48.8, + "tps": 20.0, + "rss_mb": { + "mean": 781.88, + "max": 782.8 + }, + "cpu_percent": 119.16, + "chunks_per_second": 94.63, + "unique_per_second": 3.58, + "forgotten_per_second": 94.31, + "waited_ticks_per_second": 0.0, + "chunks_total": 26003, + "chunks_per_bot": { + "walk": 2600.3 + }, + "unique_chunks_per_bot": { + "walk": 679.9 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "walk", + "start_seconds": 15.14, + "mspt": { + "average": 18.67, + "p50": 15.8, + "p95": 38.26, + "p99": 55.93 + }, + "mspt_worst_p99": 101.8, + "tps": 20.0, + "rss_mb": { + "mean": 3497.35, + "max": 3499.4 + }, + "cpu_percent": 100.8, + "chunks_per_second": 101.1, + "unique_per_second": 4.38, + "forgotten_per_second": 101.15, + "waited_ticks_per_second": 0.0, + "chunks_total": 26537, + "chunks_per_bot": { + "walk": 2653.7 + }, + "unique_chunks_per_bot": { + "walk": 687.5 + }, + "resent": 0, + "pulled_back": 5, + "moved_too_quickly": 5, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "walk", + "start_seconds": 9.82, + "mspt": { + "average": 15.01, + "p50": 13.12, + "p95": 31.12, + "p99": 50.62 + }, + "mspt_worst_p99": 101.6, + "tps": 20.0, + "rss_mb": { + "mean": 799.52, + "max": 799.7 + }, + "cpu_percent": 161.02, + "chunks_per_second": 234.3, + "unique_per_second": 8.49, + "forgotten_per_second": 234.35, + "waited_ticks_per_second": 0.0, + "chunks_total": 65926, + "chunks_per_bot": { + "walk": 2637.04 + }, + "unique_chunks_per_bot": { + "walk": 683.96 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "walk", + "start_seconds": 14.95, + "mspt": { + "average": 18.78, + "p50": 17.47, + "p95": 28.16, + "p99": 51.03 + }, + "mspt_worst_p99": 107.6, + "tps": 20.0, + "rss_mb": { + "mean": 3520.17, + "max": 3573.8 + }, + "cpu_percent": 154.9, + "chunks_per_second": 252.39, + "unique_per_second": 11.89, + "forgotten_per_second": 251.75, + "waited_ticks_per_second": 0.0, + "chunks_total": 66469, + "chunks_per_bot": { + "walk": 2658.76 + }, + "unique_chunks_per_bot": { + "walk": 689.68 + }, + "resent": 0, + "pulled_back": 10, + "moved_too_quickly": 10, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "walk", + "start_seconds": 9.52, + "mspt": { + "average": 22.72, + "p50": 16.98, + "p95": 60.19, + "p99": 84.16 + }, + "mspt_worst_p99": 105.4, + "tps": 20.0, + "rss_mb": { + "mean": 813.5, + "max": 815.8 + }, + "cpu_percent": 179.85, + "chunks_per_second": 464.75, + "unique_per_second": 16.94, + "forgotten_per_second": 464.69, + "waited_ticks_per_second": 0.0, + "chunks_total": 134839, + "chunks_per_bot": { + "walk": 2696.78 + }, + "unique_chunks_per_bot": { + "walk": 685.48 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "walk", + "start_seconds": 16.36, + "mspt": { + "average": 34.3, + "p50": 31.07, + "p95": 55.55, + "p99": 92.32 + }, + "mspt_worst_p99": 452.1, + "tps": 20.0, + "rss_mb": { + "mean": 3577.02, + "max": 3611.2 + }, + "cpu_percent": 267.05, + "chunks_per_second": 496.77, + "unique_per_second": 26.74, + "forgotten_per_second": 496.2, + "waited_ticks_per_second": 0.0, + "chunks_total": 133505, + "chunks_per_bot": { + "walk": 2670.1 + }, + "unique_chunks_per_bot": { + "walk": 688.8 + }, + "resent": 0, + "pulled_back": 39, + "moved_too_quickly": 39, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "walk", + "start_seconds": 9.51, + "mspt": { + "average": 63.33, + "p50": 58.89, + "p95": 125.04, + "p99": 175.12 + }, + "mspt_worst_p99": 261.5, + "tps": 15.79, + "rss_mb": { + "mean": 868.12, + "max": 869.9 + }, + "cpu_percent": 245.64, + "chunks_per_second": 678.18, + "unique_per_second": 31.8, + "forgotten_per_second": 676.4, + "waited_ticks_per_second": 0.0, + "chunks_total": 219787, + "chunks_per_bot": { + "walk": 2197.87 + }, + "unique_chunks_per_bot": { + "walk": 637.91 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 34 + }, + { + "server": "vanilla", + "bots": 100, + "behaviour": "walk", + "start_seconds": 15.14, + "error": "[Errno 32] Broken pipe" + }, + { + "server": "horizon", + "bots": 1, + "behaviour": "explore", + "start_seconds": 9.72, + "mspt": { + "average": 9.73, + "p50": 8.75, + "p95": 20.99, + "p99": 34.17 + }, + "mspt_worst_p99": 73.9, + "tps": 20.0, + "rss_mb": { + "mean": 836.18, + "max": 891.0 + }, + "cpu_percent": 329.64, + "chunks_per_second": 41.11, + "unique_per_second": 35.96, + "forgotten_per_second": 41.08, + "waited_ticks_per_second": 0.16, + "chunks_total": 9460, + "chunks_per_bot": { + "explore": 9460.0 + }, + "unique_chunks_per_bot": { + "explore": 8479.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "explore", + "start_seconds": 15.54, + "mspt": { + "average": 9.71, + "p50": 7.86, + "p95": 20.37, + "p99": 76.15 + }, + "mspt_worst_p99": 388.6, + "tps": 20.0, + "rss_mb": { + "mean": 3614.97, + "max": 3688.5 + }, + "cpu_percent": 247.15, + "chunks_per_second": 35.47, + "unique_per_second": 33.61, + "forgotten_per_second": 35.45, + "waited_ticks_per_second": 0.0, + "chunks_total": 7912, + "chunks_per_bot": { + "explore": 7912.0 + }, + "unique_chunks_per_bot": { + "explore": 7580.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "explore", + "start_seconds": 9.31, + "mspt": { + "average": 21.27, + "p50": 19.5, + "p95": 39.15, + "p99": 54.23 + }, + "mspt_worst_p99": 105.5, + "tps": 20.0, + "rss_mb": { + "mean": 1177.66, + "max": 1392.9 + }, + "cpu_percent": 321.97, + "chunks_per_second": 46.47, + "unique_per_second": 46.11, + "forgotten_per_second": 43.12, + "waited_ticks_per_second": 111.25, + "chunks_total": 14103, + "chunks_per_bot": { + "explore": 1410.3 + }, + "unique_chunks_per_bot": { + "explore": 1402.4 + }, + "resent": 0, + "pulled_back": 9856, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "explore", + "start_seconds": 15.24, + "mspt": { + "average": 16.94, + "p50": 14.24, + "p95": 30.28, + "p99": 109.7 + }, + "mspt_worst_p99": 1861.2, + "tps": 20.0, + "rss_mb": { + "mean": 3953.29, + "max": 4232.0 + }, + "cpu_percent": 254.11, + "chunks_per_second": 24.99, + "unique_per_second": 25.01, + "forgotten_per_second": 25.33, + "waited_ticks_per_second": 77.93, + "chunks_total": 7707, + "chunks_per_bot": { + "explore": 770.7 + }, + "unique_chunks_per_bot": { + "explore": 769.5 + }, + "resent": 0, + "pulled_back": 11123, + "moved_too_quickly": 20, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "explore", + "start_seconds": 9.92, + "mspt": { + "average": 25.76, + "p50": 23.58, + "p95": 45.01, + "p99": 61.43 + }, + "mspt_worst_p99": 108.8, + "tps": 20.0, + "rss_mb": { + "mean": 1172.1, + "max": 1482.3 + }, + "cpu_percent": 314.47, + "chunks_per_second": 61.38, + "unique_per_second": 60.7, + "forgotten_per_second": 55.11, + "waited_ticks_per_second": 304.54, + "chunks_total": 24085, + "chunks_per_bot": { + "explore": 963.4 + }, + "unique_chunks_per_bot": { + "explore": 954.76 + }, + "resent": 0, + "pulled_back": 31264, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "explore", + "start_seconds": 15.76, + "mspt": { + "average": 24.93, + "p50": 22.04, + "p95": 37.09, + "p99": 168.46 + }, + "mspt_worst_p99": 1724.8, + "tps": 20.0, + "rss_mb": { + "mean": 4040.42, + "max": 4447.6 + }, + "cpu_percent": 305.47, + "chunks_per_second": 37.91, + "unique_per_second": 37.84, + "forgotten_per_second": 38.39, + "waited_ticks_per_second": 258.66, + "chunks_total": 16865, + "chunks_per_bot": { + "explore": 674.6 + }, + "unique_chunks_per_bot": { + "explore": 671.28 + }, + "resent": 0, + "pulled_back": 33467, + "moved_too_quickly": 23, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "explore", + "start_seconds": 9.41, + "mspt": { + "average": 39.31, + "p50": 36.98, + "p95": 65.33, + "p99": 88.36 + }, + "mspt_worst_p99": 157.6, + "tps": 20.0, + "rss_mb": { + "mean": 1250.32, + "max": 1517.1 + }, + "cpu_percent": 324.77, + "chunks_per_second": 114.99, + "unique_per_second": 112.25, + "forgotten_per_second": 104.41, + "waited_ticks_per_second": 543.77, + "chunks_total": 50402, + "chunks_per_bot": { + "explore": 1008.04 + }, + "unique_chunks_per_bot": { + "explore": 997.42 + }, + "resent": 0, + "pulled_back": 64163, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "explore", + "start_seconds": 14.55, + "error": "[Errno 32] Broken pipe" + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "explore", + "start_seconds": 9.31, + "mspt": { + "average": 52.7, + "p50": 49.49, + "p95": 85.73, + "p99": 115.34 + }, + "mspt_worst_p99": 219.0, + "tps": 18.97, + "rss_mb": { + "mean": 1358.32, + "max": 3047.2 + }, + "cpu_percent": 327.95, + "chunks_per_second": 154.2, + "unique_per_second": 151.83, + "forgotten_per_second": 141.65, + "waited_ticks_per_second": 1132.9, + "chunks_total": 84433, + "chunks_per_bot": { + "explore": 844.33 + }, + "unique_chunks_per_bot": { + "explore": 839.47 + }, + "resent": 0, + "pulled_back": 116161, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 100, + "behaviour": "explore", + "start_seconds": 16.47, + "error": "[Errno 32] Broken pipe" + } + ] +} diff --git a/benchmarks/server-equal-work-2026-10-17/README.md b/benchmarks/server-equal-work-2026-10-17/README.md new file mode 100644 index 000000000..737b05858 --- /dev/null +++ b/benchmarks/server-equal-work-2026-10-17/README.md @@ -0,0 +1,168 @@ +# Horizon's server against vanilla 26.3, equal work (2026-10-17) + +The same bots on Horizon's dedicated server and on vanilla 26.3's, one server at a time, on the same +machine, with the work each server does made the same before the numbers are compared. This replaces the +first run in docs/server.md section 9, where the work wasn't equal. + +## What was made equal + +The first run (PR #556) had three differences that made the comparison unfair. Each is fixed in the code +that ran here: + +- **Refused moves.** Vanilla pulls a player back when a move is too fast ("moved too quickly") or ends + inside a block ("moved wrongly"). Horizon now runs both checks the way vanilla does (PR #586), so a bot + that flies too fast is pulled back on both servers. +- **Chunk sending.** Vanilla paces chunks by the client's acknowledgements (PlayerChunkSender: one + unacknowledged batch at first, then ten, each at most the client's desired chunks per tick). Horizon used + to send twice as many per batch; it now paces them the same way (PR #586), and the bots acknowledge + batches and ask for a rate the way vanilla's client does, so both servers send at the pace the client + asks for. Chunks sent again while the bot still held + them (`resent`) are counted: 0 on both servers in every run. +- **Movement gated on chunks.** A bot doesn't move while the chunk it stands in hasn't arrived (vanilla's + client waits the same way), so a slower server isn't asked to teleport bots into terrain it hasn't sent. + +One difference isn't in Horizon yet: vanilla 26.3's locator bar (waypoints), which costs vanilla O(players²) +work per move. Every vanilla run here sets `gamerule locator_bar false`, so neither server does it. + +## Method + +`tools/server_bench.py` runs each configuration on a fresh server: + +- the same `server.properties` on both (seed 12345, view and simulation distance 10, offline, creative, + difficulty easy, `sync-chunk-writes=true`), and `gamerule respawn_radius 0`; +- the server waits for `Done`, the bots join one a second, a 60-second warm-up, then 300 seconds of + measurement; +- MSPT (average, P50, P95, P99) comes from each server's own `/tick query`, asked every 5 seconds on the + console, so both measure themselves the same way (vanilla's ServerTickRateManager numbers, which Horizon + reproduces); TPS is 20 while the average fits in 50 ms, else 1000 / MSPT; +- RSS and CPU are the server's whole process tree, once a second (100 % is one core); +- chunk counts come from the bots: chunks received per second, chunks no bot had before (new terrain), and + pull-backs (position packets that move a bot back). + +The bots are `horizon-bots` (creative, flying 24 blocks above spawn, 20 moves a second): + +- `walk`: flies to random points within 48 blocks of spawn at sprint speed (5.6 blocks a second); +- `explore`: flies straight outwards, by default at about 22 blocks a second, as fast as the server sends + chunks. + +Machine: the ThinkPad (Intel Core i7-7500U, 2 cores / 4 threads, 32 GB, NixOS), servers under `nice -n 19` +because it also runs other services; vanilla on OpenJDK 25.0.4.1 with a 4 GB heap (`-Xms4g -Xmx4g`). The +bots ran on the Mac mini and reached the ThinkPad over the tailnet, so they took none of the server's CPU. + +What ran: Horizon from `origin/main` at bf851bfe with #586 (move checks and chunk pacing), the bots and +`server_bench.py` from this PR, #623 (sections encoded once, its first commit) and #649 (a tick's packets +handed to each connection together). The ThinkPad copy wasn't a git checkout, so the JSON reports have an +empty `commit`. Vanilla: the pinned 26.3 server jar. + +## Results + +MSPT is the average milliseconds per tick (50 is the limit for 20 TPS); P95 is the 95th percentile. CPU is +the whole process tree. "New chunks/s" are chunks no bot had before. + +### Walk (the same work on both servers) + +| Bots | Server | MSPT | P95 | TPS | RSS | CPU | Chunks/s | New chunks/s | +|---:|---|---:|---:|---:|---:|---:|---:|---:| +| 1 | Horizon | 5.5 | 12.1 | 20.0 | 1.37 GB | 57 % | 9 | 0.3 | +| 1 | Vanilla | 18.3 | 27.3 | 20.0 | 3.35 GB | 66 % | 10 | 0.3 | +| 10 | Horizon | 11.5 | 22.1 | 20.0 | 1.41 GB | 124 % | 94 | 2.4 | +| 10 | Vanilla | 16.8 | 30.5 | 20.0 | 3.41 GB | 84 % | 100 | 2.8 | +| 25 | Horizon | 20.7 | 40.4 | 20.0 | 1.45 GB | 170 % | 236 | 5.7 | +| 25 | Vanilla | 16.0 | 26.4 | 20.0 | 3.47 GB | 115 % | 252 | 6.7 | +| 50 | Horizon | 31.4 | 79.0 | 20.0 | 1.52 GB | 173 % | 451 | 10.3 | +| 50 | Vanilla | 20.5 | 29.7 | 20.0 | 3.55 GB | 194 % | 502 | 12.2 | +| 100 | Horizon | 114.5 | 256.2 | 8.7 | 1.33 GB | 181 % | 484 | 30.8 | +| 100 | Vanilla | stopped by its watchdog | | | | | | | + +Both servers sent the same chunks (about 10 a second per bot, the churn of flying around) and sent none +twice. Vanilla pulled back a few bots for moving too quickly when a tick ran long (5 to 33 per run); +Horizon none. At 100 bots vanilla's watchdog stopped the server (a tick ran over 60 s, in +`ChunkMap$TrackedEntity.updatePlayer`); Horizon kept running at 8.7 TPS. + +### Explore at a rate both servers keep up with (equal work) + +The bots fly outwards at 0.8 blocks a second (`--explore-speed 0.8`), slow enough that neither server makes +them wait for terrain, so both generate and send the same new chunks. + +| Bots | Server | MSPT | P95 | TPS | RSS | CPU | Chunks/s | New chunks/s | +|---:|---|---:|---:|---:|---:|---:|---:|---:| +| 1 | Horizon | 4.0 | 6.6 | 20.0 | 1.36 GB | 25 % | 2 | 1.3 | +| 1 | Vanilla | 18.1 | 27.1 | 20.0 | 3.32 GB | 73 % | 2 | 1.4 | +| 10 | Horizon | 13.5 | 24.8 | 20.0 | 1.64 GB | 89 % | 13 | 11.8 | +| 10 | Vanilla | 29.2 | 43.0 | 20.0 | 3.52 GB | 143 % | 13 | 11.9 | +| 25 | Horizon | 20.2 | 36.8 | 20.0 | 1.74 GB | 121 % | 32 | 28.9 | +| 25 | Vanilla | 37.0 | 49.4 | 20.0 | 3.73 GB | 169 % | 32 | 28.9 | + +### Explore as fast as each server sends chunks (not equal work) + +The default 22 blocks a second is faster than either server can generate, so each server sets the pace and +a faster server is given more work: from 10 bots Horizon generated 1.5 to 2 times vanilla's new chunks a +second. Read it as throughput, not as a like-for-like tick time. + +| Bots | Server | MSPT | P95 | TPS | RSS | CPU | Chunks/s | New chunks/s | +|---:|---|---:|---:|---:|---:|---:|---:|---:| +| 1 | Horizon | 10.6 | 24.6 | 20.0 | 1.34 GB | 322 % | 39 | 34.6 | +| 1 | Vanilla | 9.9 | 21.3 | 20.0 | 3.48 GB | 245 % | 36 | 33.4 | +| 10 | Horizon | 30.4 | 52.3 | 20.0 | 2.18 GB | 345 % | 47 | 46.7 | +| 10 | Vanilla | 17.0 | 29.6 | 20.0 | 4.04 GB | 242 % | 22 | 22.4 | +| 25 | Horizon | 50.7 | 89.3 | 19.7 | 2.30 GB | 286 % | 50 | 49.7 | +| 25 | Vanilla | 24.2 | 36.5 | 20.0 | 4.40 GB | 320 % | 34 | 33.7 | +| 50 | Horizon | 50.7 | 102.7 | 19.7 | 1.72 GB | 213 % | 97 | 96.5 | +| 50 | Vanilla | stopped by its watchdog | | | | | | | +| 100 | Horizon | 92.9 | 139.6 | 10.8 | 1.70 GB | 322 % | 114 | 113.6 | +| 100 | Vanilla | stopped by its watchdog | | | | | | | + +Vanilla's watchdog stopped it at 50 bots (in `ClientboundLightUpdatePacketData`, copying light for a chunk +packet) and at 100 (in `Entity.move` from a move packet). + +## Findings + +- Horizon's RSS is 1.9 to 2.6 times smaller in every run, and it starts in 11 s against vanilla's 15 s. + Vanilla's heap is fixed at 4 GB (`-Xms4g`), so part of its RSS is that setting rather than need. +- With 1 bot Horizon's tick is 3.3 times shorter walking and 4.5 times shorter exploring at equal work; + at 10 bots it is still shorter in both. +- At equal exploring work Horizon's tick is about half of vanilla's at 10 and 25 bots. +- When the bots only fly around spawn (`walk`), vanilla's tick hardly grows with players (16 to 20 ms from + 1 to 50 bots) while Horizon's grows by about 0.5 ms per bot, so vanilla is ahead from about 20 bots: 16.0 + against 20.7 ms at 25 and 20.5 against 31.4 ms at 50. Both keep 20 TPS up to 50. +- With 100 bots vanilla's watchdog stops it in every pass, and Horizon keeps running at 9 to 11 TPS. + +### Where Horizon's walk tick goes at 25 bots + +Profiled on the ThinkPad with `perf` (the server thread, 20 s, self time): + +| Share | What | Whose | +|---:|---|---| +| 18 % | `Streaming::update`: every tick it walks all loaded columns and proto chunks and tests each against every player's area (unloading, dropping protos, finishing and decoration candidates), so the cost grows with players times chunks | streaming / engine tick | +| 20 % | `PalettedContainer::get` and `World::block`, mostly from block entity ticks: on the Mac profile `tick_hoppers` looks up the block under every block entity in the loaded world each tick and compares names as strings, and spawners rebuild their display id | engine tick | +| 8 % | `light_data` when a chunk is sent: the light layers were built twice per chunk; a follow-up commit on #623 builds them once and keeps each section's packed layers | server (this work) | +| 7 % | encoding chunk sections and heightmaps for the chunks each bot newly sees | server | +| 4 % | `Hub::tick` (moves, tracking) | server | +| 2 % | the moved-wrongly collision check | server | + +The first two grow with the number of players but aren't specific to the server: they are the +engine's tick and streaming, reported to perf-server-2. Before #623 and #649, encoding every chunk section +once per player and waking each connection's writer thread once per packet cost more than everything above +(at 50 walking bots the tick was 281 ms; see the earlier runs). + +## Earlier runs (same machine and method) + +- `run-1-before-chunk-cache.json`: before #623, with vanilla's locator bar on. Horizon's walk tick was + 27.5, 40.7, 281 and 467 ms at 10, 25, 50 and 100 bots, and vanilla's 33.2 ms at 50 (the locator bar). +- `run-2-chunk-cache.json`: Horizon with #623 only: 13.2, 23.5, 31.4 and 84.4 ms walking at 10 to 100 + bots. + +## Files + +- `horizon.json`, `vanilla.json`: the walk and explore passes (vanilla with `locator_bar=false`). +- `explore-equal-rate.json`: the explore pass at 0.8 blocks a second, both servers. +- `run-1-before-chunk-cache.json`, `run-2-chunk-cache.json`: the earlier runs. + +To run it again (bots on another machine reached at `--connect`): + + cargo build --release -p horizon-client --bin horizon-client -p horizon-server -p horizon-bots + python3 tools/server_bench.py --servers horizon,vanilla --bots 1,10,25,50,100 --behaviour walk,explore \ + --gamerule locator_bar=false --nice 19 --bots-via 'ssh macmini' --bots-bin /path/to/horizon-bots \ + --connect --out results.json + python3 tools/server_bench.py --servers horizon,vanilla --bots 1,10,25 --behaviour explore \ + --explore-speed 0.8 --gamerule locator_bar=false --nice 19 ... --out explore-equal-rate.json diff --git a/benchmarks/server-equal-work-2026-10-17/explore-equal-rate.json b/benchmarks/server-equal-work-2026-10-17/explore-equal-rate.json new file mode 100644 index 000000000..bd097e43a --- /dev/null +++ b/benchmarks/server-equal-work-2026-10-17/explore-equal-rate.json @@ -0,0 +1,267 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T05:47:12+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon,vanilla", + "bots": "1,10,25", + "behaviour": "explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 300, + "seed": 12345, + "explore_speed": 0.8, + "gamerule": "locator_bar=false", + "heap": "4g", + "out": "/home/ludovic/scratch/sh2-bench5.json", + "nice": 19, + "bots_via": "ssh -o BatchMode=yes macmini", + "bots_bin": "/tmp/sh2-horizon-bots", + "connect": "100.72.51.8", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "explore", + "start_seconds": 10.91, + "mspt": { + "average": 4.02, + "p50": 3.75, + "p95": 6.63, + "p99": 14.55 + }, + "mspt_worst_p99": 63.3, + "tps": 20.0, + "rss_mb": { + "mean": 1392.42, + "max": 1746.1 + }, + "cpu_percent": 24.52, + "chunks_per_second": 1.69, + "unique_per_second": 1.34, + "forgotten_per_second": 1.62, + "waited_ticks_per_second": 0.0, + "chunks_total": 1048, + "chunks_per_bot": { + "explore": 1048.0 + }, + "unique_chunks_per_bot": { + "explore": 952.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "explore", + "start_seconds": 15.13, + "mspt": { + "average": 18.12, + "p50": 18.78, + "p95": 27.07, + "p99": 60.81 + }, + "mspt_worst_p99": 1397.6, + "tps": 20.0, + "rss_mb": { + "mean": 3397.31, + "max": 3430.2 + }, + "cpu_percent": 72.99, + "chunks_per_second": 1.69, + "unique_per_second": 1.38, + "forgotten_per_second": 1.62, + "waited_ticks_per_second": 0.0, + "chunks_total": 1048, + "chunks_per_bot": { + "explore": 1048.0 + }, + "unique_chunks_per_bot": { + "explore": 952.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "explore", + "start_seconds": 11.12, + "mspt": { + "average": 13.49, + "p50": 12.09, + "p95": 24.81, + "p99": 40.9 + }, + "mspt_worst_p99": 101.4, + "tps": 20.0, + "rss_mb": { + "mean": 1684.04, + "max": 2660.6 + }, + "cpu_percent": 89.04, + "chunks_per_second": 13.08, + "unique_per_second": 11.84, + "forgotten_per_second": 13.02, + "waited_ticks_per_second": 0.0, + "chunks_total": 9277, + "chunks_per_bot": { + "explore": 927.7 + }, + "unique_chunks_per_bot": { + "explore": 889.9 + }, + "resent": 0, + "pulled_back": 3381, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "explore", + "start_seconds": 14.84, + "mspt": { + "average": 29.18, + "p50": 26.76, + "p95": 43.02, + "p99": 80.16 + }, + "mspt_worst_p99": 425.5, + "tps": 20.0, + "rss_mb": { + "mean": 3609.51, + "max": 3791.6 + }, + "cpu_percent": 142.79, + "chunks_per_second": 13.1, + "unique_per_second": 11.88, + "forgotten_per_second": 13.12, + "waited_ticks_per_second": 0.0, + "chunks_total": 9245, + "chunks_per_bot": { + "explore": 924.5 + }, + "unique_chunks_per_bot": { + "explore": 885.3 + }, + "resent": 0, + "pulled_back": 3388, + "moved_too_quickly": 6, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "explore", + "start_seconds": 11.02, + "mspt": { + "average": 20.25, + "p50": 18.73, + "p95": 36.78, + "p99": 55.76 + }, + "mspt_worst_p99": 92.3, + "tps": 20.0, + "rss_mb": { + "mean": 1782.26, + "max": 2741.9 + }, + "cpu_percent": 120.8, + "chunks_per_second": 32.22, + "unique_per_second": 28.89, + "forgotten_per_second": 32.19, + "waited_ticks_per_second": 0.0, + "chunks_total": 23357, + "chunks_per_bot": { + "explore": 934.28 + }, + "unique_chunks_per_bot": { + "explore": 890.32 + }, + "resent": 0, + "pulled_back": 11580, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "explore", + "start_seconds": 14.54, + "mspt": { + "average": 37.04, + "p50": 34.77, + "p95": 49.42, + "p99": 101.67 + }, + "mspt_worst_p99": 735.2, + "tps": 20.0, + "rss_mb": { + "mean": 3815.46, + "max": 4202.0 + }, + "cpu_percent": 169.15, + "chunks_per_second": 32.34, + "unique_per_second": 28.93, + "forgotten_per_second": 32.31, + "waited_ticks_per_second": 0.0, + "chunks_total": 23306, + "chunks_per_bot": { + "explore": 932.24 + }, + "unique_chunks_per_bot": { + "explore": 886.96 + }, + "resent": 0, + "pulled_back": 11539, + "moved_too_quickly": 6, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 59 + } + ] +} diff --git a/benchmarks/server-equal-work-2026-10-17/horizon.json b/benchmarks/server-equal-work-2026-10-17/horizon.json new file mode 100644 index 000000000..d0b162c44 --- /dev/null +++ b/benchmarks/server-equal-work-2026-10-17/horizon.json @@ -0,0 +1,415 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T05:04:57+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon", + "bots": "1,10,25,50,100", + "behaviour": "walk,explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 300, + "seed": 12345, + "explore_speed": 0, + "gamerule": "locator_bar=false", + "heap": "4g", + "out": "/home/ludovic/scratch/sh2-bench4.json", + "nice": 19, + "bots_via": "ssh -o BatchMode=yes macmini", + "bots_bin": "/tmp/sh2-horizon-bots", + "connect": "100.72.51.8", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "walk", + "start_seconds": 11.02, + "mspt": { + "average": 5.45, + "p50": 4.63, + "p95": 12.14, + "p99": 30.63 + }, + "mspt_worst_p99": 91.5, + "tps": 20.0, + "rss_mb": { + "mean": 1398.5, + "max": 1708.4 + }, + "cpu_percent": 57.03, + "chunks_per_second": 9.17, + "unique_per_second": 0.26, + "forgotten_per_second": 9.2, + "waited_ticks_per_second": 0.0, + "chunks_total": 3708, + "chunks_per_bot": { + "walk": 3708.0 + }, + "unique_chunks_per_bot": { + "walk": 694.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "walk", + "start_seconds": 11.02, + "mspt": { + "average": 11.51, + "p50": 10.6, + "p95": 22.13, + "p99": 36.92 + }, + "mspt_worst_p99": 71.9, + "tps": 20.0, + "rss_mb": { + "mean": 1440.2, + "max": 1832.4 + }, + "cpu_percent": 124.19, + "chunks_per_second": 94.04, + "unique_per_second": 2.38, + "forgotten_per_second": 93.95, + "waited_ticks_per_second": 0.0, + "chunks_total": 37269, + "chunks_per_bot": { + "walk": 3726.9 + }, + "unique_chunks_per_bot": { + "walk": 688.9 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "walk", + "start_seconds": 10.91, + "mspt": { + "average": 20.74, + "p50": 19.27, + "p95": 40.42, + "p99": 57.12 + }, + "mspt_worst_p99": 102.0, + "tps": 20.0, + "rss_mb": { + "mean": 1485.4, + "max": 1871.9 + }, + "cpu_percent": 169.52, + "chunks_per_second": 235.81, + "unique_per_second": 5.68, + "forgotten_per_second": 235.83, + "waited_ticks_per_second": 0.0, + "chunks_total": 94456, + "chunks_per_bot": { + "walk": 3778.24 + }, + "unique_chunks_per_bot": { + "walk": 692.96 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "walk", + "start_seconds": 11.12, + "mspt": { + "average": 31.41, + "p50": 25.39, + "p95": 78.97, + "p99": 110.73 + }, + "mspt_worst_p99": 192.9, + "tps": 20.0, + "rss_mb": { + "mean": 1558.34, + "max": 1915.3 + }, + "cpu_percent": 173.27, + "chunks_per_second": 450.85, + "unique_per_second": 10.3, + "forgotten_per_second": 451.86, + "waited_ticks_per_second": 0.0, + "chunks_total": 186885, + "chunks_per_bot": { + "walk": 3737.7 + }, + "unique_chunks_per_bot": { + "walk": 688.9 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "walk", + "start_seconds": 18.16, + "mspt": { + "average": 114.55, + "p50": 101.37, + "p95": 256.19, + "p99": 338.64 + }, + "mspt_worst_p99": 442.6, + "tps": 8.73, + "rss_mb": { + "mean": 1357.65, + "max": 1358.4 + }, + "cpu_percent": 181.21, + "chunks_per_second": 484.16, + "unique_per_second": 30.76, + "forgotten_per_second": 478.77, + "waited_ticks_per_second": 0.0, + "chunks_total": 212947, + "chunks_per_bot": { + "walk": 2129.47 + }, + "unique_chunks_per_bot": { + "walk": 583.02 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 57 + }, + { + "server": "horizon", + "bots": 1, + "behaviour": "explore", + "start_seconds": 17.45, + "mspt": { + "average": 10.62, + "p50": 9.2, + "p95": 24.61, + "p99": 38.18 + }, + "mspt_worst_p99": 81.1, + "tps": 20.0, + "rss_mb": { + "mean": 1372.73, + "max": 1568.7 + }, + "cpu_percent": 322.38, + "chunks_per_second": 39.21, + "unique_per_second": 34.6, + "forgotten_per_second": 38.55, + "waited_ticks_per_second": 0.51, + "chunks_total": 12549, + "chunks_per_bot": { + "explore": 12549.0 + }, + "unique_chunks_per_bot": { + "explore": 11168.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "explore", + "start_seconds": 11.32, + "mspt": { + "average": 30.38, + "p50": 27.84, + "p95": 52.31, + "p99": 77.89 + }, + "mspt_worst_p99": 158.3, + "tps": 20.0, + "rss_mb": { + "mean": 2231.56, + "max": 4022.6 + }, + "cpu_percent": 344.99, + "chunks_per_second": 47.34, + "unique_per_second": 46.73, + "forgotten_per_second": 44.57, + "waited_ticks_per_second": 112.27, + "chunks_total": 19870, + "chunks_per_bot": { + "explore": 1987.0 + }, + "unique_chunks_per_bot": { + "explore": 1966.5 + }, + "resent": 0, + "pulled_back": 16130, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "explore", + "start_seconds": 11.42, + "mspt": { + "average": 50.67, + "p50": 47.61, + "p95": 89.3, + "p99": 119.15 + }, + "mspt_worst_p99": 222.3, + "tps": 19.73, + "rss_mb": { + "mean": 2358.4, + "max": 4273.7 + }, + "cpu_percent": 286.32, + "chunks_per_second": 50.39, + "unique_per_second": 49.67, + "forgotten_per_second": 47.45, + "waited_ticks_per_second": 311.85, + "chunks_total": 28954, + "chunks_per_bot": { + "explore": 1158.16 + }, + "unique_chunks_per_bot": { + "explore": 1147.56 + }, + "resent": 0, + "pulled_back": 36319, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "explore", + "start_seconds": 20.06, + "mspt": { + "average": 50.69, + "p50": 47.48, + "p95": 102.67, + "p99": 133.27 + }, + "mspt_worst_p99": 274.4, + "tps": 19.73, + "rss_mb": { + "mean": 1764.01, + "max": 2542.0 + }, + "cpu_percent": 212.83, + "chunks_per_second": 97.33, + "unique_per_second": 96.47, + "forgotten_per_second": 76.74, + "waited_ticks_per_second": 750.49, + "chunks_total": 38538, + "chunks_per_bot": { + "explore": 770.76 + }, + "unique_chunks_per_bot": { + "explore": 763.84 + }, + "resent": 0, + "pulled_back": 39880, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "explore", + "start_seconds": 11.82, + "mspt": { + "average": 92.93, + "p50": 87.84, + "p95": 139.6, + "p99": 178.38 + }, + "mspt_worst_p99": 272.9, + "tps": 10.76, + "rss_mb": { + "mean": 1736.38, + "max": 1855.7 + }, + "cpu_percent": 321.53, + "chunks_per_second": 113.89, + "unique_per_second": 113.56, + "forgotten_per_second": 101.68, + "waited_ticks_per_second": 1179.4, + "chunks_total": 84617, + "chunks_per_bot": { + "explore": 846.17 + }, + "unique_chunks_per_bot": { + "explore": 845.01 + }, + "resent": 0, + "pulled_back": 128104, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 58 + } + ] +} diff --git a/benchmarks/server-equal-work-2026-10-17/run-1-before-chunk-cache.json b/benchmarks/server-equal-work-2026-10-17/run-1-before-chunk-cache.json new file mode 100644 index 000000000..d79b3f179 --- /dev/null +++ b/benchmarks/server-equal-work-2026-10-17/run-1-before-chunk-cache.json @@ -0,0 +1,693 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T00:37:35+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon,vanilla", + "bots": "1,10,25,50,100", + "behaviour": "walk,explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 300, + "seed": 12345, + "heap": "4g", + "out": "/home/ludovic/scratch/sh2-bench.json", + "nice": 19, + "bots_via": "ssh -o BatchMode=yes macmini", + "bots_bin": "/tmp/sh2-horizon-bots", + "connect": "100.72.51.8", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "walk", + "start_seconds": 11.12, + "mspt": { + "average": 7.63, + "p50": 5.51, + "p95": 17.46, + "p99": 36.79 + }, + "mspt_worst_p99": 79.6, + "tps": 20.0, + "rss_mb": { + "mean": 1391.94, + "max": 1700.7 + }, + "cpu_percent": 60.18, + "chunks_per_second": 9.15, + "unique_per_second": 0.29, + "forgotten_per_second": 9.18, + "waited_ticks_per_second": 0.0, + "chunks_total": 3682, + "chunks_per_bot": { + "walk": 3682.0 + }, + "unique_chunks_per_bot": { + "walk": 692.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "walk", + "start_seconds": 15.35, + "mspt": { + "average": 18.08, + "p50": 18.66, + "p95": 28.05, + "p99": 46.94 + }, + "mspt_worst_p99": 456.4, + "tps": 20.0, + "rss_mb": { + "mean": 3455.72, + "max": 3471.7 + }, + "cpu_percent": 65.67, + "chunks_per_second": 9.89, + "unique_per_second": 0.29, + "forgotten_per_second": 9.92, + "waited_ticks_per_second": 0.0, + "chunks_total": 3827, + "chunks_per_bot": { + "walk": 3827.0 + }, + "unique_chunks_per_bot": { + "walk": 699.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "walk", + "start_seconds": 11.22, + "mspt": { + "average": 27.53, + "p50": 24.93, + "p95": 53.93, + "p99": 77.03 + }, + "mspt_worst_p99": 111.4, + "tps": 20.0, + "rss_mb": { + "mean": 1433.85, + "max": 1831.9 + }, + "cpu_percent": 138.65, + "chunks_per_second": 95.98, + "unique_per_second": 2.38, + "forgotten_per_second": 95.78, + "waited_ticks_per_second": 0.0, + "chunks_total": 38041, + "chunks_per_bot": { + "walk": 3804.1 + }, + "unique_chunks_per_bot": { + "walk": 690.8 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "walk", + "start_seconds": 14.83, + "mspt": { + "average": 18.92, + "p50": 16.02, + "p95": 39.0, + "p99": 56.13 + }, + "mspt_worst_p99": 180.3, + "tps": 20.0, + "rss_mb": { + "mean": 3479.45, + "max": 3535.7 + }, + "cpu_percent": 99.39, + "chunks_per_second": 99.93, + "unique_per_second": 2.94, + "forgotten_per_second": 100.04, + "waited_ticks_per_second": 0.0, + "chunks_total": 38411, + "chunks_per_bot": { + "walk": 3841.1 + }, + "unique_chunks_per_bot": { + "walk": 697.1 + }, + "resent": 0, + "pulled_back": 7, + "moved_too_quickly": 7, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "walk", + "start_seconds": 11.52, + "mspt": { + "average": 40.69, + "p50": 37.28, + "p95": 81.16, + "p99": 108.42 + }, + "mspt_worst_p99": 149.9, + "tps": 20.0, + "rss_mb": { + "mean": 1444.12, + "max": 1882.6 + }, + "cpu_percent": 176.94, + "chunks_per_second": 244.11, + "unique_per_second": 6.51, + "forgotten_per_second": 243.96, + "waited_ticks_per_second": 0.0, + "chunks_total": 95219, + "chunks_per_bot": { + "walk": 3808.76 + }, + "unique_chunks_per_bot": { + "walk": 695.64 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "walk", + "start_seconds": 15.23, + "mspt": { + "average": 18.81, + "p50": 17.26, + "p95": 30.16, + "p99": 53.9 + }, + "mspt_worst_p99": 390.0, + "tps": 20.0, + "rss_mb": { + "mean": 3517.36, + "max": 3555.7 + }, + "cpu_percent": 148.52, + "chunks_per_second": 252.34, + "unique_per_second": 7.75, + "forgotten_per_second": 251.95, + "waited_ticks_per_second": 0.0, + "chunks_total": 96645, + "chunks_per_bot": { + "walk": 3865.8 + }, + "unique_chunks_per_bot": { + "walk": 698.4 + }, + "resent": 0, + "pulled_back": 11, + "moved_too_quickly": 11, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "walk", + "start_seconds": 12.72, + "mspt": { + "average": 281.42, + "p50": 278.28, + "p95": 343.64, + "p99": 384.23 + }, + "mspt_worst_p99": 475.1, + "tps": 3.55, + "rss_mb": { + "mean": 1334.32, + "max": 1335.4 + }, + "cpu_percent": 197.11, + "chunks_per_second": 391.5, + "unique_per_second": 21.24, + "forgotten_per_second": 388.33, + "waited_ticks_per_second": 0.0, + "chunks_total": 153136, + "chunks_per_bot": { + "walk": 3062.72 + }, + "unique_chunks_per_bot": { + "walk": 661.82 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 57 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "walk", + "start_seconds": 15.74, + "mspt": { + "average": 33.21, + "p50": 29.9, + "p95": 53.37, + "p99": 109.14 + }, + "mspt_worst_p99": 833.3, + "tps": 20.0, + "rss_mb": { + "mean": 3568.07, + "max": 3594.9 + }, + "cpu_percent": 266.59, + "chunks_per_second": 496.3, + "unique_per_second": 18.64, + "forgotten_per_second": 495.77, + "waited_ticks_per_second": 0.0, + "chunks_total": 191965, + "chunks_per_bot": { + "walk": 3839.3 + }, + "unique_chunks_per_bot": { + "walk": 696.22 + }, + "resent": 0, + "pulled_back": 184, + "moved_too_quickly": 183, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "walk", + "start_seconds": 11.22, + "mspt": { + "average": 467.37, + "p50": 464.62, + "p95": 524.07, + "p99": 548.77 + }, + "mspt_worst_p99": 581.1, + "tps": 2.14, + "rss_mb": { + "mean": 1353.68, + "max": 1354.9 + }, + "cpu_percent": 191.96, + "chunks_per_second": 377.62, + "unique_per_second": 55.8, + "forgotten_per_second": 348.88, + "waited_ticks_per_second": 0.0, + "chunks_total": 165719, + "chunks_per_bot": { + "walk": 1657.19 + }, + "unique_chunks_per_bot": { + "walk": 549.8 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 56 + }, + { + "server": "vanilla", + "bots": 100, + "behaviour": "walk", + "start_seconds": 14.84, + "error": "[Errno 32] Broken pipe" + }, + { + "server": "horizon", + "bots": 1, + "behaviour": "explore", + "start_seconds": 11.12, + "mspt": { + "average": 17.07, + "p50": 16.6, + "p95": 32.82, + "p99": 50.3 + }, + "mspt_worst_p99": 113.9, + "tps": 20.0, + "rss_mb": { + "mean": 1391.72, + "max": 1566.6 + }, + "cpu_percent": 333.8, + "chunks_per_second": 39.42, + "unique_per_second": 34.77, + "forgotten_per_second": 39.34, + "waited_ticks_per_second": 0.0, + "chunks_total": 13860, + "chunks_per_bot": { + "explore": 13860.0 + }, + "unique_chunks_per_bot": { + "explore": 12379.0 + }, + "resent": 0, + "pulled_back": 192, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "explore", + "start_seconds": 16.03, + "mspt": { + "average": 9.9, + "p50": 8.04, + "p95": 20.41, + "p99": 63.62 + }, + "mspt_worst_p99": 351.1, + "tps": 20.0, + "rss_mb": { + "mean": 3709.92, + "max": 3776.2 + }, + "cpu_percent": 246.64, + "chunks_per_second": 36.06, + "unique_per_second": 33.33, + "forgotten_per_second": 35.73, + "waited_ticks_per_second": 0.0, + "chunks_total": 12369, + "chunks_per_bot": { + "explore": 12369.0 + }, + "unique_chunks_per_bot": { + "explore": 11559.0 + }, + "resent": 0, + "pulled_back": 222, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "explore", + "start_seconds": 11.42, + "mspt": { + "average": 33.72, + "p50": 31.08, + "p95": 61.07, + "p99": 89.09 + }, + "mspt_worst_p99": 142.6, + "tps": 20.0, + "rss_mb": { + "mean": 2239.97, + "max": 4108.8 + }, + "cpu_percent": 350.83, + "chunks_per_second": 46.49, + "unique_per_second": 46.08, + "forgotten_per_second": 44.33, + "waited_ticks_per_second": 111.28, + "chunks_total": 19915, + "chunks_per_bot": { + "explore": 1991.5 + }, + "unique_chunks_per_bot": { + "explore": 1974.4 + }, + "resent": 0, + "pulled_back": 17516, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "explore", + "start_seconds": 15.15, + "mspt": { + "average": 16.25, + "p50": 13.67, + "p95": 28.92, + "p99": 115.9 + }, + "mspt_worst_p99": 1202.1, + "tps": 20.0, + "rss_mb": { + "mean": 4202.72, + "max": 4502.7 + }, + "cpu_percent": 247.47, + "chunks_per_second": 22.3, + "unique_per_second": 22.25, + "forgotten_per_second": 22.64, + "waited_ticks_per_second": 78.89, + "chunks_total": 10092, + "chunks_per_bot": { + "explore": 1009.2 + }, + "unique_chunks_per_bot": { + "explore": 1007.4 + }, + "resent": 0, + "pulled_back": 16286, + "moved_too_quickly": 12, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "explore", + "start_seconds": 11.82, + "mspt": { + "average": 48.03, + "p50": 44.99, + "p95": 83.06, + "p99": 109.63 + }, + "mspt_worst_p99": 191.8, + "tps": 20.0, + "rss_mb": { + "mean": 2214.16, + "max": 4598.6 + }, + "cpu_percent": 356.03, + "chunks_per_second": 64.2, + "unique_per_second": 63.5, + "forgotten_per_second": 60.9, + "waited_ticks_per_second": 301.65, + "chunks_total": 32247, + "chunks_per_bot": { + "explore": 1289.88 + }, + "unique_chunks_per_bot": { + "explore": 1279.4 + }, + "resent": 0, + "pulled_back": 42159, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "explore", + "start_seconds": 14.73, + "mspt": { + "average": 25.73, + "p50": 22.75, + "p95": 37.72, + "p99": 201.98 + }, + "mspt_worst_p99": 4051.5, + "tps": 20.0, + "rss_mb": { + "mean": 4355.9, + "max": 4983.2 + }, + "cpu_percent": 309.3, + "chunks_per_second": 33.33, + "unique_per_second": 33.21, + "forgotten_per_second": 34.22, + "waited_ticks_per_second": 258.68, + "chunks_total": 19426, + "chunks_per_bot": { + "explore": 777.04 + }, + "unique_chunks_per_bot": { + "explore": 772.92 + }, + "resent": 0, + "pulled_back": 53918, + "moved_too_quickly": 93, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "explore", + "start_seconds": 11.01, + "mspt": { + "average": 108.61, + "p50": 107.37, + "p95": 151.96, + "p99": 177.41 + }, + "mspt_worst_p99": 271.6, + "tps": 9.21, + "rss_mb": { + "mean": 1775.98, + "max": 1956.9 + }, + "cpu_percent": 359.7, + "chunks_per_second": 100.32, + "unique_per_second": 98.91, + "forgotten_per_second": 95.42, + "waited_ticks_per_second": 518.15, + "chunks_total": 55956, + "chunks_per_bot": { + "explore": 1119.12 + }, + "unique_chunks_per_bot": { + "explore": 1111.42 + }, + "resent": 0, + "pulled_back": 69967, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "explore", + "start_seconds": 14.74, + "error": "[Errno 32] Broken pipe" + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "explore", + "start_seconds": 11.12, + "mspt": { + "average": 244.43, + "p50": 243.58, + "p95": 308.39, + "p99": 360.12 + }, + "mspt_worst_p99": 470.2, + "tps": 4.09, + "rss_mb": { + "mean": 1806.85, + "max": 2084.5 + }, + "cpu_percent": 310.46, + "chunks_per_second": 186.87, + "unique_per_second": 182.99, + "forgotten_per_second": 161.75, + "waited_ticks_per_second": 1131.65, + "chunks_total": 100389, + "chunks_per_bot": { + "explore": 1003.89 + }, + "unique_chunks_per_bot": { + "explore": 991.9 + }, + "resent": 0, + "pulled_back": 56791, + "moved_too_quickly": 344, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 57 + }, + { + "server": "vanilla", + "bots": 100, + "behaviour": "explore", + "start_seconds": 14.83, + "error": "[Errno 32] Broken pipe" + } + ] +} diff --git a/benchmarks/server-equal-work-2026-10-17/run-2-chunk-cache.json b/benchmarks/server-equal-work-2026-10-17/run-2-chunk-cache.json new file mode 100644 index 000000000..4c182395c --- /dev/null +++ b/benchmarks/server-equal-work-2026-10-17/run-2-chunk-cache.json @@ -0,0 +1,413 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T02:22:59+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon", + "bots": "1,10,25,50,100", + "behaviour": "walk,explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 300, + "seed": 12345, + "heap": "4g", + "out": "/home/ludovic/scratch/sh2-bench2.json", + "nice": 19, + "bots_via": "ssh -o BatchMode=yes macmini", + "bots_bin": "/tmp/sh2-horizon-bots", + "connect": "100.72.51.8", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "walk", + "start_seconds": 11.12, + "mspt": { + "average": 5.41, + "p50": 4.63, + "p95": 11.61, + "p99": 30.5 + }, + "mspt_worst_p99": 64.6, + "tps": 20.0, + "rss_mb": { + "mean": 1398.84, + "max": 1708.5 + }, + "cpu_percent": 56.84, + "chunks_per_second": 9.19, + "unique_per_second": 0.27, + "forgotten_per_second": 9.22, + "waited_ticks_per_second": 0.0, + "chunks_total": 3713, + "chunks_per_bot": { + "walk": 3713.0 + }, + "unique_chunks_per_bot": { + "walk": 694.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "walk", + "start_seconds": 10.92, + "mspt": { + "average": 13.18, + "p50": 11.74, + "p95": 26.5, + "p99": 44.82 + }, + "mspt_worst_p99": 87.6, + "tps": 20.0, + "rss_mb": { + "mean": 1439.83, + "max": 1831.6 + }, + "cpu_percent": 132.94, + "chunks_per_second": 93.87, + "unique_per_second": 2.38, + "forgotten_per_second": 93.77, + "waited_ticks_per_second": 0.0, + "chunks_total": 37240, + "chunks_per_bot": { + "walk": 3724.0 + }, + "unique_chunks_per_bot": { + "walk": 688.7 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "walk", + "start_seconds": 10.92, + "mspt": { + "average": 23.52, + "p50": 21.92, + "p95": 44.7, + "p99": 63.12 + }, + "mspt_worst_p99": 119.1, + "tps": 20.0, + "rss_mb": { + "mean": 1485.82, + "max": 1872.0 + }, + "cpu_percent": 173.82, + "chunks_per_second": 235.63, + "unique_per_second": 5.64, + "forgotten_per_second": 235.72, + "waited_ticks_per_second": 0.0, + "chunks_total": 94549, + "chunks_per_bot": { + "walk": 3781.96 + }, + "unique_chunks_per_bot": { + "walk": 692.8 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "walk", + "start_seconds": 10.91, + "mspt": { + "average": 31.36, + "p50": 26.08, + "p95": 70.6, + "p99": 92.83 + }, + "mspt_worst_p99": 125.5, + "tps": 20.0, + "rss_mb": { + "mean": 1556.81, + "max": 1913.0 + }, + "cpu_percent": 192.16, + "chunks_per_second": 468.69, + "unique_per_second": 10.43, + "forgotten_per_second": 468.78, + "waited_ticks_per_second": 0.0, + "chunks_total": 193547, + "chunks_per_bot": { + "walk": 3870.94 + }, + "unique_chunks_per_bot": { + "walk": 692.84 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "walk", + "start_seconds": 11.02, + "mspt": { + "average": 84.38, + "p50": 81.5, + "p95": 132.92, + "p99": 168.38 + }, + "mspt_worst_p99": 245.5, + "tps": 11.85, + "rss_mb": { + "mean": 1395.64, + "max": 1941.3 + }, + "cpu_percent": 271.28, + "chunks_per_second": 850.05, + "unique_per_second": 21.79, + "forgotten_per_second": 851.1, + "waited_ticks_per_second": 0.0, + "chunks_total": 368464, + "chunks_per_bot": { + "walk": 3684.64 + }, + "unique_chunks_per_bot": { + "walk": 680.58 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 1, + "behaviour": "explore", + "start_seconds": 11.02, + "mspt": { + "average": 11.63, + "p50": 10.27, + "p95": 24.52, + "p99": 40.53 + }, + "mspt_worst_p99": 99.9, + "tps": 20.0, + "rss_mb": { + "mean": 1413.81, + "max": 1596.1 + }, + "cpu_percent": 329.84, + "chunks_per_second": 39.47, + "unique_per_second": 34.81, + "forgotten_per_second": 39.42, + "waited_ticks_per_second": 0.0, + "chunks_total": 13798, + "chunks_per_bot": { + "explore": 13798.0 + }, + "unique_chunks_per_bot": { + "explore": 12330.0 + }, + "resent": 0, + "pulled_back": 185, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "explore", + "start_seconds": 11.02, + "mspt": { + "average": 28.49, + "p50": 26.2, + "p95": 48.58, + "p99": 72.04 + }, + "mspt_worst_p99": 125.7, + "tps": 20.0, + "rss_mb": { + "mean": 2231.06, + "max": 4077.8 + }, + "cpu_percent": 344.95, + "chunks_per_second": 46.31, + "unique_per_second": 45.88, + "forgotten_per_second": 44.14, + "waited_ticks_per_second": 111.95, + "chunks_total": 19722, + "chunks_per_bot": { + "explore": 1972.2 + }, + "unique_chunks_per_bot": { + "explore": 1957.0 + }, + "resent": 0, + "pulled_back": 18533, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "explore", + "start_seconds": 11.12, + "mspt": { + "average": 40.04, + "p50": 37.61, + "p95": 62.39, + "p99": 83.64 + }, + "mspt_worst_p99": 147.0, + "tps": 20.0, + "rss_mb": { + "mean": 2466.85, + "max": 4504.5 + }, + "cpu_percent": 340.13, + "chunks_per_second": 60.61, + "unique_per_second": 59.62, + "forgotten_per_second": 56.28, + "waited_ticks_per_second": 299.57, + "chunks_total": 32877, + "chunks_per_bot": { + "explore": 1315.08 + }, + "unique_chunks_per_bot": { + "explore": 1300.72 + }, + "resent": 0, + "pulled_back": 46272, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "explore", + "start_seconds": 11.32, + "mspt": { + "average": 61.82, + "p50": 59.21, + "p95": 90.46, + "p99": 115.58 + }, + "mspt_worst_p99": 320.9, + "tps": 16.18, + "rss_mb": { + "mean": 2634.54, + "max": 4883.1 + }, + "cpu_percent": 356.96, + "chunks_per_second": 95.26, + "unique_per_second": 94.31, + "forgotten_per_second": 85.86, + "waited_ticks_per_second": 528.08, + "chunks_total": 59251, + "chunks_per_bot": { + "explore": 1185.02 + }, + "unique_chunks_per_bot": { + "explore": 1173.96 + }, + "resent": 0, + "pulled_back": 99493, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "explore", + "start_seconds": 10.81, + "mspt": { + "average": 103.24, + "p50": 100.03, + "p95": 144.77, + "p99": 178.8 + }, + "mspt_worst_p99": 258.6, + "tps": 9.69, + "rss_mb": { + "mean": 1784.48, + "max": 1922.0 + }, + "cpu_percent": 336.94, + "chunks_per_second": 115.06, + "unique_per_second": 114.86, + "forgotten_per_second": 109.43, + "waited_ticks_per_second": 1127.57, + "chunks_total": 93839, + "chunks_per_bot": { + "explore": 938.39 + }, + "unique_chunks_per_bot": { + "explore": 935.28 + }, + "resent": 0, + "pulled_back": 133404, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 58 + } + ] +} diff --git a/benchmarks/server-equal-work-2026-10-17/vanilla.json b/benchmarks/server-equal-work-2026-10-17/vanilla.json new file mode 100644 index 000000000..014554cee --- /dev/null +++ b/benchmarks/server-equal-work-2026-10-17/vanilla.json @@ -0,0 +1,324 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T03:29:30+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "vanilla", + "bots": "1,10,25,50,100", + "behaviour": "walk,explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 300, + "seed": 12345, + "gamerule": "locator_bar=false", + "heap": "4g", + "out": "/home/ludovic/scratch/sh2-bench3.json", + "nice": 19, + "bots_via": "ssh -o BatchMode=yes macmini", + "bots_bin": "/tmp/sh2-horizon-bots", + "connect": "100.72.51.8", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "vanilla", + "bots": 1, + "behaviour": "walk", + "start_seconds": 15.43, + "mspt": { + "average": 18.32, + "p50": 19.26, + "p95": 27.34, + "p99": 45.48 + }, + "mspt_worst_p99": 393.3, + "tps": 20.0, + "rss_mb": { + "mean": 3428.43, + "max": 3437.7 + }, + "cpu_percent": 66.47, + "chunks_per_second": 9.92, + "unique_per_second": 0.29, + "forgotten_per_second": 9.95, + "waited_ticks_per_second": 0.0, + "chunks_total": 3850, + "chunks_per_bot": { + "walk": 3850.0 + }, + "unique_chunks_per_bot": { + "walk": 699.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "walk", + "start_seconds": 14.76, + "mspt": { + "average": 16.8, + "p50": 14.55, + "p95": 30.52, + "p99": 50.01 + }, + "mspt_worst_p99": 205.2, + "tps": 20.0, + "rss_mb": { + "mean": 3490.15, + "max": 3580.7 + }, + "cpu_percent": 83.7, + "chunks_per_second": 100.01, + "unique_per_second": 2.83, + "forgotten_per_second": 100.04, + "waited_ticks_per_second": 0.0, + "chunks_total": 38623, + "chunks_per_bot": { + "walk": 3862.3 + }, + "unique_chunks_per_bot": { + "walk": 697.2 + }, + "resent": 0, + "pulled_back": 5, + "moved_too_quickly": 5, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "walk", + "start_seconds": 14.84, + "mspt": { + "average": 16.01, + "p50": 14.55, + "p95": 26.39, + "p99": 51.26 + }, + "mspt_worst_p99": 397.8, + "tps": 20.0, + "rss_mb": { + "mean": 3550.02, + "max": 3593.5 + }, + "cpu_percent": 114.96, + "chunks_per_second": 251.62, + "unique_per_second": 6.72, + "forgotten_per_second": 251.16, + "waited_ticks_per_second": 0.0, + "chunks_total": 98701, + "chunks_per_bot": { + "walk": 3948.04 + }, + "unique_chunks_per_bot": { + "walk": 698.84 + }, + "resent": 0, + "pulled_back": 10, + "moved_too_quickly": 10, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "walk", + "start_seconds": 14.43, + "mspt": { + "average": 20.52, + "p50": 19.55, + "p95": 29.72, + "p99": 49.04 + }, + "mspt_worst_p99": 600.4, + "tps": 20.0, + "rss_mb": { + "mean": 3633.12, + "max": 3658.7 + }, + "cpu_percent": 193.84, + "chunks_per_second": 501.86, + "unique_per_second": 12.15, + "forgotten_per_second": 501.8, + "waited_ticks_per_second": 0.0, + "chunks_total": 203429, + "chunks_per_bot": { + "walk": 4068.58 + }, + "unique_chunks_per_bot": { + "walk": 698.66 + }, + "resent": 0, + "pulled_back": 33, + "moved_too_quickly": 32, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "vanilla", + "bots": 100, + "behaviour": "walk", + "start_seconds": 15.34, + "error": "[Errno 32] Broken pipe" + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "explore", + "start_seconds": 15.55, + "mspt": { + "average": 9.93, + "p50": 8.12, + "p95": 21.33, + "p99": 60.19 + }, + "mspt_worst_p99": 373.0, + "tps": 20.0, + "rss_mb": { + "mean": 3564.11, + "max": 3655.0 + }, + "cpu_percent": 245.18, + "chunks_per_second": 35.93, + "unique_per_second": 33.35, + "forgotten_per_second": 35.64, + "waited_ticks_per_second": 0.0, + "chunks_total": 12340, + "chunks_per_bot": { + "explore": 12340.0 + }, + "unique_chunks_per_bot": { + "explore": 11569.0 + }, + "resent": 0, + "pulled_back": 261, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "explore", + "start_seconds": 15.03, + "mspt": { + "average": 16.99, + "p50": 14.46, + "p95": 29.61, + "p99": 132.18 + }, + "mspt_worst_p99": 1244.0, + "tps": 20.0, + "rss_mb": { + "mean": 4135.2, + "max": 4453.1 + }, + "cpu_percent": 242.32, + "chunks_per_second": 22.39, + "unique_per_second": 22.41, + "forgotten_per_second": 22.78, + "waited_ticks_per_second": 78.78, + "chunks_total": 10177, + "chunks_per_bot": { + "explore": 1017.7 + }, + "unique_chunks_per_bot": { + "explore": 1016.2 + }, + "resent": 0, + "pulled_back": 17314, + "moved_too_quickly": 19, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "explore", + "start_seconds": 14.84, + "mspt": { + "average": 24.19, + "p50": 21.22, + "p95": 36.51, + "p99": 174.82 + }, + "mspt_worst_p99": 1532.8, + "tps": 20.0, + "rss_mb": { + "mean": 4504.55, + "max": 4988.9 + }, + "cpu_percent": 319.55, + "chunks_per_second": 33.78, + "unique_per_second": 33.66, + "forgotten_per_second": 34.64, + "waited_ticks_per_second": 269.22, + "chunks_total": 20522, + "chunks_per_bot": { + "explore": 820.88 + }, + "unique_chunks_per_bot": { + "explore": 815.76 + }, + "resent": 0, + "pulled_back": 46246, + "moved_too_quickly": 28, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "explore", + "start_seconds": 14.73, + "error": "[Errno 32] Broken pipe" + }, + { + "server": "vanilla", + "bots": 100, + "behaviour": "explore", + "start_seconds": 14.54, + "error": "[Errno 32] Broken pipe" + } + ] +} diff --git a/crates/horizon-bots/src/main.rs b/crates/horizon-bots/src/main.rs index d76da5e84..090daeb4e 100644 --- a/crates/horizon-bots/src/main.rs +++ b/crates/horizon-bots/src/main.rs @@ -9,6 +9,11 @@ //! horizon-bots --server 127.0.0.1:25565 --bots 25 --behaviour mixed --seconds 360 --report bots.json //! //! It prints one JSON line a second (bots online, chunks received) and writes a summary with `--report`. +//! A bot moves only while it holds the chunk it stands in: vanilla's client stops ticking its player in a chunk +//! it hasn't received, so a player can't outrun the server's chunk sending, on any server. +//! Each bot also keeps the chunks it holds, as a client's chunk cache does, so the report tells chunks that +//! entered the view apart from chunks sent again while the bot still held them (`resent`), and counts the +//! times the server pulled a bot back (`pulled_back`: a teleport after the first, as for "moved too quickly"). use horizon_protocol::{ PROTOCOL_VERSION, @@ -25,6 +30,7 @@ use horizon_protocol::{ }; use serde_json::json; use std::{ + collections::HashSet, sync::{ Arc, Mutex, atomic::{AtomicBool, AtomicU64, Ordering}, @@ -43,8 +49,9 @@ horizon-bots: load-test bots for a Minecraft Java Edition 26.3 server (offline m --seconds N how long to run after the first bot joins; default 60 --view-distance N what the bots ask for; default 10 --seed N default 12345 + --explore-speed B blocks a second an explore bot flies; default 22 (as fast as chunks come) --name PREFIX bot names: PREFIX0, PREFIX1...; default Bot - --report FILE a JSON summary at the end + --report FILE a JSON summary at the end (- prints it after the per-second lines) "; #[derive(Clone, Copy, Debug, PartialEq)] @@ -73,6 +80,7 @@ struct Options { seconds: u64, view_distance: i8, seed: u64, + explore_speed: f64, name: String, report: Option, } @@ -87,6 +95,7 @@ fn options() -> Result { seconds: 60, view_distance: 10, seed: 12345, + explore_speed: 22.0, name: "Bot".into(), report: None, }; @@ -110,6 +119,9 @@ fn options() -> Result { "--seconds" => o.seconds = value.parse().map_err(|_| number("seconds"))?, "--view-distance" => o.view_distance = value.parse().map_err(|_| number("2 to 32"))?, "--seed" => o.seed = value.parse().map_err(|_| number("a number"))?, + "--explore-speed" => { + o.explore_speed = value.parse().map_err(|_| number("blocks a second"))?; + } "--name" => o.name = value, "--report" => o.report = Some(value), _ => return Err(format!("unknown option {arg}; --help lists them")), @@ -129,6 +141,17 @@ fn options() -> Result { struct Bot { online: AtomicBool, chunks: AtomicU64, + /// Chunks received while the bot already held them (no ForgetLevelChunk in between). + resent: AtomicU64, + /// Different chunks received over the run. + unique: AtomicU64, + forgotten: AtomicU64, + /// Teleports after the spawn one: the server refused a move. + pulled_back: AtomicU64, + /// Ticks the bot couldn't move because it didn't hold its chunk yet. + waited: AtomicU64, + /// The chunks the bot holds (ClientChunkCache). + held: Mutex>, /// Where the server last put the bot (a teleport), to start from. teleport: Mutex>, error: Mutex>, @@ -268,6 +291,36 @@ fn join(o: &Options, name: &str) -> Result { } } +/// ChunkBatchSizeCalculator: the chunks per tick a vanilla client asks for, from how long its batches take +/// to arrive. +struct BatchSize { + nanos_per_chunk: f64, + old_samples_weight: u32, + started: Instant, +} + +impl BatchSize { + fn new() -> Self { + Self { + nanos_per_chunk: 2_000_000.0, + old_samples_weight: 1, + started: Instant::now(), + } + } + fn finished(&mut self, size: i32) { + if size > 0 { + let per_chunk = self.started.elapsed().as_nanos() as f64 / f64::from(size); + let clamped = per_chunk.clamp(self.nanos_per_chunk / 3.0, self.nanos_per_chunk * 3.0); + let weight = f64::from(self.old_samples_weight); + self.nanos_per_chunk = (self.nanos_per_chunk * weight + clamped) / (weight + 1.0); + self.old_samples_weight = (self.old_samples_weight + 1).min(49); + } + } + fn desired_chunks_per_tick(&self) -> f32 { + (7_000_000.0 / self.nanos_per_chunk) as f32 + } +} + /// Reads the play state: answers what a client must answer, counts chunks, records teleports. fn read( mut reader: horizon_protocol::connection::ConnReader, @@ -277,6 +330,9 @@ fn read( use ids::play::clientbound as cb; use ids::play::serverbound as sb; let send = |body: Vec| writer.lock().unwrap().send(&body); + let mut seen = HashSet::new(); + let mut batch = BatchSize::new(); + let mut teleports = 0u64; loop { let (id, body) = match reader.recv() { Ok(packet) => packet, @@ -299,14 +355,38 @@ fn read( }, cb::LEVEL_CHUNK_WITH_LIGHT => { bot.chunks.fetch_add(1, Ordering::Relaxed); + if let (Ok(x), Ok(z)) = (r.i32(), r.i32()) { + if !bot.held.lock().unwrap().insert((x, z)) { + bot.resent.fetch_add(1, Ordering::Relaxed); + } + if seen.insert((x, z)) { + bot.unique.fetch_add(1, Ordering::Relaxed); + } + } Ok(()) } - cb::CHUNK_BATCH_FINISHED => send( - play::Serverbound::ChunkBatchReceived(play::ChunkBatchReceived { - chunks_per_tick: 25.0, - }) - .encode(), - ), + cb::FORGET_LEVEL_CHUNK => { + if let Ok(play::Clientbound::ForgetLevelChunk(p)) = + play::Clientbound::decode(id, &body) + && bot.held.lock().unwrap().remove(&(p.pos[0], p.pos[1])) + { + bot.forgotten.fetch_add(1, Ordering::Relaxed); + } + Ok(()) + } + cb::CHUNK_BATCH_START => { + batch.started = Instant::now(); + Ok(()) + } + cb::CHUNK_BATCH_FINISHED => { + batch.finished(r.varint().unwrap_or(0)); + send( + play::Serverbound::ChunkBatchReceived(play::ChunkBatchReceived { + chunks_per_tick: batch.desired_chunks_per_tick(), + }) + .encode(), + ) + } cb::PLAYER_POSITION => match play::Clientbound::decode(id, &body) { Ok(play::Clientbound::PlayerPosition(p)) => { let mut at = bot.teleport.lock().unwrap(); @@ -320,6 +400,10 @@ fn read( } }); *at = Some(pos); + teleports += 1; + if teleports > 1 { + bot.pulled_back.fetch_add(1, Ordering::Relaxed); + } send( play::Serverbound::AcceptTeleportation(play::AcceptTeleportation { id: p.teleport, @@ -416,7 +500,10 @@ fn run_bot( if let Some(at) = bot.teleport.lock().unwrap().take() { pos = at; } - if pos[1] < cruise { + let here = ((pos[0].floor() as i32) >> 4, (pos[2].floor() as i32) >> 4); + if !bot.held.lock().unwrap().contains(&here) { + bot.waited.fetch_add(1, Ordering::Relaxed); + } else if pos[1] < cruise { pos[1] = (pos[1] + 0.5).min(cruise); } else { match behaviour { @@ -440,9 +527,11 @@ fn run_bot( } } Behaviour::Explore => { - // Flying fast in creative: about 22 blocks a second, which keeps new chunks coming. - pos[0] += heading.cos() * 1.1; - pos[2] += heading.sin() * 1.1; + // Flying in creative, by default about 22 blocks a second, which keeps new + // chunks coming as fast as the server sends them. + let step = o.explore_speed / 20.0; + pos[0] += heading.cos() * step; + pos[2] += heading.sin() * step; } } } @@ -520,6 +609,9 @@ fn main() { .filter(|b| b.online.load(Ordering::SeqCst)) .count(); let chunks: u64 = bots.iter().map(|b| b.chunks.load(Ordering::Relaxed)).sum(); + let total = |f: fn(&Bot) -> &AtomicU64| -> u64 { + bots.iter().map(|b| f(b).load(Ordering::Relaxed)).sum() + }; let failed = bots .iter() .filter(|b| b.error.lock().unwrap().is_some()) @@ -536,6 +628,11 @@ fn main() { "failed": failed, "chunks": chunks, "chunks_per_second": chunks - previous_chunks, + "unique": total(|b| &b.unique), + "forgotten": total(|b| &b.forgotten), + "resent": total(|b| &b.resent), + "pulled_back": total(|b| &b.pulled_back), + "waited_ticks": total(|b| &b.waited), }) ); previous_chunks = chunks; @@ -554,19 +651,30 @@ fn main() { "bots": o.bots, "behaviour": o.behaviour, "seed": o.seed, + "explore_speed": o.explore_speed, "view_distance": o.view_distance, "seconds": o.seconds, "joined": bots.iter().filter(|b| b.joined_after_ms.load(Ordering::SeqCst) > 0).count(), "chunks": bots.iter().map(|b| b.chunks.load(Ordering::Relaxed)).sum::(), + "resent": bots.iter().map(|b| b.resent.load(Ordering::Relaxed)).sum::(), + "pulled_back": bots.iter().map(|b| b.pulled_back.load(Ordering::Relaxed)).sum::(), + "waited_ticks": bots.iter().map(|b| b.waited.load(Ordering::Relaxed)).sum::(), "per_bot": bots.iter().enumerate().map(|(i, b)| json!({ "name": format!("{}{i}", o.name), "behaviour": behaviour_of(&o.behaviour, i).name(), "joined_after_ms": b.joined_after_ms.load(Ordering::SeqCst), "chunks": b.chunks.load(Ordering::Relaxed), + "unique_chunks": b.unique.load(Ordering::Relaxed), + "resent": b.resent.load(Ordering::Relaxed), + "forgotten": b.forgotten.load(Ordering::Relaxed), + "pulled_back": b.pulled_back.load(Ordering::Relaxed), + "waited_ticks": b.waited.load(Ordering::Relaxed), "error": *b.error.lock().unwrap(), })).collect::>(), }); - if let Some(path) = &o.report { + if o.report.as_deref() == Some("-") { + println!("{summary:#}"); + } else if let Some(path) = &o.report { if let Err(e) = std::fs::write(path, format!("{summary:#}\n")) { eprintln!("horizon-bots: {path}: {e}"); } diff --git a/crates/horizon-client/examples/lan_flat.rs b/crates/horizon-client/examples/lan_flat.rs index 16fc36b95..4800f05fa 100644 --- a/crates/horizon-client/examples/lan_flat.rs +++ b/crates/horizon-client/examples/lan_flat.rs @@ -22,12 +22,7 @@ fn main() -> Result<(), Box> { let port: u16 = args.next().ok_or("port")?.parse()?; let assets = Assets::load(&root)?; let facts = BlockFacts::load(&root, assets.registry)?; - let state = |name: &str| { - assets - .registry - .default_state(name) - .map_or(0, |s| s.0 as u16) - }; + let state = |name: &str| assets.registry.default_state(name).map_or(0, |s| s.0); let sync = Arc::new(SyncData::load(&root)?); let biomes: Vec = sync .dynamic @@ -121,6 +116,7 @@ fn main() -> Result<(), Box> { clock_rate: 1.0, tick_rate: 20.0, tick_frozen: false, + collision: None, }; for event in hub.tick(&mut ctx) { match event { @@ -132,7 +128,7 @@ fn main() -> Result<(), Box> { eprintln!("[lan] {packet:?}"); } } - HostEvent::Chat(line) => println!("{line}"), + HostEvent::Chat(line) | HostEvent::Warn(line) => println!("{line}"), HostEvent::Left(_) => {} } } diff --git a/crates/horizon-client/examples/light_parity.rs b/crates/horizon-client/examples/light_parity.rs index afc3e3156..29488130e 100644 --- a/crates/horizon-client/examples/light_parity.rs +++ b/crates/horizon-client/examples/light_parity.rs @@ -232,7 +232,7 @@ fn incremental( c.lit = true; world.insert((x, z), Arc::new(c)); } - let palette: Vec = [ + let palette: Vec = [ "minecraft:air", "minecraft:stone", "minecraft:torch", @@ -242,7 +242,7 @@ fn incremental( "minecraft:glass", ] .iter() - .filter_map(|n| registry.default_state(n).map(|s| s.0 as u16)) + .filter_map(|n| registry.default_state(n).map(|s| s.0)) .chain( facts .states @@ -257,7 +257,7 @@ fn incremental( ] .contains(&&*f.name) }) - .map(|(i, _)| i as u16) + .map(|(i, _)| i as u32) .step_by(3), ) .collect(); diff --git a/crates/horizon-client/examples/random_tick_eligibility_bench.rs b/crates/horizon-client/examples/random_tick_eligibility_bench.rs index 856d7d520..49c32a8f7 100644 --- a/crates/horizon-client/examples/random_tick_eligibility_bench.rs +++ b/crates/horizon-client/examples/random_tick_eligibility_bench.rs @@ -56,16 +56,16 @@ fn main() -> horizon_client::Result<()> { "resource_load_ms={:.3}", start.elapsed().as_secs_f64() * 1000.0 ); - let inactive: Vec = facts + let inactive: Vec = facts .states .iter() .enumerate() .filter(|(_, f)| !f.random_ticks) .take(128) - .map(|(i, _)| i as u16) + .map(|(i, _)| i as u32) .collect(); - let active = registry.default_state("minecraft:grass_block").unwrap().0 as u16; - assert!(facts.get(BlockStateId(u32::from(active))).random_ticks); + let active = registry.default_state("minecraft:grass_block").unwrap().0; + assert!(facts.get(BlockStateId(active)).random_ticks); for (name, palette) in [("sparse", 1), ("dense", 128)] { let start = Instant::now(); let mut chunks = FxHashMap::default(); diff --git a/crates/horizon-client/examples/resource_memory.rs b/crates/horizon-client/examples/resource_memory.rs new file mode 100644 index 000000000..6deb5a9d4 --- /dev/null +++ b/crates/horizon-client/examples/resource_memory.rs @@ -0,0 +1,165 @@ +//! Resident memory of each resource loader, in the game's start order: what a +//! larger registry (content mods, docs/modpacks.md) costs, loader by loader. +//! +//! resource_memory RESOURCES +//! +//! RESOURCES is a prepared root or a content-mod root (`.horizon-cache/mod-content`). +//! Prints, after each step, the live heap (a counting allocator: what the +//! step keeps), the heap's peak during the step (what it parsed on the way) +//! and the process RSS (what the allocator holds on to). On macOS it ends +//! with `footprint`'s physical footprint, the number the OS charges: RSS also +//! counts freed pages the allocator marked reusable. +use horizon_client::{ + assets::Assets, biome::Biomes, blocks::BlockFacts, collisions, crafting::Recipes, items::Items, + light::LightTables, mesher::MeshTables, models, motion::MotionResources, + vanillagen::VanillaTerrain, +}; +use std::{ + alloc::{GlobalAlloc, Layout, System}, + sync::atomic::{AtomicUsize, Ordering::Relaxed}, +}; +use std::{path::PathBuf, process::Command}; +type Result = std::result::Result>; + +struct Counting; +static LIVE: AtomicUsize = AtomicUsize::new(0); +static PEAK: AtomicUsize = AtomicUsize::new(0); +// SAFETY: forwards to the system allocator, only counting sizes. +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + let p = unsafe { System.alloc(layout) }; + if !p.is_null() { + let now = LIVE.fetch_add(layout.size(), Relaxed) + layout.size(); + PEAK.fetch_max(now, Relaxed); + } + p + } + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + unsafe { System.dealloc(ptr, layout) }; + LIVE.fetch_sub(layout.size(), Relaxed); + } + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new: usize) -> *mut u8 { + let p = unsafe { System.realloc(ptr, layout, new) }; + if !p.is_null() { + if new >= layout.size() { + let now = LIVE.fetch_add(new - layout.size(), Relaxed) + new - layout.size(); + PEAK.fetch_max(now, Relaxed); + } else { + LIVE.fetch_sub(layout.size() - new, Relaxed); + } + } + p + } +} +#[global_allocator] +static ALLOC: Counting = Counting; +const MB: f64 = 1048576.0; + +fn rss_mb() -> f64 { + let out = Command::new("ps") + .args(["-o", "rss=", "-p", &std::process::id().to_string()]) + .output() + .ok(); + out.and_then(|o| String::from_utf8(o.stdout).ok()) + .and_then(|s| s.trim().parse::().ok()) + .map_or(0.0, |kb| kb / 1024.0) +} + +fn main() -> Result<()> { + let root = PathBuf::from( + std::env::args() + .nth(1) + .ok_or("usage: resource_memory RESOURCES")?, + ); + println!( + "{:<24} {:>8} {:>8} {:>10} {:>8}", + "step", "live MB", "+live", "step peak", "RSS MB" + ); + let mut last = 0usize; + let mut step = |name: &str| { + let live = LIVE.load(Relaxed); + let peak = PEAK.swap(live, Relaxed); + println!( + "{name:<24} {:>8.0} {:>+8.0} {:>10.0} {:>8.0}", + live as f64 / MB, + (live as f64 - last as f64) / MB, + peak as f64 / MB, + rss_mb() + ); + last = live; + }; + step("start"); + let registry = horizon_world::level::data::load_registry(&root)?; + step("registry alone"); + drop(registry); + step("registry dropped"); + let assets = Assets::load(&root)?; + step("assets"); + println!( + " sprites: {} layers of {}px, {:.0} MB of pixels", + assets.texture_layers, + assets.sprite_size, + assets.pixels.len() as f64 / MB + ); + // The game decodes gameplay facts once for both tables (BlockFacts::load_pair). + let (facts, behaviours) = BlockFacts::load_pair(&root, assets.registry)?; + step("block facts+behaviours"); + let items = Items::load(&root, assets.registry, &facts)?; + step("items"); + let recipes = Recipes::load(&root, &items)?; + step("recipes"); + let biomes = Biomes::load(&root)?; + step("biomes"); + let light = LightTables::load(&root, assets.registry, &facts)?; + step("light tables"); + let tables = MeshTables::new( + &assets, + &facts, + models::load_visibility(&root, assets.registry)?, + )?; + step("mesh tables"); + let collision = collisions::load(&root, assets.registry)?; + step("collision"); + let motion = MotionResources::load(&root, &assets)?; + step("motion"); + for name in [ + "worldgen/blocks/block-properties.nbt", + "worldgen/blocks/cached-collision.nbt", + "worldgen/blocks/cached-support.nbt", + "cached-collision.nbt", + "occlusion.nbt", + "movement-properties.nbt", + ] { + let bytes = std::fs::read(root.join(name))?; + let tree = horizon_world::nbt::read_named(&bytes, horizon_world::nbt::Limits::tables())?; + step(&format!(" tree of {name}")); + drop((tree, bytes)); + step(" dropped"); + } + let terrain = VanillaTerrain::new(&root.join("worldgen"), assets.registry, &biomes, 1234)?; + step("worldgen"); + println!( + "{} block states; live {:.0} MB, RSS {:.0} MB", + facts.states.len(), + LIVE.load(Relaxed) as f64 / MB, + rss_mb() + ); + if let Ok(out) = Command::new("footprint") + .arg(std::process::id().to_string()) + .output() + { + let text = String::from_utf8_lossy(&out.stdout); + for line in text + .lines() + .filter(|l| l.contains("Footprint") || l.contains("phys_footprint")) + { + println!(" {}", line.trim()); + } + } + // Keep everything alive until the end. + drop(( + terrain, behaviours, motion, collision, tables, light, biomes, recipes, items, facts, + assets, + )); + Ok(()) +} diff --git a/crates/horizon-client/examples/save_batch_bench.rs b/crates/horizon-client/examples/save_batch_bench.rs index 11c4f64ed..4ee5103de 100644 --- a/crates/horizon-client/examples/save_batch_bench.rs +++ b/crates/horizon-client/examples/save_batch_bench.rs @@ -4,7 +4,7 @@ //! Exact NBT equality is always validated. No GPU, compression or disk I/O timed. use horizon_client::{ biome::Biomes, - chunk::{BLOCK_STRATEGY, Chunk}, + chunk::{Chunk, block_strategy}, containers::BlockEntity, items::ItemStack, save::{self, ChunkExtras}, @@ -64,7 +64,7 @@ fn fixture(per_chunk: usize) -> (Vec>, Entities, Names) { }; let mut template = Chunk::empty(0, 0); for s in &mut template.sections[..8] { - Arc::make_mut(s).blocks = PalettedContainer::new(BLOCK_STRATEGY, 1); + Arc::make_mut(s).blocks = PalettedContainer::new(block_strategy(), 1); } template.heights = Arc::new([64; 256]); for i in 0..256 { diff --git a/crates/horizon-client/examples/save_parity.rs b/crates/horizon-client/examples/save_parity.rs index ba2c4b0fa..3954e3bb3 100644 --- a/crates/horizon-client/examples/save_parity.rs +++ b/crates/horizon-client/examples/save_parity.rs @@ -257,9 +257,9 @@ fn main() -> horizon_client::Result<()> { ); Ok(()) } -fn tables_air(assets: &Assets) -> u16 { +fn tables_air(assets: &Assets) -> u32 { assets .registry .default_state("minecraft:air") - .map_or(0, |s| s.0 as u16) + .map_or(0, |s| s.0) } diff --git a/crates/horizon-client/examples/section_mesh_fixture.rs b/crates/horizon-client/examples/section_mesh_fixture.rs index a42448794..6359f32d0 100644 --- a/crates/horizon-client/examples/section_mesh_fixture.rs +++ b/crates/horizon-client/examples/section_mesh_fixture.rs @@ -83,7 +83,7 @@ fn scene( for block in row["blocks"].as_array().ok_or("missing blocks")? { let (x, y, z) = (int(&block[0])?, int(&block[1])?, int(&block[2])?); let i = chunk_index(x, z)?; - chunks[i].set(x & 15, y, z & 15, u16::try_from(int(&block[3])?)?); + chunks[i].set(x & 15, y, z & 15, u32::try_from(int(&block[3])?)?); } for cell in row["lights"].as_array().ok_or("missing lights")? { let (x, y, z) = (int(&cell[0])?, int(&cell[1])?, int(&cell[2])?); diff --git a/crates/horizon-client/src/advancements.rs b/crates/horizon-client/src/advancements.rs index 22ffcc9d7..16028e220 100644 --- a/crates/horizon-client/src/advancements.rs +++ b/crates/horizon-client/src/advancements.rs @@ -607,6 +607,29 @@ pub struct Entities<'a> { pub tool: Option<&'a ItemView>, pub block_pos: Option<[i32; 3]>, } +/// Conditions shared by item/entity interactions and thrown-item pickups. +pub fn item_entity( + v: &Value, + player: &EntityView, + target: &EntityView, + stack: &ItemView, + w: &dyn World, +) -> bool { + let pctx = Entities { + this: Some(player), + origin: player.position, + tool: None, + block_pos: None, + }; + let ectx = Entities { + this: Some(target), + ..pctx + }; + conditions(&v["player"], &pctx, w) + && conditions(&v["entity"], &ectx, w) + && item(&v["item"], stack, w) +} + /// A `ContextAwarePredicate`: a list of loot conditions (or one condition). pub fn conditions(v: &Value, ctx: &Entities, w: &dyn World) -> bool { match v { @@ -996,7 +1019,75 @@ mod tests { false } fn in_tag(&self, _: &str, tag: &str, id: &str) -> bool { - tag == "minecraft:stone_tool_materials" && id == "minecraft:cobblestone" + (tag == "minecraft:stone_tool_materials" && id == "minecraft:cobblestone") + || (tag == "minecraft:sulfur_cube_archetype/explosive" && id == "minecraft:tnt") + } + } + #[test] + fn uh_oh_accepts_either_tnt_event_only_for_adult_sulfur_cubes() { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join( + "../../.local/horizon-client/26.3/data/minecraft/advancement/husbandry/uh_oh.json", + ); + if !path.exists() { + return; + } + let json = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); + let advancement = parse("minecraft:husbandry/uh_oh", &json).unwrap(); + assert_eq!(advancement.criteria.len(), 2); + let player = EntityView { + kind: "minecraft:player".into(), + ..Default::default() + }; + let mut target = EntityView { + kind: "minecraft:sulfur_cube".into(), + ..Default::default() + }; + let mut stack = ItemView { + id: "minecraft:tnt".into(), + count: 1, + ..Default::default() + }; + for criterion in &advancement.criteria { + assert!(item_entity( + &criterion.conditions, + &player, + &target, + &stack, + &Flat + )); + let mut progress = Progress::default(); + progress.grant(&advancement.id, &criterion.name, "test"); + assert!( + progress.done(&advancement), + "either criterion must award Uh Oh" + ); + target.baby = true; + assert!(!item_entity( + &criterion.conditions, + &player, + &target, + &stack, + &Flat + )); + target.baby = false; + target.kind = "minecraft:pig".into(); + assert!(!item_entity( + &criterion.conditions, + &player, + &target, + &stack, + &Flat + )); + target.kind = "minecraft:sulfur_cube".into(); + stack.id = "minecraft:stone".into(); + assert!(!item_entity( + &criterion.conditions, + &player, + &target, + &stack, + &Flat + )); + stack.id = "minecraft:tnt".into(); } } #[test] diff --git a/crates/horizon-client/src/assets.rs b/crates/horizon-client/src/assets.rs index b8551a059..f278740f5 100644 --- a/crates/horizon-client/src/assets.rs +++ b/crates/horizon-client/src/assets.rs @@ -189,6 +189,9 @@ impl Assets { .default_state(&format!("minecraft:{name}")) .ok_or_else(|| invalid("missing test-scene material"))?; } + // Chunks hold every state of this registry: content mods can take it + // past vanilla's 16-bit global palette. + crate::chunk::set_block_states(registry.len()); let registry: &'static BlockRegistry = Box::leak(Box::new(registry)); Self::with_models( root, diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 9c90e8ebf..db6bf7b79 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -737,6 +737,8 @@ pub struct Scene<'a> { pub struct BlockEntityRenderer { models: HashMap<&'static str, ModelPart>, kinds: Vec, + // Closed chest geometry: dimension lighting, chest part, horizontal facing. + closed_chests: [[[Vec; 4]; 3]; 2], /// Item id to its `PROVIDES_POTTERY_PATTERN` side texture (`Sheets.DECORATED_POT_MAPPER`). pot_patterns: HashMap, /// `Block.shouldRenderFace` for End gateway faces (its occlusion pair cache needs a lock). @@ -817,6 +819,43 @@ impl BlockEntityRenderer { Ok(renderer) } fn new(models: HashMap<&'static str, ModelPart>, registry: &BlockRegistry) -> Self { + let closed_chests = [false, true].map(|nether| { + ["chest", "double_chest_left", "double_chest_right"].map(|name| { + [0.0f32, 90.0, 180.0, 270.0].map(|y_rot| { + let mut vertices = Vec::new(); + if let Some(model) = models.get(name) { + draw_part( + model, + "root", + around( + Mat4::from_rotation_y((-y_rot).to_radians()), + Vec3::new(0.5, 0.0, 0.5), + ), + &|name, p| { + if name == "lid" || name == "lock" { + p[3] = crate::block_entity_anim::chest_lid_x_rot(0.0); + } + }, + Paint { + sprite: Rect { + u0: 0.0, + v0: 0.0, + u1: 1.0, + v1: 1.0, + w: 16, + h: 16, + }, + tint: 0xFFFFFF, + light: 0, + lights: diffuse_lights(nether), + }, + &mut vertices, + ); + } + vertices + }) + }) + }); let kinds = (0..registry.len() as u32) .map(|id| { registry.state(BlockStateId(id)).map_or(Kind::None, |s| { @@ -831,6 +870,7 @@ impl BlockEntityRenderer { Self { models, kinds, + closed_chests, pot_patterns: HashMap::new(), visibility: None, } @@ -876,7 +916,7 @@ impl BlockEntityRenderer { .as_vec3(); let base = Mat4::from_translation(origin); let packed = scene.world.light(pos[0], pos[1], pos[2]); - self.render_one(scene, *pos, kind, base, packed, lights, false, out); + self.render_one(scene, *pos, kind, base, packed, lights, false, true, out); } } /// One block entity at `pos` drawn under `base` with the given packed light @@ -892,7 +932,7 @@ impl BlockEntityRenderer { ) { let kind = self.kind(state); let lights = diffuse_lights(scene.nether); - self.render_one(scene, pos, kind, base, packed, lights, false, out); + self.render_one(scene, pos, kind, base, packed, lights, false, false, out); } /// Whether this block state has a block-entity renderer here. pub fn renders(&self, state: u32) -> bool { @@ -915,6 +955,7 @@ impl BlockEntityRenderer { 0xff, diffuse_lights(scene.nether), true, + false, out, ); crate::breaking::entity_geometry(&mut out[start..], origin); @@ -991,7 +1032,17 @@ impl BlockEntityRenderer { let kind = self.kind(state); if !matches!(kind, Kind::None) { let lights = diffuse_lights(scene.nether); - self.render_one(scene, [i32::MAX; 3], kind, base, packed, lights, false, out); + self.render_one( + scene, + [i32::MAX; 3], + kind, + base, + packed, + lights, + false, + false, + out, + ); } } #[allow(clippy::too_many_arguments)] @@ -1004,6 +1055,7 @@ impl BlockEntityRenderer { packed: u8, lights: (Vec3, Vec3), crumbling: bool, + world_chests: bool, out: &mut Vec, ) { let sprite = |name: &str| scene.sprites.get(name).copied(); @@ -1107,6 +1159,23 @@ impl BlockEntityRenderer { let l = scene.world.light(other[0], other[1], other[2]); packed = (packed >> 4).max(l >> 4) << 4 | (packed & 15).max(l & 15); } + if world_chests && open == 0.0 { + if let Some(paint) = paint(texture, 0xFFFFFF, packed) { + let vertices = &self.closed_chests[usize::from(scene.nether)] + [*part as usize][*y_rot as usize / 90]; + let origin = base.w_axis.truncate(); + out.extend(vertices.iter().map(|v| Vertex { + pos: (Vec3::from_array(v.pos) + origin).to_array(), + uv: [ + paint.sprite.u0 + (paint.sprite.u1 - paint.sprite.u0) * v.uv[0], + paint.sprite.v0 + (paint.sprite.v1 - paint.sprite.v0) * v.uv[1], + ], + light: paint.light, + ..*v + })); + } + return; + } let m = base * around( Mat4::from_rotation_y((-y_rot).to_radians()), @@ -1791,16 +1860,18 @@ mod tests { ( name.to_owned(), Rect { - u0: 0.0, - v0: 0.0, - u1: 1.0, - v1: 1.0, + u0: 0.25, + v0: 0.125, + u1: 0.375, + v1: 0.25, w: 16, h: 16, }, ) }) .collect(); + let cache_open = std::cell::Cell::new(0.0); + let cache_lid = |_| cache_open.get(); let mut scene = Scene { camera: DVec3::ZERO, orientation: Quat::IDENTITY, @@ -1817,6 +1888,56 @@ mod tests { banner: &|_| Vec::new(), glyph: &|_| (None, 0.0), }; + // Compare the cached world path with the original model renderer, + // including atlas replacement, current light and animated fallback. + scene.lid = &cache_lid; + for nether in [false, true] { + scene.nether = nether; + for part in [ChestPart::Single, ChestPart::Left, ChestPart::Right] { + for y_rot in [0.0, 90.0, 180.0, 270.0] { + let kind = Kind::Chest { + block: "chest".into(), + texture: "entity/chest/normal", + part, + y_rot, + double_with: None, + }; + for (open, packed) in [(0.0, 0xF0), (0.0, 0x7F), (0.5, 0x7F)] { + cache_open.set(open); + let base = Mat4::from_translation(Vec3::new(3.25, -8.5, 12.75)); + let mut cached = Vec::new(); + let mut original = Vec::new(); + for (use_cache, out) in [(true, &mut cached), (false, &mut original)] { + renderer.render_one( + &scene, + [0; 3], + &kind, + base, + packed, + diffuse_lights(nether), + false, + use_cache, + out, + ); + } + assert!(!cached.is_empty()); + assert_eq!(cached.len(), original.len()); + for (a, b) in cached.iter().zip(&original) { + assert!( + (Vec3::from_array(a.pos) - Vec3::from_array(b.pos)).length() < 3e-6 + ); + assert_eq!(a.uv, b.uv); + assert_eq!(a.color, b.color); + assert_eq!(a.light, b.light); + assert_eq!(a.normal, b.normal); + assert_eq!(a.layer, b.layer); + } + } + } + } + } + scene.nether = false; + scene.lid = &|_| 0.0; for state in 0..names.len() as u32 { let mut base = Vec::new(); renderer.render_block(&scene, [0; 3], state, Mat4::IDENTITY, 0xff, &mut base); diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs index b0b2ef262..ce2c4ea71 100644 --- a/crates/horizon-client/src/chunk.rs +++ b/crates/horizon-client/src/chunk.rs @@ -9,11 +9,26 @@ pub const MIN_Y: i32 = -64; pub const HEIGHT: i32 = 384; pub const SECTIONS: usize = (HEIGHT / 16) as usize; -/// Block states are `PalettedContainer`s over the pinned registry (35,723 -/// states: a 16-bit global palette); biomes are 4x4x4 containers over the -/// biome table (67 entries: a 7-bit global palette). -pub const BLOCK_STRATEGY: Strategy = Strategy::blocks(16); +/// Biomes are 4x4x4 containers over the biome table (67 entries: a 7-bit +/// global palette). pub const BIOME_STRATEGY: Strategy = Strategy::biomes(7); + +/// Bits of the block states' global palette: 16 for vanilla's 35,723 states +/// (what vanilla servers and clients send), more when content mods add states +/// past 65,536 (docs/modpacks.md). Set once, before the first chunk. +static BLOCK_BITS: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(16); + +/// Block states are `PalettedContainer`s over the registry: vanilla's 16-bit +/// global palette, wider with enough content mods. +pub fn block_strategy() -> Strategy { + Strategy::blocks(BLOCK_BITS.load(std::sync::atomic::Ordering::Relaxed)) +} + +/// Sizes the block states' global palette for a registry of `states`. +pub fn set_block_states(states: usize) { + let bits = horizon_core::paletted::ceil_log2(states).max(16); + BLOCK_BITS.store(bits, std::sync::atomic::Ordering::Relaxed); +} /// Packed light per block: sky light in the high nibble, block light in the low one. #[derive(Clone)] pub enum Light { @@ -43,7 +58,7 @@ pub struct Section { impl Default for Section { fn default() -> Self { Self { - blocks: PalettedContainer::new(BLOCK_STRATEGY, 0), + blocks: PalettedContainer::new(block_strategy(), 0), biomes: PalettedContainer::new(BIOME_STRATEGY, 0), light: Light::Uniform(0xF0), } @@ -51,27 +66,26 @@ impl Default for Section { } impl Section { #[inline] - pub fn get(&self, i: usize) -> u16 { - self.blocks.get(i) as u16 + pub fn get(&self, i: usize) -> u32 { + self.blocks.get(i) } - pub fn set(&mut self, i: usize, v: u16) -> u16 { - self.blocks.set(i, u32::from(v)) as u16 + pub fn set(&mut self, i: usize, v: u32) -> u32 { + self.blocks.set(i, v) } /// All 4,096 block states in index order. - pub fn unpack(&self, out: &mut [u16; 4096]) { - self.blocks.unpack_u16(out); + pub fn unpack(&self, out: &mut [u32; 4096]) { + self.blocks.unpack(out); } /// The block states of a whole section at once. - pub fn from_blocks(values: &[u16; 4096]) -> PalettedContainer { - let wide: Vec = values.iter().map(|&v| u32::from(v)).collect(); - PalettedContainer::from_values(BLOCK_STRATEGY, &wide) + pub fn from_blocks(values: &[u32; 4096]) -> PalettedContainer { + PalettedContainer::from_values(block_strategy(), values) } #[inline] pub fn light(&self, i: usize) -> u8 { self.light.get(i) } - pub fn is_uniform(&self, v: u16) -> bool { - self.blocks.is_uniform(u32::from(v)) + pub fn is_uniform(&self, v: u32) -> bool { + self.blocks.is_uniform(v) } /// Heap bytes held by the block, biome and light storage (benchmark accounting). pub fn heap_bytes(&self) -> usize { @@ -147,7 +161,7 @@ impl Chunk { } } #[inline] - pub fn get(&self, x: i32, y: i32, z: i32) -> u16 { + pub fn get(&self, x: i32, y: i32, z: i32) -> u32 { let s = (y - MIN_Y) >> 4; if !(0..SECTIONS as i32).contains(&s) { return 0; @@ -156,11 +170,11 @@ impl Chunk { } #[inline] pub fn block(&self, x: i32, y: i32, z: i32) -> BlockStateId { - BlockStateId(u32::from(self.get(x, y, z))) + BlockStateId(self.get(x, y, z)) } /// The highest y where `matches`, scanning down. Sections holding only /// `skip` are passed over whole: `matches` must be false for it. - pub fn highest(&self, skip: u16, mut matches: impl FnMut(i32) -> bool) -> Option { + pub fn highest(&self, skip: u32, mut matches: impl FnMut(i32) -> bool) -> Option { self.sections .iter() .enumerate() @@ -171,7 +185,7 @@ impl Chunk { (base..base + 16).rev().find(|&y| matches(y)) }) } - pub fn set(&mut self, x: i32, y: i32, z: i32, v: u16) -> u16 { + pub fn set(&mut self, x: i32, y: i32, z: i32, v: u32) -> u32 { let s = (y - MIN_Y) >> 4; if !(0..SECTIONS as i32).contains(&s) { return v; @@ -228,15 +242,15 @@ mod tests { Arc::make_mut(&mut chunk.sections[5]).set(i, cave_air); } chunk.set(3, 150, 4, stone); - let full = |c: &Chunk, matches: &dyn Fn(u16) -> bool| { + let full = |c: &Chunk, matches: &dyn Fn(u32) -> bool| { (MIN_Y..MIN_Y + HEIGHT) .rev() .find(|&y| matches(c.get(3, y, 4))) }; for matches in [ - &(|v: u16| v != air) as &dyn Fn(u16) -> bool, - &|v: u16| v == stone, - &|v: u16| v == cave_air, + &(|v: u32| v != air) as &dyn Fn(u32) -> bool, + &|v: u32| v == stone, + &|v: u32| v == cave_air, ] { let fast = chunk.highest(air, |y| matches(chunk.get(3, y, 4))); assert_eq!(fast, full(&chunk, matches)); diff --git a/crates/horizon-client/src/chunk_map.rs b/crates/horizon-client/src/chunk_map.rs index 81e06f020..ed25491c5 100644 --- a/crates/horizon-client/src/chunk_map.rs +++ b/crates/horizon-client/src/chunk_map.rs @@ -76,7 +76,7 @@ impl<'a> IntoIterator for &'a ChunkMap { } } impl crate::light::LightWorld for ChunkMap { - fn state(&self, x: i32, y: i32, z: i32) -> Option { + 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 { diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index 457ddf497..0b8f2856b 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -1209,7 +1209,15 @@ impl Recipes { for (prefix, path) in files { let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or(""); let name = format!("{prefix}{stem}"); - let v: Value = serde_json::from_slice(&fs::read(&path)?)?; + // Vanilla's RecipeManager logs a file that does not parse and + // goes on ("Couldn't parse data file"). + let v: Value = match serde_json::from_slice(&fs::read(&path)?) { + Ok(v) => v, + Err(e) => { + log::warn!("Horizon: recipe {name} not loaded: {e}"); + continue; + } + }; let text = |k: &str| v[k].as_str().unwrap_or("").to_owned(); meta.insert(name.clone(), (text("category"), text("group"))); let ing = |k: &str| Ingredient::parse(&v[k], items); diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index 5e6a3336a..3fa6e68a1 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -16,6 +16,7 @@ pub struct ItemEntity { pub fire_ticks: i32, pub id: u32, pub stack: ItemStack, + pub thrower: Option<[i32; 4]>, pub position: Vec3, pub previous: Vec3, pub velocity: Vec3, @@ -610,6 +611,7 @@ mod fire_environment_tests { .unwrap(); let make = |id: &str| ItemEntity { id: 1, + thrower: None, stack: ItemStack { item: std::sync::Arc::from(id), count: 1, diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index adeb1da25..bf02f689f 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -863,7 +863,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - Some(m) } -/// `ItemEntity`: Health, Age, PickupDelay, Item. +/// `ItemEntity`: Health, Age, PickupDelay, Item, Thrower. pub fn item_entity_to_nbt(e: &ItemEntity, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { let base = Base { id: "minecraft:item", @@ -887,6 +887,11 @@ pub fn item_entity_to_nbt(e: &ItemEntity, uuid: [i32; 4], raw: Option<&Tag>) -> ] { put(&mut tag, key, value); } + if let Some(thrower) = e.thrower { + put(&mut tag, "Thrower", Tag::IntArray(thrower.to_vec())); + } else if let Tag::Compound(map) = &mut tag { + map.remove(&"Thrower".into()); + } tag } pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option { @@ -897,6 +902,7 @@ pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option, + layers: Vec, biome: u16, } impl FlatTerrain { @@ -30,7 +30,7 @@ impl FlatTerrain { for layer in list { let block = crate::save::text(layer.get("block"))?; let height = crate::save::number(layer.get("height")).unwrap_or(0).max(0); - let state = registry.default_state(&block)?.0 as u16; + let state = registry.default_state(&block)?.0; layers.extend(std::iter::repeat_n(state, height as usize)); } } @@ -44,6 +44,113 @@ impl FlatTerrain { crate::chunk::MIN_Y + self.layers.len().min(crate::chunk::HEIGHT as usize) as i32 } } +/// DimensionType.Y_SIZE: the most layers FlatLevelGeneratorSettings takes. +const Y_SIZE: i64 = 4064; + +/// FlatLevelGeneratorSettings.CODEC reading a dedicated server's +/// `generator-settings` (DedicatedServerProperties.WorldDimensionData for +/// the `minecraft:flat` preset): the settings as `world_gen_settings` stores +/// them, and the errors vanilla logs, in order (the constructor's, then +/// `resultOrPartial`'s). No settings means the preset's own layers; a layer +/// that doesn't parse is left out, as the codec's partial result leaves it. +/// `is_block` says whether a block id is registered, `is_biome` a biome id. +pub fn settings_from_json( + json: &crate::server::json::Json, + is_block: impl Fn(&str) -> bool, + is_biome: impl Fn(&str) -> bool, +) -> (Option, Vec) { + use crate::server::json::Json; + let id = |s: &str| { + if s.contains(':') { + s.to_owned() + } else { + format!("minecraft:{s}") + } + }; + let Some(Json::Array(list)) = json.get("layers") else { + let error = match json.get("layers") { + None => format!("No key layers in MapLike[{}]", json.compact()), + Some(v) => format!("Not a list: {}", v.compact()), + }; + return (None, vec![error]); + }; + let mut errors = Vec::new(); + let mut layers = Vec::new(); + let mut total = 0; + for layer in list { + let height = layer.get("height").and_then(Json::as_string); + let height = height.as_deref().and_then(|h| h.parse::().ok()); + let block = layer.get("block").and_then(Json::as_string).map(|b| id(&b)); + match (height, block) { + (Some(h), _) if !(0..=Y_SIZE).contains(&h) => { + errors.push(format!("Value {h} outside of range [0:{Y_SIZE}]")); + } + (Some(h), Some(b)) if is_block(&b) => { + total += h; + layers.push(Tag::compound([ + ("height", Tag::Int(h as i32)), + ("block", Tag::String(b.as_str().into())), + ])); + } + (Some(_), Some(b)) => errors.push(format!( + "Unknown registry key in ResourceKey[minecraft:root / minecraft:block]: {b}" + )), + (None, _) => errors.push(format!("No key height in MapLike[{}]", layer.compact())), + (_, None) => errors.push(format!("No key block in MapLike[{}]", layer.compact())), + } + } + // The constructor: Biome.CODEC is lenient, and a biome that is missing + // or unknown is Plains. + let biome = json + .get("biome") + .and_then(Json::as_string) + .map(|b| id(&b)) + .filter(|b| is_biome(b)); + let mut logged = Vec::new(); + if biome.is_none() { + logged.push("Unknown biome, defaulting to plains".to_owned()); + } + let biome = biome.unwrap_or_else(|| "minecraft:plains".to_owned()); + // validateHeight. + if total > Y_SIZE { + errors.push(format!("Sum of layer heights is > {Y_SIZE}")); + logged.push(errors.join("; ")); + return (None, logged); + } + let flag = |key: &str| match json.get(key) { + Some(Json::Bool(b)) => *b, + Some(Json::Number(n)) => n.parse::().is_ok_and(|v| v != 0.0), + _ => false, + }; + let mut settings = Vec::new(); + // RegistryCodecs.holderSet, lenient too: a tag or a list of ids. + match json.get("structure_overrides") { + Some(Json::String(s)) => { + settings.push(("structure_overrides", Tag::String(s.as_str().into()))) + } + Some(Json::Array(ids)) if ids.iter().all(|i| matches!(i, Json::String(_))) => settings + .push(( + "structure_overrides", + Tag::List( + ids.iter() + .filter_map(Json::as_string) + .map(|i| Tag::String(id(&i).as_str().into())) + .collect(), + ), + )), + _ => {} + } + settings.extend([ + ("layers", Tag::List(layers)), + ("lakes", Tag::Byte(i8::from(flag("lakes")))), + ("features", Tag::Byte(i8::from(flag("features")))), + ("biome", Tag::String(biome.as_str().into())), + ]); + if !errors.is_empty() { + logged.push(errors.join("; ")); + } + (Some(Tag::compound(settings)), logged) +} impl ChunkGenerator for FlatTerrain { type Worker = (); fn worker(&self) {} @@ -75,3 +182,71 @@ impl ChunkGenerator for FlatTerrain { *proto.downcast::().expect("flat terrain proto") } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::save::{number, text}; + use crate::server::json::{self, Json}; + + fn read(text: &str) -> (Option, Vec) { + let json: Json = json::parse(text, false).unwrap(); + settings_from_json( + &json, + |b| ["minecraft:stone", "minecraft:bedrock"].contains(&b), + |b| ["minecraft:plains", "minecraft:desert"].contains(&b), + ) + } + + #[test] + fn generator_settings_read_as_flat_level_generator_settings() { + // server.properties' default: the preset's own layers, and the codec's error. + assert_eq!( + read("{}"), + (None, vec!["No key layers in MapLike[{}]".into()]) + ); + let (settings, errors) = read( + r#"{"layers":[{"block":"bedrock","height":1},{"block":"minecraft:stone","height":3}],"biome":"desert","features":true}"#, + ); + assert!(errors.is_empty()); + let settings = settings.unwrap(); + let Some(Tag::List(layers)) = settings.get("layers") else { + panic!("{settings:?}") + }; + assert_eq!(layers.len(), 2); + assert_eq!( + text(layers[0].get("block")).as_deref(), + Some("minecraft:bedrock") + ); + assert_eq!(number(layers[1].get("height")), Some(3)); + assert_eq!( + text(settings.get("biome")).as_deref(), + Some("minecraft:desert") + ); + assert_eq!(number(settings.get("features")), Some(1)); + assert_eq!(number(settings.get("lakes")), Some(0)); + // A layer that doesn't parse is left out; an unknown biome is Plains, and logged first. + let (settings, errors) = read( + r#"{"layers":[{"block":"nope","height":2},{"block":"stone","height":2}],"biome":"x"}"#, + ); + assert_eq!(errors.len(), 2); + assert_eq!(errors[0], "Unknown biome, defaulting to plains"); + assert!(errors[1].contains("minecraft:nope")); + let settings = settings.unwrap(); + let Some(Tag::List(layers)) = settings.get("layers") else { + panic!("{settings:?}") + }; + assert_eq!(layers.len(), 1); + assert_eq!( + text(settings.get("biome")).as_deref(), + Some("minecraft:plains") + ); + // validateHeight. + assert_eq!( + read( + r#"{"layers":[{"block":"stone","height":4000},{"block":"stone","height":100}],"biome":"plains"}"# + ), + (None, vec!["Sum of layer heights is > 4064".into()]) + ); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 29c9b26de..117f7a194 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -71,6 +71,7 @@ mod lan_trading; mod lan_waypoints; mod leads; mod level_particles; +mod levels; mod lightning; mod llamas; mod loom; @@ -975,8 +976,14 @@ struct Game<'a> { world_root: PathBuf, /// A player carried through a portal, re-placed once the destination loads. travelling: Option<(PlayerMotion, Vec3)>, - /// A server's lone player on its way to another level. - server_trip: Option, + /// A server's players on their way to another level, each waiting for + /// the destination to load around them. + server_trips: Vec, + /// A server's levels other than the one in place (game/levels.rs). + levels: levels::Levels, + /// Which pass of a server tick runs (`tick_server`): the first one reads + /// the network, the last one ends the players' tick. + level_pass: levels::Pass, /// Nether portals: the player's, items' and mobs' (game/nether_portal.rs). portals: nether_portal::Portals, /// The pending travel goes through an End portal (EndPortalBlock destinations). @@ -1127,7 +1134,7 @@ struct Game<'a> { lan_events: Vec<(i32, [i32; 3], i32, Option)>, /// Block events (position, b0, b1, state) and entity events (id, event, /// position) for the guests. - lan_block_events: Vec<([i32; 3], i32, i32, u16)>, + lan_block_events: Vec<([i32; 3], i32, i32, u32)>, lan_entity_events: Vec<(i32, i8, [f64; 3])>, /// `ContainerOpenersCounter`: how many players (the host and the guests) /// have each chest open. @@ -1139,6 +1146,10 @@ struct Game<'a> { lan_acting_uuid: Option, /// Command feedback to forward to a guest. chat_capture: Option>, + /// `broadcastToAdmins` lines a guest's command queued, sent once it + /// returns: the line, whether operators get it and whether the console + /// logs it. + admin_feedback: Vec<(horizon_client::text::Text, bool, bool)>, /// State of `/spectate`, `/posteffect`, `/debug`, `/waypoint` and friends. cmds: commands::extra::CommandExtras, ui: chat::UiState, @@ -1158,7 +1169,7 @@ struct Game<'a> { tab_list: horizon_client::tab_list::TabList, subtitles: subtitle_hud::SubtitleState, adv: advancements::AdvState, - restore_player_environment: bool, + restore_player_state: bool, stats_ui: stats_screen::StatsUi, adv_ui: advancements_screen::AdvUi, camera_type: perspective::CameraType, @@ -1166,7 +1177,7 @@ struct Game<'a> { /// The local player as a model (third person, the inventory). player_model: Option, } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] enum Dim { Overworld, Nether, @@ -1529,6 +1540,7 @@ impl Game<'_> { self.dropped.push(ItemEntity { health: 5, fire_ticks: 0, + thrower: None, id: self.next_entity, stack, position: p, @@ -1611,6 +1623,10 @@ impl Game<'_> { yaw.cos() * pitch.cos() * 0.3 + spread.sin() * strength, ]; self.spawn_item(thrown, [eye[0], eye[1] - 0.3, eye[2]], v, 40); + if self.lan_acting.is_none() { + let uuid = self.level.ensure_player_uuid(); + self.dropped.last_mut().unwrap().thrower = Some(uuid); + } } fn tick_items(&mut self) { let mut items = std::mem::take(&mut self.dropped); @@ -3077,10 +3093,7 @@ impl Game<'_> { }; let mut player = PlayerMotion::new(self.motion, feet)?; player.yaw = self.yaw; - player.load_environment_once( - &mut self.restore_player_environment, - self.level.player_extra.as_ref(), - ); + player.load_saved_state_once(&mut self.restore_player_state, &self.level)?; let spectator = self.mode == horizon_client::command::args::GameMode::Spectator; player.may_fly = self.creative || spectator; player.invulnerable = self.creative || spectator; @@ -3096,10 +3109,12 @@ impl Game<'_> { .get(&s.item) .is_some_and(|i| i.glider && (i.max_damage == 0 || s.damage + 1 < i.max_damage)) }); - if self.level.health > 0.0 && self.ticks < 2 { - player.set_health(self.level.health, false)?; - player.health.food.food = self.level.food; - player.health.food.saturation = self.level.saturation; + // A saved death already dropped inventory/XP and counted the death. + if player.health.dead_or_dying() { + self.screen = Screen::Dead; + self.ui.died_at = Some(Instant::now()); + self.ui.death_text = None; + self.capture(false); } self.previous_position = feet; self.player = Some(player); @@ -3677,6 +3692,11 @@ impl Game<'_> { ) || self.book.is_some()) } fn capture(&mut self, capture: bool) { + // A guest's action (`as_guest`) opens and closes screens on the + // guest's own client: the window's pointer stays the host's (#687). + if self.lan_acting.is_some() { + return; + } // MouseHandler.grabMouse never captures an inactive window. if capture && !self.focused { return; @@ -5592,6 +5612,9 @@ impl Game<'_> { ) }; let visible = r.block_entities().filter(|(p, state)| { + if !self.res.block_entity_render.renders(*state) { + return false; + } off_screen(*state) || view.is_none_or(|v| { let o = @@ -5713,9 +5736,10 @@ impl Game<'_> { let start = out.len(); self.block_model_vertices( f.state, - f.start_pos, + horizon_core::random::position_seed(f.start_pos), glam::Mat4::from_translation(o), packed, + false, &mut out, ); let tint = horizon_client::mobs::render::abgr(tint); @@ -6239,7 +6263,8 @@ impl Game<'_> { self.fns = Default::default(); self.bosses = Default::default(); reset_world_progress(&mut self.adv, &mut self.stats); - self.restore_player_environment = true; + self.prefetch_advancement_tree(); + self.restore_player_state = true; // RandomSequences: the world's data/minecraft/random_sequences.dat. self.rand_sequences = horizon_client::save::read_dat(&save_root.join("data/minecraft/random_sequences.dat")) @@ -8444,18 +8469,10 @@ impl Game<'_> { 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_later(&chunks, self.pack.assets.registry, &self.res.biomes)?; - if wait { - self.save.flush(); - } - self.save_entities(wait)?; + self.save_level(wait)?; + self.save_parked_levels(wait)?; self.save_maps(); self.save_random_sequences(); - self.save_raids(); self.save_fight(); self.save_wandering_trader(); self.save_portal_arrivals(); @@ -8472,6 +8489,20 @@ impl Game<'_> { self.message = Some(("Saved the game".into(), Instant::now())); Ok(()) } + /// Save the level in place: its changed chunks, its entities and its raids. + fn save_level(&mut self, wait: bool) -> Result<()> { + 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_later(&chunks, self.pack.assets.registry, &self.res.biomes)?; + if wait { + self.save.flush(); + } + self.save_entities(wait)?; + self.save_raids(); + Ok(()) + } fn render(&mut self) -> Result { self.poll_shader_pack(); let Some(size) = self @@ -10160,7 +10191,9 @@ impl<'a> Game<'a> { dim: Dim::Overworld, world_root: PathBuf::new(), travelling: None, - server_trip: None, + server_trips: Vec::new(), + levels: Default::default(), + level_pass: Default::default(), portals: Default::default(), end_travel: false, respawn_config: None, @@ -10266,6 +10299,7 @@ impl<'a> Game<'a> { lan_acting_name: None, lan_acting_uuid: None, chat_capture: None, + admin_feedback: Vec::new(), cmds: Default::default(), ui: Default::default(), combat: Default::default(), @@ -10282,7 +10316,7 @@ impl<'a> Game<'a> { tab_list: Default::default(), subtitles: Default::default(), adv: Default::default(), - restore_player_environment: true, + restore_player_state: true, stats_ui: Default::default(), adv_ui: Default::default(), camera_type: Default::default(), diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 22d9a4da0..882b5cc93 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -88,6 +88,9 @@ pub(super) struct AdvState { pub(super) changed: BTreeSet, pub(super) unlocked: Vec, pub(super) announced: Vec, + /// The tree being read on another thread since the world opened + /// (`prefetch_advancement_tree`), taken by the first `advancement_tree`. + pub(super) pending_tree: Option>, } /// The game's world for predicates. struct View<'a, 'g>(&'a Game<'g>); @@ -221,10 +224,27 @@ impl Game<'_> { /// The advancement tree, loaded once. pub(super) fn advancement_tree(&mut self) -> Arc { if self.adv.tree.list.is_empty() { - self.adv.tree = Arc::new(Tree::load(&self.options.resources.join("data"))); + let tree = match self.adv.pending_tree.take().map(|h| h.join()) { + Some(Ok(tree)) => tree, + _ => Tree::load(&self.options.resources.join("data")), + }; + self.adv.tree = Arc::new(tree); } self.adv.tree.clone() } + /// Start reading the advancement files on another thread while the world + /// loads. The first tick's first criterion trigger used to read and parse + /// all of them on the game thread (about 60 ms). + pub(super) fn prefetch_advancement_tree(&mut self) { + if !self.adv.tree.list.is_empty() || self.adv.pending_tree.is_some() { + return; + } + let data = self.options.resources.join("data"); + self.adv.pending_tree = std::thread::Builder::new() + .name("horizon-advancements".into()) + .spawn(move || Tree::load(&data)) + .ok(); + } pub(super) fn load_advancements(&mut self) { if self.adv.loaded || self.remote.is_some() || self.no_player_here() { return; @@ -622,6 +642,19 @@ impl Game<'_> { adv::conditions(&c["player"], &pctx, w) && adv::item(&c["item"], &it, w) }); } + pub(super) fn trigger_item_entity( + &mut self, + name: &str, + stack: &ItemStack, + target: &EntityView, + ) { + if self.lan_acting.is_some() { + return; + } + let me = self.player_entity(); + let it = item_view(stack); + self.trigger(name, |c, w| adv::item_entity(c, &me, target, &it, w)); + } /// `EnterBlockTrigger`: the block, its state properties and the player. pub(super) fn trigger_enter_block(&mut self, state: horizon_world::registry::BlockStateId) { let Some(definition) = self.pack.assets.registry.state(state).cloned() else { diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 18c6cd963..8e956373e 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -469,6 +469,9 @@ impl Game<'_> { "time": { "day_time": self.world.day_time, "day": self.world.day_time.div_euclid(24000), "time_of_day": self.world.day_time.rem_euclid(24000) }, "weather": { "raining": self.world.weather.raining, "thundering": self.world.weather.thundering }, "paused": self.pause, + // Mouse movement turns the camera (`apply_mouse_look`): the real + // pointer is grabbed, or an agent's `mouse-move` stands in for it. + "pointer_grabbed": self.captured || self.agent_pointer, "player": player, "selected": self.selected + 1, "held": self.held().map(|s| self.stack_value(s)), diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index 03a60faca..80e42169d 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -700,7 +700,7 @@ impl Game<'_> { } } /// `AbstractSkullBlock.getType` of a skull item. -fn skull_kind(item: &str) -> Option<&'static str> { +pub(super) fn skull_kind(item: &str) -> Option<&'static str> { Some(match item { "minecraft:skeleton_skull" => "skeleton", "minecraft:wither_skeleton_skull" => "wither_skeleton", diff --git a/crates/horizon-client/src/game/beacon.rs b/crates/horizon-client/src/game/beacon.rs index 15a7de79d..c8c437965 100644 --- a/crates/horizon-client/src/game/beacon.rs +++ b/crates/horizon-client/src/game/beacon.rs @@ -220,7 +220,11 @@ impl Game<'_> { levels } /// `applyEffects`: the powers for players within `levels * 10 + 10` (any height above). + /// `BeaconBlockEntity.applyEffects`: every player in range. fn beacon_effects(&mut self, p: [i32; 3], b: &Beacon) { + self.for_each_player(|g| g.beacon_effects_on_player(p, b)); + } + fn beacon_effects_on_player(&mut self, p: [i32; 3], b: &Beacon) { let Some(primary) = b.primary.as_deref().and_then(effect_id) else { return; }; diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 6c4817f63..1995efbf4 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1,5 +1,6 @@ //! Command execution (the `execute` side of each vanilla command class): //! entity selectors resolved against the game, vanilla feedback and errors. +mod admin; pub(super) mod compute; mod data; mod effects; @@ -160,8 +161,38 @@ impl Game<'_> { return; } if self.ui.rules.bool("send_command_feedback") { - self.system_message(message); + self.system_message(message.clone()); } + self.broadcast_to_admins(message); + } + /// CommandSourceStack.broadcastToAdmins, for a guest's command on a + /// dedicated server (`sendSuccess` with `broadcast`): `[name: message]`, + /// gray and italic, for the other operators when `send_command_feedback` + /// and the console when `log_admin_commands`. Queued while the guest acts; + /// `send_admin_feedback` sends it. + fn broadcast_to_admins(&mut self, message: Text) { + if self.lan_acting.is_none() + || self.options.dedicated.is_none() + || message + .translation_key() + .is_some_and(|k| admin::QUIET.contains(&k)) + { + return; + } + let ops = self.ui.rules.bool("send_command_feedback"); + let console = self.ui.rules.bool("log_admin_commands"); + if !ops && !console { + return; + } + // getDisplayName: the entity the command runs as (`execute as`). + let who = self + .command_source + .and_then(|s| s.entity) + .unwrap_or(Target::Player); + let line = Text::translate("chat.type.admin", &[self.target_name(who), message]) + .with_color(text::GRAY) + .italic(); + self.admin_feedback.push((line, ops, console)); } fn source_position(&self) -> [f64; 3] { if let Some(s) = &self.command_source { @@ -321,12 +352,16 @@ impl Game<'_> { .map_or_else(String::new, |o| o.kind.clone()), } } + /// The name of the player the game acts for: a guest's own while their + /// command or action runs (`Player.getName`). + pub(super) fn acting_player_name(&self) -> &str { + self.lan_acting_name.as_deref().unwrap_or(PLAYER_NAME) + } /// Entity.getDisplayName. pub(super) fn target_name(&self, t: Target) -> Text { match t { Target::Player => { - // A guest's commands name the guest. - let name = self.lan_acting_name.as_deref().unwrap_or(PLAYER_NAME); + let name = self.acting_player_name(); match self.score.board.players_team(name) { // PlayerTeam.formatNameForTeam. Some(team) => team.formatted_name(Text::literal(name)), @@ -767,7 +802,7 @@ impl Game<'_> { } self.feedback(Text::translate( "commands.gamemode.success.other", - &[Text::literal(PLAYER_NAME), mode_name], + &[Text::literal(self.acting_player_name()), mode_name], )); } } @@ -922,7 +957,7 @@ impl Game<'_> { &[ Text::literal(count.to_string()), name, - Text::literal(PLAYER_NAME), + Text::literal(self.acting_player_name()), ], ) } else { @@ -1794,7 +1829,7 @@ impl Game<'_> { ), _ => None, }; - let player = Text::literal(PLAYER_NAME); + let player = Text::literal(self.acting_player_name()); let players = targets.len(); if let (Some(i), Some(Arg::Str(criterion))) = (index, ctx.get("criterion")) { let a = &tree.list[i]; @@ -1904,7 +1939,10 @@ impl Game<'_> { }; self.system_message(Text::translate( &format!("commands.experience.query.{unit}"), - &[Text::literal(PLAYER_NAME), Text::literal(value.to_string())], + &[ + Text::literal(self.acting_player_name()), + Text::literal(value.to_string()), + ], )); return Ok(value); } @@ -1941,7 +1979,7 @@ impl Game<'_> { &key, &[ Text::literal(amount.to_string()), - Text::literal(PLAYER_NAME), + Text::literal(self.acting_player_name()), ], )); Ok(targets.len() as i32) @@ -2248,7 +2286,7 @@ impl Game<'_> { return Err(if targets.len() == 1 { CommandError::new(Text::translate( "clear.failed.single", - &[Text::literal(PLAYER_NAME)], + &[Text::literal(self.acting_player_name())], )) } else { err("clear.failed.multiple", &[&targets.len()]) @@ -2259,7 +2297,7 @@ impl Game<'_> { &format!("commands.clear.{kind}.single"), &[ Text::literal(removed.to_string()), - Text::literal(PLAYER_NAME), + Text::literal(self.acting_player_name()), ], )); Ok(removed) @@ -2312,7 +2350,7 @@ impl Game<'_> { }; let from = self.source_position().map(|v| v.floor() as i32); const RANGE: i32 = 256; - let mut cache: std::collections::HashMap> = + let mut cache: std::collections::HashMap> = std::collections::HashMap::new(); let mut best: Option<(i64, [i32; 3], &'static str)> = None; let (cx0, cz0) = ((from[0] - RANGE) >> 4, (from[2] - RANGE) >> 4); @@ -2323,15 +2361,12 @@ impl Game<'_> { continue; }; for (i, section) in chunk.sections.iter().enumerate() { - let mut wanted_state = |v: u32| { - let state = v as u16; + let mut wanted_state = |state: u32| { cache .entry(state) .or_insert_with(|| { - self.poi_type(horizon_world::registry::BlockStateId(u32::from( - state, - ))) - .filter(|t| wanted.iter().any(|w| w == t)) + self.poi_type(horizon_world::registry::BlockStateId(state)) + .filter(|t| wanted.iter().any(|w| w == t)) }) .is_some() }; @@ -2513,7 +2548,7 @@ impl Game<'_> { let name = match self.command_source.map(|s| s.entity) { Some(Some(t)) => self.target_name(t), Some(None) => Text::literal("Server"), - None => Text::literal(PLAYER_NAME), + None => Text::literal(self.acting_player_name()), }; let line = match id { "say" => Text::translate("chat.type.announcement", &[name, message]), @@ -2523,14 +2558,14 @@ impl Game<'_> { // Whispering to yourself: the incoming and outgoing lines. let out = Text::translate( "commands.message.display.outgoing", - &[Text::literal(PLAYER_NAME), message.clone()], + &[Text::literal(self.acting_player_name()), message.clone()], ) .with_color(text::GRAY) .italic(); self.system_message(out); Text::translate( "commands.message.display.incoming", - &[Text::literal(PLAYER_NAME), message], + &[Text::literal(self.acting_player_name()), message], ) .with_color(text::GRAY) .italic() diff --git a/crates/horizon-client/src/game/commands/admin.rs b/crates/horizon-client/src/game/commands/admin.rs new file mode 100644 index 000000000..1a5115f4d --- /dev/null +++ b/crates/horizon-client/src/game/commands/admin.rs @@ -0,0 +1,92 @@ +//! Which command feedback vanilla tells the other operators and the console +//! about (`CommandSourceStack.sendSuccess`'s `broadcast`). + +/// The replies vanilla sends with `broadcast` false: queries and lists, which +/// only the player who asked sees. Every other success message is broadcast. +pub(super) const QUIET: &[&str] = &[ + "commands.attribute.base_value.get.success", + "commands.attribute.base_value.reset.success", + "commands.attribute.base_value.set.success", + "commands.attribute.modifier.add.success", + "commands.attribute.modifier.remove.success", + "commands.attribute.modifier.value.get.success", + "commands.attribute.value.get.success", + "commands.banlist.entry", + "commands.banlist.list", + "commands.banlist.none", + "commands.bossbar.list.bars.none", + "commands.bossbar.list.bars.some", + "commands.data.block.get", + "commands.data.block.query", + "commands.data.entity.get", + "commands.data.entity.query", + "commands.data.storage.get", + "commands.data.storage.query", + "commands.datapack.list.available.none", + "commands.datapack.list.available.success", + "commands.datapack.list.enabled.none", + "commands.datapack.list.enabled.success", + "commands.difficulty.query", + "commands.execute.conditional.pass", + "commands.execute.conditional.pass_count", + "commands.experience.query.levels", + "commands.experience.query.points", + "commands.fetchprofile.copy_component", + "commands.fetchprofile.copy_text", + "commands.fetchprofile.give_item", + "commands.fetchprofile.summon_mannequin", + "commands.forceload.list.multiple", + "commands.forceload.list.single", + "commands.forceload.query.success", + "commands.gamerule.query", + "commands.jfr.started", + "commands.jfr.stopped", + "commands.list.players", + "commands.locate.biome.success", + "commands.locate.poi.success", + "commands.locate.structure.success", + "commands.perf.started", + "commands.perf.stopped", + "commands.posteffect.list.empty", + "commands.posteffect.list.success", + "commands.random.reset.all.success", + "commands.random.reset.success", + "commands.random.sample.success", + "commands.save.saving", + "commands.scoreboard.objectives.list.empty", + "commands.scoreboard.objectives.list.success", + "commands.scoreboard.players.get.success", + "commands.scoreboard.players.list.empty", + "commands.scoreboard.players.list.entity.empty", + "commands.scoreboard.players.list.entity.entry", + "commands.scoreboard.players.list.entity.success", + "commands.scoreboard.players.list.success", + "commands.seed.success", + "commands.spectate.success.started", + "commands.spectate.success.stopped", + "commands.team.list.members.empty", + "commands.team.list.members.success", + "commands.team.list.teams.empty", + "commands.team.list.teams.success", + "commands.team.option.prefix.success", + "commands.team.option.suffix.success", + "commands.tick.query.percentiles", + "commands.tick.query.rate.running", + "commands.tick.query.rate.sprinting", + "commands.tick.status.frozen", + "commands.tick.status.lagging", + "commands.tick.status.running", + "commands.tick.status.sprinting", + "commands.time.query.absolute", + "commands.time.query.gametime", + "commands.time.query.timeline", + "commands.time.query.timeline.repetitions", + "commands.waypoint.list.empty", + "commands.waypoint.list.success", + "commands.waypoint.modify.color", + "commands.waypoint.modify.color.reset", + "commands.waypoint.modify.style", + "commands.whitelist.list", + "commands.whitelist.none", + "commands.worldborder.get", +]; diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 578153247..2055798f4 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -1,7 +1,6 @@ //! `/recipe`, `/damage`, `/rotate`, `/swing`, `/playsound`, `/stopsound`, //! `/particle`, `/attribute`, `/ride` and `/spreadplayers`. use super::{Arg, Context, Game, R, Target, err}; -use crate::game::chat::PLAYER_NAME; use horizon_client::{ mobs::{Damage, DamageKind, Who}, scoreboard_cmd::{Holder, Tracker}, @@ -313,7 +312,7 @@ impl Game<'_> { (pos, volume) }; self.audio.play_on(source, &sound, Some(at), v, pitch); - tracker.mark(&holder(Text::literal(PLAYER_NAME))); + tracker.mark(&holder(Text::literal(self.acting_player_name()))); } let name = Text::literal(sound.clone()); let (message, total) = tracker.message( diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 94592e69c..fa72c7a40 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -173,6 +173,16 @@ impl Game<'_> { .chain(super::pad::HELP) .collect::>() }))), "setblock" | "fill" | "particle" | "signedit" => self.render_command(&words), + "section-draws" => { + let r = self.renderer.as_mut().ok_or("no renderer")?; + match words.get(1).copied() { + None => {} + Some("flat") => r.set_flat_draws(true)?, + Some("indirect") => r.set_flat_draws(false)?, + Some(other) => return Err(format!("unknown section draw mode {other}").into()), + } + Ok(Some(json!({ "ok": true, "flat": r.flat_draws() }))) + } "sculk" => Ok(Some(self.sculk_command(&words)?)), "status" => Ok(Some(self.control_status())), "pad" => Ok(Some(self.pad_command(&words)?)), @@ -672,6 +682,8 @@ impl Game<'_> { "size": [r.config.width, r.config.height], "present_mode": format!("{:?}", r.config.present_mode), "drawn_sections": r.drawn_sections, + "section_draws": r.section_draws, + "section_draw_calls": r.section_draw_calls, "uploaded_bytes": r.uploaded_bytes, "resident_sections": r.resident_sections(), "arena_bytes": arena_bytes, diff --git a/crates/horizon-client/src/game/creaking.rs b/crates/horizon-client/src/game/creaking.rs index 1caa419ff..099f3d7d8 100644 --- a/crates/horizon-client/src/game/creaking.rs +++ b/crates/horizon-client/src/game/creaking.rs @@ -333,7 +333,7 @@ impl Game<'_> { } for i in 0..4096 { let id = section.get(i); - if !hearts.get(usize::from(id)).copied().unwrap_or(false) { + if !hearts.get(id as usize).copied().unwrap_or(false) { continue; } let (lx, lz, ly) = ((i & 15) as i32, ((i >> 4) & 15) as i32, (i >> 8) as i32); @@ -362,3 +362,11 @@ pub(super) struct CreakingState { /// Which block states are creaking hearts, by state id. hearts: Vec, } + +impl CreakingState { + /// Exchange the chunks scanned for creaking hearts with another level's + /// (game/levels.rs). + pub(super) fn swap_level(&mut self, other: &mut Self) { + std::mem::swap(&mut self.scanned, &mut other.scanned); + } +} diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 076c2fbef..6c7fd67fc 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1358,25 +1358,52 @@ impl Game<'_> { /// mining fatigue III for five minutes unless a stronger or longer one /// is on, with the curse sound and the elder's apparition. fn elder_curse(&mut self, at: [f64; 3]) { + let mut cursed = Vec::new(); + self.for_each_player(|g| { + if g.elder_curse_player(at) { + cursed.push(g.lan_acting); + } + }); + // A guest's client shows the apparition and plays the curse itself + // (ClientboundGameEventPacket.GUARDIAN_ELDER_EFFECT). + if let Some(host) = self.lan.as_ref() { + for conn in cursed.into_iter().flatten() { + host.hub.send_to( + conn, + &horizon_protocol::packets::play::Clientbound::GameEvent( + horizon_protocol::packets::play::GameEvent { + event: horizon_client::lan::hub::game_event::GUARDIAN_ELDER_EFFECT, + param: 1.0, + }, + ), + ); + } + } + } + /// The curse on the player in place; whether it took. + fn elder_curse_player(&mut self, at: [f64; 3]) -> bool { if self.creative || self.spectator() { - return; + return false; } let Some(p) = self.player.as_ref() else { - return; + return false; }; let d = p.position.subtract(Vec3::new(at[0], at[1], at[2])); if d.x * d.x + d.y * d.y + d.z * d.z >= 2500.0 || p.health.dead_or_dying() { - return; + return false; } let active = self.potions.effects.get("minecraft:mining_fatigue"); if active.is_some_and(|e| e.amplifier >= 2 && e.duration >= 1200) { - return; + return false; } let at = [p.position.x, p.position.y, p.position.z]; self.give_player_effect("minecraft:mining_fatigue", 6000, 2); - self.audio - .play("minecraft:entity.elder_guardian.curse", Some(at), 1.0, 1.0); - self.creatures.elder_apparition = super::mob_blocks::APPARITION_TICKS; + if self.lan_acting.is_none() { + self.audio + .play("minecraft:entity.elder_guardian.curse", Some(at), 1.0, 1.0); + self.creatures.elder_apparition = super::mob_blocks::APPARITION_TICKS; + } + true } /// Damage of a given type to the player from a point. pub(super) fn mob_hits_player_kind(&mut self, amount: f32, from: [f64; 3], kind: &str) { @@ -2253,6 +2280,10 @@ impl Game<'_> { return Ok(true); } if self.interact_sulfur_cube(index, &item) { + if let Some(stack) = &held { + let target = self.mob_entity(&self.mobs[index]); + self.trigger_item_entity("minecraft:player_interacted_with_entity", stack, &target); + } self.swing_arm(); return Ok(true); } @@ -2802,6 +2833,17 @@ impl Game<'_> { if mob.fire_ticks > 0 || matches!(mob.species(), Species::Blaze | Species::MagmaCube) { packed = (15 * 16) | ((15 * 16) << 8); } + if mob.species() == Species::SulfurCube + && !horizon_client::mobs::trader::is_invisible(mob) + { + self.sulfur_cube_body_geometry( + mob, + alpha as f32, + horizon_client::mobs::render::base_transform(mob, alpha as f32, camera), + packed, + out, + ); + } // Other players on a server: PlayerRenderer's HumanoidArmorLayer. let armor = if &*mob.kind.id == "minecraft:player" { self.worn_armor_layers(mob) diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index 33bedf696..49b77eb13 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -290,6 +290,78 @@ impl Lists { } } +/// The world presets of 26.3's `worldgen/world_preset`. +const WORLD_PRESETS: [&str; 6] = [ + "minecraft:normal", + "minecraft:flat", + "minecraft:large_biomes", + "minecraft:amplified", + "minecraft:single_biome_surface", + "minecraft:debug_all_block_states", +]; + +/// Identifier.tryParse: `namespace:path`, or a path in `minecraft`. +fn parse_identifier(text: &str) -> Option { + let (namespace, path) = text.split_once(':').unwrap_or(("minecraft", text)); + let valid = |s: &str, extra: &[char]| { + s.chars() + .all(|c| matches!(c, 'a'..='z' | '0'..='9' | '_' | '.' | '-') || extra.contains(&c)) + }; + (valid(namespace, &[]) && valid(path, &['/'])).then(|| format!("{namespace}:{path}")) +} + +impl Game<'_> { + /// DedicatedServerProperties.createDimensions for a world that doesn't + /// exist yet: `level-type`'s preset, a flat world's `generator-settings` + /// and `generate-structures`, written before the world opens so that + /// streaming reads them. Horizon generates the normal and flat presets. + fn write_world_gen(&self, dir: &std::path::Path, props: &ServerProperties) -> Result<()> { + let level_type = &props.level_type; + let preset = parse_identifier(level_type) + .filter(|id| WORLD_PRESETS.contains(&id.as_str())) + .unwrap_or_else(|| { + log_from( + "Worker-Main-1", + "WARN", + &format!( + "Failed to parse level-type {level_type}, defaulting to minecraft:normal" + ), + ); + "minecraft:normal".to_owned() + }); + let flat = preset == "minecraft:flat"; + if !flat && preset != "minecraft:normal" { + log_from( + "Worker-Main-1", + "WARN", + &format!( + "Horizon doesn't generate the {preset} world preset yet: using minecraft:normal" + ), + ); + } + let settings = if flat { + let biomes = &self.res.biomes; + let (settings, errors) = horizon_client::flatgen::settings_from_json( + &props.generator_settings, + |b| self.pack.assets.registry.default_state(b).is_some(), + |b| biomes.get(biomes.id(b)).name == b, + ); + for e in errors { + log_from("Worker-Main-1", "ERROR", &e); + } + settings + } else { + None + }; + let options = horizon_client::save::WorldGen { + flat, + structures: props.generate_structures, + bonus_chest: false, + }; + horizon_client::save::write_world_gen_settings_with(dir, props.seed, options, settings) + } +} + /// PlayerList.BAN_DATE_FORMAT ("yyyy-MM-dd 'at' HH:mm:ss z"), in UTC. fn ban_date(millis: i64) -> String { let s = format_date(millis); @@ -345,6 +417,13 @@ impl Game<'_> { .get() .and_then(|m| m.lock().unwrap().take()) .ok_or("dedicated server not prepared")?; + // Main's WorldLoader: a new world's dimensions come from + // server.properties before the server starts. + let world_dir = std::env::current_dir()?.join(&universe).join(&level_name); + let new_world = !world_dir.join("level.dat").exists(); + if new_world { + self.write_world_gen(&world_dir, &props)?; + } // The console thread starts first, as in initServer. let (tx, console) = mpsc::channel(); std::thread::Builder::new() @@ -425,9 +504,7 @@ impl Game<'_> { lists.enforce_whitelist = props.enforce_whitelist; let lists = Arc::new(Mutex::new(lists)); log("INFO", &format!("Preparing level \"{level_name}\"")); - 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), @@ -565,18 +642,12 @@ impl Game<'_> { ); self.save_game()?; } - self.update_dedicated_streaming(); - self.update_world(); - if paused { - // MinecraftServer.tickServer: only the connections run. - self.tick_lan(); - } else { - if !state.autosave { - // `save-off`: the periodic save inside the tick is skipped. - self.ticks = self.ticks.max(1); - } - self.tick()?; + if !paused && !state.autosave { + // `save-off`: the periodic save inside the tick is skipped. + self.ticks = self.ticks.max(1); } + // MinecraftServer.tickServer: while paused only the connections run. + self.tick_server(paused)?; if idle_timeout > 0 { self.kick_idle(idle_timeout); } @@ -617,7 +688,13 @@ impl Game<'_> { let center = self .lan .as_ref() - .and_then(|h| h.hub.guests.iter().find(|g| g.placed).map(|g| g.chunk())) + .and_then(|h| { + h.hub + .guests + .iter() + .find(|g| h.hub.here(g)) + .map(|g| g.chunk()) + }) .or_else(|| { self.spawn .map(|s| ((s.x.floor() as i32) >> 4, (s.z.floor() as i32) >> 4)) diff --git a/crates/horizon-client/src/game/falling_damage.rs b/crates/horizon-client/src/game/falling_damage.rs index 16a003c04..f10a3b738 100644 --- a/crates/horizon-client/src/game/falling_damage.rs +++ b/crates/horizon-client/src/game/falling_damage.rs @@ -23,7 +23,7 @@ impl Game<'_> { .guests .iter() .filter(|g| { - g.placed + host.hub.here(g) && g.loaded && !g.dead && !g.creative() diff --git a/crates/horizon-client/src/game/fov.rs b/crates/horizon-client/src/game/fov.rs index 71b18a97c..64047b4f7 100644 --- a/crates/horizon-client/src/game/fov.rs +++ b/crates/horizon-client/src/game/fov.rs @@ -112,7 +112,7 @@ impl Game<'_> { let hurt = &p.health.hurt; let state = BobState { living: Some(HurtBob { - hurt_time: hurt.hurt_time as f32 - partial, + hurt_time: p.health.hurt_animation_time as f32 - partial, hurt_duration: hurt.hurt_duration, hurt_dir: 0.0, death_time: self.death_time().map(|t| t as f32 + partial), diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index 7b5f3cced..412c41693 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -314,14 +314,12 @@ impl Game<'_> { let mut next = Instant::now(); while !flags.stop.load(Ordering::Relaxed) { self.run_tasks(); - self.update_dedicated_streaming(); - self.update_world(); if flags.paused.load(Ordering::Relaxed) { // Only the connections run. - self.tick_lan(); + self.tick_server(true)?; } else { let started = Instant::now(); - self.tick()?; + self.tick_server(false)?; self.debug_charts.log_tick(started, started.elapsed()); flags.smoothed_tick_ms.store( self.debug_charts.smoothed_tick_ms.to_bits(), diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index aae200b50..b05f4fbf5 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -213,7 +213,7 @@ impl Game<'_> { owner.is_local_player = true; owner.is_view_entity = true; if let (Some((slot, ticks)), Some(stack)) = (self.using, stack) - && self.inventory.get(slot).and_then(Option::as_ref) == Some(stack) + && self.stack_in(slot) == Some(stack) { let view = item_render::stack_view(stack); let duration = use_duration(&self.pack.item_renderer.models.components(&view)); diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 8948347aa..88f1133f6 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -52,7 +52,7 @@ pub(super) struct LanHost { /// Blocks broken this tick (their sound is a level event for the guests). pub broken: Vec<[f64; 3]>, /// Hurt and death state of the mobs guests see. - mob_state: HashMap, + mob_state: HashMap>, /// The guest each mob sees as its player, when not the host (game/lan_mobs.rs). pub mob_players: HashMap, /// An integrated server's owner (game/integrated.rs). @@ -262,7 +262,7 @@ fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> { meta.push(( 16, serializer::OPTIONAL_BLOCK_STATE, - Value::Id(i32::from(state.0 as u16)), + Value::Id(state.0 as i32), )); } } @@ -788,8 +788,25 @@ impl Game<'_> { }, tick_rate: self.clock.rate(), tick_frozen: self.clock.frozen(), + collision: Some(self.collision), }; - host.hub.tick(&mut ctx) + host.hub.movement_checks = ( + self.ui.rules.bool("player_movement_check"), + self.ui.rules.bool("elytra_movement_check"), + ); + // A server with several levels runs a pass for each + // (`tick_server`): the network is read once, before the first. + let pass = self.level_pass; + let mut events = if pass.first { + host.hub.poll(&mut ctx) + } else { + Vec::new() + }; + events.extend(host.hub.tick_level(&mut ctx)); + if pass.last { + host.hub.end_tick(); + } + events }; if let Some(state) = &state && host.host_mode != state.game_mode @@ -830,7 +847,15 @@ impl Game<'_> { if let Some(pos) = guest.menu.as_ref().and_then(|m| m.pos) && !guest.spectator() { - self.container_openers_changed(pos, false); + // In the level they were in. + let back = self.dim; + let theirs = super::Dim::from_id(&guest.dimension); + if self.enter_level(Some(&mut host), theirs).is_ok() { + self.container_openers_changed(pos, false); + } + if let Err(e) = self.enter_level(Some(&mut host), back) { + log::error!("could not reopen {}: {e}", back.id()); + } } self.lan_crafting_left(&mut host, &mut guest); self.save_guest(&host, &guest); @@ -852,6 +877,10 @@ impl Game<'_> { super::dedicated::log("INFO", &format!("[Not Secure] {line}")); } HostEvent::Chat(line) => self.system_message(Text::literal(line)), + HostEvent::Warn(line) if self.options.dedicated.is_some() => { + super::dedicated::log("WARN", &line); + } + HostEvent::Warn(line) => log::warn!("{line}"), HostEvent::Packet(conn, packet) => { self.lan_guest_packet(&mut host, conn, *packet); } @@ -883,6 +912,7 @@ impl Game<'_> { let default_mode = host.hub.config.default_game_mode; let force = host.hub.config.force_game_mode; let root = self.world_root.clone(); + let in_place = host.hub.config.dimension.clone(); let owner = host.owner.as_mut(); let Some(g) = host.hub.guest_mut(conn) else { return; @@ -905,8 +935,28 @@ impl Game<'_> { g.previous_position = spawn; g.health = 20.0; g.food = 20; + g.dimension = super::Dim::Overworld.id().to_owned(); + } + // A server places each player in their own level + // (`PlayerList.placeNewPlayer`); the in-frame game has one. + let back = self.dim; + let level = super::Dim::from_id(&g.dimension); + let elsewhere = self.options.dedicated.is_some() && level != back; + if !elsewhere { + g.dimension = in_place; } self.load_guest_records(host, conn); + let theirs; + let entities = if elsewhere { + if let Err(e) = self.enter_level(Some(host), level) { + log::error!("could not open {}: {e}", level.id()); + return; + } + theirs = self.lan_entities(&mut host.hub); + &theirs[..] + } else { + entities + }; let mut ctx = TickCtx { world: &mut self.world, host: state, @@ -918,8 +968,12 @@ impl Game<'_> { clock_rate: self.ui.clock.rate, tick_rate: self.clock.rate(), tick_frozen: self.clock.frozen(), + collision: Some(self.collision), }; host.hub.place_new_player(conn, &mut ctx); + if elsewhere && let Err(e) = self.enter_level(Some(host), back) { + log::error!("could not reopen {}: {e}", back.id()); + } } /// Level events the game queued, for the guests (`process_level_events`). @@ -940,7 +994,7 @@ impl Game<'_> { /// `Level.blockEvent` for the guests (`ClientboundBlockEventPacket`). pub(super) fn lan_block_event(&mut self, pos: [i32; 3], b0: i32, b1: i32) { if self.audio.capture.is_some() { - let state = self.world.block(pos[0], pos[1], pos[2]).0 as u16; + let state = self.world.block(pos[0], pos[1], pos[2]).0; self.lan_block_events.push((pos, b0, b1, state)); } } @@ -974,7 +1028,11 @@ impl Game<'_> { let mut seen = HashMap::new(); for m in &self.mobs { let dead = !m.alive(); - let old = host.mob_state.get(&m.id).copied(); + let old = host + .mob_state + .get(&self.dim) + .and_then(|s| s.get(&m.id)) + .copied(); let at = [m.position.x, m.position.y, m.position.z]; if m.hurt_time > old.map_or(0, |o| o.0) && !dead { host.hub.entity_event(m.id as i32, 2, at); @@ -984,7 +1042,7 @@ impl Game<'_> { } seen.insert(m.id, (m.hurt_time, dead)); } - host.mob_state = seen; + host.mob_state.insert(self.dim, seen); } /// Keep the chunks around every guest loaded. @@ -993,7 +1051,7 @@ impl Game<'_> { .hub .guests .iter() - .filter(|g| g.placed) + .filter(|g| host.hub.here(g)) // The tracked square's corners and their lit neighbours lie // within (view distance + 2) * √2 of the player's chunk. .map(|g| (g.chunk(), (g.view_distance + 2) * 3 / 2 + 1)) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index ec4e9eed4..9281cc3a1 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -54,6 +54,8 @@ pub(super) struct GuestPlay { /// `ServerPlayer.getStats` and the inventory `inventory_changed` last saw. pub(super) stats: super::stats::Stats, last_inventory: u64, + /// `Entity.portalProcess` and `portalCooldown` (game/server_travel.rs). + pub(super) portal: horizon_client::nether_portal::PortalState, } struct ItemRules<'a>(&'a horizon_client::items::Items); @@ -140,13 +142,20 @@ impl Game<'_> { total: g.xp_total, }, ); - let sneak = self.keys.contains(&KeyCode::ShiftLeft); + // The host's held keys stay theirs: the guest holds only sneak, and a + // screen the guest opens (`keys.clear()`) leaves the host walking. + let host_keys = std::mem::take(&mut self.keys); if g.sneaking { self.keys.insert(KeyCode::ShiftLeft); - } else { - self.keys.remove(&KeyCode::ShiftLeft); } + // The window's screens are the host's: a sign, book, command block or + // mount menu the guest's action opens is not drawn over the host's + // world (#687). The guest's client opens its own. let screen = std::mem::replace(&mut self.screen, Screen::Playing); + let host_sign = self.sign_edit.take(); + let host_book = self.book.take(); + let host_command_block = self.command_block_screen.take(); + let host_mount_menu = std::mem::take(&mut self.mount_menu); // The host's crafting grid stays theirs; a crafting table the guest // opens shows as the 3x3 size. let craft_size = std::mem::replace(&mut self.craft_size, 2); @@ -205,11 +214,11 @@ impl Game<'_> { play.swing = std::mem::replace(&mut self.swing, swing); self.container = container; self.screen = screen; - if sneak { - self.keys.insert(KeyCode::ShiftLeft); - } else { - self.keys.remove(&KeyCode::ShiftLeft); - } + self.sign_edit = host_sign; + self.book = host_book; + self.command_block_screen = host_command_block; + self.mount_menu = host_mount_menu; + self.keys = host_keys; let g = &mut host.hub.guests[i]; std::mem::swap(&mut self.ender_items, &mut g.ender_items); std::mem::swap(&mut self.adv.progress, &mut g.advancements); @@ -282,6 +291,32 @@ impl Game<'_> { Some(result) } + /// `ServerLevel.players()` in turn: the host's own player, then each + /// guest in the level in place with their state swapped in (`as_guest`). + /// What reaches the players around a point (a beacon's powers, a splash + /// potion, a warden's darkness, an elder guardian's curse) lands on each + /// of them, not only on the host. A server has no player of its own. + /// Inside a guest's action (the hub taken) only that player is in place. + pub(super) fn for_each_player(&mut self, mut f: impl FnMut(&mut Self)) { + if self.player.is_some() { + f(self); + } + let Some(mut host) = self.lan.take() else { + return; + }; + let conns: Vec = host + .hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead) + .map(|g| g.conn) + .collect(); + for conn in conns { + self.as_guest(&mut host, conn, &mut f); + } + self.lan = Some(host); + } + /// The game mode fields without `set_mode`'s side effects on the host. fn set_mode_raw(&mut self, id: i32) { use horizon_client::command::args::GameMode; @@ -650,6 +685,7 @@ impl Game<'_> { }), ); } + self.send_admin_feedback(host, conn); } } S::Unknown(8, payload) => { @@ -861,6 +897,32 @@ impl Game<'_> { }), ); } + self.send_admin_feedback(host, conn); + } + + /// The `broadcastToAdmins` lines a guest's command queued: every other + /// operator gets them, and the console logs them as the server's own + /// system messages (MinecraftServer.sendSystemMessage). + fn send_admin_feedback(&mut self, host: &mut LanHost, source: u32) { + for (line, ops, console) in std::mem::take(&mut self.admin_feedback) { + if ops { + let content = horizon_client::lan::data::component_nbt(&line.component()); + for g in host + .hub + .guests + .iter() + .filter(|g| g.conn != source && g.permission > 0) + { + g.send(&C::SystemChat(play::SystemChat { + content: content.clone(), + overlay: false, + })); + } + } + if console { + super::dedicated::log("INFO", &format!("System chat: {}", line.plain())); + } + } } /// ServerGamePacketListenerImpl.handleCustomCommandSuggestions: the @@ -911,7 +973,18 @@ impl Game<'_> { if !host.hub.guests[i].dead { return; } - self.respawn_level(host); + // PlayerList.respawn: a server's player comes back in the Overworld, + // where the world spawn is (respawn anchors and beds aside). + let back = self.dim; + let away = self.options.dedicated.is_some() + && host.hub.guests[i].dimension != super::Dim::Overworld.id(); + if away { + self.server_trips.retain(|t| !t.is(conn)); + if let Err(e) = self.enter_level(Some(host), super::Dim::Overworld) { + log::error!("could not open the Overworld: {e}"); + return; + } + } let g = &mut host.hub.guests[i]; g.dead = false; g.health = 20.0; @@ -945,8 +1018,12 @@ impl Game<'_> { }, tick_rate: self.clock.rate(), tick_frozen: self.clock.frozen(), + collision: Some(self.collision), }; host.hub.respawn(i, spawn, &ctx); + if away && let Err(e) = self.enter_level(Some(host), back) { + log::error!("could not reopen {}: {e}", back.id()); + } } /// Per tick, for every guest: dig, use items, pick up drops, die. @@ -957,7 +1034,7 @@ impl Game<'_> { .hub .guests .iter() - .filter(|g| g.placed && g.loaded) + .filter(|g| host.hub.here(g) && g.loaded) .map(|g| g.conn) .collect(); for conn in conns { @@ -1349,6 +1426,9 @@ impl Game<'_> { let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else { continue; }; + if !host.hub.here(g) { + continue; + } let (id, at) = (g.entity_id, g.position); let play = host.play.get_mut(&conn).expect("play"); let swinging = play.swing.swinging() && play.swing.ticks == 0; diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 7cef7cda6..53b79407c 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -92,7 +92,7 @@ impl Game<'_> { .hub .guests .iter() - .filter(|g| g.placed && g.loaded && !g.dead) + .filter(|g| host.hub.here(g) && g.loaded && !g.dead) .map(|g| { let moved = [0, 1, 2].map(|k| g.position[k] - g.previous_position[k]); (g.conn, g.uuid, moved) @@ -138,7 +138,7 @@ impl Game<'_> { host.hub .guests .iter() - .filter(|g| g.placed && g.loaded && !g.dead && !g.spectator()) + .filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator()) .map(|g| (Who::Mob(g.entity_id as u32), guest_bounds(g))) .collect() } @@ -209,9 +209,12 @@ pub(super) struct Present { impl Game<'_> { /// Every guest in the world (`ServerLevel.getPlayers` past the host). pub(super) fn lan_present(&self) -> Vec { - let guests = self.lan.iter().flat_map(|h| &h.hub.guests); + let guests = self + .lan + .iter() + .flat_map(|h| h.hub.guests.iter().filter(|g| h.hub.here(g))); guests - .filter(|g| g.placed && g.loaded) + .filter(|g| g.loaded) .map(|g| { let [x, y, z] = g.position; Present { diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index bd10241ff..1bdf9146a 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -32,7 +32,7 @@ impl Game<'_> { host.hub .guests .iter() - .filter(|g| g.placed && g.loaded && !g.dead && !g.spectator()) + .filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator()) .filter_map(|g| Some((g.conn, ray_box(eye, dir, reach, guest_bounds(g))?))) .min_by(|a, b| a.1.total_cmp(&b.1)) } @@ -64,7 +64,7 @@ impl Game<'_> { host.hub .guests .iter() - .find(|g| g.entity_id == id && g.conn != conn && g.placed && !g.dead) + .find(|g| g.entity_id == id && g.conn != conn && host.hub.here(g) && !g.dead) .map(|g| Victim::Guest(g.conn)) } diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index d6bfc4141..ee6b55d16 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -372,7 +372,7 @@ impl Game<'_> { .hub .guests .iter() - .find(|g| g.conn == conn) + .find(|g| g.conn == conn && host.hub.here(g)) .map(|g| uuid_words(g.uuid)) else { continue; diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs new file mode 100644 index 000000000..3a84e2f78 --- /dev/null +++ b/crates/horizon-client/src/game/levels.rs @@ -0,0 +1,350 @@ +//! A server's levels, one per dimension (`MinecraftServer.levels`). +//! +//! The game's tick code reads one level: the one in place, held in `Game`'s +//! own fields (the world, its streaming and save, block ticks, entities). +//! A server (the dedicated server and single player's server thread) keeps +//! the other dimensions' levels here and ticks each one that has players by +//! swapping it into place (`enter_level`), the way `as_guest` swaps a player +//! in, so the tick code runs unchanged, one level at a time. The in-frame +//! game holds one level, which follows its player (`enter_dimension`). +//! +//! Shared by every level, as vanilla's derived levels share the +//! Overworld's level data: the game time, the day time and the weather, the +//! game rules, the scoreboard, the maps and the entities waiting to arrive +//! through a portal. + +use super::{ + Dim, ExperienceOrb, FallingBlock, Game, ItemEntity, Mob, boats, commands, + creaking::CreakingState, dragon, fireworks, lan::LanHost, lightning, machines, minecarts, + ominous_item_spawner, persist, raids::Raiding, sculk::SculkState, tnt, trident, +}; +use horizon_client::{ + Result, block_entity_anim::BlockEntityAnims, random_tick_sections::RandomTickSections, + save::SaveDir, streaming::Streaming, tick_chunk_membership::TickChunkMembership, world::World, +}; +use horizon_world::level::{LevelEvent, Ticks}; +use std::{collections::HashMap, sync::Arc}; + +/// Server ticks a level other than the Overworld stays loaded with no player +/// in it, before it is saved and closed (vanilla unloads a level's chunks +/// once no ticket holds them; the Overworld stays loaded). +const IDLE_TICKS: u32 = 300; + +/// A level that is not in place: every per-level field of `Game`. +pub(super) struct Parked { + world: World, + streaming: Streaming, + save: Arc, + block_ticks: Ticks, + tick_chunks: TickChunkMembership, + random_tick_sections: RandomTickSections, + level_events: Vec, + falling: Vec, + paintings: Vec, + item_frames: Vec, + armor_stands: Vec, + others: Vec, + boats: Vec, + carts: Vec, + jukebox_sounds: HashMap<(i32, i32, i32), u64>, + bolts: Vec, + crystals: Vec, + dragon: Option, + dragon_fireballs: Vec, + breath_clouds: Vec, + tridents: Vec, + rockets: Vec, + ominous_spawners: Vec, + tnts: Vec, + hoppers: HashMap<(i32, i32, i32), machines::HopperState>, + mobs: Vec, + projectiles: Vec, + dropped: Vec, + orbs: Vec, + persist: persist::EntityMemory, + lectern_pulses: Vec<((i32, i32, i32), i32)>, + lid_openers: HashMap<(i32, i32, i32), i32>, + lan_events: Vec<(i32, [i32; 3], i32, Option)>, + lan_block_events: Vec<([i32; 3], i32, i32, u32)>, + lan_entity_events: Vec<(i32, i8, [f64; 3])>, + /// Only the per-level parts of these are used (`swap_level`). + anims: BlockEntityAnims, + raiding: Raiding, + sculk: SculkState, + creaking: CreakingState, + /// Server ticks since a player was last in the level. + idle: u32, +} + +/// Which passes of the server tick the level in place runs: the first +/// reads the network (`Hub::poll`), the last ends the tick for every player +/// (`Hub::end_tick`). A tick with one level is both. +#[derive(Clone, Copy)] +pub(super) struct Pass { + pub first: bool, + pub last: bool, +} + +impl Default for Pass { + fn default() -> Self { + Self { + first: true, + last: true, + } + } +} + +/// The levels not in place, by dimension. +#[derive(Default)] +pub(super) struct Levels { + parked: HashMap, +} + +impl Game<'_> { + /// A new level for `dim`, opened from the save (`MinecraftServer.createLevels`). + fn open_level(&self, dim: Dim) -> Result { + let (streaming, save) = + self.make_streaming(&self.world_root.clone(), dim, self.level.seed)?; + let mut world = World::new(self.res.facts.air, self.level.seed); + world.fast_lava = dim == Dim::Nether; + Ok(Parked { + world, + streaming, + save, + block_ticks: Ticks::new(self.level.seed as i32), + tick_chunks: Default::default(), + random_tick_sections: Default::default(), + level_events: Vec::new(), + falling: Vec::new(), + paintings: Vec::new(), + item_frames: Vec::new(), + armor_stands: Vec::new(), + others: Vec::new(), + boats: Vec::new(), + carts: Vec::new(), + jukebox_sounds: HashMap::new(), + bolts: Vec::new(), + crystals: Vec::new(), + dragon: None, + dragon_fireballs: Vec::new(), + breath_clouds: Vec::new(), + tridents: Vec::new(), + rockets: Vec::new(), + ominous_spawners: Vec::new(), + tnts: Vec::new(), + hoppers: HashMap::new(), + mobs: Vec::new(), + projectiles: Vec::new(), + dropped: Vec::new(), + orbs: Vec::new(), + persist: Default::default(), + lectern_pulses: Vec::new(), + lid_openers: HashMap::new(), + lan_events: Vec::new(), + lan_block_events: Vec::new(), + lan_entity_events: Vec::new(), + anims: Default::default(), + raiding: Default::default(), + sculk: Default::default(), + creaking: Default::default(), + idle: 0, + }) + } + + /// Exchange the level in place with `p`. + fn swap_level(&mut self, p: &mut Parked) { + use std::mem::swap; + swap(&mut self.world, &mut p.world); + swap(&mut self.streaming, &mut p.streaming); + swap(&mut self.save, &mut p.save); + swap(&mut self.block_ticks, &mut p.block_ticks); + swap(&mut self.tick_chunks, &mut p.tick_chunks); + swap(&mut self.random_tick_sections, &mut p.random_tick_sections); + swap(&mut self.level_events, &mut p.level_events); + swap(&mut self.falling, &mut p.falling); + swap(&mut self.paintings, &mut p.paintings); + swap(&mut self.item_frames, &mut p.item_frames); + swap(&mut self.armor_stands, &mut p.armor_stands); + swap(&mut self.others, &mut p.others); + swap(&mut self.boats, &mut p.boats); + swap(&mut self.carts, &mut p.carts); + swap(&mut self.jukebox_sounds, &mut p.jukebox_sounds); + swap(&mut self.bolts, &mut p.bolts); + swap(&mut self.crystals, &mut p.crystals); + swap(&mut self.dragon, &mut p.dragon); + swap(&mut self.dragon_fireballs, &mut p.dragon_fireballs); + swap(&mut self.breath_clouds, &mut p.breath_clouds); + swap(&mut self.tridents, &mut p.tridents); + swap(&mut self.rockets, &mut p.rockets); + swap(&mut self.ominous_spawners, &mut p.ominous_spawners); + swap(&mut self.tnts, &mut p.tnts); + swap(&mut self.hoppers, &mut p.hoppers); + swap(&mut self.mobs, &mut p.mobs); + swap(&mut self.creatures.projectiles, &mut p.projectiles); + swap(&mut self.dropped, &mut p.dropped); + swap(&mut self.orbs, &mut p.orbs); + swap(&mut self.persist, &mut p.persist); + swap(&mut self.lectern_pulses, &mut p.lectern_pulses); + swap(&mut self.lid_openers, &mut p.lid_openers); + swap(&mut self.lan_events, &mut p.lan_events); + swap(&mut self.lan_block_events, &mut p.lan_block_events); + swap(&mut self.lan_entity_events, &mut p.lan_entity_events); + let (a, b) = (&mut self.be_anims, &mut p.anims); + swap(&mut a.chests, &mut b.chests); + swap(&mut a.books, &mut b.books); + swap(&mut a.shulkers, &mut b.shulkers); + swap(&mut a.bells, &mut b.bells); + swap(&mut a.conduits, &mut b.conduits); + swap(&mut a.skulls, &mut b.skulls); + swap(&mut a.pots, &mut b.pots); + swap(&mut a.gateways, &mut b.gateways); + swap(&mut a.gateway_servers, &mut b.gateway_servers); + self.raiding.swap_level(&mut p.raiding); + self.sculk.swap_level(&mut p.sculk); + self.creaking.swap_level(&mut p.creaking); + // What only the client draws starts over. + self.particles.clear(); + self.pickups.clear(); + } + + /// Put `target`'s level in place, opening it first if it is not loaded. + /// The level that was in place is kept with the others; the shared + /// clock and weather go with the swap. `host` is the hub when the caller + /// holds it (`self.lan` is taken during the network tick). + pub(super) fn enter_level(&mut self, host: Option<&mut LanHost>, target: Dim) -> Result<()> { + // The in-frame game keeps its one level (`enter_dimension`). + if self.options.dedicated.is_none() { + return Ok(()); + } + if target != self.dim { + let (mut p, opened) = match self.levels.parked.remove(&target) { + Some(p) => (p, false), + None => (self.open_level(target)?, true), + }; + p.world.game_time = self.world.game_time; + p.world.day_time = self.world.day_time; + p.world.weather = self.world.weather; + // The sculk tables' watched blocks are built once per game. + p.world.watched = std::mem::take(&mut self.world.watched); + self.swap_level(&mut p); + p.idle = 0; + let left = std::mem::replace(&mut self.dim, target); + self.levels.parked.insert(left, p); + if opened { + // The new streaming's radius and meshing options. + self.apply_settings(); + } + } + let host = match host { + Some(h) => Some(h), + None => self.lan.as_mut(), + }; + if let Some(h) = host { + h.hub.set_dimension(target.id()); + } + Ok(()) + } + + /// One server tick (`MinecraftServer.tickServer`): each level with + /// players in turn (`tickChildren`), its chunks streamed and loaded and + /// its world ticked. The first pass reads the network and runs the + /// tick's shared parts (the clock, the weather, functions, the autosave); + /// the next ones only their level. While `paused`, only the connections + /// run. + pub(super) fn tick_server(&mut self, paused: bool) -> Result<()> { + let dims = self.levels_to_tick(); + let n = dims.len(); + let mut result = Ok(()); + for (k, dim) in dims.into_iter().enumerate() { + if let Err(e) = self.enter_level(None, dim) { + result = Err(e); + break; + } + self.level_pass = Pass { + first: k == 0, + last: k + 1 == n, + }; + self.update_dedicated_streaming(); + self.update_world(); + result = if paused { + self.tick_lan(); + Ok(()) + } else if k == 0 { + self.tick() + } else { + let running = self.clock.world_runs(); + if running { + self.tick_weather_effects(); + } + self.tick_world(running) + }; + if result.is_err() { + break; + } + } + self.level_pass = Pass::default(); + result?; + self.close_idle_levels() + } + + /// The levels this server tick runs, in `MinecraftServer.levels` order + /// (the Overworld, the Nether, the End): every level with a player in + /// it, or the Overworld while nobody is online. + pub(super) fn levels_to_tick(&self) -> Vec { + let guests = self + .lan + .as_ref() + .map_or(&[][..], |h| h.hub.guests.as_slice()); + let mut dims: Vec = [Dim::Overworld, Dim::Nether, Dim::End] + .into_iter() + .filter(|d| guests.iter().any(|g| g.dimension == d.id())) + .collect(); + if dims.is_empty() { + dims.push(Dim::Overworld); + } + dims + } + + /// Count the parked levels' empty ticks, and save and close the ones + /// (other than the Overworld) nobody has been in for a while. + pub(super) fn close_idle_levels(&mut self) -> Result<()> { + let occupied = self.levels_to_tick(); + let mut closing = Vec::new(); + for (dim, p) in &mut self.levels.parked { + if occupied.contains(dim) { + p.idle = 0; + continue; + } + p.idle += 1; + if *dim != Dim::Overworld && p.idle >= IDLE_TICKS { + closing.push(*dim); + } + } + if closing.is_empty() { + return Ok(()); + } + let back = self.dim; + for dim in closing { + self.enter_level(None, dim)?; + self.save_level(true)?; + self.enter_level(None, back)?; + self.levels.parked.remove(&dim); + } + Ok(()) + } + + /// Save every parked level (`MinecraftServer.saveAllChunks`); the level + /// in place is the caller's to save. + pub(super) fn save_parked_levels(&mut self, wait: bool) -> Result<()> { + if self.levels.parked.is_empty() { + return Ok(()); + } + let back = self.dim; + let dims: Vec = self.levels.parked.keys().copied().collect(); + for dim in dims { + self.enter_level(None, dim)?; + self.save_level(wait)?; + } + self.enter_level(None, back) + } +} diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index 0d334d248..6947041f2 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -506,11 +506,15 @@ impl Game<'_> { .default_state("minecraft:hopper") .map(|s| self.res.facts.get(s).name.clone()); let Some(hopper) = hopper else { return Ok(()) }; + // A hopper's block entity is a plain container (`Chest`): only those + // need their block looked up (the ticker runs for a HopperBlockEntity + // whose block is still a hopper, `BlockEntityType.isValid`). let mut positions: Vec = self .world .block_entities - .keys() - .copied() + .iter() + .filter(|(_, e)| matches!(e, BlockEntity::Chest(_))) + .map(|(p, _)| *p) .filter(|p| self.res.facts.get(self.world.block(p.0, p.1, p.2)).name == hopper) .collect(); positions.sort_unstable(); diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index de42c4907..21ba79b46 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -17,7 +17,6 @@ use horizon_client::{ }; use horizon_core::{ geometry::{Aabb, Vec3}, - position::BlockPos, random::RandomSource, }; use horizon_world::registry::BlockStateId; @@ -91,6 +90,10 @@ pub(super) struct Minecart { } const WIDTH: f64 = 0.98; const HEIGHT: f64 = 0.7; +/// AbstractMinecart.getDefaultDisplayOffset, in sixteenths of a block. +fn display_offset(kind: CartKind) -> f64 { + if kind == CartKind::Hopper { 1.0 } else { 6.0 } +} /// The minecart's passenger attachment minus Player.DEFAULT_VEHICLE_ATTACHMENT. const SEAT: f64 = 0.1875 - 0.6; /// The placeholder container key under which an open cart's items live. @@ -1139,16 +1142,17 @@ impl Game<'_> { } } } - /// A block model's faces under `m` (block space 0..1), lit flat. + /// Baked block faces with terrain shade or block-item diffuse lighting. pub(super) fn block_model_vertices( &self, state: BlockStateId, - seed_pos: BlockPos, + seed: i64, m: glam::Mat4, light: u32, + diffuse: bool, out: &mut Vec, ) { - let Ok(models) = self.pack.assets.model_catalog.collect(state, seed_pos) else { + let Ok(models) = self.pack.assets.model_catalog.collect_seeded(state, seed) else { return; }; for (_, model) in &models { @@ -1168,12 +1172,30 @@ impl Game<'_> { D::North | D::South => 204, D::West | D::East => 153, }; - let color = 0xFF00_0000 | shade << 16 | shade << 8 | shade; + let color = if diffuse { + u32::MAX + } else { + 0xFF00_0000 | shade << 16 | shade << 8 | shade + }; + let normal = if diffuse { + use horizon_client::item_render::{direction_vector, transform_normal}; + let n = transform_normal(m, direction_vector(face.quad.facing)); + let n = n.to_array().map(|v| (v.clamp(-1.0, 1.0) * 127.0) as i8); + [n[0], n[1], n[2], 127] + } else { + [0; 4] + }; + let light = if diffuse { + let emission = u32::from(face.quad.light_emission) * 16; + (light & 0xFF) | (light >> 8 & 0xFF).max(emission) << 8 + } else { + light + }; for k in 0..4 { let p = face.quad.positions[k]; let uv = face.quad.uv[k]; out.push(Vertex { - normal: [0; 4], + normal, pos: m.transform_point3(glam::Vec3::from_array(p)).to_array(), uv: [s.u0 + uv[0] * (s.u1 - s.u0), s.v0 + uv[1] * (s.v1 - s.v0)], layer: 0, @@ -1212,24 +1234,52 @@ impl Game<'_> { /// front and back points, pitched on slopes, with the display block. pub(super) fn cart_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let a = alpha as f32; + let Some(uv) = self + .atlas + .sprites + .get("entity/minecart/minecart") + .map(|r| [r.u0, r.v0, r.u1, r.v1]) + else { + return; + }; + // Entity.shouldRenderAtSqrDistance: 64 times the bounding box's mean + // edge, scaled by the entity distance option. + let range = + (WIDTH + HEIGHT + WIDTH) / 3.0 * 64.0 * f64::from(self.settings.entity_distance); for c in &self.carts { let entity_start = out.len(); let Some(model) = self.cart_models.models.get(&c.kind) else { continue; }; - let Some(uv) = self - .atlas - .sprites - .get("entity/minecart/minecart") - .map(|r| [r.u0, r.v0, r.u1, r.v1]) - else { - continue; - }; let (x, y, z) = ( c.previous.x + (c.position.x - c.previous.x) * alpha, c.previous.y + (c.position.y - c.previous.y) * alpha, c.previous.z + (c.position.z - c.previous.z) * alpha, ); + // LevelExtractor.isEntityVisible: the cart the player rides always draws. + if self.riding != Some(c.id) { + let d = glam::DVec3::new(c.position.x, c.position.y, c.position.z) - camera; + if d.length_squared() >= range * range { + continue; + } + // EntityRenderer.shouldRender: the interpolated box grown by 0.5; + // AbstractMinecartRenderer.getBoundingBoxForCulling stretches it + // up by the display block's offset. + if let Some(view) = &self.view_frustum { + let top = HEIGHT + + if c.kind == CartKind::Rideable { + 0.0 + } else { + display_offset(c.kind) * 0.75 / 16.0 + }; + let p = glam::DVec3::new(x, y, z) - camera; + let lo = p - glam::DVec3::new(WIDTH / 2.0 + 0.5, 0.5, WIDTH / 2.0 + 0.5); + let hi = p + glam::DVec3::new(WIDTH / 2.0 + 0.5, top + 0.5, WIDTH / 2.0 + 0.5); + if !view.intersects(lo.as_vec3(), hi.as_vec3()) { + continue; + } + } + } let mut yaw = c.previous_yaw + ((c.yaw - c.previous_yaw + 180.0).rem_euclid(360.0) - 180.0) * a; let mut pitch = 0.0f32; @@ -1297,7 +1347,7 @@ impl Game<'_> { * glam::Mat4::from_translation(glam::Vec3::splat(-0.5)); let flash = c.kind == CartKind::Tnt && c.fuse > -1 && (c.fuse / 5) % 2 == 0; let start = out.len(); - self.block_model_vertices(state, BlockPos::default(), m, packed, out); + self.block_model_vertices(state, 0, m, packed, false, out); if flash { // submitWhiteSolidBlock: OverlayTexture.u(1.0) on the cart's own light. for v in &mut out[start..] { diff --git a/crates/horizon-client/src/game/mob_blocks.rs b/crates/horizon-client/src/game/mob_blocks.rs index c2246cf5b..8b2b2da40 100644 --- a/crates/horizon-client/src/game/mob_blocks.rs +++ b/crates/horizon-client/src/game/mob_blocks.rs @@ -257,20 +257,36 @@ impl Game<'_> { out: &mut Vec, ) { // ItemInHandLayer submits with OverlayTexture.NO_OVERLAY: no hurt tint. - for (item, left) in [(&mob.extra.main_hand, false), (&mob.extra.off_hand, true)] { + for (item, off_hand) in [(&mob.extra.main_hand, false), (&mob.extra.off_hand, true)] { let Some(item) = item else { continue }; + let left = off_hand != mob.extra.main_hand_left; let Some(t) = render::held_item_transform(mob, alpha as f32, camera, &self.res.mob_data, left) else { continue; }; - let slot = if left { + let slot = if off_hand { horizon_client::mobs::gear::OFF } else { horizon_client::mobs::gear::MAIN }; - let mut stack = ItemStack::new(item, 1); - if horizon_client::mobs::gear::enchanted(mob, slot) { + let local_player = self + .player_model + .as_ref() + .is_some_and(|p| p.id == mob.id && p.kind.id == mob.kind.id); + let mut stack = if local_player { + let Some(stack) = self.stack_in(if off_hand { + super::shield::OFFHAND_SLOT + } else { + self.selected + }) else { + continue; + }; + stack.clone() + } else { + ItemStack::new(item, 1) + }; + if !local_player && horizon_client::mobs::gear::enchanted(mob, slot) { // The gear's enchantments are not tracked, only that it has some. stack.enchant("minecraft:unbreaking", 1); } @@ -284,12 +300,13 @@ impl Game<'_> { ); // The local player's rod while its hook is out. owner.fishing_cast_with_this_item = self.cast_rod().is_some() - && self.main_hand_rod() != left + && self.main_hand_rod() != off_hand && self .player_model .as_ref() .is_some_and(|p| std::ptr::eq(p, mob)); - if !left && mob.extra.using_item > 0 { + owner.main_arm_left = mob.extra.main_hand_left; + if off_hand == mob.extra.using_off_hand && mob.extra.using_item > 0 { owner.using_this_item = true; owner.use_duration = 72_000; owner.use_item_remaining_ticks = 72_000 - mob.extra.using_item; diff --git a/crates/horizon-client/src/game/natural_spawning.rs b/crates/horizon-client/src/game/natural_spawning.rs index 571bbf5e0..80d26a823 100644 --- a/crates/horizon-client/src/game/natural_spawning.rs +++ b/crates/horizon-client/src/game/natural_spawning.rs @@ -206,7 +206,7 @@ impl NaturalLevel for GameLevel<'_, '_> { .chunks .get(&(x >> 4, z >> 4)) .and_then(|chunk| { - chunk.highest(world.air.0 as u16, |y| { + chunk.highest(world.air.0, |y| { spawn_selection::heightmap_blocks(self, kind, x, y, z) }) }) diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index 7e9b0eeb6..4214bdd70 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -305,6 +305,13 @@ impl Game<'_> { let (position, flying) = (p.position, p.flying || p.fall_flying); let (fall_flying, fly_ticks, velocity) = (p.fall_flying, p.fall_fly_ticks, p.velocity); let using = self.using.map(|(_, ticks)| ticks as i32 + 1).unwrap_or(0); + let using_off_hand = self + .using + .is_some_and(|(slot, _)| slot == super::shield::OFFHAND_SLOT); + let blocking = self + .using + .and_then(|(slot, _)| self.stack_in(slot)) + .is_some_and(|stack| self.blocks_attacks(stack).is_some()); let charged = self.inventory[self.selected] .as_ref() .is_some_and(|s| s.data().is_some_and(|d| !d.charged.is_empty())); @@ -328,7 +335,7 @@ impl Game<'_> { .map(|s| s.item.clone()); let off = self.offhand.as_ref().map(|s| s.item.clone()); let riding = self.riding.is_some(); - let hurt = p.health.hurt.hurt_time; + let hurt = p.health.hurt_animation_time; let Some(m) = self.player_model.as_mut() else { return; }; @@ -384,6 +391,8 @@ impl Game<'_> { m.extra.fall_fly_ticks = fly_ticks; m.extra.main_hand_left = self.settings.main_hand_left; m.extra.using_item = using; + m.extra.using_off_hand = using_off_hand; + m.extra.blocking = blocking; m.extra.charged = charged; m.extra.ints[5] = charge_duration; m.extra.elytra.tick(fall_flying, crouching, velocity); diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index a60926256..ffa63b7c9 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -467,6 +467,41 @@ impl Game<'_> { self.splash(&stack, at); } } + /// A splash potion's effects on the player in place, by their distance. + fn splash_on_player( + &mut self, + effects: &'static [(&'static str, i32, i32)], + at: Vec3, + scale: f64, + ) { + if let Some(p) = self.player.as_ref() { + let center = Vec3::new( + p.position.x, + p.position.y + f64::from(p.dimensions.height) / 2.0, + p.position.z, + ); + let d2 = + (center.x - at.x).powi(2) + (center.y - at.y).powi(2) + (center.z - at.z).powi(2); + if d2 < 16.0 && (center.y - at.y).abs() <= 2.0 + f64::from(p.dimensions.height) { + let intensity = 1.0 - d2.sqrt() / 4.0; + for (id, duration, amp) in effects { + let instant = brewing::effect(id).is_some_and(|e| e.instant); + if instant { + if let Some(a) = horizon_client::effects::instant(id, *amp, intensity) { + self.apply_effect_action(a); + } + } else { + let d = (intensity * f64::from(*duration) * scale + 0.5) as i32; + if d > 20 + && let Some(e) = brewing::effect(id) + { + self.potions.effects.add(EffectInstance::new(e.id, d, *amp)); + } + } + } + } + } + } /// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash). fn splash(&mut self, stack: &ItemStack, at: Vec3) { if &*stack.item == "minecraft:experience_bottle" { @@ -527,34 +562,9 @@ impl Game<'_> { let Some(def) = stack.potion().and_then(brewing::potion) else { return; }; - // The player. - if let Some(p) = self.player.as_ref() { - let center = Vec3::new( - p.position.x, - p.position.y + f64::from(p.dimensions.height) / 2.0, - p.position.z, - ); - let d2 = - (center.x - at.x).powi(2) + (center.y - at.y).powi(2) + (center.z - at.z).powi(2); - if d2 < 16.0 && (center.y - at.y).abs() <= 2.0 + f64::from(p.dimensions.height) { - let intensity = 1.0 - d2.sqrt() / 4.0; - for (id, duration, amp) in def.effects { - let instant = brewing::effect(id).is_some_and(|e| e.instant); - if instant { - if let Some(a) = horizon_client::effects::instant(id, *amp, intensity) { - self.apply_effect_action(a); - } - } else { - let d = (intensity * f64::from(*duration) * scale + 0.5) as i32; - if d > 20 - && let Some(e) = brewing::effect(id) - { - self.potions.effects.add(EffectInstance::new(e.id, d, *amp)); - } - } - } - } - } + // Every player in range (`ThrownSplashPotion.applySplash` over + // `LivingEntity`s, the players among them). + self.for_each_player(|g| g.splash_on_player(def.effects, at, scale)); // Mobs take the instant effects (undead invert healing and harming). let undead = &self.res.stations.enchantments.entity_tags; let mut hits = Vec::new(); diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index 63f45c1c5..25a440af3 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -39,6 +39,17 @@ pub(super) struct Raiding { homes: HashMap>)>, } +impl Raiding { + /// Exchange the level-held parts (`ServerLevel.getRaids`) with another + /// level's (game/levels.rs). + pub(super) fn swap_level(&mut self, other: &mut Self) { + std::mem::swap(&mut self.raids, &mut other.raids); + std::mem::swap(&mut self.loaded, &mut other.loaded); + std::mem::swap(&mut self.bar_hurts, &mut other.bar_hurts); + std::mem::swap(&mut self.homes, &mut other.homes); + } +} + /// `SectionPos` of a block position. pub(super) fn section(p: [i32; 3]) -> (i32, i32, i32) { (p[0] >> 4, p[1] >> 4, p[2] >> 4) @@ -613,17 +624,17 @@ impl Game<'_> { raider::state_mut(m).ticks_outside_raid = ticks; } } - Action::Victory { heroes, amplifier } => { - let me = self.level.player_uuid; - if me.is_some_and(|u| heroes.contains(&u)) && !self.spectator() { + // Raid.tick on a victory: each hero who is still alive. + Action::Victory { heroes, amplifier } => self.for_each_player(|g| { + if heroes.contains(&g.acting_uuid()) && !g.spectator() { let mut effect = EffectInstance::new("hero_of_the_village", raid::HERO_DURATION, amplifier); effect.visible = false; - self.potions.effects.add(effect); - self.stats.custom("raid_win", 1); - self.trigger_player("minecraft:hero_of_the_village"); + g.potions.effects.add(effect); + g.stats.custom("raid_win", 1); + g.trigger_player("minecraft:hero_of_the_village"); } - } + }), } } /// `Raid.playSound`: the horn, 13 blocks away from the player toward the diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index a871c55c3..089748295 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -9,7 +9,7 @@ use super::{Dim, Game, Mining, Screen}; use horizon_client::{ Result, - chunk::{BIOME_STRATEGY, BLOCK_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, Section}, + chunk::{BIOME_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, Section, block_strategy}, containers::{BlockEntity, Furnace, FurnaceKind}, entities::{Experience, ItemEntity}, hud::{HudBatch, rgba}, @@ -22,7 +22,11 @@ use horizon_client::{ streaming::{ChunkGenerator, Proto, Streaming}, world::World, }; -use horizon_core::{geometry::Vec3, paletted::PalettedContainer, random::RandomSource}; +use horizon_core::{ + geometry::Vec3, + paletted::{PalettedContainer, Strategy}, + random::RandomSource, +}; use horizon_protocol::{ entity_data::{ITEM_ENTITY_ITEM, Value}, item::{Hashed, Stack}, @@ -648,11 +652,31 @@ impl Game<'_> { if !(0..SECTIONS as i32).contains(&target) { continue; } - let strategy = BLOCK_STRATEGY; + // A global section is as wide as the server's registry: 16 bits + // from a vanilla server, wider from a Horizon host with the same + // content mods. Read it at that width, then widen it to ours. + let ours = block_strategy(); + let strategy = if ours.wire_has_palette(s.states.bits) { + ours + } else { + Strategy::blocks(s.states.bits) + }; let palette = s.states.palette.iter().map(|&p| p as u32).collect(); let words = s.states.data.iter().map(|&w| w as u64).collect(); - let blocks = PalettedContainer::from_wire(strategy, s.states.bits, palette, words) + let mut blocks = PalettedContainer::from_wire(strategy, s.states.bits, palette, words) .map_err(|e| e.to_string())?; + if strategy.global_bits != ours.global_bits { + let mut values = [0u32; 4096]; + blocks.unpack(&mut values); + // Ids past our registry (a host with mods we lack) read as air. + let limit = 1u64 << ours.global_bits; + for v in &mut values { + if u64::from(*v) >= limit { + *v = 0; + } + } + blocks = PalettedContainer::from_values(ours, &values); + } let mut section = Section { blocks, biomes: PalettedContainer::from_values(BIOME_STRATEGY, &cells), @@ -1454,6 +1478,21 @@ impl Game<'_> { } } C::GameEvent(p) => match p.event { + // GUARDIAN_ELDER_EFFECT: the apparition, and the curse sound + // unless the elder guardian is silent. + 10 => { + self.creatures.elder_apparition = super::mob_blocks::APPARITION_TICKS; + if p.param == 1.0 + && let Some(at) = self.player.as_ref().map(|m| m.position) + { + self.audio.play( + "minecraft:entity.elder_guardian.curse", + Some([at.x, at.y, at.z]), + 1.0, + 1.0, + ); + } + } 1 => { self.world.weather.raining = true; self.world.weather.rain_level = (0.0, 0.0); @@ -2029,6 +2068,7 @@ impl Game<'_> { self.dropped.push(ItemEntity { health: 5, fire_ticks: 0, + thrower: None, id: id as u32, stack, position: at, diff --git a/crates/horizon-client/src/game/render_control.rs b/crates/horizon-client/src/game/render_control.rs index 10add4668..e9a08c6a2 100644 --- a/crates/horizon-client/src/game/render_control.rs +++ b/crates/horizon-client/src/game/render_control.rs @@ -11,6 +11,7 @@ pub const HELP: &[&str] = &[ "fill X1 Y1 Z1 X2 Y2 Z2 STATE fill a box with a block state without updates", "particle NAME X Y Z [DX DY DZ] [COUNT] spawn particles (vanilla /particle spread)", "signedit X Y Z [front|back] open the sign editor for the sign at X Y Z", + "section-draws [flat|indirect] how terrain sections are drawn (A/B checks); replies the mode", ]; impl Game<'_> { diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 2e7e1df07..4e715c7b7 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -130,7 +130,7 @@ impl Game<'_> { /// `ScoreHolder.getScoreboardName`: the player's name, an entity's UUID. pub(super) fn holder_name(&mut self, t: Target) -> Option { match t { - Target::Player => Some(PLAYER_NAME.to_owned()), + Target::Player => Some(self.acting_player_name().to_owned()), Target::Mob(id) | Target::Item(id) => Some(uuid_text(self.uuid_for(id))), _ => None, } @@ -146,7 +146,7 @@ impl Game<'_> { } /// The entity with the given scoreboard name. fn target_of_holder(&self, name: &str) -> Option { - if name == PLAYER_NAME { + if name == self.acting_player_name() { return Some(Target::Player); } let uuid = uuid_from_text(name).filter(|_| name.len() == 36)?; @@ -379,8 +379,9 @@ impl Game<'_> { /// `ServerPlayer.die`: the death count. pub(super) fn score_player_died(&mut self) { let display = self.player_display_comp(); + let me = self.acting_player_name().to_owned(); let board = &mut self.score.board; - board.for_all_objectives_with(sb::CRITERIA_DEATH_COUNT, PLAYER_NAME, Some(&display), |v| { + board.for_all_objectives_with(sb::CRITERIA_DEATH_COUNT, &me, Some(&display), |v| { v.wrapping_add(1) }); // A respawned player has everything to record again. @@ -390,25 +391,21 @@ impl Game<'_> { pub(super) fn score_player_killed(&mut self, victim: Target) { let victim_name = self.holder_name(victim); let display = self.player_display_comp(); + let me = self.acting_player_name().to_owned(); let board = &mut self.score.board; let inc = |v: i32| v.wrapping_add(1); - board.for_all_objectives_with(sb::CRITERIA_TOTAL_KILLS, PLAYER_NAME, Some(&display), inc); + board.for_all_objectives_with(sb::CRITERIA_TOTAL_KILLS, &me, Some(&display), inc); if victim == Target::Player { - board.for_all_objectives_with( - sb::CRITERIA_PLAYER_KILLS, - PLAYER_NAME, - Some(&display), - inc, - ); + board.for_all_objectives_with(sb::CRITERIA_PLAYER_KILLS, &me, Some(&display), inc); } let color_of = |board: &Scoreboard, name: &str| board.players_team(name).and_then(|t| t.color.clone()); if let Some(victim_name) = victim_name { if let Some(color) = color_of(board, &victim_name) { let criteria = format!("teamkill.{color}"); - board.for_all_objectives_with(&criteria, PLAYER_NAME, Some(&display), inc); + board.for_all_objectives_with(&criteria, &me, Some(&display), inc); } - if let Some(color) = color_of(board, PLAYER_NAME) { + if let Some(color) = color_of(board, &me) { let criteria = format!("killedByTeam.{color}"); board.for_all_objectives(&criteria, &victim_name, inc); } @@ -430,7 +427,7 @@ impl Game<'_> { self.score.board.players_team(&uuid_text(*uuid)) } pub(super) fn player_team(&self) -> Option<&sb::Team> { - self.score.board.players_team(PLAYER_NAME) + self.score.board.players_team(self.acting_player_name()) } /// The teams of the player and of the mobs on one (empty without teams). pub(super) fn mob_teams(&self) -> horizon_client::mobs::Teams { @@ -464,16 +461,17 @@ impl Game<'_> { } /// `Player.getDisplayName`: the name with the team's prefix, suffix and colour. pub(super) fn player_display_comp(&self) -> Comp { - let name = literal(PLAYER_NAME); + let name = literal(self.acting_player_name()); match self.player_team() { Some(t) => t.formatted_name_comp(&name), None => name, } } pub(super) fn player_display_text(&self) -> Text { + let name = Text::literal(self.acting_player_name()); match self.player_team() { - Some(t) => t.formatted_name(Text::literal(PLAYER_NAME)), - None => Text::literal(PLAYER_NAME), + Some(t) => t.formatted_name(name), + None => name, } } @@ -686,7 +684,7 @@ impl Env for GameEnv<'_, '_> { .collect() } fn named(&mut self, name: &str) -> Holder { - if name.eq_ignore_ascii_case(PLAYER_NAME) && self.g.player.is_some() { + if name.eq_ignore_ascii_case(self.g.acting_player_name()) && self.g.player.is_some() { return self .g .holder_for(Target::Player) @@ -703,7 +701,7 @@ impl Env for GameEnv<'_, '_> { None => Some(Target::Player), }?; let name = match entity { - Target::Player => PLAYER_NAME.to_owned(), + Target::Player => self.g.acting_player_name().to_owned(), Target::Mob(id) | Target::Item(id) => uuid_text(self.g.uuid_for(id)), _ => return None, }; diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index 6901200f1..04e02d360 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -80,6 +80,15 @@ pub(super) struct SculkState { ticks: u32, pub tracker_loaded: bool, } + +impl SculkState { + /// Exchange the level-held parts (its sculk block entities and the + /// chunks scanned for them) with another level's (game/levels.rs). + pub(super) fn swap_level(&mut self, other: &mut Self) { + std::mem::swap(&mut self.index, &mut other.index); + std::mem::swap(&mut self.known, &mut other.known); + } +} /// An insertion-ordered set of block positions (`Level.blockEntityTickers` /// keeps the order block entities were added in). #[derive(Default)] @@ -301,11 +310,11 @@ impl Game<'_> { self.world.watched = t.kinds.iter().map(|k| *k != 0).collect(); self.sculk.tables = t; } - fn kind_of_state(&self, state: u16) -> u8 { + fn kind_of_state(&self, state: u32) -> u8 { self.sculk .tables .kinds - .get(usize::from(state)) + .get(state as usize) .copied() .unwrap_or(0) } @@ -345,10 +354,10 @@ impl Game<'_> { // SculkShriekerBlockEntity.preRemoveSideEffects. if old_kind == KIND_SHRIEKER && let Some(BlockEntity::Sculk(e)) = self.world.block_entities.get(&key) - && self.shrieker_shrieking(BlockStateId(u32::from(old))) + && self.shrieker_shrieking(BlockStateId(old)) { let warning = e.warning_level; - self.shrieker_respond(key, BlockStateId(u32::from(old)), warning); + self.shrieker_respond(key, BlockStateId(old), warning); } if matches!( self.world.block_entities.get(&key), @@ -375,17 +384,14 @@ impl Game<'_> { let y0 = MIN_Y + s as i32 * 16; // Without a sculk state in its palette, no block of the section // is one: most sections are passed over without reading a block. - if !section - .blocks - .maybe_has(|v| u16::try_from(v).is_ok_and(|v| self.kind_of_state(v) != 0)) - { + if !section.blocks.maybe_has(|v| self.kind_of_state(v) != 0) { continue; } if section.blocks.uniform().is_some() { // A uniform section of sculk blocks does not exist. continue; } - let mut a = [0u16; 4096]; + let mut a = [0u32; 4096]; section.unpack(&mut a); for (i, v) in a.iter().enumerate() { if self.kind_of_state(*v) != 0 { @@ -855,12 +861,12 @@ impl Game<'_> { let state = self.world.block(key.0, key.1, key.2); let is_warden = matches!(who, Who::Mob(id) if self.mobs.iter().any(|m| m.id == id && m.species() == Species::Warden)); - match self.kind_of_state(state.0 as u16) { + match self.kind_of_state(state.0) { KIND_SENSOR | KIND_CALIBRATED => { if is_warden || !self.res.behaviours.sculk_sensor_can_activate(state) { continue; } - let calibrated = self.kind_of_state(state.0 as u16) == KIND_CALIBRATED; + let calibrated = self.kind_of_state(state.0) == KIND_CALIBRATED; if calibrated { let back = self.calibrated_signal(key); if back != 0 && back != 1 { @@ -1171,6 +1177,9 @@ impl Game<'_> { /// `Warden.applyDarknessAround` / `MobEffectUtil.addEffectToPlayersAround`. pub(super) fn apply_darkness(&mut self, at: [f64; 3], radius: f64) { + self.for_each_player(|g| g.darkness_on_player(at, radius)); + } + fn darkness_on_player(&mut self, at: [f64; 3], radius: f64) { if self.creative || self.spectator() { return; } diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs index d5b1e4d95..6312254c7 100644 --- a/crates/horizon-client/src/game/server_travel.rs +++ b/crates/horizon-client/src/game/server_travel.rs @@ -1,59 +1,81 @@ -//! A server's player between dimensions. +//! A server's players between dimensions. //! -//! The server holds one level at a time, as the in-frame game does. While a -//! single player is online (single player on the server thread, or a world -//! with one player in it) that level follows the player through Nether and -//! End portals, and back to the Overworld when the player respawns. The swap -//! is the in-frame path's (`switch_level`, the portal plans, the arrival -//! search); the player hears it as `ServerPlayer.teleport` into another -//! level: a Respawn packet keeping all data, then a teleport to the exit once -//! the destination has loaded. With several players online the portals do -//! not take anyone yet: that needs the server to hold every level. +//! A server holds a level per dimension (game/levels.rs). A player who steps +//! into a Nether or End portal moves to the destination's level, which opens +//! if nobody was there: the swap is the in-frame path's portal plans and +//! arrival search, and the player hears it as `ServerPlayer.teleport` into +//! another level: a Respawn packet keeping all data, then a teleport to the +//! exit once the destination has loaded around them. -use super::nether_portal::PLAYER_DELAY; +use super::nether_portal::{PLAYER_DELAY, Plan}; use super::{Dim, Game, lan::LanHost}; use horizon_client::lan::hub::TickCtx; use horizon_core::{geometry::Vec3, position::BlockPos}; -/// A trip under way: the level has changed and its chunks are loading -/// around `target`. +/// A trip under way: the player is in the destination's level, whose +/// chunks are loading around `target`. pub(super) struct Trip { conn: u32, + dim: Dim, target: Vec3, - /// Through an End portal (or out of the End by respawning). + /// Through an End portal. end: bool, + /// The Nether portal plan, whose exit is found or built on arrival. + plan: Option, } -/// The lone player's box: Player's standing dimensions. +/// A player's box: Player's standing dimensions. const WIDTH: f64 = 0.6; const HEIGHT: f64 = 1.8; +impl Trip { + pub(super) fn is(&self, conn: u32) -> bool { + self.conn == conn + } +} + impl Game<'_> { /// Whether `conn` is between two levels: the server leaves its body /// alone until it arrives. pub(super) fn on_server_trip(&self, conn: u32) -> bool { - self.server_trip.as_ref().is_some_and(|t| t.conn == conn) + self.server_trips.iter().any(|t| t.conn == conn) } - /// Per server tick, after the guests' own: `Entity.handlePortal` for the - /// lone player (Nether portals count up their transition time, End - /// portals take it at once), or the arrival of the trip under way. + /// Per server tick in each level, after the guests' own: the arrivals of + /// the trips into this level, then `Entity.handlePortal` for each player + /// in it (Nether portals count up their transition time, End portals + /// take them at once). pub(super) fn tick_server_travel(&mut self, host: &mut LanHost) { if self.options.dedicated.is_none() { return; } - if self.server_trip.is_some() { - self.arrive_server_trip(host); - return; + self.arrive_server_trips(host); + let conns: Vec = host + .hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator()) + .map(|g| g.conn) + .collect(); + for conn in conns { + if self.on_server_trip(conn) { + continue; + } + // `Entity.portalProcess` and `portalCooldown` are the player's own. + let mut portal = host.play.entry(conn).or_default().portal; + std::mem::swap(&mut self.portals.player, &mut portal); + self.handle_server_portal(host, conn); + std::mem::swap(&mut self.portals.player, &mut portal); + host.play.entry(conn).or_default().portal = portal; } - let [g] = host.hub.guests.as_slice() else { + } + + /// `Entity.handlePortal` for one player, whose portal state is in place. + fn handle_server_portal(&mut self, host: &mut LanHost, conn: u32) { + let Some(g) = host.hub.guest(conn) else { return; }; - if !g.placed || !g.loaded || g.dead || g.spectator() { - return; - } - let (conn, at, invulnerable, sleeping) = ( - g.conn, + let (at, invulnerable, sleeping) = ( Vec3::new(g.position[0], g.position[1], g.position[2]), g.creative(), g.sleeping, @@ -70,7 +92,7 @@ impl Game<'_> { } else { Dim::End }; - self.start_server_trip(host, conn, target, true); + self.start_server_trip(host, conn, target, None); } // Entity.setAsInsidePortal while cooling down restarts the cooldown. self.portals.player.cooldown = 10; @@ -93,11 +115,10 @@ impl Game<'_> { if !self.may_enter(plan.dim) { return; } - self.portals.travel = Some(plan); - self.start_server_trip(host, conn, plan.dim, false); + self.start_server_trip(host, conn, plan.dim, Some(plan)); } - /// A Nether portal block the lone player's box is in. + /// A Nether portal block a player's box is in. fn nether_portal_inside(&self, at: Vec3) -> Option { let w = WIDTH / 2.0 - 1.0e-5; let lo = [at.x - w, at.y + 1.0e-5, at.z - w]; @@ -114,9 +135,16 @@ impl Game<'_> { None } - /// The level swap, and the player told it is in the new level at the - /// approximate exit while it loads. - fn start_server_trip(&mut self, host: &mut LanHost, conn: u32, target: Dim, end: bool) { + /// The player moves to `target`'s level (opened if nobody was there) + /// and is told it is there, at the approximate exit, while it loads. The + /// level whose tick is running is put back in place afterwards. + fn start_server_trip( + &mut self, + host: &mut LanHost, + conn: u32, + target: Dim, + plan: Option, + ) { let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else { return; }; @@ -124,105 +152,100 @@ impl Game<'_> { let from = Vec3::new(g.position[0], g.position[1], g.position[2]); let yaw = g.yaw; let source = self.dim; + let end = plan.is_none(); + // Coordinates scale by 8 between the Overworld and the Nether; an + // End portal has fixed destinations. + let scale = match (source, target) { + (Dim::Overworld, Dim::Nether) | (Dim::End, Dim::Nether) => 1.0 / 8.0, + (Dim::Nether, Dim::Overworld) => 8.0, + _ => 1.0, + }; self.end_portal_travel = end; - let switched = self.switch_level(target, from); + let scaled = self.end_destination(target).unwrap_or(Vec3::new( + from.x * scale, + from.y, + from.z * scale, + )); self.end_portal_travel = false; - let destination = match switched { - Ok(d) => d, - Err(e) => { - log::error!("could not open {}: {e}", target.id()); - return; - } + if let Err(e) = self.enter_level(Some(host), target) { + log::error!("could not open {}: {e}", target.id()); + return; + } + let destination = match plan { + Some(plan) => self.arrival_centre(&plan), + None => scaled, }; - let destination = match self.portals.travel { - Some(plan) if !end => self.arrival_centre(&plan), - _ => destination, - }; - host.hub.set_dimension(target.id()); let at = [destination.x, destination.y, destination.z]; let ctx = self.server_ctx(); host.hub.change_level(i, at, yaw, &ctx); self.as_guest(host, conn, |g| g.trigger_dimension(source, target)); - self.server_trip = Some(Trip { + self.server_trips.push(Trip { conn, + dim: target, target: destination, end, + plan, }); + if let Err(e) = self.enter_level(Some(host), source) { + log::error!("could not reopen {}: {e}", source.id()); + } } - /// Once the destination has loaded around the trip's target: the exit - /// (the Nether portal found or built, the End platform, the Overworld's - /// spawn column) and the teleport there. - fn arrive_server_trip(&mut self, host: &mut LanHost) { - let Some(trip) = self.server_trip.as_ref() else { - return; - }; - let Some(i) = host.hub.guests.iter().position(|g| g.conn == trip.conn) else { - // They left on the way. - self.server_trip = None; - self.portals.travel = None; - return; - }; - let (cx, cz) = ( - (trip.target.x.floor() as i32) >> 4, - (trip.target.z.floor() as i32) >> 4, - ); - if !(-2..=2).all(|dz| (-2..=2).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) { - return; - } - let Some(trip) = self.server_trip.take() else { - return; - }; - self.resolve_arrivals(); - let (position, yaw) = if trip.end { - match self.end_arrival(trip.target) { - Ok((at, yaw)) => (at, yaw.unwrap_or(host.hub.guests[i].yaw)), - Err(e) => { - log::error!("End arrival: {e}"); - (trip.target, host.hub.guests[i].yaw) - } + /// The trips into the level in place whose destination has loaded + /// around their target: the exit (the Nether portal found or built, the + /// End platform, the Overworld's spawn column) and the teleport there. + fn arrive_server_trips(&mut self, host: &mut LanHost) { + let mut k = 0; + while k < self.server_trips.len() { + let trip = &self.server_trips[k]; + let Some(i) = host.hub.guests.iter().position(|g| g.conn == trip.conn) else { + // They left on the way. + self.server_trips.remove(k); + continue; + }; + let (cx, cz) = ( + (trip.target.x.floor() as i32) >> 4, + (trip.target.z.floor() as i32) >> 4, + ); + if trip.dim != self.dim + || !(-2..=2).all(|dz| (-2..=2).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) + { + k += 1; + continue; } - } else { - let plan = self.portals.travel.take(); - let exit = plan.as_ref().and_then(|plan| self.nether_exit_portal(plan)); - match (plan, exit) { - (Some(plan), Some(exit)) => { - let (at, rotation) = self.arrival(&plan, exit); - (at, host.hub.guests[i].yaw + rotation) + let trip = self.server_trips.remove(k); + self.resolve_arrivals(); + let yaw = host.hub.guests[i].yaw; + let (position, yaw) = if trip.end { + match self.end_arrival(trip.target) { + Ok((at, turned)) => (at, turned.unwrap_or(yaw)), + Err(e) => { + log::error!("End arrival: {e}"); + (trip.target, yaw) + } } - _ => (trip.target, host.hub.guests[i].yaw), - } - }; - // Player.getDimensionChangingDelay. - self.portals.player.cooldown = 10; - let g = &mut host.hub.guests[i]; - g.yaw = yaw; - // A new body at the exit: no fall distance or motion carried over. - g.motion = None; - host.hub - .teleport(i, Some([position.x, position.y, position.z])); - } - - /// `PlayerList.respawn` away from the Overworld: the lone player's level - /// goes back to the Overworld first, where the world spawn is. - pub(super) fn respawn_level(&mut self, host: &mut LanHost) { - if self.options.dedicated.is_none() || self.dim == Dim::Overworld { - return; + } else { + let exit = trip + .plan + .as_ref() + .and_then(|plan| self.nether_exit_portal(plan)); + match (trip.plan, exit) { + (Some(plan), Some(exit)) => { + let (at, rotation) = self.arrival(&plan, exit); + (at, yaw + rotation) + } + _ => (trip.target, yaw), + } + }; + // Player.getDimensionChangingDelay. + host.play.entry(trip.conn).or_default().portal.cooldown = 10; + let g = &mut host.hub.guests[i]; + g.yaw = yaw; + // A new body at the exit: no fall distance or motion carried over. + g.motion = None; + host.hub + .teleport(i, Some([position.x, position.y, position.z])); } - if host.hub.guests.len() != 1 { - return; - } - self.server_trip = None; - self.portals.travel = None; - self.end_portal_travel = true; - let from = self.spawn.unwrap_or(Vec3::ZERO); - let switched = self.switch_level(Dim::Overworld, from); - self.end_portal_travel = false; - if let Err(e) = switched { - log::error!("could not open the Overworld: {e}"); - return; - } - host.hub.set_dimension(Dim::Overworld.id()); } /// The hub's view of the server for packets sent outside its own tick. @@ -243,6 +266,7 @@ impl Game<'_> { }, tick_rate: self.clock.rate(), tick_frozen: self.clock.frozen(), + collision: Some(self.collision), } } } diff --git a/crates/horizon-client/src/game/spawner.rs b/crates/horizon-client/src/game/spawner.rs index ba7bd66a1..c42299c86 100644 --- a/crates/horizon-client/src/game/spawner.rs +++ b/crates/horizon-client/src/game/spawner.rs @@ -427,6 +427,15 @@ impl Game<'_> { * glam::Mat4::from_scale(glam::Vec3::splat(scale)); let light = self.world.light(key.0, key.1, key.2); let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); + if mob.species() == horizon_client::mobs::Species::SulfurCube { + self.sulfur_cube_body_geometry( + mob, + alpha as f32, + horizon_client::mobs::render::base_transform_at(mob, alpha as f32, origin), + packed, + out, + ); + } horizon_client::mobs::render::render_posed( mob, alpha as f32, diff --git a/crates/horizon-client/src/game/sulfur_cubes.rs b/crates/horizon-client/src/game/sulfur_cubes.rs index 4606f6859..c4cee6319 100644 --- a/crates/horizon-client/src/game/sulfur_cubes.rs +++ b/crates/horizon-client/src/game/sulfur_cubes.rs @@ -5,11 +5,77 @@ use super::Game; use horizon_client::{ items::ItemStack, + mesher::Vertex, mobs::{Mob, Species, sulfur_cube}, }; use horizon_core::random::RandomSource; +fn block_transform(base: glam::Mat4, baby: bool) -> glam::Mat4 { + base * glam::Mat4::from_scale(glam::Vec3::new(1.0, -1.0, -1.0)) + * glam::Mat4::from_scale(glam::Vec3::splat(if baby { 0.5 } else { 1.0 })) + * glam::Mat4::from_translation(glam::Vec3::new(-0.5, -0.518, -0.5)) +} + +fn block_overlay(fuse_ticks: i32, alpha: f32, hurt: bool) -> u32 { + let fuse = if fuse_ticks >= 0 { + fuse_ticks as f32 - alpha + 1.0 + } else { + 0.0 + }; + if fuse > 0.0 && (fuse / 5.0) as i32 % 2 == 0 { + horizon_client::overlay::living(1.0, false) + } else { + horizon_client::overlay::living(0.0, hurt) + } +} + +fn block_light(light: u32, emission: u8) -> u32 { + let block = (light >> 8 & 0xFF).max(u32::from(emission) * 16); + (light & 0xFF) | block << 8 +} + impl Game<'_> { + /// The swallowed block replaces the opaque core and precedes the shell. + pub(super) fn sulfur_cube_body_geometry( + &self, + mob: &Mob, + alpha: f32, + base: glam::Mat4, + light: u32, + out: &mut Vec, + ) { + let Some(item) = mob.extra.head.as_deref() else { + return; + }; + if super::armor_stands::skull_kind(item).is_some() { + return; + } + // shortcut: the body slot retains only an item id; preserve the stack + // before supporting its block-state components here. + let Some(state) = self.res.items.get(item).and_then(|item| item.block) else { + return; + }; + let start = out.len(); + self.block_model_vertices( + state, + 42, + block_transform(base, mob.is_baby()), + block_light(light, self.res.facts.get(state).emission), + true, + out, + ); + let overlay = block_overlay( + sulfur_cube::fuse(mob), + alpha, + mob.hurt_time > 0 || mob.death_time > 0, + ); + if overlay != 0 { + for vertex in &mut out[start..] { + vertex.layer = overlay; + } + } + } + fn sulfur_sound(&mut self, index: usize, sound: &str) { let at = self.mobs[index].center(); self.audio @@ -126,6 +192,11 @@ impl Game<'_> { continue; } let item = e.stack.item.clone(); + let thrown_by_player = e + .thrower + .is_some_and(|uuid| Some(uuid) == self.level.player_uuid); + let mut swallowed = e.stack.clone(); + swallowed.count = 1; let (taken_item, id) = (e.clone(), self.mobs[i].id); self.add_pickup( super::pickups::Taken::Item(Box::new(taken_item)), @@ -140,6 +211,14 @@ impl Game<'_> { m.extra.head = Some(item); m.extra.point = None; self.sulfur_sound(i, "entity.sulfur_cube.absorb"); + if thrown_by_player { + let target = self.mob_entity(&self.mobs[i]); + self.trigger_item_entity( + "minecraft:thrown_item_picked_up_by_entity", + &swallowed, + &target, + ); + } } } /// `AbstractCubeMob.remove`: a dead adult splits into two babies (none @@ -167,3 +246,46 @@ impl Game<'_> { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn swallowed_block_uses_vanilla_lift_and_baby_scale() { + let base = glam::Mat4::from_translation(glam::Vec3::new(3.0, 4.0, -2.0)) + * glam::Mat4::from_rotation_y(0.7) + * glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0)); + for baby in [false, true] { + let size = if baby { 0.5 } else { 1.0 }; + let block = block_transform(base, baby); + for (point, expected) in [ + (glam::Vec3::ZERO, glam::Vec3::new(-0.5, 0.518, 0.5)), + (glam::Vec3::ONE, glam::Vec3::new(0.5, -0.482, -0.5)), + ] { + let actual = block.transform_point3(point); + let expected = base.transform_point3(expected * size); + assert!(actual.abs_diff_eq(expected, 1e-5), "baby={baby}"); + } + assert!(block.transform_vector3(glam::Vec3::Y).y > 0.0); + } + } + + #[test] + fn swallowed_tnt_flashes_white_over_hurt_using_the_interpolated_fuse() { + let white = horizon_client::overlay::WHITE + 15; + assert_eq!(block_overlay(-1, 0.0, false), 0); + assert_eq!(block_overlay(-1, 0.0, true), 1); + assert_eq!(block_overlay(9, 0.0, true), white); + assert_eq!(block_overlay(9, 0.5, false), 0); + assert_eq!(block_overlay(9, 0.5, true), 1); + assert_eq!(block_overlay(0, 0.5, false), white); + } + + #[test] + fn contained_block_emission_preserves_brighter_light_and_the_sky_channel() { + assert_eq!(block_light(0x2050, 1), 0x2050); + assert_eq!(block_light(0x2050, 7), 0x7050); + assert_eq!(block_light(0x0070, 0), 0x0070); + } +} diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index aea4179fd..3c232c755 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -58,6 +58,7 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6] } mod arena; +mod flat; mod java_stages; mod occlusion; mod pack_stages; @@ -101,6 +102,8 @@ struct SectionGpu { faces: crate::mesher::FaceGroups, sort: translucency::SortState, sorted_indices: Option<(u32, u64)>, + /// Its id for flat draws (`flat::Flat::add`), when they are on. + flat_id: Option, } /// Line segments the hit outline can hold. const MAX_OUTLINE_EDGES: u64 = 256; @@ -251,6 +254,10 @@ pub struct Renderer { pub config: wgpu::SurfaceConfiguration, solid: wgpu::RenderPipeline, translucent: wgpu::RenderPipeline, + /// Flat section draws (`flat`), where multi-draw is emulated. + flat: Option, + /// `flat` draws this frame's sections (off: the per-section draws). + flat_on: bool, sky: wgpu::RenderPipeline, dark_disc: wgpu::RenderPipeline, lines: wgpu::RenderPipeline, @@ -355,6 +362,10 @@ pub struct Renderer { pub info: wgpu::AdapterInfo, pub suspended: bool, pub drawn_sections: usize, + /// Last frame's section draws (face ranges and translucent sections), + /// and the draw calls the backend issued for them. + pub section_draws: usize, + pub section_draw_calls: usize, pub uploaded_bytes: u64, started: Instant, /// Write the next presented frame to this PNG path (control socket). @@ -385,7 +396,7 @@ fn sprite_split() -> u32 { .unwrap_or(SPRITE_SPLIT) } /// Sprite arrays terrain.wgsl binds (`sprites`, `sprites_1`...). -const SPRITE_ARRAYS: u32 = 4; +const SPRITE_ARRAYS: u32 = 8; /// The views of terrain.wgsl's sprite arrays, the unused ones a 1-layer /// stand-in. fn sprite_views( @@ -441,6 +452,10 @@ fn terrain_group( view(5, &sprites[1]), view(6, &sprites[2]), view(7, &sprites[3]), + view(8, &sprites[4]), + view(9, &sprites[5]), + view(10, &sprites[6]), + view(11, &sprites[7]), ], }) } @@ -743,6 +758,10 @@ impl Renderer { entry(5, vf, sprite_array), entry(6, vf, sprite_array), entry(7, vf, sprite_array), + entry(8, vf, sprite_array), + entry(9, vf, sprite_array), + entry(10, vf, sprite_array), + entry(11, vf, sprite_array), ], }); let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { @@ -777,18 +796,19 @@ impl Renderer { step_mode: wgpu::VertexStepMode::Instance, attributes: &debug_line_attributes, })]; - let pipeline = |label: &str, - vertex: &str, - fragment: &str, - buffers: &[Option>], - topology: wgpu::PrimitiveTopology, - cull: Option, - depth_write: bool, - depth_test: bool, - blend: Option| { + let pipeline_in = |layout: &wgpu::PipelineLayout, + label: &str, + vertex: &str, + fragment: &str, + buffers: &[Option>], + topology: wgpu::PrimitiveTopology, + cull: Option, + depth_write: bool, + depth_test: bool, + blend: Option| { device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some(label), - layout: Some(&layout), + layout: Some(layout), vertex: wgpu::VertexState { module: &shader, entry_point: Some(vertex), @@ -829,6 +849,28 @@ impl Renderer { cache: None, }) }; + let pipeline = |label: &str, + vertex: &str, + fragment: &str, + buffers: &[Option>], + topology: wgpu::PrimitiveTopology, + cull: Option, + depth_write: bool, + depth_test: bool, + blend: Option| { + pipeline_in( + &layout, + label, + vertex, + fragment, + buffers, + topology, + cull, + depth_write, + depth_test, + blend, + ) + }; let tri = wgpu::PrimitiveTopology::TriangleList; let solid = pipeline( "Terrain solid", @@ -1645,7 +1687,34 @@ impl Renderer { std::mem::size_of::() as u64, 1 << 20, ); - let sorted_indices = arena::Arena::indices(&device, 1 << 16); + // Sections as one index list per frame where multi-draw is emulated. + let flat = flat::wanted(&adapter, &device).then(|| { + let buffers = [Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &TERRAIN_ATTRIBUTES, + })]; + flat::Flat::new( + &device, + &bindings, + arena.page_vertices(), + |layout, label, fragment, blend| { + pipeline_in( + layout, + label, + "vs_terrain_flat", + fragment, + &buffers, + tri, + Some(wgpu::Face::Back), + true, + true, + blend, + ) + }, + ) + }); + let sorted_indices = arena::Arena::indices(&device, 1 << 16, flat.is_some()); let indirect = device.create_buffer(&wgpu::BufferDescriptor { label: Some("Section draws"), size: 1024 * 20, @@ -1680,6 +1749,8 @@ impl Renderer { config, solid, translucent, + flat_on: flat.is_some(), + flat, sky, dark_disc, lines, @@ -1759,6 +1830,8 @@ impl Renderer { info, suspended: size.width == 0 || size.height == 0, drawn_sections: 0, + section_draws: 0, + section_draw_calls: 0, uploaded_bytes: 0, started: Instant::now(), screenshot: None, @@ -1839,30 +1912,12 @@ impl Renderer { }) .create_view(&Default::default()) } - /// VSync on: tear-free presentation (Mailbox, else Fifo); off: Immediate when available. - /// VSync, unless Horizon's present-mode setting names a supported mode. + /// VSync on presents with Fifo, capped to the display's refresh rate in a + /// window and in fullscreen alike; Horizon's present-mode setting applies + /// only with VSync off (`window::chosen_present_mode`). pub fn set_present_mode(&mut self, vsync: bool, mode: crate::graphics::PresentMode) { use crate::graphics::PresentMode as P; - let wanted = match mode { - P::Auto => None, - P::Fifo => Some(wgpu::PresentMode::Fifo), - P::Mailbox => Some(wgpu::PresentMode::Mailbox), - P::Immediate => Some(wgpu::PresentMode::Immediate), - }; - match wanted.filter(|m| self.present_modes.contains(m)) { - Some(m) => { - if self.config.present_mode != m - && let Some(surface) = &self.surface - { - self.config.present_mode = m; - surface.configure(&self.device, &self.config); - } - } - None => self.set_vsync(vsync), - } - } - pub fn set_vsync(&mut self, vsync: bool) { - use crate::window::{PresentMode, vsync_present_mode}; + use crate::window::{PresentMode, chosen_present_mode}; let supported: Vec = self .present_modes .iter() @@ -1873,8 +1928,13 @@ impl Renderer { _ => None, }) .collect(); - // GpuSurface.PresentMode.getSupportedVsyncMode. - let mode = match vsync_present_mode(&supported, vsync) { + let setting = match mode { + P::Auto => None, + P::Fifo => Some(PresentMode::Fifo), + P::Mailbox => Some(PresentMode::Mailbox), + P::Immediate => Some(PresentMode::Immediate), + }; + let mode = match chosen_present_mode(&supported, vsync, setting) { Some(PresentMode::Mailbox) => wgpu::PresentMode::Mailbox, Some(PresentMode::Immediate) => wgpu::PresentMode::Immediate, _ => wgpu::PresentMode::Fifo, @@ -1900,6 +1960,18 @@ impl Renderer { } self.depth = Self::depth(&self.device, &self.config); } + /// Whether sections are drawn as one index list per frame (`flat`). + pub fn flat_draws(&self) -> bool { + self.flat_on + } + /// Switches between flat and per-section draws, for A/B checks. + pub fn set_flat_draws(&mut self, on: bool) -> Result<()> { + if on && self.flat.is_none() { + return Err("flat section draws are off on this device".into()); + } + self.flat_on = on; + Ok(()) + } pub fn section_count(&self) -> usize { self.sections.len() } @@ -1941,6 +2013,10 @@ impl Renderer { } else { None }; + let flat_id = self + .flat + .as_mut() + .map(|f| f.add(&self.device, &self.queue, page, start, vertices)); let stride = std::mem::size_of::() as u64; for (offset, part) in [(0, &mesh.solid), (mesh.solid.len(), &mesh.translucent)] { if !part.is_empty() { @@ -1970,6 +2046,7 @@ impl Renderer { .collect(), ), sorted_indices, + flat_id, }, ); } @@ -2000,6 +2077,9 @@ impl Renderer { } fn release_section(&mut self, key: SectionKey) { if let Some(s) = self.sections.remove(key) { + if let (Some(flat), Some(id)) = (&mut self.flat, s.flat_id) { + flat.remove(id); + } if let Some((page, start)) = s.sorted_indices { self.sorted_indices .release(page, start, u64::from(s.translucent) * 6); @@ -2016,6 +2096,9 @@ impl Renderer { self.block_entities.clear(); self.sections.clear(); self.arena.clear(); + if let Some(flat) = &mut self.flat { + flat.clear(); + } self.sorted_indices.clear(); self.translucency_cursor = 0; self.occlusion.clear(); @@ -2198,6 +2281,9 @@ impl Renderer { pub fn render(&mut self, frame: &Frame) -> Result { self.arena.trim(); self.sorted_indices.trim(); + if let Some(flat) = &mut self.flat { + flat.trim(|page| self.arena.has_page(page)); + } if self.suspended { return Ok(false); } @@ -2388,18 +2474,22 @@ impl Renderer { let culling = !frame.title && frame.cave_culling; if culling { let radius = (frame.distance / 16.0) as i32 + 2; - self.occlusion.update(camera_section, radius); + crate::spans::time("occlusion", || { + self.occlusion.update(camera_section, radius) + }); } let reachable = &self.occlusion; let mut visible = std::mem::take(&mut self.visible); visible.clear(); - self.sections.visible( - camera, - (frame.distance / 16.0) as i32, - &view, - |k| !culling || reachable.contains(k), - &mut visible, - ); + crate::spans::time("visibility", || { + self.sections.visible( + camera, + (frame.distance / 16.0) as i32, + &view, + |k| !culling || reachable.contains(k), + &mut visible, + ) + }); self.drawn_sections = visible.len(); if visible.len() as u64 > self.instance_capacity { self.instance_capacity = (visible.len() as u64).next_power_of_two(); @@ -2487,7 +2577,45 @@ impl Renderer { } self.translucency_cursor += budget; let translucent_draws = self.draws.len() as u32 - solid_draws; - if self.multi_draw && !self.draws.is_empty() { + self.section_draws = self.draws.len(); + // Metal replays a multi-draw as one draw call per entry. + self.section_draw_calls = if self.multi_draw && self.info.backend != wgpu::Backend::Metal { + (0..self.draws.len()) + .filter(|&i| { + i == 0 + || i == solid_draws as usize + || self.draw_pages[i] != self.draw_pages[i - 1] + }) + .count() + } else { + self.draws.len() + }; + let flat_frame = match &mut self.flat { + Some(flat) + if self.flat_on && !self.draws.is_empty() && self.draws.len() >= flat.min_draws => + { + let sections = &self.sections; + let sorted = &self.sorted_indices; + crate::spans::time("flatten", || { + flat.prepare( + &self.device, + &mut encoder, + &mut self.uploads, + &self.draws, + &self.draw_pages, + solid_draws as usize, + visible + .iter() + .filter_map(|v| sections.get(v.slot).flat_id.map(|id| (id, v.origin))), + |page| sorted.buffer(page).clone(), + ) + }) + } + _ => false, + }; + if flat_frame { + self.section_draw_calls = self.flat.as_ref().map_or(0, |f| f.calls.len()); + } else if self.multi_draw && !self.draws.is_empty() { if self.draws.len() as u64 > self.indirect_capacity { self.indirect_capacity = (self.draws.len() as u64).next_power_of_two(); self.indirect = self.device.create_buffer(&wgpu::BufferDescriptor { @@ -2722,10 +2850,22 @@ impl Renderer { pass.draw(0..3, 0..1); } } - pass.set_pipeline(&self.solid); - pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); - pass.set_vertex_buffer(1, self.instances.slice(..)); - self.draw_sections(&mut pass, 0, solid_draws); + match self.flat.as_ref().filter(|_| flat_frame) { + Some(flat) => { + pass.set_pipeline(&flat.solid); + flat.draw(&mut pass, &flat.calls[..flat.solid_calls], |p| { + self.arena.buffer(p) + }); + pass.set_bind_group(0, &self.group, &[]); + pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); + } + None => { + pass.set_pipeline(&self.solid); + pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.set_vertex_buffer(1, self.instances.slice(..)); + self.draw_sections(&mut pass, 0, solid_draws); + } + } if entity_quads > 0 { pass.set_pipeline(&self.entity_pipeline); pass.set_bind_group(0, &self.entity_group, &[]); @@ -2762,10 +2902,22 @@ impl Renderer { pass.set_vertex_buffer(0, self.debug_line_buffer.slice(..)); pass.draw(0..4, debug_depth..debug_depth + debug_top); } - pass.set_pipeline(&self.translucent); - pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); - pass.set_vertex_buffer(1, self.instances.slice(..)); - self.draw_sections(&mut pass, solid_draws, translucent_draws); + match self.flat.as_ref().filter(|_| flat_frame) { + Some(flat) => { + pass.set_pipeline(&flat.translucent); + flat.draw(&mut pass, &flat.calls[flat.solid_calls..], |p| { + self.arena.buffer(p) + }); + pass.set_bind_group(0, &self.group, &[]); + pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); + } + None => { + pass.set_pipeline(&self.translucent); + pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.set_vertex_buffer(1, self.instances.slice(..)); + self.draw_sections(&mut pass, solid_draws, translucent_draws); + } + } // LevelRenderer.executeClassicTransparency: translucent targets' // outlines follow terrain, so its blending cannot wash them out. if outline_edges > 0 && frame.outline_after_terrain { @@ -3006,7 +3158,8 @@ impl Renderer { .take() .map(|path| (path, self.copy_frame(&mut encoder, &target_texture))); self.uploads.finish(&encoder); - let submission = self.queue.submit([encoder.finish()]); + let commands = crate::spans::time("encode", || encoder.finish()); + let submission = crate::spans::time("submit", || self.queue.submit([commands])); if let Some(timer) = &mut self.gpu_timer { timer.submitted(); timer.collect(&self.device, &mut self.gpu_times); diff --git a/crates/horizon-client/src/gfx/arena.rs b/crates/horizon-client/src/gfx/arena.rs index 8becb6499..74d3b98e9 100644 --- a/crates/horizon-client/src/gfx/arena.rs +++ b/crates/horizon-client/src/gfx/arena.rs @@ -2,8 +2,11 @@ //! a frame binds it once and draws every section with indirect multi-draw. use std::collections::BTreeMap; -/// Ranges are rounded up to this many vertices to limit fragmentation. -const GRAIN: u64 = 256; +/// Ranges are rounded up to this many vertices to limit fragmentation, and +/// start at multiples of it (`flat` names sections by these blocks). +pub const GRAIN: u64 = 256; +/// The largest page, in bytes. +pub const PAGE_BYTES: u64 = 256 << 20; /// Free vertex ranges: start -> length, never adjacent. #[derive(Debug, PartialEq)] @@ -65,8 +68,14 @@ impl Arena { pub fn new(device: &wgpu::Device, stride: u64, capacity: u64) -> Self { Self::with_usage(device, stride, capacity, wgpu::BufferUsages::VERTEX) } - pub fn indices(device: &wgpu::Device, capacity: u64) -> Self { - Self::with_usage(device, 4, capacity, wgpu::BufferUsages::INDEX) + /// Sorted translucent indices; `storage` when compute passes read them. + pub fn indices(device: &wgpu::Device, capacity: u64, storage: bool) -> Self { + let usage = if storage { + wgpu::BufferUsages::INDEX | wgpu::BufferUsages::STORAGE + } else { + wgpu::BufferUsages::INDEX + }; + Self::with_usage(device, 4, capacity, usage) } fn with_usage( device: &wgpu::Device, @@ -75,7 +84,7 @@ impl Arena { usage: wgpu::BufferUsages, ) -> Self { // 256 MiB pages, or less where the device's buffers are smaller. - let bytes = device.limits().max_buffer_size.min(256 << 20); + let bytes = device.limits().max_buffer_size.min(PAGE_BYTES); let page_limit = (bytes / stride) / GRAIN * GRAIN; let capacity = capacity.next_multiple_of(GRAIN).min(page_limit); Self { @@ -132,6 +141,13 @@ impl Arena { pub fn bytes(&self) -> u64 { self.pages.iter().flatten().map(|p| p.capacity).sum::() * self.stride } + /// The most vertices a page holds. + pub fn page_vertices(&self) -> u64 { + self.page_limit + } + pub fn has_page(&self, page: u32) -> bool { + self.pages.get(page as usize).is_some_and(Option::is_some) + } pub fn buffer(&self, page: u32) -> &wgpu::Buffer { &self.pages[page as usize] .as_ref() @@ -338,7 +354,7 @@ mod tests { }; for mut arena in [ Arena::new(&device, 28, GRAIN), - Arena::indices(&device, GRAIN), + Arena::indices(&device, GRAIN, false), ] { arena.alloc(&device, &queue, GRAIN).unwrap(); assert_eq!(arena.bytes(), arena.stride * GRAIN); @@ -397,7 +413,7 @@ mod tests { { return; } - let mut arena = Arena::indices(&device, GRAIN); + let mut arena = Arena::indices(&device, GRAIN, false); let (page, start) = arena.alloc(&device, &queue, GRAIN).unwrap(); queue.write_buffer(arena.buffer(page), start * 4, &7u32.to_le_bytes()); arena.video_memory_full = true; @@ -422,7 +438,7 @@ mod tests { let Some((device, queue)) = device() else { return; }; - let mut arena = Arena::indices(&device, GRAIN); + let mut arena = Arena::indices(&device, GRAIN, false); arena.alloc(&device, &queue, GRAIN).unwrap(); arena.video_memory_full = true; // Without mappable primary buffers nothing can spill: the request diff --git a/crates/horizon-client/src/gfx/flat.rs b/crates/horizon-client/src/gfx/flat.rs new file mode 100644 index 000000000..b867a42c2 --- /dev/null +++ b/crates/horizon-client/src/gfx/flat.rs @@ -0,0 +1,658 @@ +//! Flat section draws: where indirect multi-draw is emulated, as on Metal +//! (wgpu replays it as one draw call per indirect entry), the frame's section +//! draws are copied by a compute pass into one index list, in draw order, and +//! drawn with one draw call per run of sections in the same arena page. +//! +//! The picture is the one the per-section draws give: the same triangles +//! from the same vertices in the same order, through the same vertex and +//! fragment code. Only where a vertex finds its section's origin changes: +//! from the instance attribute to a table. A section's vertices fill whole +//! blocks of `GRAIN` vertices of its page (the arena rounds every range up), +//! so each block names one section: its id here, which indexes the frame's +//! camera-relative origins (computed on the CPU exactly as for the instance +//! attribute). +use super::arena::GRAIN; + +/// One section draw for `flatten.wgsl`: index count, first sorted index (or +/// `QUADS` for a solid draw), base vertex, first index in the list. +type Range = [u32; 4]; +const QUADS: u32 = u32::MAX; +const GROUP_LIMIT: u32 = 65535; + +struct PageTable { + /// Section id of every block of the page. + blocks: wgpu::Buffer, + group: Option, +} + +/// A run of the frame's index list drawn from one arena page. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Call { + pub page: u32, + pub first: u32, + pub count: u32, +} + +pub struct Flat { + pub solid: wgpu::RenderPipeline, + pub translucent: wgpu::RenderPipeline, + flatten: wgpu::ComputePipeline, + compute_layout: wgpu::BindGroupLayout, + draw_layout: wgpu::BindGroupLayout, + blocks_per_page: u64, + pages: Vec>, + free_ids: Vec, + next_id: u32, + origins: wgpu::Buffer, + origin_capacity: u64, + origin_data: Vec<[f32; 4]>, + /// The frame's index list. + pub indices: wgpu::Buffer, + index_capacity: u64, + ranges: wgpu::Buffer, + range_capacity: u64, + range_data: Vec, + /// Segments of `range_data` by index source: (sorted index page or + /// `None` for solid draws, first range, ranges). + segments: Vec<(Option, u64, u64)>, + empty: wgpu::Buffer, + /// This frame's draw calls: solid ones, then translucent ones. + pub calls: Vec, + pub solid_calls: usize, + /// Frames with fewer section draws keep the per-section draws. + pub min_draws: usize, + range_align: u64, +} + +/// Section draws from which a frame is drawn flat. Below it the index list +/// costs the GPU more than the draw calls cost the CPU: on an M4 Pro at +/// render distance 16 (2,900 draws) the copy and the list add about 0.4 ms +/// of GPU time for 0.5–0.8 ms less CPU time; at 32 (9,300 draws) the CPU +/// saves 1.3 ms. +const MIN_DRAWS: usize = 4096; + +/// Whether flat draws apply: the backend emulates multi-draw, and vertex +/// shaders can read storage buffers large enough for an index page. +/// `HORIZON_FLAT_DRAWS=1` draws every frame flat, `0` none. +pub fn wanted(adapter: &wgpu::Adapter, device: &wgpu::Device) -> bool { + match std::env::var("HORIZON_FLAT_DRAWS").as_deref() { + Ok("0") => return false, + Ok("1") => return supported(adapter, device), + _ => {} + } + adapter.get_info().backend == wgpu::Backend::Metal && supported(adapter, device) +} + +fn supported(adapter: &wgpu::Adapter, device: &wgpu::Device) -> bool { + let flags = adapter.get_downlevel_capabilities().flags; + let limits = device.limits(); + flags.contains(wgpu::DownlevelFlags::VERTEX_STORAGE | wgpu::DownlevelFlags::COMPUTE_SHADERS) + && limits.max_storage_buffers_per_shader_stage >= 3 + && limits.max_storage_buffer_binding_size >= super::arena::PAGE_BYTES +} + +fn storage(binding: u32, stage: wgpu::ShaderStages, read_only: bool) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: stage, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + } +} + +fn buffer( + device: &wgpu::Device, + label: &str, + size: u64, + usage: wgpu::BufferUsages, +) -> wgpu::Buffer { + device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size: size.max(16), + usage: usage | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }) +} + +/// Lays out the frame's index list: each draw's range (destinations in draw +/// order) grouped by index source into `ranges`, every group padded to +/// `align` entries for binding, with `segments` naming each group; and the +/// draw calls, one per run of draws in the same vertex page, solid and +/// translucent apart. Returns the first translucent call and the list's +/// length. +fn plan( + draws: &[[u32; 5]], + pages: &[(u32, Option)], + solid_draws: usize, + align: u64, + calls: &mut Vec, + ranges: &mut Vec, + segments: &mut Vec<(Option, u64, u64)>, +) -> (usize, u64) { + calls.clear(); + ranges.clear(); + segments.clear(); + let mut solid_calls = None; + let mut total = 0u64; + let mut by_source: Vec<(Option, Vec)> = Vec::new(); + for (i, (d, &(page, sorted))) in draws.iter().zip(pages).enumerate() { + let first = if sorted.is_some() { d[2] } else { QUADS }; + let range = [d[0], first, d[3], total as u32]; + match by_source.iter_mut().find(|(s, _)| *s == sorted) { + Some((_, list)) => list.push(range), + None => by_source.push((sorted, vec![range])), + } + if i == solid_draws { + solid_calls = Some(calls.len()); + } + match calls.last_mut() { + Some(last) if last.page == page && i != solid_draws => last.count += d[0], + _ => calls.push(Call { + page, + first: total as u32, + count: d[0], + }), + } + total += u64::from(d[0]); + } + for (source, list) in by_source { + segments.push((source, ranges.len() as u64, list.len() as u64)); + ranges.extend(list); + let padded = (ranges.len() as u64).next_multiple_of(align); + ranges.resize(padded as usize, [0; 4]); + } + (solid_calls.unwrap_or(calls.len()), total) +} + +impl Flat { + /// `pipeline(layout, label, vertex entry, fragment entry, blend)` builds a + /// terrain pipeline as the per-section ones, without the origin buffer. + pub fn new( + device: &wgpu::Device, + terrain_layout: &wgpu::BindGroupLayout, + page_vertices: u64, + pipeline: impl Fn( + &wgpu::PipelineLayout, + &str, + &str, + Option, + ) -> wgpu::RenderPipeline, + ) -> Self { + let vertex = wgpu::ShaderStages::VERTEX; + let compute = wgpu::ShaderStages::COMPUTE; + let draw_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Flat section draws"), + entries: &[storage(0, vertex, true), storage(1, vertex, true)], + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Flat terrain layout"), + bind_group_layouts: &[Some(terrain_layout), Some(&draw_layout)], + ..Default::default() + }); + let compute_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Flatten section draws"), + entries: &[ + storage(0, compute, true), + storage(1, compute, true), + storage(2, compute, false), + ], + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Flatten section draws"), + source: wgpu::ShaderSource::Wgsl(include_str!("flatten.wgsl").into()), + }); + let flatten = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("Flatten section draws"), + layout: Some( + &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Flatten section draws"), + bind_group_layouts: &[Some(&compute_layout)], + ..Default::default() + }), + ), + module: &module, + entry_point: Some("flatten"), + compilation_options: Default::default(), + cache: None, + }); + let storage_usage = wgpu::BufferUsages::STORAGE; + Self { + solid: pipeline(&layout, "Terrain solid (flat)", "fs_solid", None), + translucent: pipeline( + &layout, + "Terrain translucent (flat)", + "fs_translucent", + Some(wgpu::BlendState::ALPHA_BLENDING), + ), + flatten, + compute_layout, + draw_layout, + blocks_per_page: page_vertices.div_ceil(GRAIN), + pages: Vec::new(), + free_ids: Vec::new(), + next_id: 0, + origins: buffer(device, "Section origins by id", 16, storage_usage), + origin_capacity: 1, + origin_data: Vec::new(), + indices: buffer( + device, + "Flat section indices", + 16, + wgpu::BufferUsages::INDEX | storage_usage, + ), + index_capacity: 4, + ranges: buffer(device, "Flat section ranges", 16, storage_usage), + range_capacity: 1, + range_data: Vec::new(), + segments: Vec::new(), + empty: buffer(device, "No sorted indices", 16, storage_usage), + calls: Vec::new(), + solid_calls: 0, + min_draws: if std::env::var("HORIZON_FLAT_DRAWS").as_deref() == Ok("1") { + 0 + } else { + MIN_DRAWS + }, + range_align: (u64::from(device.limits().min_storage_buffer_offset_alignment) / 16) + .max(1), + } + } + /// A section uploaded to `vertices` vertices from `start` of `page`: its + /// id, which its blocks now name. + pub fn add( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + page: u32, + start: u64, + vertices: u64, + ) -> u32 { + let id = self.free_ids.pop().unwrap_or_else(|| { + self.next_id += 1; + self.next_id - 1 + }); + let page = page as usize; + if self.pages.len() <= page { + self.pages.resize_with(page + 1, || None); + } + let table = self.pages[page].get_or_insert_with(|| PageTable { + blocks: buffer( + device, + "Section ids by block", + self.blocks_per_page * 4, + wgpu::BufferUsages::STORAGE, + ), + group: None, + }); + let first = start / GRAIN; + let ids = vec![id; vertices.div_ceil(GRAIN) as usize]; + queue.write_buffer(&table.blocks, first * 4, bytemuck::cast_slice(&ids)); + id + } + pub fn remove(&mut self, id: u32) { + self.free_ids.push(id); + } + pub fn clear(&mut self) { + self.pages.clear(); + self.free_ids.clear(); + self.next_id = 0; + } + /// Forgets the tables of pages the arena released. + pub fn trim(&mut self, live: impl Fn(u32) -> bool) { + for (i, page) in self.pages.iter_mut().enumerate() { + if page.is_some() && !live(i as u32) { + *page = None; + } + } + } + /// Builds the frame's index list from `draws` (`DrawIndexedIndirectArgs`: + /// index count, instances, first index, base vertex, first instance), + /// solid ones first, with their (vertex page, sorted index page) and + /// the origins of the sections they draw by id. Records the copy into + /// `encoder`; `calls` then lists the frame's draw calls. False when the + /// frame cannot be drawn flat (the per-section draws then apply). + #[allow(clippy::too_many_arguments)] + pub fn prepare( + &mut self, + device: &wgpu::Device, + encoder: &mut wgpu::CommandEncoder, + uploads: &mut super::upload::Uploads, + draws: &[[u32; 5]], + pages: &[(u32, Option)], + solid_draws: usize, + origins: impl Iterator, + sorted_page: impl Fn(u32) -> wgpu::Buffer, + ) -> bool { + // Origins by section id. + self.origin_data.clear(); + for (id, o) in origins { + let id = id as usize; + if self.origin_data.len() <= id { + self.origin_data.resize(id + 1, [0.0; 4]); + } + self.origin_data[id] = [o[0], o[1], o[2], 0.0]; + } + if self.origin_data.len() as u64 > self.origin_capacity { + self.origin_capacity = (self.origin_data.len() as u64).next_power_of_two(); + self.origins = buffer( + device, + "Section origins by id", + self.origin_capacity * 16, + wgpu::BufferUsages::STORAGE, + ); + for page in self.pages.iter_mut().flatten() { + page.group = None; + } + } + if !self.origin_data.is_empty() { + uploads.buffer( + encoder, + &self.origins, + 0, + bytemuck::cast_slice(&self.origin_data), + ); + } + let (solid_calls, total) = plan( + draws, + pages, + solid_draws, + self.range_align, + &mut self.calls, + &mut self.range_data, + &mut self.segments, + ); + self.solid_calls = solid_calls; + if total == 0 || total * 4 > device.limits().max_storage_buffer_binding_size { + self.calls.clear(); + self.solid_calls = 0; + return false; + } + if self.range_data.len() as u64 > self.range_capacity { + self.range_capacity = (self.range_data.len() as u64).next_power_of_two(); + self.ranges = buffer( + device, + "Flat section ranges", + self.range_capacity * 16, + wgpu::BufferUsages::STORAGE, + ); + } + if total > self.index_capacity { + self.index_capacity = total.next_power_of_two(); + self.indices = buffer( + device, + "Flat section indices", + self.index_capacity * 4, + wgpu::BufferUsages::INDEX | wgpu::BufferUsages::STORAGE, + ); + } + uploads.buffer( + encoder, + &self.ranges, + 0, + bytemuck::cast_slice(&self.range_data), + ); + let groups: Vec<(wgpu::BindGroup, u32)> = self + .segments + .iter() + .map(|&(source, first, count)| { + let sorted = source.map(&sorted_page); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Flatten section draws"), + layout: &self.compute_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &self.ranges, + offset: first * 16, + size: wgpu::BufferSize::new(count * 16), + }), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: sorted.as_ref().unwrap_or(&self.empty).as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: self.indices.as_entire_binding(), + }, + ], + }); + (group, count as u32) + }) + .collect(); + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("Flatten section draws"), + timestamp_writes: None, + }); + pass.set_pipeline(&self.flatten); + for (group, count) in &groups { + pass.set_bind_group(0, group, &[]); + pass.dispatch_workgroups((*count).min(GROUP_LIMIT), count.div_ceil(GROUP_LIMIT), 1); + } + drop(pass); + for page in self.calls.iter().map(|c| c.page) { + let table = self.pages[page as usize] + .as_mut() + .expect("a drawn page has its block table"); + if table.group.is_none() { + table.group = Some(device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Flat section draws"), + layout: &self.draw_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: table.blocks.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: self.origins.as_entire_binding(), + }, + ], + })); + } + } + true + } + /// Draws `calls` with a flat pipeline set and `vertices` giving each + /// page's vertex buffer. + pub fn draw<'a>( + &self, + pass: &mut wgpu::RenderPass<'_>, + calls: &[Call], + vertices: impl Fn(u32) -> &'a wgpu::Buffer, + ) { + pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); + for call in calls { + let table = self.pages[call.page as usize] + .as_ref() + .and_then(|t| t.group.as_ref()) + .expect("prepared page"); + pass.set_vertex_buffer(0, vertices(call.page).slice(..)); + pass.set_bind_group(1, table, &[]); + pass.draw_indexed(call.first..call.first + call.count, 0, 0..1); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Draws as `render` writes them: solid (page, quads at a base vertex) + /// first, then translucent (page, sorted page, count, first sorted index, + /// base vertex). + fn sample() -> (Vec<[u32; 5]>, Vec<(u32, Option)>, usize) { + let draws = vec![ + [6 * 3, 1, 0, 0, 0], + [6 * 2, 1, 0, 512, 1], + [6, 1, 0, 256, 2], + [6 * 4, 1, 0, 1024, 3], + [6 * 2, 1, 6, 768, 1], + [6, 1, 0, 40, 0], + ]; + let pages = vec![ + (0, None), + (0, None), + (1, None), + (0, None), + (0, Some(0)), + (0, Some(1)), + ]; + (draws, pages, 4) + } + + #[test] + fn plan_draws_runs_of_a_page_in_order() { + let (draws, pages, solid) = sample(); + let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new()); + let (solid_calls, total) = plan( + &draws, + &pages, + solid, + 4, + &mut calls, + &mut ranges, + &mut segments, + ); + assert_eq!(total, 6 * 13); + let call = |page, first, count| Call { page, first, count }; + // Pages 0, 0 | 1 | 0, then translucent 0, 0 (never merged with solid). + assert_eq!( + calls, + [ + call(0, 0, 30), + call(1, 30, 6), + call(0, 36, 24), + call(0, 60, 18) + ] + ); + assert_eq!(solid_calls, 3); + // Solid ranges, then each sorted page's, every group padded to 4. + assert_eq!(segments, [(None, 0, 4), (Some(0), 4, 1), (Some(1), 8, 1)]); + assert_eq!(ranges[3], [24, QUADS, 1024, 36]); + assert_eq!(ranges[4], [12, 6, 768, 60]); + assert_eq!(ranges[8], [6, 0, 40, 72]); + assert_eq!(ranges.len(), 12); + } + + /// The compute pass writes exactly the indices the per-section draws + /// read: quads 0 1 2 0 2 3 for solid draws, sorted indices otherwise, + /// plus the base vertex. + #[test] + fn flatten_writes_the_indices_of_the_per_section_draws() { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { + eprintln!("no GPU adapter: skipped"); + return; + }; + let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default())) + else { + eprintln!("no GPU device: skipped"); + return; + }; + use wgpu::util::DeviceExt; + let (draws, pages, solid) = sample(); + let align = (u64::from(device.limits().min_storage_buffer_offset_alignment) / 16).max(1); + let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new()); + let (_, total) = plan( + &draws, + &pages, + solid, + align, + &mut calls, + &mut ranges, + &mut segments, + ); + let sorted: [Vec; 2] = [ + (0..32).map(|i| (i * 7) % 32).collect(), + (0..8).rev().collect(), + ]; + let mut expected = Vec::new(); + for (d, (_, page)) in draws.iter().zip(&pages) { + for k in 0..d[0] { + let i = match page { + None => (k / 6) * 4 + [0, 1, 2, 0, 2, 3][(k % 6) as usize], + Some(p) => sorted[*p as usize][(d[2] + k) as usize], + }; + expected.push(d[3] + i); + } + } + let storage = |entries: &[u32]| { + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: None, + contents: bytemuck::cast_slice(entries), + usage: wgpu::BufferUsages::STORAGE, + }) + }; + let range_buffer = storage(bytemuck::cast_slice(&ranges)); + let sorted_buffers = [storage(&sorted[0]), storage(&sorted[1]), storage(&[0; 4])]; + let out = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: total * 4, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, + mapped_at_creation: false, + }); + let read = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: total * 4, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(include_str!("flatten.wgsl").into()), + }); + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: None, + module: &module, + entry_point: Some("flatten"), + compilation_options: Default::default(), + cache: None, + }); + let mut encoder = device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + for &(source, first, count) in &segments { + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &pipeline.get_bind_group_layout(0), + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &range_buffer, + offset: first * 16, + size: wgpu::BufferSize::new(count * 16), + }), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: sorted_buffers[source.map_or(2, |p| p as usize)] + .as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: out.as_entire_binding(), + }, + ], + }); + pass.set_bind_group(0, &group, &[]); + pass.dispatch_workgroups(count as u32, 1, 1); + } + } + encoder.copy_buffer_to_buffer(&out, 0, &read, 0, total * 4); + queue.submit([encoder.finish()]); + read.slice(..).map_async(wgpu::MapMode::Read, |_| {}); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let got: Vec = + bytemuck::cast_slice(&read.slice(..).get_mapped_range().unwrap()).to_vec(); + assert_eq!(got, expected); + } +} diff --git a/crates/horizon-client/src/gfx/flatten.wgsl b/crates/horizon-client/src/gfx/flatten.wgsl new file mode 100644 index 000000000..2f57f8775 --- /dev/null +++ b/crates/horizon-client/src/gfx/flatten.wgsl @@ -0,0 +1,35 @@ +// Flat section draws (gfx/flat.rs): copies each section draw's indices into +// one index list, in draw order, offset by the draw's base vertex. Solid +// draws index quads (0 1 2 0 2 3 per quad, as Renderer::quad_indices); +// translucent ones read their sorted indices. +struct Range { + count: u32, + // First sorted index, or QUADS for a solid draw. + first: u32, + base: u32, + dst: u32, +} +const QUADS: u32 = 0xffffffffu; +const GROUP: u32 = 64u; +@group(0) @binding(0) var ranges: array; +@group(0) @binding(1) var sorted: array; +@group(0) @binding(2) var out: array; +@compute @workgroup_size(64) +fn flatten(@builtin(workgroup_id) group: vec3, + @builtin(local_invocation_index) lane: u32) { + let r = group.y * 65535u + group.x; + if r >= arrayLength(&ranges) { + return; + } + let d = ranges[r]; + for (var k = lane; k < d.count; k += GROUP) { + var i: u32; + if d.first == QUADS { + let c = k % 6u; + i = (k / 6u) * 4u + select(select(c - 2u, 0u, c == 3u), c, c < 3u); + } else { + i = sorted[d.first + k]; + } + out[d.dst + k] = d.base + i; + } +} diff --git a/crates/horizon-client/src/gfx/timing.rs b/crates/horizon-client/src/gfx/timing.rs index b3daeeaa4..5d2354234 100644 --- a/crates/horizon-client/src/gfx/timing.rs +++ b/crates/horizon-client/src/gfx/timing.rs @@ -1,5 +1,9 @@ //! GPU frame time from timestamp queries, read back a few frames late so the //! CPU never waits for it. Frames whose readback slot is still busy go untimed. +//! +//! Where the GPU can only time pass boundaries (Apple GPUs on Metal), the +//! frame is bracketed by two one-thread compute passes that write the +//! timestamps (Metal leaves an empty pass's timestamps at zero). use std::sync::{ Arc, atomic::{AtomicU8, Ordering}, @@ -23,24 +27,18 @@ pub struct GpuTimer { current: Option, next: usize, period_ns: f32, + /// Timestamps between commands, or else this pass's boundaries. + marker: Option, } impl GpuTimer { - /// The features timing needs; `None` when the adapter lacks them. + /// The features timing uses that the adapter has (none: no timing). pub fn features(adapter: &wgpu::Adapter) -> wgpu::Features { - let wanted = - wgpu::Features::TIMESTAMP_QUERY | wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS; - if adapter.features().contains(wanted) { - wanted - } else { - wgpu::Features::empty() - } + adapter.features() + & (wgpu::Features::TIMESTAMP_QUERY | wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS) } pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Option { - if !device - .features() - .contains(wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS) - { + if !device.features().contains(wgpu::Features::TIMESTAMP_QUERY) { return None; } let queries = device.create_query_set(&wgpu::QuerySetDescriptor { @@ -72,21 +70,56 @@ impl GpuTimer { current: None, next: 0, period_ns: queue.get_timestamp_period(), + marker: (!device + .features() + .contains(wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS)) + .then(|| { + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Frame timestamp"), + source: wgpu::ShaderSource::Wgsl( + "@compute @workgroup_size(1) fn mark() {}".into(), + ), + }); + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("Frame timestamp"), + layout: None, + module: &module, + entry_point: Some("mark"), + compilation_options: Default::default(), + cache: None, + }) + }), }) } pub fn begin(&mut self, encoder: &mut wgpu::CommandEncoder) { let slot = self.next; self.current = (self.slots[slot].state.load(Ordering::Acquire) == FREE).then_some(slot); if self.current.is_some() { - encoder.write_timestamp(&self.queries, 0); + self.stamp(encoder, 0); } } pub fn end(&mut self, encoder: &mut wgpu::CommandEncoder) { let Some(slot) = self.current else { return }; - encoder.write_timestamp(&self.queries, 1); + self.stamp(encoder, 1); encoder.resolve_query_set(&self.queries, 0..2, &self.resolve, 0); encoder.copy_buffer_to_buffer(&self.resolve, 0, &self.slots[slot].buffer, 0, 16); } + fn stamp(&self, encoder: &mut wgpu::CommandEncoder, index: u32) { + let Some(marker) = &self.marker else { + encoder.write_timestamp(&self.queries, index); + return; + }; + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("Frame timestamp"), + timestamp_writes: Some(wgpu::ComputePassTimestampWrites { + query_set: &self.queries, + beginning_of_pass_write_index: (index == 0).then_some(0), + end_of_pass_write_index: (index == 1).then_some(1), + }), + }); + pass.set_pipeline(marker); + pass.dispatch_workgroups(1, 1, 1); + } /// After the frame's submission: start reading its timestamps back. pub fn submitted(&mut self) { let Some(slot) = self.current.take() else { diff --git a/crates/horizon-client/src/graphics.rs b/crates/horizon-client/src/graphics.rs index f10c6b3b3..e8fb2bff1 100644 --- a/crates/horizon-client/src/graphics.rs +++ b/crates/horizon-client/src/graphics.rs @@ -53,7 +53,9 @@ impl Preset { /// How the swapchain presents frames. #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] pub enum PresentMode { - /// Follow vanilla's VSync option (Mailbox or Fifo on, Immediate off). + /// Vanilla's choice: Fifo with VSync on, else the first of Immediate, + /// Mailbox and Fifo the surface supports. The other modes apply only + /// with VSync off: VSync on always presents with Fifo. #[default] Auto, Fifo, diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index 745cd5d80..4d7619037 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -211,7 +211,7 @@ pub fn rows(level: Level) -> Vec { h( H::PresentMode, None, - "How frames reach the screen. Auto follows VSync.", + "How frames reach the screen while VSync is off.", ), h( H::Pacing, diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index db0677d5f..493488732 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -161,6 +161,8 @@ pub struct PlayerHealth { pub ids: PlayerFloatIds, pub food: FoodData, pub hurt: State, + /// Client hurt animation; fully blocked hits only refresh the server's hurt state. + pub hurt_animation_time: i32, pub dead: bool, pub sync_velocity: bool, pub game_time: i64, @@ -210,6 +212,7 @@ impl PlayerHealth { last_source: None, last_stamp: 0, }, + hurt_animation_time: 0, dead: false, sync_velocity: false, game_time: 0, @@ -242,6 +245,9 @@ impl PlayerHealth { if self.hurt.hurt_time > 0 { self.hurt.hurt_time -= 1; } + if self.hurt_animation_time > 0 { + self.hurt_animation_time -= 1; + } } } impl PlayerMotion { @@ -300,8 +306,11 @@ impl PlayerMotion { sound: environment.block_sound, }; if environment.totem_fired { - self.health.totem_used = true; - self.health.totem_ready = false; + h.totem_used = true; + h.totem_ready = false; + } + if outcome.hurt { + h.hurt_animation_time = h.hurt.hurt_time; } Ok(outcome) } diff --git a/crates/horizon-client/src/hunger.rs b/crates/horizon-client/src/hunger.rs index 90b11f18d..fa1b62a5e 100644 --- a/crates/horizon-client/src/hunger.rs +++ b/crates/horizon-client/src/hunger.rs @@ -55,6 +55,7 @@ impl PlayerMotion { data: &mut h.data, ids: h.ids, hurt: &mut h.hurt, + hurt_animation_time: &mut h.hurt_animation_time, dead: &mut h.dead, sync_velocity: &mut h.sync_velocity, game_time: h.game_time, @@ -70,6 +71,7 @@ struct TickWorld<'a> { data: &'a mut SyncedFloats, ids: PlayerFloatIds, hurt: &'a mut State, + hurt_animation_time: &'a mut i32, dead: &'a mut bool, sync_velocity: &'a mut bool, game_time: i64, @@ -142,8 +144,11 @@ impl FoodWorld for TickWorld<'_> { totem: false, totem_fired: false, }; - ServerPlayerCombat::new(self.attributes, self.data, food, self.ids, &mut environment)? - .hurt(self.hurt, amount)?; + if ServerPlayerCombat::new(self.attributes, self.data, food, self.ids, &mut environment)? + .hurt(self.hurt, amount)? + { + *self.hurt_animation_time = self.hurt.hurt_time; + } Ok(()) } } diff --git a/crates/horizon-client/src/lan/advancements.rs b/crates/horizon-client/src/lan/advancements.rs index 801694326..2e478e2b8 100644 --- a/crates/horizon-client/src/lan/advancements.rs +++ b/crates/horizon-client/src/lan/advancements.rs @@ -144,6 +144,13 @@ impl ServerAdvancements { ) -> Option> { let n = self.tree.list.len(); let first = visible.len() != n; + // flushDirty does nothing unless it is the first packet or progress + // changed: visibility follows progress alone, and every grant and + // revoke is in `changed`. This skips walking the whole tree for + // every player every tick. + if !first && changed.is_empty() { + return None; + } let now = self .tree .visible(&self.kids, |i| progress.done(&self.tree.list[i])); diff --git a/crates/horizon-client/src/lan/chunks.rs b/crates/horizon-client/src/lan/chunks.rs index 6b8c41e55..04eb9f224 100644 --- a/crates/horizon-client/src/lan/chunks.rs +++ b/crates/horizon-client/src/lan/chunks.rs @@ -4,6 +4,7 @@ use crate::{ chunk::{Chunk, Light, MIN_Y, SECTIONS, Section}, containers::BlockEntity, + fast_hash::FxHashMap, }; use horizon_protocol::{ buf::set_bit, @@ -91,7 +92,7 @@ pub struct ChunkEncoder { /// The save's tables, for the heightmaps. pub tables: Option>, /// Sections already looked at, by address (see `Encoded`). - cache: std::sync::Mutex>, + cache: std::sync::Mutex>, /// Each column's heightmaps, with the sections they were made from. heights: std::sync::Mutex>, /// The level's sections among a column's: all of them in the Overworld, @@ -115,12 +116,16 @@ struct Heights { struct Encoded { section: std::sync::Weak
, non_air: bool, - /// LevelChunkSection.write, and whether it holds block entity blocks. - wire: Option<(Arc<[u8]>, bool)>, + /// LevelChunkSection.write, and its block entity blocks. + wire: Option<(Arc<[u8]>, Entities)>, /// The section's light as the wire's two DataLayers, when not uniform. light: Option>, } +/// A section's blocks that have a block entity type, as (index, state) in +/// index order (y, then z, then x). +type Entities = Arc<[(u16, u32)]>; + /// One section's light as DataLayers (two blocks per byte, the even one in /// the low nibble), and whether each holds any light. struct Layers { @@ -258,22 +263,29 @@ impl ChunkEncoder { /// The cached entry for a section, made with `non_air` when missing. fn cached(&self, section: &Arc
, read: impl FnOnce(&mut Encoded) -> T) -> T { - let mut cache = self.cache.lock().unwrap(); + read(self.entry(&mut self.cache.lock().unwrap(), section)) + } + + /// A section's entry in the locked cache, made with `non_air` when missing. + fn entry<'a>( + &self, + cache: &'a mut FxHashMap, + section: &Arc
, + ) -> &'a mut Encoded { if cache.len() >= CACHE_SWEEP { cache.retain(|_, e| e.section.strong_count() > 0); if cache.len() >= CACHE_SWEEP / 2 { cache.clear(); } } - let entry = cache + cache .entry(Arc::as_ptr(section) as usize) .or_insert_with(|| Encoded { section: Arc::downgrade(section), non_air: self.non_air(section), wire: None, light: None, - }); - read(entry) + }) } /// LevelChunkSection.hasOnlyAir, negated. @@ -291,14 +303,14 @@ impl ChunkEncoder { } /// A section on the wire, from the cache or encoded now. - fn section_wire(&self, section: &Arc
) -> (Arc<[u8]>, bool) { + fn section_wire(&self, section: &Arc
) -> (Arc<[u8]>, Entities) { if let Some(wire) = self.cached(section, |e| e.wire.clone()) { return wire; } let (encoded, entities) = self.section(section); let mut w = horizon_protocol::buf::Writer::new(); encoded.write(&mut w); - let wire: (Arc<[u8]>, bool) = (w.data.into(), entities); + let wire: (Arc<[u8]>, Entities) = (w.data.into(), entities.into()); self.cached(section, |e| e.wire = Some(wire.clone())); wire } @@ -314,23 +326,23 @@ impl ChunkEncoder { // The heightmaps depend on the level's height. self.heights.get_mut().unwrap().clear(); } - pub fn entity_type(&self, state: u16) -> Option { + pub fn entity_type(&self, state: u32) -> Option { self.entity_types - .get(usize::from(state)) + .get(state as usize) .filter(|t| **t >= 0) .map(|t| i32::from(*t)) } - pub fn is_air(&self, state: u16) -> bool { + pub fn is_air(&self, state: u32) -> bool { self.flags - .get(usize::from(state)) + .get(state as usize) .is_none_or(|f| f & NON_AIR == 0) } - fn section(&self, section: &Section) -> (horizon_protocol::chunk::Section, bool) { + fn section(&self, section: &Section) -> (horizon_protocol::chunk::Section, Vec<(u16, u32)>) { let mut values = Vec::with_capacity(BLOCKS); - let (mut non_empty, mut fluids, mut entities) = (0i16, 0i16, false); - let mut count = |state: u16, n: i16| { - let f = self.flags.get(usize::from(state)).copied().unwrap_or(0); + let (mut non_empty, mut fluids, mut entities) = (0i16, 0i16, Vec::new()); + let mut count = |state: u32, n: i16| { + let f = self.flags.get(state as usize).copied().unwrap_or(0); if f & NON_AIR != 0 { non_empty += n; if f & FLUID != 0 { @@ -342,13 +354,17 @@ impl ChunkEncoder { // One block everywhere (all air, mostly): what from_values would give. let uniform = section.blocks.uniform(); if let Some(v) = uniform { - entities = count(v as u16, BLOCKS as i16); + if count(v, BLOCKS as i16) { + entities = (0..BLOCKS as u16).map(|i| (i, v)).collect(); + } } else { - let mut unpacked = [0u16; BLOCKS]; + let mut unpacked = [0u32; BLOCKS]; section.unpack(&mut unpacked); - for &v in &unpacked { - entities |= count(v, 1); - values.push(i32::from(v)); + for (i, &v) in unpacked.iter().enumerate() { + if count(v, 1) { + entities.push((i as u16, v)); + } + values.push(v as i32); } } let biome_values: Vec = (0..BIOMES) @@ -370,7 +386,11 @@ impl ChunkEncoder { palette: vec![v as i32], data: Vec::new(), }, - None => Paletted::from_values(&values, Strategy::Blocks, 16), + None => Paletted::from_values( + &values, + Strategy::Blocks, + crate::chunk::block_strategy().global_bits, + ), }, biomes: Paletted::from_values(&biome_values, Strategy::Biomes, self.biome_bits), }, @@ -382,8 +402,10 @@ impl ChunkEncoder { /// The non-air sections of a column as bits (LevelChunkSection.hasOnlyAir). fn occupied(&self, chunk: &Chunk) -> u64 { let mut bits = 0u64; + // One lock for the column: encode_in asks for nine columns' sections. + let mut cache = self.cache.lock().unwrap(); for (i, s) in chunk.sections[self.sections.clone()].iter().enumerate() { - if self.cached(s, |e| e.non_air) { + if self.entry(&mut cache, s).non_air { bits |= 1 << i; } } @@ -431,29 +453,30 @@ impl ChunkEncoder { .skip(self.sections.start) .take(self.sections.len()) { - let (encoded, has_entities) = self.section_wire(s); - if has_entities { - for y in 0..16 { - for z in 0..16 { - for x in 0..16 { - let state = s.get(crate::chunk::index(x, y, z)); - if let Some(kind) = self.entity_type(state) { - let wy = MIN_Y + (i as i32) * 16 + y; - let pos = (chunk.x * 16 + x, wy, chunk.z * 16 + z); - entity_infos.push(BlockEntityInfo { - packed_xz: ((x << 4) | z) as i8, - y: wy as i16, - kind, - // BlockEntityInfo.create: an empty update tag is not sent. - tag: block_entities - .get(&pos) - .and_then(entity_tag) - .unwrap_or(Tag::End), - }); - } - } - } - } + let (encoded, entities) = self.section_wire(s); + // The section's block entity blocks, kept with its bytes, in the + // order a scan of every block would find them. + for &(index, state) in entities.iter() { + let Some(kind) = self.entity_type(state) else { + continue; + }; + let (x, y, z) = ( + i32::from(index & 15), + i32::from(index >> 8), + i32::from(index >> 4 & 15), + ); + let wy = MIN_Y + (i as i32) * 16 + y; + let pos = (chunk.x * 16 + x, wy, chunk.z * 16 + z); + entity_infos.push(BlockEntityInfo { + packed_xz: ((x << 4) | z) as i8, + y: wy as i16, + kind, + // BlockEntityInfo.create: an empty update tag is not sent. + tag: block_entities + .get(&pos) + .and_then(entity_tag) + .unwrap_or(Tag::End), + }); } buffer.extend_from_slice(&encoded); } @@ -669,6 +692,73 @@ mod tests { assert_eq!(block_entity_type("minecraft:stone"), None); } + #[test] + fn block_entities_come_from_the_cached_section_in_scan_order() { + let builtin = Builtin::parse( + r#"{"minecraft:block_entity_type": {"entries": { + "minecraft:chest": {"protocol_id": 1}, + "minecraft:sign": {"protocol_id": 7}}}}"#, + ) + .unwrap(); + let states = [ + "minecraft:air", + "minecraft:stone", + "minecraft:chest", + "minecraft:oak_sign", + ] + .map(|n| (Arc::::from(n), false)); + let encoder = ChunkEncoder::new(states, &builtin, &[], &[]); + let mut chunk = Chunk::empty(2, -3); + for (x, y, z, state) in [(15, 3, 0, 2), (0, 3, 15, 3), (4, 3, 4, 1), (7, 40, 2, 2)] { + chunk.set(x, MIN_Y + y, z, state); + } + // Every block of a section looked at, as the scan did before the cache. + let scan = |chunk: &Chunk| { + let mut found = Vec::new(); + for (i, s) in chunk.sections.iter().enumerate() { + for y in 0..16 { + for z in 0..16 { + for x in 0..16 { + let state = s.get(crate::chunk::index(x, y, z)); + if let Some(kind) = encoder.entity_type(state) { + found.push((x, MIN_Y + i as i32 * 16 + y, z, kind)); + } + } + } + } + } + // Then the order the packet gives them, as encode_blocks does. + java_hash_order(&mut found, |e| { + (chunk.x * 16 + e.0, e.1, chunk.z * 16 + e.2) + }); + found + }; + let sent = |chunk: &Chunk| { + let packet = encoder.encode(chunk, &HashMap::new()); + let infos = packet.chunk.block_entities; + infos + .iter() + .map(|e| { + let xz = e.packed_xz as u8; + ( + i32::from(xz >> 4), + i32::from(e.y), + i32::from(xz & 15), + e.kind, + ) + }) + .collect::>() + }; + let expected = scan(&chunk); + assert_eq!(expected.len(), 3); + assert_eq!(sent(&chunk), expected); + // From the cache the second time, and after an edit. + assert_eq!(sent(&chunk), expected); + chunk.set(15, MIN_Y + 3, 0, 0); + chunk.set(9, MIN_Y + 3, 9, 3); + assert_eq!(sent(&chunk), scan(&chunk)); + } + fn encoder() -> ChunkEncoder { let states = ["minecraft:air", "minecraft:stone", "minecraft:water"] .map(|n| (Arc::::from(n), n.ends_with("water"))); diff --git a/crates/horizon-client/src/lan/containers.rs b/crates/horizon-client/src/lan/containers.rs index 0fa47510a..3ecd58b80 100644 --- a/crates/horizon-client/src/lan/containers.rs +++ b/crates/horizon-client/src/lan/containers.rs @@ -25,7 +25,7 @@ impl Hub { for g in self .guests .iter() - .filter(|g| g.placed && Some(g.conn) != except) + .filter(|g| self.here(g) && Some(g.conn) != except) { let d: f64 = (0..3).map(|k| (g.position[k] - at[k]).powi(2)).sum(); if d <= range * range { @@ -79,11 +79,11 @@ impl Hub { } /// ClientboundBlockEventPacket (`PlayerList.broadcast` within 64 blocks). - pub fn block_event(&self, pos: [i32; 3], b0: i32, b1: i32, state: u16) { + pub fn block_event(&self, pos: [i32; 3], b0: i32, b1: i32, state: u32) { let block = self .encoder .block_ids - .get(usize::from(state)) + .get(state as usize) .copied() .unwrap_or(0); let at = [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]; @@ -464,7 +464,7 @@ impl Hub { let Some(menu) = self.guests[i] .menu .as_ref() - .filter(|_| self.guests[i].placed) + .filter(|_| self.here(&self.guests[i])) else { continue; }; diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index 3b926b372..a37010d79 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -58,7 +58,7 @@ struct Sent { #[derive(Default)] pub struct Tracker { - sent: std::collections::HashMap, + sent: crate::fast_hash::FxHashMap, } /// VecDeltaCodec.encode. @@ -66,11 +66,11 @@ fn encode(v: f64) -> i64 { (v * 4096.0).round() as i64 } -/// The horizontal range within which a client sees an entity of `kind` -/// (TrackedEntity.updatePlayer: the type's range, capped by the view distance). -pub fn visible_range(kind: &str, view_distance: i32) -> f64 { - let chunks = i32::from(tracking::settings(kind).0); - f64::from(chunks.min(view_distance) * 16) +/// The type's tracking range in chunks: a client sees an entity of `kind` +/// within it, capped by the view distance, horizontally +/// (TrackedEntity.updatePlayer). +pub fn tracking_chunks(kind: &str) -> i32 { + i32::from(tracking::settings(kind).0) } impl Tracker { diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index db426ca21..545bb6ace 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -8,7 +8,7 @@ use horizon_protocol::{ packets::{configuration::ClientInformation, play}, }; use std::{ - collections::{HashSet, VecDeque}, + collections::VecDeque, sync::{Arc, atomic::AtomicI32}, }; @@ -73,15 +73,31 @@ pub struct Guest { /// the client accepts it (ServerGamePacketListenerImpl.awaitingPositionFromClient). pub awaiting_teleport: Option<(i32, [f64; 3])>, pub teleport_counter: i32, + /// The hub tick the pending teleport was (re)sent on (awaitingTeleportTime). + pub teleport_tick: u64, + /// Where the player was when this tick's packets began (firstGoodX/Y/Z), + /// for the moved-too-quickly check. + pub first_good: [f64; 3], + /// Position moves received in all and by the start of this tick + /// (receivedMovePacketCount, knownMovePacketCount). + pub received_moves: i32, + pub known_moves: i32, + /// A position move arrived since the client's last ClientTickEnd + /// (receivedPositionThisTick): a second one is a protocol error. + pub position_this_tick: bool, /// The client finished loading terrain (ServerboundPlayerLoadedPacket). pub loaded: bool, // Chunks. pub center: Option<(i32, i32)>, - pub sent_chunks: HashSet<(i32, i32)>, + pub sent_chunks: crate::fast_hash::FxHashSet<(i32, i32)>, pub chunk_queue: Vec<(i32, i32)>, + /// PlayerChunkSender: batches sent but not yet acknowledged, how many + /// may be (1 until the client's first acknowledgement, then 10), the + /// rate the client asks for and the chunks the next batch may hold. pub unacknowledged: u32, + pub max_unacknowledged: u32, pub chunks_per_tick: f32, - pub chunk_credit: f32, + pub batch_quota: f32, // Entities. pub tracker: Tracker, // Player state the gameplay code reads and writes. @@ -131,6 +147,9 @@ pub struct Guest { pub dead: bool, /// The join packets were sent (PlayerList.placeNewPlayer ran). pub placed: bool, + /// The level the player is in (`ServerPlayer.level().dimension()`): the + /// hub's level passes only reach the players in theirs. + pub dimension: String, /// The open block container, if any. pub menu: Option, pub next_window: i32, @@ -187,13 +206,19 @@ impl Guest { sleeping: false, awaiting_teleport: None, teleport_counter: 0, + teleport_tick: 0, + first_good: position, + received_moves: 0, + known_moves: 0, + position_this_tick: false, loaded: false, center: None, - sent_chunks: HashSet::new(), + sent_chunks: Default::default(), chunk_queue: Vec::new(), unacknowledged: 0, + max_unacknowledged: 1, chunks_per_tick: 9.0, - chunk_credit: 0.0, + batch_quota: 0.0, tracker: Tracker::default(), motion: None, inventory: vec![None; 36], @@ -226,6 +251,7 @@ impl Guest { moves_from_ground: false, dead: false, placed: false, + dimension: "minecraft:overworld".into(), menu: None, next_window: 0, drag: None, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 126824168..e20dd9044 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -12,17 +12,24 @@ use super::{ guest::{Guest, SentEffect, stack_to_network}, }; use crate::{ + collisions::SceneCollisions, effects::{EffectInstance, PlayerEffects}, items::ItemStack, world::World, }; +use horizon_core::geometry::{Aabb, ShapeOp, Vec3, VoxelShape}; use horizon_protocol::ids::play::clientbound as ids; use horizon_protocol::{ entity_data::{Value, serializer}, packets::play::{self, Clientbound as C, Serverbound as S}, text::{literal, translatable}, }; -use horizon_world::nbt::{JavaString, Tag}; +use horizon_world::{ + block_collision::BlockCollisionRegistry, + block_collision_scan::BlockCollisionScan, + collision_context::CollisionContext, + nbt::{JavaString, Tag}, +}; use std::sync::{Arc, atomic::Ordering}; /// GameEvent types (ClientboundGameEventPacket). @@ -32,6 +39,7 @@ pub mod game_event { pub const CHANGE_GAME_MODE: u8 = 3; pub const RAIN_LEVEL: u8 = 7; pub const THUNDER_LEVEL: u8 = 8; + pub const GUARDIAN_ELDER_EFFECT: u8 = 10; pub const LEVEL_CHUNKS_LOAD_START: u8 = 13; } @@ -88,6 +96,9 @@ pub struct TickCtx<'a> { /// TickRateManager: the tick rate and whether the game is frozen. pub tick_rate: f32, pub tick_frozen: bool, + /// Block collisions, for ServerGamePacketListenerImpl's moved-wrongly + /// check (none: moves are not checked against blocks). + pub collision: Option<&'a BlockCollisionRegistry<'a>>, } /// What the gameplay code has to do for a guest. @@ -99,6 +110,8 @@ pub enum HostEvent { Packet(u32, Box), /// A chat line to show on the host (already broadcast to the guests). Chat(String), + /// A server log warning (ServerGamePacketListenerImpl's LOGGER.warn). + Warn(String), } pub struct Hub { @@ -108,10 +121,16 @@ pub struct Hub { pub guests: Vec, pub(super) sync: Arc, pub ticks: u64, + /// The `player_movement_check` and `elytra_movement_check` game rules, + /// set by the game before each tick. + pub movement_checks: (bool, bool), last_clock: i64, last_rate: f32, ticking: (f32, bool), weather: (bool, f32, f32), + /// The clock and weather last sent in the levels not in place, by + /// dimension (`set_dimension` swaps them with the fields above). + level_sync: std::collections::HashMap, /// Operators and their permission levels (dedicated servers). pub ops: std::collections::HashMap, chat_type: i32, @@ -180,6 +199,24 @@ fn tracked(cx: i32, cz: i32, r: i32, x: i32, z: i32) -> bool { dx * dx + dz * dz < i64::from(r) * i64::from(r) } +/// What a level's players were last told of its clock and weather. +#[derive(Clone, Copy)] +struct LevelSync { + last_clock: i64, + last_rate: f32, + weather: (bool, f32, f32), +} + +impl Default for LevelSync { + fn default() -> Self { + Self { + last_clock: i64::MIN, + last_rate: 0.0, + weather: (false, 0.0, 0.0), + } + } +} + impl Hub { pub fn new(lan: Lan, sync: Arc, encoder: ChunkEncoder, config: HubConfig) -> Self { let chat_type = sync @@ -199,11 +236,13 @@ impl Hub { guests: Vec::new(), sync, ticks: 0, + movement_checks: (true, true), last_clock: i64::MIN, last_rate: 0.0, ticking: (20.0, false), ops: Default::default(), weather: (false, 0.0, 0.0), + level_sync: Default::default(), chat_type, dimension_type, clock_ids, @@ -257,6 +296,18 @@ impl Hub { g.sender.send(body.clone()); } } + /// Whether a guest is placed in the level in place (`config.dimension`). + pub fn here(&self, g: &Guest) -> bool { + g.placed && g.dimension == self.config.dimension + } + /// `PlayerList.broadcastAll(packet, dimension)`: the players in the + /// level in place. + pub fn broadcast_level(&self, packet: &C) { + let body = packet.encode(); + for g in self.guests.iter().filter(|g| self.here(g)) { + g.sender.send(body.clone()); + } + } pub fn broadcast_except(&self, conn: u32, packet: &C) { let body = packet.encode(); for g in self.guests.iter().filter(|g| g.placed && g.conn != conn) { @@ -448,6 +499,7 @@ impl Hub { guest.joined_tick = self.ticks; guest.position = ctx.spawn; guest.previous_position = ctx.spawn; + guest.dimension = self.config.dimension.clone(); self.guests.push(guest); conn } @@ -727,7 +779,9 @@ impl Hub { /// ServerGamePacketListenerImpl.teleport: move the client and wait for its confirmation. pub fn teleport(&mut self, i: usize, position: Option<[f64; 3]>) { + let ticks = self.ticks; let g = &mut self.guests[i]; + g.teleport_tick = ticks; if let Some(p) = position { g.position = p; g.previous_position = p; @@ -871,7 +925,19 @@ impl Hub { // ---- per tick ------------------------------------------------------ + /// A whole tick with one level: the network, the level, then the + /// players' latencies. pub fn tick(&mut self, ctx: &mut TickCtx) -> Vec { + let mut events = self.poll(ctx); + events.extend(self.tick_level(ctx)); + self.end_tick(); + events + } + + /// The network since the last tick, once per server tick before any + /// level ticks: joins (into the level in place), leaves, and each guest's + /// packets queued for its own level's pass. + pub fn poll(&mut self, ctx: &mut TickCtx) -> Vec { self.ticks += 1; let mut events = Vec::new(); for event in self.lan.poll() { @@ -907,13 +973,25 @@ impl Hub { } } } + events + } + + /// The level in place's part of the tick (`ServerLevel.tick`'s chunk + /// map and the connections of the players in it): their packets, then + /// the chunks, block changes, containers and entities they see. + pub fn tick_level(&mut self, ctx: &mut TickCtx) -> Vec { + let mut events = Vec::new(); for i in 0..self.guests.len() { - if self.guests[i].placed { + if self.here(&self.guests[i]) { self.process_inbox(i, ctx, &mut events); } } - if !self.guests.iter().any(|g| g.placed) { - if self.guests.is_empty() { + if !self.guests.iter().any(|g| self.here(g)) { + if !self + .guests + .iter() + .any(|g| g.dimension == self.config.dimension) + { let _ = ctx.world.block_log.take(); } return events; @@ -923,7 +1001,7 @@ impl Hub { } self.sync_world(ctx); for i in 0..self.guests.len() { - if self.guests[i].placed { + if self.here(&self.guests[i]) { self.update_chunks(i, ctx); } } @@ -931,7 +1009,7 @@ impl Hub { // ServerGamePacketListenerImpl.tick: the actions handled since the last tick are // acknowledged after the block changes they made were sent, so a client's predicted // blocks settle on the server's states. - for g in &self.guests { + for g in self.guests.iter().filter(|g| self.here(g)) { let sequence = g.ack_up_to.replace(-1); if sequence >= 0 { g.send(&C::BlockChangedAck(play::BlockChangedAck { sequence })); @@ -940,11 +1018,16 @@ impl Hub { self.sync_containers(ctx.world); self.track_entities(ctx); for i in 0..self.guests.len() { - if self.guests[i].placed { + if self.here(&self.guests[i]) { self.sync_player_state(i); self.sync_effects(i); } } + events + } + + /// After every level: `PlayerList.tick`. + pub fn end_tick(&mut self) { let latencies: Vec<_> = self .guests .iter() @@ -966,7 +1049,6 @@ impl Hub { entries, })); } - events } fn remove_guest(&mut self, i: usize, reason: &str) -> Guest { @@ -997,7 +1079,7 @@ impl Hub { // MinecraftServer.tickServer: the game time every 20 ticks // (forceGameTimeSynchronization, no clocks). if self.ticks.is_multiple_of(20) { - self.broadcast(&C::SetTime(play::SetTime { + self.broadcast_level(&C::SetTime(play::SetTime { game_time: world.game_time, clocks: Vec::new(), })); @@ -1013,7 +1095,7 @@ impl Hub { .sync .id("minecraft:world_clock", "minecraft:overworld") .unwrap_or(0); - self.broadcast(&C::SetTime(play::SetTime { + self.broadcast_level(&C::SetTime(play::SetTime { game_time: world.game_time, clocks: vec![play::ClockState { clock: overworld, @@ -1032,7 +1114,7 @@ impl Hub { let w = &world.weather; let (raining, rain, thunder) = self.weather; if w.raining != raining { - self.broadcast(&C::GameEvent(play::GameEvent { + self.broadcast_level(&C::GameEvent(play::GameEvent { event: if w.raining { game_event::START_RAINING } else { @@ -1042,13 +1124,13 @@ impl Hub { })); } if (w.rain_level.1 - rain).abs() > f32::EPSILON { - self.broadcast(&C::GameEvent(play::GameEvent { + self.broadcast_level(&C::GameEvent(play::GameEvent { event: game_event::RAIN_LEVEL, param: w.rain_level.1, })); } if (w.thunder_level.1 - thunder).abs() > f32::EPSILON { - self.broadcast(&C::GameEvent(play::GameEvent { + self.broadcast_level(&C::GameEvent(play::GameEvent { event: game_event::THUNDER_LEVEL, param: w.thunder_level.1, })); @@ -1096,15 +1178,16 @@ impl Hub { g.chunk_queue .sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2)); } - // Send ready chunks, closest first, in batches. - if g.chunk_queue.is_empty() || g.unacknowledged >= 10 || self.ticks <= g.placed_at + 1 { + // PlayerChunkSender.sendNextChunks: ready chunks, closest first, in + // batches the client's acknowledgements pace. + if self.ticks <= g.placed_at + 1 || g.unacknowledged >= g.max_unacknowledged { return; } - g.chunk_credit = (g.chunk_credit + g.chunks_per_tick).min(g.chunks_per_tick.max(1.0) * 2.0); - let budget = g.chunk_credit.floor() as usize; - if budget == 0 { + g.batch_quota = (g.batch_quota + g.chunks_per_tick).min(g.chunks_per_tick.max(1.0)); + if g.batch_quota < 1.0 || g.chunk_queue.is_empty() { return; } + let budget = g.batch_quota.floor() as usize; let mut packets = Vec::new(); let mut taken = Vec::new(); for (idx, key) in g.chunk_queue.iter().enumerate() { @@ -1125,7 +1208,7 @@ impl Hub { if packets.is_empty() { return; } - g.chunk_credit -= packets.len() as f32; + g.batch_quota -= packets.len() as f32; g.send(&C::ChunkBatchStart(horizon_protocol::packets::Empty)); for p in &packets { g.send(p); @@ -1178,7 +1261,7 @@ impl Hub { for ((sx, sy, sz), positions) in sections { let viewers: Vec = (0..self.guests.len()) .filter(|&i| { - self.guests[i].placed && self.guests[i].sent_chunks.contains(&(sx, sz)) + self.here(&self.guests[i]) && self.guests[i].sent_chunks.contains(&(sx, sz)) }) .collect(); if viewers.is_empty() { @@ -1188,7 +1271,7 @@ impl Hub { let (x, y, z) = positions[0]; C::BlockUpdate(play::BlockUpdate { pos: [x, y, z], - state: i32::from(world.block(x, y, z).0 as u16), + state: world.block(x, y, z).0 as i32, }) } else { C::SectionBlocksUpdate(play::SectionBlocksUpdate { @@ -1217,7 +1300,7 @@ impl Hub { let Some(tag) = super::chunks::entity_tag(entity) else { continue; }; - let state = world.block(x, y, z).0 as u16; + let state = world.block(x, y, z).0; let Some(kind) = self.encoder.entity_type(state) else { continue; }; @@ -1343,7 +1426,7 @@ impl Hub { )); } let placed: Vec = (0..self.guests.len()) - .filter(|&i| self.guests[i].placed) + .filter(|&i| self.here(&self.guests[i])) .collect(); let guest_states: Vec<_> = placed .into_iter() @@ -1376,8 +1459,14 @@ impl Hub { all.extend(ctx.entities.iter().cloned()); let by_id: std::collections::HashMap = all.iter().enumerate().map(|(i, e)| (e.id, i)).collect(); + // Each entity type's tracking range, looked up once rather than for + // every player. + let ranges: Vec = all + .iter() + .map(|e| super::entity::tracking_chunks(&e.kind)) + .collect(); for gi in 0..self.guests.len() { - if !self.guests[gi].placed { + if !self.here(&self.guests[gi]) { continue; } let view = self.guests[gi].view_distance; @@ -1385,8 +1474,9 @@ impl Hub { let origin = self.guests[gi].position; // TrackedEntity.updatePlayer: within the type's range (capped by the // view distance) horizontally, in a chunk the client has. - let visible = |g: &Guest, e: &EntityState| { - let range = super::entity::visible_range(&e.kind, view); + let visible = |g: &Guest, ei: usize| { + let e = &all[ei]; + let range = f64::from(ranges[ei].min(view) * 16); let (dx, dz) = (origin[0] - e.position[0], origin[2] - e.position[2]); let chunk = ( (e.position[0].floor() as i32) >> 4, @@ -1398,7 +1488,7 @@ impl Hub { let mut removed = Vec::new(); for id in self.guests[gi].tracker.ids() { match by_id.get(&id) { - Some(&ei) if visible(&self.guests[gi], &all[ei]) => {} + Some(&ei) if visible(&self.guests[gi], ei) => {} _ => removed.push(id), } } @@ -1408,14 +1498,14 @@ impl Hub { } self.guests[gi].send(&C::RemoveEntities(play::RemoveEntities { ids: removed })); } - for e in &all { + for (ei, e) in all.iter().enumerate() { if e.id == me { continue; } if self.guests[gi].tracker.is_tracking(e.id) { let packets = self.guests[gi].tracker.update(e); self.guests[gi].send_all(&packets); - } else if visible(&self.guests[gi], e) { + } else if visible(&self.guests[gi], ei) { let Some(kind) = self.entity_type(&e.kind) else { continue; }; @@ -1581,6 +1671,11 @@ impl Hub { } fn process_inbox(&mut self, i: usize, ctx: &mut TickCtx, events: &mut Vec) { + // ServerGamePacketListenerImpl.tickPlayer ran between the last + // tick's packets and these: resetPosition, and the moves it counted. + let g = &mut self.guests[i]; + g.first_good = g.position; + g.known_moves = g.received_moves; let mut budget = 400; while budget > 0 { let Some(packet) = self.guests[i].inbox.pop_front() else { @@ -1609,23 +1704,42 @@ impl Hub { self.guests[i].last_action_tick = self.ticks; } match packet { + // handleAcceptTeleportPacket. S::AcceptTeleportation(p) => { let g = &mut self.guests[i]; - if g.awaiting_teleport.is_some_and(|(id, _)| id == p.id) { + if let Some((id, at)) = g.awaiting_teleport + && id == p.id + { + if p.x.is_nan() + || p.y.is_nan() + || p.z.is_nan() + || !p.yaw.is_finite() + || !p.pitch.is_finite() + { + self.kick(conn, invalid_movement()); + continue; + } + g.position = at; g.awaiting_teleport = None; + let rot = (p.yaw, p.pitch); + self.position_change(i, [p.x, p.y, p.z], rot, 0, ctx, events); } } S::MovePlayerPos(p) => { - self.move_player(i, Some([p.x, p.y, p.z]), None, p.flags); + self.move_player(i, Some([p.x, p.y, p.z]), None, p.flags, ctx, events); } S::MovePlayerPosRot(p) => { - self.move_player(i, Some([p.x, p.y, p.z]), Some((p.yaw, p.pitch)), p.flags); + let (pos, rot) = ([p.x, p.y, p.z], (p.yaw, p.pitch)); + self.move_player(i, Some(pos), Some(rot), p.flags, ctx, events); } S::MovePlayerRot(p) => { - self.move_player(i, None, Some((p.yaw, p.pitch)), p.flags); + self.move_player(i, None, Some((p.yaw, p.pitch)), p.flags, ctx, events); + } + S::MovePlayerStatus(p) => { + self.move_player(i, None, None, p.flags, ctx, events); } - S::MovePlayerStatus(p) => self.move_player(i, None, None, p.flags), S::PlayerLoaded(_) => self.guests[i].loaded = true, + // PlayerChunkSender.onChunkBatchReceivedByClient. S::ChunkBatchReceived(p) => { let g = &mut self.guests[i]; g.unacknowledged = g.unacknowledged.saturating_sub(1); @@ -1634,7 +1748,12 @@ impl Hub { } else { p.chunks_per_tick.clamp(0.01, 64.0) }; + if g.unacknowledged == 0 { + g.batch_quota = 1.0; + } + g.max_unacknowledged = 10; } + S::ClientTickEnd(_) => self.guests[i].position_this_tick = false, S::ClientInformation(info) => { let g = &mut self.guests[i]; g.view_distance = @@ -1653,7 +1772,6 @@ impl Hub { 0 => self.guests[i].sleeping = false, _ => {} }, - S::ClientTickEnd(_) => {} S::Chat(c) => { let text: String = c.message.chars().filter(|c| !c.is_control()).collect(); if !text.is_empty() { @@ -1665,48 +1783,205 @@ impl Hub { other => events.push(HostEvent::Packet(conn, Box::new(other))), } } - let _ = ctx; } /// ServerGamePacketListenerImpl.handleMovePlayer. - fn move_player(&mut self, i: usize, pos: Option<[f64; 3]>, rot: Option<(f32, f32)>, flags: u8) { - let g = &mut self.guests[i]; - if g.awaiting_teleport.is_some() || !g.loaded && g.ticks == 0 && pos.is_none() { + fn move_player( + &mut self, + i: usize, + pos: Option<[f64; 3]>, + rot: Option<(f32, f32)>, + flags: u8, + ctx: &TickCtx, + events: &mut Vec, + ) { + let conn = self.guests[i].conn; + // containsInvalidValues, on the packet's values (0 where it has none). + let (yaw, pitch) = rot.unwrap_or_default(); + if pos.is_some_and(|p| p.iter().any(|v| v.is_nan())) + || !yaw.is_finite() + || !pitch.is_finite() + { + self.kick(conn, invalid_movement()); return; } - if let Some(p) = pos { - if p.iter().any(|v| !v.is_finite() || v.abs() > 3.0e7) { + let g = &mut self.guests[i]; + if pos.is_some() { + if g.position_this_tick { + self.kick(conn, invalid_movement()); return; } - // A jump of more than a hundred blocks is a rejected move. - let d2: f64 = (0..3).map(|k| (p[k] - g.position[k]).powi(2)).sum(); - if d2 > 100.0 * 100.0 { - let at = g.position; - self.teleport(i, Some(at)); - return; - } - g.previous_position = g.position; - g.position = p; + g.position_this_tick = true; } - let moved = pos.map_or([0.0; 3], |_| { - [0, 1, 2].map(|k| g.position[k] - g.previous_position[k]) - }); + if !g.loaded && g.ticks == 0 && pos.is_none() { + return; + } + // updateAwaitingTeleport: moves wait for the client to accept the + // teleport, which is sent again after 20 ticks without an answer. + if let Some((_, at)) = g.awaiting_teleport { + if self.ticks - g.teleport_tick > 20 { + self.teleport(i, Some(at)); + } + return; + } + let to = pos.unwrap_or(g.position); + let rot = rot.unwrap_or((g.yaw, g.pitch)); + self.position_change(i, to, rot, flags, ctx, events); + } + + /// ServerGamePacketListenerImpl.handlePlayerPositionChange. + fn position_change( + &mut self, + i: usize, + to: [f64; 3], + (yaw, pitch): (f32, f32), + flags: u8, + ctx: &TickCtx, + events: &mut Vec, + ) { + let (frozen, (check, elytra_check)) = (self.ticking.1, self.movement_checks); + let g = &mut self.guests[i]; + let to = [ + to[0].clamp(-3.0E7, 3.0E7), + to[1].clamp(-2.0E7, 2.0E7), + to[2].clamp(-3.0E7, 3.0E7), + ]; + let (yaw, pitch) = (wrap_degrees(yaw), wrap_degrees(pitch)); + let d = [0, 1, 2].map(|k| to[k] - g.first_good[k]); + let moved = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; + if g.sleeping { + if moved > 1.0 { + (g.yaw, g.pitch) = (yaw, pitch); + self.teleport(i, None); + } + return; + } + // TickRateManager.runsNormally: not frozen (a frozen game's steps + // are not counted either; Horizon's hub does not see them). + if !frozen { + g.received_moves += 1; + let mut packets = g.received_moves - g.known_moves; + if packets > 5 { + packets = 1; + } + // shouldCheckPlayerMovement. The server holds no velocity for a + // guest (getDeltaMovement), so nothing is expected. + if check && (!g.fall_flying || elytra_check) { + let limit = if g.fall_flying { 300.0 } else { 100.0 }; + if moved > limit * f64::from(packets) { + events.push(HostEvent::Warn(format!( + "{} moved too quickly! {},{},{}", + g.name, + crate::java_text::double_to_string(d[0]), + crate::java_text::double_to_string(d[1]), + crate::java_text::double_to_string(d[2]) + ))); + self.teleport(i, None); + return; + } + } + } + let start = g.position; + let (wrongly, refused) = self.collide(i, to, ctx); + if wrongly { + let line = format!("{} moved wrongly!", self.guests[i].name); + events.push(HostEvent::Warn(line)); + } + if refused { + let g = &mut self.guests[i]; + (g.yaw, g.pitch) = (yaw, pitch); + self.teleport(i, Some(start)); + return; + } + let g = &mut self.guests[i]; + g.previous_position = g.position; + g.position = to; + let moved = [0, 1, 2].map(|k| g.position[k] - g.previous_position[k]); if g.moves.is_empty() { g.moves_from_ground = g.on_ground; } g.moves.push((moved, flags & 1 != 0)); - if let Some((yaw, pitch)) = rot - && yaw.is_finite() - && pitch.is_finite() - { - g.yaw = yaw % 360.0; - g.pitch = pitch.clamp(-90.0, 90.0); - g.head_yaw = g.yaw; - } + g.yaw = yaw; + g.pitch = pitch.clamp(-90.0, 90.0); + g.head_yaw = g.yaw; g.on_ground = flags & 1 != 0; g.ticks = g.ticks.max(1); } + /// The collision part of handlePlayerPositionChange: whether the move + /// counts as moved wrongly (logged), and whether it is refused (the + /// player is sent back where they were). + fn collide(&self, i: usize, to: [f64; 3], ctx: &TickCtx) -> (bool, bool) { + let g = &self.guests[i]; + // noPhysics (spectators) and sleepers move freely. + let Some(binding) = ctx.collision else { + return (false, false); + }; + if g.spectator() || g.sleeping { + return (false, false); + } + let height = if g.fall_flying { + 0.6 + } else if g.sneaking { + 1.5 + } else { + 1.8 + }; + let at = |p: [f64; 3]| { + Aabb::new( + Vec3::new(p[0] - 0.3, p[1], p[2] - 0.3), + Vec3::new(p[0] + 0.3, p[1] + height, p[2] + 0.3), + ) + }; + let (old, new) = (at(g.position), at(to)); + let mut scene = SceneCollisions { + world: ctx.world, + binding, + subject: None, + }; + // player.move, then how far from the target it ended (vanilla drops + // the vertical part: `yDist > -0.5 || yDist < 0.5` always holds). + let movement = Vec3::new( + to[0] - g.position[0], + to[1] - g.position[1], + to[2] - g.position[2], + ); + let fail = !g.creative() + && scene + .resolve(old, movement, 0.6, g.on_ground) + .is_ok_and(|done| { + let (dx, dz) = (movement.x - done.x, movement.z - done.z); + dx * dx + dz * dz > 0.0625 + }); + if fail && scene.unobstructed(old).unwrap_or(true) { + return (true, true); + } + // isEntityCollidingWithAnythingNew: a block the old box did not + // already touch. + let shrink = f64::from(1.0E-5_f32); + let shrink = Vec3::new(shrink, shrink, shrink); + let Ok(old_shape) = VoxelShape::from_box(old.deflate(shrink)) else { + return (fail, false); + }; + let context = CollisionContext::position(g.position[1]); + let Ok(scan) = + BlockCollisionScan::new(&mut scene, context, new.deflate(shrink), false, 1 << 20) + else { + return (fail, false); + }; + for hit in scan { + let Ok(hit) = hit else { break }; + if !hit + .shape + .join_is_not_empty(&old_shape, ShapeOp::AND) + .unwrap_or(true) + { + return (fail, true); + } + } + (fail, false) + } + /// Acknowledge a block interaction (ClientboundBlockChangedAckPacket). /// ServerGamePacketListenerImpl.ackBlockChangesUpTo: sent with the next tick's block /// changes (`tick`). @@ -1786,12 +2061,15 @@ impl Hub { let mode = self.guests[i].game_mode; let mut info = self.spawn_info(mode); // Player.getLastDeathLocation, set where the player died. + // The level they died in: theirs until now. info.last_death = self.guests[i].last_death.map(|pos| play::GlobalPos { - dimension: self.config.dimension.clone(), + dimension: self.guests[i].dimension.clone(), pos, }); self.close_container_for(i); let g = &mut self.guests[i]; + // PlayerList.respawn: into the level in place (the respawn level). + g.dimension = self.config.dimension.clone(); // ServerLevel.removePlayerImmediately: every entity paired with the dead player is // removed (ServerEntity.removePairing, one packet each). Its chunks are dropped // without ForgetLevelChunk (PlayerChunkSender.dropChunk skips dead players): the @@ -1860,6 +2138,20 @@ impl Hub { /// The level the players are in: the server holds one at a time, and the /// hub's packets name it. pub fn set_dimension(&mut self, dimension: &str) { + if self.config.dimension == dimension { + return; + } + // What this level's players were told stays with it. + let leaving = LevelSync { + last_clock: self.last_clock, + last_rate: self.last_rate, + weather: self.weather, + }; + let entering = self.level_sync.remove(dimension).unwrap_or_default(); + self.level_sync + .insert(std::mem::take(&mut self.config.dimension), leaving); + (self.last_clock, self.last_rate, self.weather) = + (entering.last_clock, entering.last_rate, entering.weather); self.config.dimension = dimension.to_owned(); self.dimension_type = self .sync @@ -1879,6 +2171,7 @@ impl Hub { let info = self.spawn_info(mode); self.close_container_for(i); let g = &mut self.guests[i]; + g.dimension = self.config.dimension.clone(); g.tracker.clear(); g.sent_chunks.clear(); g.chunk_queue.clear(); @@ -1934,6 +2227,23 @@ impl Hub { } /// A packet Horizon sends as raw bytes (no fields worth a type). +/// multiplayer.disconnect.invalid_player_movement. +/// Mth.wrapDegrees. +fn wrap_degrees(degrees: f32) -> f32 { + let mut wrapped = degrees % 360.0; + if wrapped >= 180.0 { + wrapped -= 360.0; + } + if wrapped < -180.0 { + wrapped += 360.0; + } + wrapped +} + +fn invalid_movement() -> Tag { + translatable("multiplayer.disconnect.invalid_player_movement", &[]) +} + fn raw(id: i32, payload: Vec) -> C { C::Unknown(id, payload) } diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index 555463685..44b269a8f 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -71,6 +71,10 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.selected = (level.selected_slot.max(0) as usize).min(8); guest.saved = level.player_extra.clone(); guest.recipe_book = level.recipe_book.clone(); + guest.dimension = match level.dimension.as_str() { + d @ ("minecraft:the_nether" | "minecraft:the_end") => d.to_owned(), + _ => "minecraft:overworld".to_owned(), + }; if level.ender_items.len() == 27 { guest.ender_items = level.ender_items.clone(); } @@ -100,7 +104,6 @@ pub fn apply(guest: &mut Guest, level: &Level) { pub fn save(guest: &Guest, world: &Path) { let mut level = Level { player_uuid: Some(uuid_ints(guest.uuid)), - dimension: "minecraft:overworld".into(), ..Level::default() }; store(guest, &mut level); @@ -114,6 +117,7 @@ pub fn save(guest: &Guest, world: &Path) { /// Put a guest's state in `level`'s player fields. pub fn store(guest: &Guest, level: &mut Level) { level.position = Some(guest.position); + level.dimension = guest.dimension.clone(); level.rotation = [guest.yaw, guest.pitch]; level.health = guest.health; level.food = guest.food; diff --git a/crates/horizon-client/src/light.rs b/crates/horizon-client/src/light.rs index fd271f40f..595efd9b2 100644 --- a/crates/horizon-client/src/light.rs +++ b/crates/horizon-client/src/light.rs @@ -165,14 +165,14 @@ impl LightTables { fn edge_occluded(&self, top: usize, bottom: usize) -> bool { self.cells[bottom].dampening != 0 || self.blocked(top, bottom, Direction::Down as usize) } - pub fn emission(&self, state: u16) -> u8 { + pub fn emission(&self, state: u32) -> u8 { self.cells[state as usize].emission } - pub fn dampening(&self, state: u16) -> u8 { + pub fn dampening(&self, state: u32) -> u8 { self.cells[state as usize].dampening } /// Whether a state change can change light (`hasDifferentLightProperties`). - pub fn differs(&self, old: u16, new: u16) -> bool { + pub fn differs(&self, old: u32, new: u32) -> bool { let (a, b) = (&self.cells[old as usize], &self.cells[new as usize]); old != new && (a.dampening != b.dampening || a.emission != b.emission || a.shaped || b.shaped) @@ -211,12 +211,12 @@ pub fn light_chunk( // up to 14 blocks into it (sky light there is always 15). let h = ((top_section + 1) * 16).min(HEIGHT as usize); let at = |x: usize, y: usize, z: usize| (y * W + z) * W + x; - let mut states = vec![0u16; W * W * h]; + let mut states = vec![0u32; W * W * h]; let mut sky = vec![0u8; W * W * h]; let mut block = vec![0u8; W * W * h]; let mut queue = VecDeque::new(); let mut sky_queue = VecDeque::new(); - let mut ids = Box::new([0u16; 4096]); + let mut ids = Box::new([0u32; 4096]); for (dz, row) in region.iter().enumerate() { for (dx, chunk) in row.iter().enumerate() { let Some(chunk) = chunk else { continue }; @@ -391,13 +391,13 @@ pub fn apply_relighting(chunk: &mut Chunk, lights: Vec) -> Vec<(i32, i32, /// Resident chunks the incremental relighter reads and writes. pub trait LightWorld { - fn state(&self, x: i32, y: i32, z: i32) -> Option; + fn state(&self, x: i32, y: i32, z: i32) -> Option; /// Packed light (sky << 4 | block), None outside loaded chunks. fn light(&self, x: i32, y: i32, z: i32) -> Option; fn set_light(&mut self, x: i32, y: i32, z: i32, packed: u8); } impl LightWorld for HashMap<(i32, i32), Arc, S> { - fn state(&self, x: i32, y: i32, z: i32) -> Option { + fn state(&self, x: i32, y: i32, z: i32) -> Option { if !(MIN_Y..MIN_Y + HEIGHT).contains(&y) { return None; } @@ -611,10 +611,10 @@ fn relight_layer( mod tests { use super::*; - const AIR: u16 = 0; - const STONE: u16 = 1; - const TORCH: u16 = 2; - const SLAB: u16 = 3; + const AIR: u32 = 0; + const STONE: u32 = 1; + const TORCH: u32 = 2; + const SLAB: u32 = 3; /// Air, stone, torch and a bottom slab (full bottom face, half sides, /// empty top), with a third face shape for the half sides. fn tables() -> LightTables { @@ -889,7 +889,7 @@ mod tests { for (si, s) in fixture.sections.iter_mut().enumerate() { let section = Arc::make_mut(s); for i in 0..4096 { - section.set(i, ((i + si) % 16) as u16); + section.set(i, ((i + si) % 16) as u32); } for i in 0..64 { section.biomes.set(i, (i % 4) as u32); diff --git a/crates/horizon-client/src/mesher.rs b/crates/horizon-client/src/mesher.rs index 7f1191126..c3990f598 100644 --- a/crates/horizon-client/src/mesher.rs +++ b/crates/horizon-client/src/mesher.rs @@ -434,17 +434,17 @@ fn pi(x: i32, y: i32, z: i32) -> usize { } /// Blocks and light of one section plus a `B`-block border. struct Padded { - blocks: Vec, + blocks: Vec, light: Vec, } impl Padded { fn new(region: &[[Option<&Chunk>; 3]; 3], sy: i32) -> Self { - let mut blocks = vec![0u16; P * P * P]; + let mut blocks = vec![0u32; P * P * P]; let mut light = vec![0u8; P * P * P]; let base_y = MIN_Y + sy * 16; // The section itself is unpacked in one pass; the border cells of the // neighbouring sections are read one by one. - let mut own = Box::new([0u16; 4096]); + let mut own = Box::new([0u32; 4096]); let center = region[1][1].map(|c| &c.sections[sy as usize]); if let Some(section) = center { section.unpack(&mut own); @@ -643,10 +643,8 @@ impl Mesher<'_> { } let state = &info[id as usize]; if state.block_entity { - out.block_entities.push(( - [center.x * 16 + x, base_y + y, center.z * 16 + z], - u32::from(id), - )); + out.block_entities + .push(([center.x * 16 + x, base_y + y, center.z * 16 + z], id)); } if state.solid && Direction::ALL.iter().all(|d| { @@ -665,10 +663,7 @@ impl Mesher<'_> { continue; } let world = BlockPos::new(center.x * 16 + x, base_y + y, center.z * 16 + z); - let Ok(models) = self - .assets - .model_catalog - .collect(BlockStateId(id.into()), world) + let Ok(models) = self.assets.model_catalog.collect(BlockStateId(id), world) else { continue; }; @@ -700,8 +695,8 @@ impl Mesher<'_> { && self .visibility .should_render_face( - BlockStateId(id.into()), - BlockStateId(neighbor.into()), + BlockStateId(id), + BlockStateId(neighbor), d, true, ) diff --git a/crates/horizon-client/src/mesher/fluid.rs b/crates/horizon-client/src/mesher/fluid.rs index 41b1e200e..c29f2b92c 100644 --- a/crates/horizon-client/src/mesher/fluid.rs +++ b/crates/horizon-client/src/mesher/fluid.rs @@ -159,28 +159,28 @@ struct FlowView<'a> { info: &'a [Info], } impl FlowView<'_> { - fn id(&self, p: BlockPos) -> u16 { + fn id(&self, p: BlockPos) -> u32 { self.pad.blocks[pi(p.x, p.y, p.z)] } } impl FluidFlowWorld for FlowView<'_> { type Error = Infallible; - type Block = u16; + type Block = u32; fn fluid(&mut self, p: BlockPos) -> Result { Ok(self.info[self.id(p) as usize].fluid) } - fn block(&mut self, p: BlockPos) -> Result { + fn block(&mut self, p: BlockPos) -> Result { Ok(self.id(p)) } - fn blocks_fluid_flow(&self, state: u16) -> bool { + fn blocks_fluid_flow(&self, state: u32) -> bool { self.info[state as usize].blocks_flow } - fn is_ice_class(&self, state: u16) -> bool { + fn is_ice_class(&self, state: u32) -> bool { self.info[state as usize].ice } fn is_face_sturdy( &mut self, - state: u16, + state: u32, _: BlockPos, d: Direction, ) -> Result { diff --git a/crates/horizon-client/src/mesher/leaf_culling_tests.rs b/crates/horizon-client/src/mesher/leaf_culling_tests.rs index 16ea98cef..9369a1ba2 100644 --- a/crates/horizon-client/src/mesher/leaf_culling_tests.rs +++ b/crates/horizon-client/src/mesher/leaf_culling_tests.rs @@ -13,12 +13,12 @@ fn leaf_culling_removes_only_internal_leaf_and_root_faces() { let visibility = crate::models::load_visibility(&root, assets.registry).unwrap(); let tables = MeshTables::new(&assets, &facts, visibility.clone()).unwrap(); let biomes = Biomes::load(&root).unwrap(); - let state = |name| assets.registry.default_state(name).unwrap().0 as u16; + let state = |name| assets.registry.default_state(name).unwrap().0; let oak = state("minecraft:oak_leaves"); let birch = state("minecraft:birch_leaves"); let roots = state("minecraft:mangrove_roots"); let stone = state("minecraft:stone"); - let mesh = |blocks: &[([i32; 3], u16)], cull_leaves, cutout_leaves| { + let mesh = |blocks: &[([i32; 3], u32)], cull_leaves, cutout_leaves| { let mut center = Chunk::empty(0, 0); let mut east = Chunk::empty(1, 0); for &([x, y, z], state) in blocks { @@ -51,7 +51,7 @@ fn leaf_culling_removes_only_internal_leaf_and_root_faces() { let vertices = mesh(&[(at, id)], false, true); let models = assets .model_catalog - .collect(BlockStateId(id.into()), BlockPos::new(at[0], at[1], at[2])) + .collect(BlockStateId(id), BlockPos::new(at[0], at[1], at[2])) .unwrap(); let faces: Vec<_> = models.iter().flat_map(|(_, model)| &model.faces).collect(); assert_eq!(vertices.len(), faces.len() * 4); diff --git a/crates/horizon-client/src/mesher/visibility_tests.rs b/crates/horizon-client/src/mesher/visibility_tests.rs index 2f95c45cf..32eb4800c 100644 --- a/crates/horizon-client/src/mesher/visibility_tests.rs +++ b/crates/horizon-client/src/mesher/visibility_tests.rs @@ -105,7 +105,7 @@ fn fixture(mut opaque: impl FnMut(i32, i32, i32) -> bool) -> Padded { for y in 0..16 { for z in 0..16 { for x in 0..16 { - pad.blocks[pi(x, y, z)] = u16::from(opaque(x, y, z)) + 2 * ((x + y + z) as u16 & 1); + pad.blocks[pi(x, y, z)] = u32::from(opaque(x, y, z)) + 2 * ((x + y + z) as u32 & 1); } } } diff --git a/crates/horizon-client/src/minimap.rs b/crates/horizon-client/src/minimap.rs index 8015e2ab2..8b250e1af 100644 --- a/crates/horizon-client/src/minimap.rs +++ b/crates/horizon-client/src/minimap.rs @@ -75,8 +75,8 @@ impl Palette { } } #[inline] - fn get(&self, id: u16) -> (u8, u8) { - let i = usize::from(id); + fn get(&self, id: u32) -> (u8, u8) { + let i = id as usize; ( self.color.get(i).copied().unwrap_or(0), self.flags.get(i).copied().unwrap_or(AIR), @@ -137,7 +137,7 @@ fn scan_column( (0, MIN_Y as i16, 0) } /// The highest block of a chunk worth scanning from. -fn top_of(chunk: &Chunk, air: u16, layer: Layer) -> i32 { +fn top_of(chunk: &Chunk, air: u32, layer: Layer) -> i32 { let surface = (0..SECTIONS) .rev() .find(|&s| { @@ -152,7 +152,7 @@ fn top_of(chunk: &Chunk, air: u16, layer: Layer) -> i32 { Layer::Below(head) => surface.min(head), } } -fn scan_tile(chunk: &Chunk, palette: &Palette, air: u16, layer: Layer, revision: u64) -> Tile { +fn scan_tile(chunk: &Chunk, palette: &Palette, air: u32, layer: Layer, revision: u64) -> Tile { let top = top_of(chunk, air, layer); let mut tile = Tile { color: [0; 256], @@ -287,7 +287,7 @@ impl Minimap { ) -> usize { let palette = self.palette.get_or_insert_with(|| Palette::new(facts)); let started = Instant::now(); - let air = world.air.0 as u16; + let air = world.air.0; // Tiles of unloaded or distant chunks go. self.tiles.retain(|k, _| { (k.0 - center.0).abs() <= radius + 2 @@ -417,7 +417,7 @@ mod tests { (LAVA, 2), ]) } - fn chunk(columns: &[(i32, i32, &[(i32, u16)])]) -> Chunk { + fn chunk(columns: &[(i32, i32, &[(i32, u32)])]) -> Chunk { let mut c = Chunk::empty(0, 0); for &(x, z, blocks) in columns { for &(y, id) in blocks { @@ -467,7 +467,7 @@ mod tests { fn below_a_height_shows_the_floor_and_cuts_walls() { let p = palette(); // A cave: stone everywhere from 0 to 20, air at 10 and 11 in column 0. - let mut blocks: Vec<(i32, u16)> = (0..=20).map(|y| (y, 2)).collect(); + let mut blocks: Vec<(i32, u32)> = (0..=20).map(|y| (y, 2)).collect(); let solid = blocks.clone(); blocks.retain(|&(y, _)| y != 10 && y != 11); let c = chunk(&[(0, 0, &blocks), (1, 0, &solid)]); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 2ab4c0557..0611f0c85 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -686,6 +686,8 @@ pub struct Extra { pub legs: Option>, pub feet: Option>, pub using_item: i32, + pub using_off_hand: bool, + pub blocking: bool, pub fall_flying: bool, pub fall_fly_ticks: i32, pub main_hand_left: bool, diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index 4f76ff70c..1410bf858 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -4,7 +4,7 @@ use super::{Mob, Part, keyframes::AnimationState, living::wrap}; use horizon_core::geometry::trig::Mth; use std::collections::HashMap; -use std::f32::consts::PI; +use std::f32::consts::{FRAC_PI_6, PI}; /// The setupAnim implementation a model uses. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -232,6 +232,7 @@ fn bob(p: &mut Poses, n: &str, age: f32, scale: f32) { pub enum ArmPose { Empty, Item, + Block, Bow, CrossbowHold, CrossbowCharge, @@ -355,6 +356,14 @@ fn pose_arm(p: &mut Poses, pose: ArmPose, right: bool, h: &Hum) { p.xrot(arm, x * 0.5 - PI / 10.0); p.yrot(arm, 0.0); } + ArmPose::Block => { + let x = p.get(arm)[3] * 0.5 - 0.942_477_9 + hx.clamp(-1.396_263_4, 0.436_332_32); + p.xrot(arm, x); + p.yrot( + arm, + if right { -FRAC_PI_6 } else { FRAC_PI_6 } + hy.clamp(-FRAC_PI_6, FRAC_PI_6), + ); + } ArmPose::Bow => { p.yrot("right_arm", -0.1 + hy - if right { 0.0 } else { 0.4 }); p.yrot("left_arm", 0.1 + hy + if right { 0.4 } else { 0.0 }); @@ -661,11 +670,13 @@ pub fn setup( } else { ArmPose::Empty }; + let using_main = m.extra.using_item > 0 && !m.extra.using_off_hand; let pose = if player { match m.extra.main_hand.as_deref() { - Some("minecraft:bow") if m.extra.using_item > 0 => ArmPose::Bow, - Some("minecraft:trident") if m.extra.using_item > 0 => ArmPose::ThrowTrident, - Some("minecraft:crossbow") if m.extra.using_item > 0 && !m.extra.charged => { + Some(_) if using_main && m.extra.blocking => ArmPose::Block, + Some("minecraft:bow") if using_main => ArmPose::Bow, + Some("minecraft:trident") if using_main => ArmPose::ThrowTrident, + Some("minecraft:crossbow") if using_main && !m.extra.charged => { ArmPose::CrossbowCharge } Some("minecraft:crossbow") if m.extra.charged && s.swing == 0.0 => { @@ -678,7 +689,11 @@ pub fn setup( right }; let off = if player && m.extra.off_hand.is_some() && !pose.affects_offhand() { - ArmPose::Item + if m.extra.using_item > 0 && m.extra.using_off_hand && m.extra.blocking { + ArmPose::Block + } else { + ArmPose::Item + } } else { ArmPose::Empty }; @@ -791,6 +806,42 @@ pub fn setup( #[cfg(test)] mod flight_pose_tests { use super::*; + + #[test] + fn blocking_arm_follows_the_head_with_limits_in_both_hands() { + for right in [false, true] { + for (pitch, yaw, expected_pitch, expected_yaw) in [ + (0.0, 0.0, -0.742_477_9, 0.0), + (2.0, 2.0, -0.306_145_58, FRAC_PI_6), + (-2.0, -2.0, -2.138_741_3, -FRAC_PI_6), + ] { + let mut p = Poses { + map: ["head", "right_arm", "left_arm"] + .into_iter() + .map(|n| (n.to_string(), [0.0; 9])) + .collect(), + dummy: [0.0; 9], + skipped: Default::default(), + hidden: Default::default(), + }; + let arm = if right { "right_arm" } else { "left_arm" }; + p.xrot("head", pitch); + p.yrot("head", yaw); + p.xrot(arm, 0.4); + pose_arm( + &mut p, + ArmPose::Block, + right, + &Hum::new(ArmPose::Empty, ArmPose::Empty), + ); + let pose = *p.get(arm); + assert!((pose[3] - expected_pitch).abs() < 1e-6); + let side = if right { -FRAC_PI_6 } else { FRAC_PI_6 }; + assert!((pose[4] - (side + expected_yaw)).abs() < 1e-6); + assert_eq!(p.get(if right { "left_arm" } else { "right_arm" })[3], 0.0); + } + } + } #[test] fn flight_slows_limbs_and_sets_the_head_pose() { let state = State { diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 21ab88aa3..a0dce0e08 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -1041,17 +1041,24 @@ fn render_visible( .unwrap_or_else(|| m.kind.model.clone()); let mut poses = Poses::new(&model); anim::setup(m, &s, &mut poses, &data.animations); - if let Some(uv) = atlas(&texture) { - draw( - &model, - base, - &poses, - uv, - body_color(m, alpha), - light, - body_overlay(m, alpha), - out, - ); + let draw_body = |out: &mut Vec| { + if let Some(uv) = atlas(&texture) { + draw( + &model, + base, + &poses, + uv, + body_color(m, alpha), + light, + body_overlay(m, alpha), + out, + ); + } + }; + // The translucent shell writes depth: draw the opaque core before it. + let shell_last = m.species() == Species::SulfurCube; + if !shell_last { + draw_body(out); } for (part, uv, color) in extra { draw(part, base, &poses, *uv, *color, light, overlay, out); @@ -1109,6 +1116,9 @@ fn render_visible( } } } + if shell_last { + draw_body(out); + } } /// The equipment slot of a `HumanoidArmorLayer` model (`zombie#helmet`). fn armor_slot(model: &str) -> Option { @@ -1249,3 +1259,93 @@ pub fn held_item_transform( anim::setup(m, &s, &mut poses, &data.animations); hand_base(m, &model, base, &poses, left) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sulfur_cube_opaque_core_is_submitted_before_its_translucent_shell() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client/26.3"); + if !root.join("entity-models.json").exists() { + return; + } + let mut types = super::super::MobTypes::load(&root).unwrap(); + let kind = std::sync::Arc::new(types.types.remove("minecraft:sulfur_cube").unwrap()); + let data = MobData { + states: Vec::new(), + placements: Default::default(), + heightmaps: Default::default(), + animations: Default::default(), + biome_tags: Default::default(), + entity_tags: Default::default(), + villager_hats: Default::default(), + pois: Default::default(), + }; + let atlas = |name: &str| { + Some(if name.contains("_inner") { + [0.0, 0.0, 0.25, 0.25] + } else { + [0.5, 0.5, 0.75, 0.75] + }) + }; + for baby in [false, true] { + let mut mob = Mob::new(1, kind.clone(), horizon_core::geometry::Vec3::ZERO, 0.0); + mob.extra.age = if baby { -24000 } else { 0 }; + super::super::sulfur_cube::finalize(&mut mob); + assert_eq!(mob.is_baby(), baby); + for posed in [false, true] { + let mut vertices = Vec::new(); + if posed { + render_posed( + &mob, + 0.5, + glam::Mat4::IDENTITY, + &atlas, + 0xf0f0, + &data, + &mut vertices, + ); + } else { + render( + &mob, + 0.5, + glam::DVec3::ZERO, + &atlas, + 0xf0f0, + &data, + &mut vertices, + ); + } + assert_eq!( + vertices.len(), + 48, + "both real six-face models must be drawn" + ); + assert!( + vertices[..24].iter().all(|v| v.uv[0] <= 0.25), + "opaque core must precede shell" + ); + assert!(vertices[24..].iter().all(|v| v.uv[0] >= 0.5)); + } + mob.extra.head = Some("minecraft:stone".into()); + let mut vertices = Vec::new(); + render( + &mob, + 0.5, + glam::DVec3::ZERO, + &atlas, + 0xf0f0, + &data, + &mut vertices, + ); + assert_eq!( + vertices.len(), + 24, + "a swallowed block still hides the default core" + ); + assert!(vertices.iter().all(|v| v.uv[0] >= 0.5)); + } + } +} diff --git a/crates/horizon-client/src/mod_content.rs b/crates/horizon-client/src/mod_content.rs index f78808da7..25df87352 100644 --- a/crates/horizon-client/src/mod_content.rs +++ b/crates/horizon-client/src/mod_content.rs @@ -323,7 +323,7 @@ impl<'a> Plan<'a> { } let list: Vec = by_mod.iter().map(|(m, n)| format!("{m} {n}")).collect(); return Err(format!( - "{next} block states, more than the {MAX_STATES} chunks can hold ({} in the game; \ + "{next} block states, more than the {MAX_STATES} a world can hold ({} in the game; \ the mods: {})", names.len(), list.join(", ") @@ -644,9 +644,11 @@ const NBT_TABLES: [&str; 6] = [ /// In a root built here: the content mods' ids, the namespaces loaders /// read besides `minecraft`. const MARKER: &str = "horizon-mod-content.json"; -/// Block states a world can hold: chunk sections store a state in 16 bits -/// (crate::chunk). Mods past it are refused, not wrapped onto other blocks. -pub const MAX_STATES: u32 = 1 << 16; +/// Block states a world can hold. Chunk sections widen their global palette +/// past vanilla's 16 bits to fit the registry (crate::chunk::set_block_states); +/// this caps it at 20 bits, about 29 times vanilla's 35,723 states. Mods past +/// it are refused, not wrapped onto other blocks. +pub const MAX_STATES: u32 = 1 << 20; /// The content mods' namespaces in a root built by [`build`]; none in any /// other root, so vanilla's loaders read exactly what they did. diff --git a/crates/horizon-client/src/mod_content_tests.rs b/crates/horizon-client/src/mod_content_tests.rs index 7067eef40..2a040b0fc 100644 --- a/crates/horizon-client/src/mod_content_tests.rs +++ b/crates/horizon-client/src/mod_content_tests.rs @@ -266,17 +266,17 @@ fn refuses_unknown_templates_and_vanilla_ids() { } #[test] -fn refuses_more_states_than_chunks_hold() { +fn refuses_more_states_than_a_world_holds() { let Some(base) = prepared() else { return; }; let scratch = std::env::temp_dir().join(format!("horizon-mod-states-{}", std::process::id())); let _ = fs::remove_dir_all(&scratch); let mut m = ruby_mod(&scratch.join("ruby")); - // Redstone wire has 1296 states: 40 copies pass any game's 65536. + // Redstone wire has 1296 states: 810 copies pass 2^20 with any game. let mut wire = m.content.blocks[0].clone(); wire.template = "minecraft:redstone_wire".into(); - for i in 0..40 { + for i in 0..810 { let mut b = wire.clone(); b.id = format!("ruby:wire_{i}"); m.content.blocks.push(b); @@ -284,13 +284,33 @@ fn refuses_more_states_than_chunks_hold() { let e = build(&base, std::slice::from_ref(&m), &scratch.join("out")).unwrap_err(); assert!( e.to_string() - .contains("more than the 65536 chunks can hold"), + .contains("more than the 1048576 a world can hold"), "{e}" ); assert!(e.to_string().contains("the mods: ruby "), "{e}"); fs::remove_dir_all(&scratch).unwrap(); } +#[test] +fn builds_past_sixteen_bit_states() { + let Some(base) = prepared() else { + return; + }; + let scratch = std::env::temp_dir().join(format!("horizon-mod-wide-{}", std::process::id())); + let _ = fs::remove_dir_all(&scratch); + let mut m = ruby_mod(&scratch.join("ruby")); + // 40 redstone wires: 51,840 states, past 65,536 with vanilla's 35,723. + let mut wire = m.content.blocks[0].clone(); + wire.template = "minecraft:redstone_wire".into(); + for i in 0..40 { + let mut b = wire.clone(); + b.id = format!("ruby:wire_{i}"); + m.content.blocks.push(b); + } + build(&base, std::slice::from_ref(&m), &scratch.join("out")).unwrap(); + fs::remove_dir_all(&scratch).unwrap(); +} + #[test] fn no_content_keeps_the_base_root() { let base = Path::new("/nonexistent/base"); diff --git a/crates/horizon-client/src/model_library.rs b/crates/horizon-client/src/model_library.rs index 7f7852ad0..c6a1a9d87 100644 --- a/crates/horizon-client/src/model_library.rs +++ b/crates/horizon-client/src/model_library.rs @@ -42,25 +42,52 @@ impl ParsedModels { /// Blocks require every referenced resource, including parents. Items instead /// skip broken resources and use the resolver's missing-model fallback. - pub(crate) fn block_library( + pub(crate) fn block_library(&self, root: &Path, pending: Vec) -> Result { + self.block_models(root, pending, false) + } + /// [`Self::block_library`], but a model that does not read takes the + /// built-in missing model, logged, as vanilla's model discovery does + /// ("Missing block model"). Mods' content gets this; vanilla's resources + /// always read. + pub(crate) fn block_library_or_missing( + &self, + root: &Path, + pending: Vec, + ) -> Result { + self.block_models(root, pending, true) + } + fn block_models( &self, root: &Path, mut pending: Vec, + or_missing: bool, ) -> Result { let mut models = BTreeMap::new(); + let mut skipped = std::collections::BTreeSet::new(); while let Some(name) = pending.pop() { - if models.contains_key(&name) { + if models.contains_key(&name) || skipped.contains(&name) { continue; } let model = match self.models.get(&name) { Some(model) => Arc::clone(model), None => { - let (namespace, path) = - name.split_once(':').ok_or("invalid model identifier")?; - let text = fs::read_to_string( - root.join(format!("assets/{namespace}/models/{path}.json")), - )?; - Arc::new(CuboidModel::from_json(&text)?) + let read = || -> Result { + let (namespace, path) = + name.split_once(':').ok_or("invalid model identifier")?; + let text = fs::read_to_string( + root.join(format!("assets/{namespace}/models/{path}.json")), + )?; + Ok(CuboidModel::from_json(&text)?) + }; + match read() { + Ok(model) => Arc::new(model), + Err(e) if or_missing => { + log::warn!("Horizon: missing block model {name}: {e}"); + skipped.insert(name); + continue; + } + Err(e) => return Err(e), + } } }; if let Some(parent) = &model.parent { @@ -141,6 +168,13 @@ mod tests { .to_string() }; assert_eq!(load(&direct), load(&parsed)); + // Mods' content: vanilla's missing model instead of an error. + let lenient = parsed.block_library_or_missing(&fixture.0, vec![name.into()])?; + assert_eq!( + format!("{:?}", lenient.resolve(name)?.elements()), + format!("{:?}", lenient.resolve(MISSING_MODEL)?.elements()), + "{name}" + ); } let items = parsed.into_item_library()?; let block = shared.resolve("horizon:nested/child")?; diff --git a/crates/horizon-client/src/models/catalog.rs b/crates/horizon-client/src/models/catalog.rs index ecedd0f95..be550d8c6 100644 --- a/crates/horizon-client/src/models/catalog.rs +++ b/crates/horizon-client/src/models/catalog.rs @@ -136,11 +136,29 @@ impl StateModels { }) .collect::>()?; let possible: Vec = serde_json::from_value(facts["states"].clone())?; - let resource = fs::read_to_string( + // Vanilla's BlockStateModelLoader: a definition that does not + // read or bind is logged and its block gets no model; the other + // blocks still load. + let loaded = fs::read_to_string( root.join(format!("assets/{namespace}/blockstates/{path}.json")), - )?; - let definition = BlockStateDefinition::from_json(&resource)?; - let bound = definition.bind(&schema, &possible)?; + ) + .map_err(|e| e.to_string()) + .and_then(|text| BlockStateDefinition::from_json(&text).map_err(|e| e.to_string())) + .and_then(|definition| { + let bound = definition + .bind(&schema, &possible) + .map_err(|e| e.to_string())?; + Ok((definition, bound)) + }); + let (definition, bound) = match loaded { + Ok(loaded) => loaded, + Err(e) => { + log::warn!( + "Horizon: blockstate definition of {namespace}:{path} not loaded: {e}" + ); + continue; + } + }; let native_order: Vec<_> = by_name .get(name.as_str()) .map(Vec::as_slice) @@ -185,10 +203,14 @@ impl StateModels { } choices.push(CompiledChoices::new(&definition)?); } - let library = models.block_library( - root, - variants.iter().map(|(name, _, _)| name.clone()).collect(), - )?; + let names: Vec = variants.iter().map(|(name, _, _)| name.clone()).collect(); + let library = match models.block_library(root, names.clone()) { + Ok(library) => library, + Err(e) => { + log::warn!("Horizon: block models incomplete ({e}); using the missing model"); + models.block_library_or_missing(root, names)? + } + }; let mut baked = BTreeMap::new(); for (name, turns, lock) in variants { let model = library.resolve(&name)?; @@ -231,14 +253,20 @@ impl StateModels { &self, state: BlockStateId, position: BlockPos, + ) -> Result> { + // Blocks use their position seed; contained/displayed blocks can supply one. + self.collect_seeded(state, position_seed(position)) + } + pub fn collect_seeded( + &self, + state: BlockStateId, + seed: i64, ) -> Result> { let (choice, selected) = self .states .get(&state) .ok_or("unbound gallery block state")?; - // These inspection blocks use Block's default position seed. Blocks with - // specialized model seeds (e.g. two-block structures) need their callbacks. - let mut random = LegacyRandom::new(position_seed(position)); + let mut random = LegacyRandom::new(seed); let mut variants = Vec::new(); self.choices[*choice].collect(selected, &mut random, &mut variants)?; variants diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 0eb79d65c..7dab3a5aa 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -292,19 +292,25 @@ impl PlayerMotion { && movement.x * movement.x + movement.z * movement.z < limit * limit && sword } - pub fn load_environment_once( + /// Restore login state once; a later respawn starts with fresh health and food. + pub fn load_saved_state_once( &mut self, pending: &mut bool, - extra: Option<&horizon_world::nbt::Tag>, - ) { + level: &crate::save::Level, + ) -> Result<()> { if std::mem::take(pending) { + let extra = level.player_extra.as_ref(); self.fire_ticks = extra .and_then(|t| crate::save::number(t.get("Fire"))) .unwrap_or(-20) as i32; self.air = extra .and_then(|t| crate::save::number(t.get("Air"))) .unwrap_or(300) as i32; + self.set_health(level.health, false)?; + self.health.food.food = level.food; + self.health.food.saturation = level.saturation; } + Ok(()) } pub fn set_remaining_fire_ticks(&mut self, ticks: i32) { self.fire_ticks = if self.invulnerable { @@ -2166,8 +2172,13 @@ mod tests { #[test] fn player_fire_damage_queues_hurt_sound_only_for_fresh_hits() { - let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + let root = std::env::var_os("HORIZON_TEST_RESOURCES") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3") + }); if !root.join("movement-properties.nbt").exists() { + eprintln!("skipped damage regression: prepared resources unavailable"); return; } let assets = Assets::load(&root).unwrap(); @@ -2195,6 +2206,8 @@ mod tests { .count(), 1 ); + assert_eq!(player.health.hurt_animation_time, 10); + player.health.advance_clock(); player.events.clear(); assert!( !player @@ -2207,9 +2220,14 @@ mod tests { .iter() .any(|e| matches!(e, MotionEvent::HurtSound(_))) ); + assert_eq!( + player.health.hurt_animation_time, 9, + "cooldown hit must not restart animation" + ); for _ in 0..20 { player.health.advance_clock(); } + assert_eq!(player.health.hurt_animation_time, 0); player.invulnerable = true; player.events.clear(); assert!( @@ -2271,16 +2289,62 @@ mod tests { Default::default(), source, 4.0, - Some(shield), + Some(shield.clone()), ) .unwrap(); assert!(!outcome.hurt && outcome.sound && outcome.blocked == 4.0); + assert_eq!( + player.health.hurt.hurt_time, 10, + "preserve server damage bookkeeping" + ); + assert_eq!( + player.health.hurt_animation_time, 0, + "a fully blocked arrow must not animate hurt" + ); assert!( !player .events .iter() .any(|e| matches!(e, MotionEvent::HurtSound(_))) ); + // An unblocked hit after the shield block must still animate normally. + for _ in 0..20 { + player.health.advance_clock(); + } + assert!( + player + .hurt(&resources.health, Default::default(), source, 4.0) + .unwrap() + ); + assert_eq!(player.health.hurt_animation_time, 10); + player.health.advance_clock(); + assert!( + !player + .hurt_blocking( + &resources.health, + Default::default(), + source, + 4.0, + Some(shield) + ) + .unwrap() + .hurt + ); + assert_eq!( + player.health.hurt_animation_time, 9, + "blocking must not erase or restart an existing animation" + ); + let mut starving = PlayerMotion::new(&resources, Vec3::ZERO).unwrap(); + starving.health.food.food = 0; + starving.health.food.timer = 79; + starving + .food_tick(&resources.health, Default::default()) + .unwrap(); + assert_eq!(starving.health.health(), 19.0); + assert_eq!( + starving.health.hurt_animation_time, 10, + "starvation must still animate hurt" + ); } /// Footsteps on the prepared vanilla resources, when they are present: @@ -2329,8 +2393,13 @@ mod tests { #[test] fn resident_water_and_lava_are_not_treated_as_air() { - let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + let root = std::env::var_os("HORIZON_TEST_RESOURCES") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3") + }); if !root.join("movement-properties.nbt").exists() { + eprintln!("skipping resident water/lava test: prepared resources unavailable"); return; } let assets = Assets::load(&root).unwrap(); @@ -2536,12 +2605,41 @@ mod tests { ("Fire", horizon_world::nbt::Tag::Short(160)), ("Air", horizon_world::nbt::Tag::Short(8)), ]); + let mut level = crate::save::Level { + health: 13.0, + food: 11, + saturation: 2.25, + player_extra: Some(extra), + ..Default::default() + }; let mut pending = true; - w.player.load_environment_once(&mut pending, Some(&extra)); + w.player + .load_saved_state_once(&mut pending, &level) + .unwrap(); assert_eq!((w.player.fire_ticks, w.player.air), (160, 8)); + assert_eq!( + ( + w.player.health.health(), + w.player.health.food.food, + w.player.health.food.saturation + ), + (13.0, 11, 2.25) + ); let mut respawn = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap(); - respawn.load_environment_once(&mut pending, Some(&extra)); + respawn.load_saved_state_once(&mut pending, &level).unwrap(); assert_eq!((respawn.fire_ticks, respawn.air), (-20, 300)); + assert_eq!( + (respawn.health.health(), respawn.health.food.food), + (20.0, 20) + ); + // Reopening another world restores its state, including a saved death. + pending = true; + level.health = 0.0; + w.player + .load_saved_state_once(&mut pending, &level) + .unwrap(); + assert!(w.player.health.dead_or_dying()); + assert!(!pending); w.player.fluids.was_touching_water = false; assert!( w.player.moving_slowly(), diff --git a/crates/horizon-client/src/poi_sections.rs b/crates/horizon-client/src/poi_sections.rs index 2116362e0..79ff0441d 100644 --- a/crates/horizon-client/src/poi_sections.rs +++ b/crates/horizon-client/src/poi_sections.rs @@ -54,12 +54,12 @@ impl PoiSections { return cached.pois.clone(); } let pois: SectionPois = if section.blocks.maybe_has(|v| kind(v).is_some()) { - let mut states = [0u16; 4096]; + let mut states = [0u32; 4096]; section.unpack(&mut states); states .iter() .enumerate() - .filter_map(|(i, &state)| kind(u32::from(state)).map(|poi| (i as u16, poi))) + .filter_map(|(i, &state)| kind(state).map(|poi| (i as u16, poi))) .collect() } else { Arc::from([]) diff --git a/crates/horizon-client/src/random_tick_sections.rs b/crates/horizon-client/src/random_tick_sections.rs index 97a1f02fa..cd06f2ac9 100644 --- a/crates/horizon-client/src/random_tick_sections.rs +++ b/crates/horizon-client/src/random_tick_sections.rs @@ -134,7 +134,7 @@ mod tests { let mut chunk = Chunk::empty(0, 0); for i in [0, 9, SECTIONS - 1] { Arc::make_mut(&mut chunk.sections[i]).blocks = - Section::from_blocks(&std::array::from_fn(|j| (j % 300) as u16)); + Section::from_blocks(&std::array::from_fn(|j| (j % 300) as u32)); } let chunk = Arc::new(chunk); let mut cache = RandomTickSections::default(); @@ -176,12 +176,9 @@ mod tick_parity { } fn set_raw(&mut self, pos: BlockPos, state: BlockStateId) -> Option { let chunk = self.chunks.get_mut(&(pos.x >> 4, pos.z >> 4))?; - Some(BlockStateId(u32::from(Arc::make_mut(chunk).set( - pos.x, - pos.y, - pos.z, - state.0 as u16, - )))) + Some(BlockStateId( + Arc::make_mut(chunk).set(pos.x, pos.y, pos.z, state.0), + )) } fn is_loaded(&self, pos: BlockPos) -> bool { self.chunks.contains_key(&(pos.x >> 4, pos.z >> 4)) @@ -233,7 +230,7 @@ mod tick_parity { // Every sampled block can run real behaviour and change to dirt. for i in [4, 7] { Arc::make_mut(&mut c.sections[i]).blocks = - crate::chunk::Section::from_blocks(&[grass.0 as u16; 4096]); + crate::chunk::Section::from_blocks(&[grass.0; 4096]); } Arc::new(c) }; diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 4411a353c..29038849f 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -16,7 +16,7 @@ use crate::{ Result, biome::Biomes, - chunk::{BIOME_STRATEGY, BLOCK_STRATEGY, Chunk, Light, MIN_Y, SECTIONS}, + chunk::{BIOME_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, block_strategy}, streaming::ChunkGenerator, }; use horizon_core::{ @@ -238,7 +238,7 @@ pub struct SaveTables { default_state: Vec, block_entity: Vec, heightmaps: crate::assets::Properties, - air: u16, + air: u32, } impl SaveTables { pub fn new(assets: &crate::assets::Assets) -> Self { @@ -266,9 +266,7 @@ impl SaveTables { default_state, block_entity: Vec::new(), heightmaps: assets.properties.clone(), - air: registry - .default_state("minecraft:air") - .map_or(0, |s| s.0 as u16), + air: registry.default_state("minecraft:air").map_or(0, |s| s.0), } } /// Which states carry a block entity (`BlockFacts`), to drop entries for @@ -1035,8 +1033,8 @@ fn decode_column( } } } - let air = registry.default_state("minecraft:air")?.0 as u16; - let mut cache: HashMap = HashMap::new(); + let air = registry.default_state("minecraft:air")?.0; + let mut cache: HashMap = HashMap::new(); let Some(Tag::List(sections)) = tag.get("sections") else { return Some(chunk); }; @@ -1051,7 +1049,7 @@ fn decode_column( if let Some(states) = section.get("block_states") && let Some(Tag::List(palette)) = states.get("palette") { - let ids: Vec = palette + let palette: Vec = palette .iter() .map(|p| { let state = BlockState::from_nbt(p).ok(); @@ -1074,7 +1072,7 @@ fn decode_column( registry.id(&full).or(Some(default)) }) }) - .map_or(air, |id| id.0 as u16) + .map_or(air, |id| id.0) }) }) .collect(); @@ -1085,9 +1083,8 @@ fn decode_column( } _ => None, }; - let palette: Vec = ids.iter().map(|&id| u32::from(id)).collect(); if let Ok(blocks) = - PalettedContainer::from_packed(BLOCK_STRATEGY, palette, data.as_deref()) + PalettedContainer::from_packed(block_strategy(), palette, data.as_deref()) { target.blocks = blocks; } @@ -1980,40 +1977,51 @@ impl Default for WorldGen { } /// Writes a new world's `world_gen_settings` (seed, options and dimensions). pub fn write_world_gen_settings(dir: &Path, seed: i64, options: WorldGen) -> Result<()> { + write_world_gen_settings_with(dir, seed, options, None) +} +/// [`write_world_gen_settings`] with a flat overworld's own generator +/// settings (FlatLevelGeneratorSettings, as `flatgen::settings_from_json` +/// reads them) instead of the Superflat preset's classic layers. +pub fn write_world_gen_settings_with( + dir: &Path, + seed: i64, + options: WorldGen, + flat_settings: Option, +) -> Result<()> { fs::create_dir_all(dir)?; // worldgen/world_preset/flat.json's overworld: the classic flat layers. let layer = |block: &str, height: i32| { Tag::compound([("block", string(block)), ("height", Tag::Int(height))]) }; + let classic = || { + Tag::compound([ + ("biome", string("minecraft:plains")), + ("features", Tag::Byte(0)), + ("lakes", Tag::Byte(0)), + ( + "layers", + Tag::List(vec![ + layer("minecraft:bedrock", 1), + layer("minecraft:dirt", 2), + layer("minecraft:grass_block", 1), + ]), + ), + ( + "structure_overrides", + Tag::List(vec![ + string("minecraft:strongholds"), + string("minecraft:villages"), + ]), + ), + ]) + }; let flat = Tag::compound([ ("type", string("minecraft:overworld")), ( "generator", Tag::compound([ ("type", string("minecraft:flat")), - ( - "settings", - Tag::compound([ - ("biome", string("minecraft:plains")), - ("features", Tag::Byte(0)), - ("lakes", Tag::Byte(0)), - ( - "layers", - Tag::List(vec![ - layer("minecraft:bedrock", 1), - layer("minecraft:dirt", 2), - layer("minecraft:grass_block", 1), - ]), - ), - ( - "structure_overrides", - Tag::List(vec![ - string("minecraft:strongholds"), - string("minecraft:villages"), - ]), - ), - ]), - ), + ("settings", flat_settings.unwrap_or_else(classic)), ]), ), ]); @@ -2143,6 +2151,18 @@ pub struct Level { pub player_extra: Option, } impl Level { + /// Initialize the offline single-player identity before saving or dropping items. + pub fn ensure_player_uuid(&mut self) -> [i32; 4] { + *self.player_uuid.get_or_insert_with(|| { + let u = horizon_protocol::crypto::offline_uuid("Player"); + [ + (u >> 96) as u32 as i32, + (u >> 64) as u32 as i32, + (u >> 32) as u32 as i32, + u as u32 as i32, + ] + }) + } pub fn game_rule(&self, name: &str) -> i32 { self.game_rules .get(name) @@ -2600,17 +2620,7 @@ impl Level { map.remove(&JavaString::from(key)); } } - // A new world's player has the offline profile id of its name - // (UUIDUtil.createOfflinePlayerUUID), as in an offline single-player game. - let uuid = *self.player_uuid.get_or_insert_with(|| { - let u = horizon_protocol::crypto::offline_uuid("Player"); - [ - (u >> 96) as u32 as i32, - (u >> 64) as u32 as i32, - (u >> 32) as u32 as i32, - u as u32 as i32, - ] - }); + let uuid = self.ensure_player_uuid(); // A new world's first spawn point is its world spawn. if self.world_spawn.is_none() { self.world_spawn = self.spawn.map(|s| { @@ -3207,6 +3217,17 @@ mod tests { third.ender_items[3].as_ref().map(|s| (&*s.item, s.count)), Some(("minecraft:diamond", 2)) ); + // A dead player's empty inventory replaces the previously loaded items. + let mut dead = third; + dead.health = 0.0; + dead.inventory.clear(); + dead.inventory_components.clear(); + dead.write(&dir).unwrap(); + let dead = Level::read(&dir).unwrap(); + assert_eq!(dead.health, 0.0); + assert!(dead.inventory.is_empty()); + assert!(dead.inventory_components.is_empty()); + assert!(dead.player_extra.unwrap().get("equipment").is_none()); assert!(dir.join("data/minecraft/world_gen_settings.dat").exists()); let _ = fs::remove_dir_all(&dir); } diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 1754f1550..38fa33c7d 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -264,25 +264,34 @@ impl GenerationScan { } { let mut wanted = Vec::new(); - let areas: Vec<((i32, i32), i32)> = - std::iter::once((input.ranges.center, input.ranges.radius)) - .chain(input.ranges.extra.iter().copied()) - .collect(); - for (center, radius) in areas { + // Each area's square of columns, as one run per row. Players' + // areas overlap (a server's players often stand together), so + // the runs of a row are merged and each column is looked at once. + let mut runs: Vec<(i32, i32, i32)> = Vec::new(); + for (center, radius) in std::iter::once((input.ranges.center, input.ranges.radius)) + .chain(input.ranges.extra.iter().copied()) + { let r = radius + margin.max(reach + 1); - for dz in -r..=r { - for dx in -r..=r { - let (x, z) = (center.0 + dx, center.1 + dz); - if !input.ranges.requested(x, z, input.decorates) - || input.world.chunks.contains_key(&(x, z)) - || input.generating.contains(&(x, z)) - || input.protos.contains_key(&(x, z)) - || input.finishing.contains(&(x, z)) - { - continue; - } - wanted.push((input.ranges.distance(x, z), x, z)); + runs.extend((center.1 - r..=center.1 + r).map(|z| (z, center.0 - r, center.0 + r))); + } + runs.sort_unstable(); + let mut runs = runs.into_iter().peekable(); + while let Some((z, x0, mut x1)) = runs.next() { + while let Some((_, _, next_x1)) = + runs.next_if(|&(nz, nx0, _)| nz == z && nx0 <= x1.saturating_add(1)) + { + x1 = x1.max(next_x1); + } + for x in x0..=x1 { + if !input.ranges.requested(x, z, input.decorates) + || input.world.chunks.contains_key(&(x, z)) + || input.generating.contains(&(x, z)) + || input.protos.contains_key(&(x, z)) + || input.finishing.contains(&(x, z)) + { + continue; } + wanted.push((input.ranges.distance(x, z), x, z)); } } // Forced chunks and their generation neighbourhood. @@ -1569,6 +1578,38 @@ mod tests { } } + #[test] + fn generation_scan_looks_at_overlapping_areas_once() { + // A server's players: many areas around one spot, some apart, one + // touching another only at a corner, and part of the land present. + for decorates in [false, true] { + let mut f = GenerationFixture::new(10, decorates); + for i in 0..40 { + f.extra.push(((i % 7 - 3, i / 7 - 3), 19)); + } + f.extra.push(((200, -150), 19)); + f.extra.push(((243, -107), 19)); + f.extra.push(((-60, 5), 4)); + f.forced.insert((90, 90)); + let chunk = Arc::new(Chunk::empty(0, 0)); + for x in -40i32..40 { + for z in -40i32..40 { + match (x * 7 + z * 13).rem_euclid(5) { + 0 => drop(f.world.chunks.insert((x, z), chunk.clone())), + 1 => drop(f.protos.insert((x, z), None)), + 2 if x % 3 == 0 => drop(f.generating.insert((x, z))), + _ => {} + } + } + } + assert!(baseline_candidates(f.input(), usize::MAX).len() > 1000); + for capacity in [usize::MAX, f.generating.len() + 7] { + let mut gate = GenerationScan::default(); + assert!(f.assert_same(&mut gate, capacity)); + } + } + } + #[test] #[ignore = "reproducible actual generation scheduler benchmark; run with --ignored --nocapture"] fn generation_scan_benchmark() { diff --git a/crates/horizon-client/src/terrain.wgsl b/crates/horizon-client/src/terrain.wgsl index 4689e7d2b..504d197aa 100644 --- a/crates/horizon-client/src/terrain.wgsl +++ b/crates/horizon-client/src/terrain.wgsl @@ -31,6 +31,10 @@ struct Globals { @group(0) @binding(5) var sprites_1: texture_2d_array; @group(0) @binding(6) var sprites_2: texture_2d_array; @group(0) @binding(7) var sprites_3: texture_2d_array; +@group(0) @binding(8) var sprites_4: texture_2d_array; +@group(0) @binding(9) var sprites_5: texture_2d_array; +@group(0) @binding(10) var sprites_6: texture_2d_array; +@group(0) @binding(11) var sprites_7: texture_2d_array; // How many sprite arrays hold layers (a pipeline constant): 1 for vanilla, // which then samples exactly as before. override SPRITE_ARRAYS: u32 = 1u; @@ -47,7 +51,11 @@ fn sprite(uv: vec2, layer: u32) -> vec4 { case 0u: { return textureSampleGrad(sprites, sprite_sampler, uv, l, dx, dy); } case 1u: { return textureSampleGrad(sprites_1, sprite_sampler, uv, l, dx, dy); } case 2u: { return textureSampleGrad(sprites_2, sprite_sampler, uv, l, dx, dy); } - default: { return textureSampleGrad(sprites_3, sprite_sampler, uv, l, dx, dy); } + case 3u: { return textureSampleGrad(sprites_3, sprite_sampler, uv, l, dx, dy); } + case 4u: { return textureSampleGrad(sprites_4, sprite_sampler, uv, l, dx, dy); } + case 5u: { return textureSampleGrad(sprites_5, sprite_sampler, uv, l, dx, dy); } + case 6u: { return textureSampleGrad(sprites_6, sprite_sampler, uv, l, dx, dy); } + default: { return textureSampleGrad(sprites_7, sprite_sampler, uv, l, dx, dy); } } } @@ -68,7 +76,24 @@ fn sample_lightmap(sky: f32, block: f32) -> vec4 { @location(0) position: vec3, @location(1) uv: vec2, @location(2) layer: u32, @location(3) color: vec4, @location(4) light: vec2, @location(5) origin: vec4) -> TerrainOut { - let pos = position + origin.xyz; + return terrain_vertex(position, uv, layer, color, light, origin.xyz); +} +// Flat section draws (gfx/flat.rs): one draw per arena page over the frame's +// index list. A section's vertices fill whole 256-vertex blocks of its page: +// the block gives its resident slot, the slot its camera-relative origin. +@group(1) @binding(0) var block_slots: array; +@group(1) @binding(1) var slot_origins: array>; +@vertex fn vs_terrain_flat( + @builtin(vertex_index) vertex: u32, + @location(0) position: vec3, @location(1) uv: vec2, + @location(2) layer: u32, @location(3) color: vec4, @location(4) light: vec2 +) -> TerrainOut { + let origin = slot_origins[block_slots[vertex >> 8u]]; + return terrain_vertex(position, uv, layer, color, light, origin.xyz); +} +fn terrain_vertex(position: vec3, uv: vec2, layer: u32, color: vec4, + light: vec2, origin: vec3) -> TerrainOut { + let pos = position + origin; var out: TerrainOut; out.clip = globals.view_proj * vec4(pos, 1.0); out.uv = uv; diff --git a/crates/horizon-client/src/testgen.rs b/crates/horizon-client/src/testgen.rs index e0a5d49b3..6268a8b6c 100644 --- a/crates/horizon-client/src/testgen.rs +++ b/crates/horizon-client/src/testgen.rs @@ -4,24 +4,24 @@ use crate::{chunk::Chunk, streaming::ChunkGenerator}; use horizon_world::registry::BlockRegistry; pub struct TestTerrain { - stone: u16, - dirt: u16, - grass: u16, - water: u16, - sand: u16, - bedrock: u16, - log: u16, - leaves: u16, - short_grass: u16, + stone: u32, + dirt: u32, + grass: u32, + water: u32, + sand: u32, + bedrock: u32, + log: u32, + leaves: u32, + short_grass: u32, plains: u16, } impl TestTerrain { pub fn new(registry: &BlockRegistry, biomes: &crate::biome::Biomes) -> crate::Result { - let id = |name: &str| -> crate::Result { + let id = |name: &str| -> crate::Result { Ok(registry .default_state(name) .ok_or_else(|| format!("missing {name}"))? - .0 as u16) + .0) }; Ok(Self { stone: id("minecraft:stone")?, @@ -41,7 +41,7 @@ impl TestTerrain { ] .into(), })? - .0 as u16, + .0, short_grass: id("minecraft:short_grass")?, plains: biomes.id("minecraft:plains"), }) diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client/src/text.rs index e9710e442..e0b144714 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client/src/text.rs @@ -233,6 +233,10 @@ impl Text { } /// The `Component` as vanilla's JSON (ComponentSerialization): the one /// built through the constructors, else the spans as literal siblings. + /// The key of a `Component.translatable` built through [`Text::translate`]. + pub fn translation_key(&self) -> Option<&str> { + self.source.as_deref()?.get("translate")?.as_str() + } pub fn component(&self) -> Value { if let Some(c) = &self.source { return (**c).clone(); diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index 6f0c4edaf..657817bb9 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -119,7 +119,7 @@ impl VanillaTerrain { chunk.terrain.min_y().max(MIN_Y), (chunk.terrain.min_y() + chunk.terrain.height()).min(MIN_Y + HEIGHT), ); - let mut values = Box::new([0u16; 4096]); + let mut values = Box::new([0u32; 4096]); for si in 0..SECTIONS as i32 { let base = MIN_Y + si * 16; if base + 16 <= lo || base >= hi { @@ -130,7 +130,7 @@ impl VanillaTerrain { for y in base.max(lo)..(base + 16).min(hi) { for z in 0..16 { for x in 0..16 { - let id = chunk.block(bx + x, y, bz + z).0 as u16; + let id = chunk.block(bx + x, y, bz + z).0; values[((y & 15) << 8 | z << 4 | x) as usize] = id; any |= id != 0; } diff --git a/crates/horizon-client/src/window.rs b/crates/horizon-client/src/window.rs index 7c77d85c6..33ff52111 100644 --- a/crates/horizon-client/src/window.rs +++ b/crates/horizon-client/src/window.rs @@ -128,6 +128,20 @@ pub fn vsync_present_mode(supported: &[PresentMode], vsync: bool) -> Option, +) -> Option { + setting + .filter(|m| !vsync && supported.contains(m)) + .or_else(|| vsync_present_mode(supported, vsync)) +} + /// `FramerateLimiter.limitDisplayFPS` with an injectable clock so the sleep /// and spin decisions are testable. #[derive(Clone, Debug)] @@ -415,4 +429,23 @@ mod tests { Some(PresentMode::Fifo) ); } + #[test] + fn vsync_on_waits_for_the_display_whatever_the_present_mode() { + use PresentMode::*; + let all = [Mailbox, Fifo, Immediate]; + for setting in [None, Some(Fifo), Some(Mailbox), Some(Immediate)] { + assert_eq!(chosen_present_mode(&all, true, setting), Some(Fifo)); + } + assert_eq!(chosen_present_mode(&all, false, None), Some(Immediate)); + assert_eq!( + chosen_present_mode(&all, false, Some(Mailbox)), + Some(Mailbox) + ); + assert_eq!(chosen_present_mode(&all, false, Some(Fifo)), Some(Fifo)); + // Metal has no Mailbox: vanilla's choice instead. + assert_eq!( + chosen_present_mode(&[Fifo, Immediate], false, Some(Mailbox)), + Some(Immediate) + ); + } } diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index 44e442ec1..05b89234c 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -21,7 +21,7 @@ pub struct World { pub dirty_light: crate::fast_hash::FxHashSet<(i32, i32)>, /// Edits on lit chunks (position, old state, new state), relit /// incrementally by streaming. - pub light_edits: Vec<((i32, i32, i32), u16, u16)>, + pub light_edits: Vec<((i32, i32, i32), u32, u32)>, /// Saved entities of chunks that just loaded, spawned by the game. pub loaded_entities: Vec<((i32, i32), Vec)>, /// Chunks changed since the last save. @@ -36,7 +36,7 @@ pub struct World { /// blocks, which need a block entity). pub watched: Vec, /// Writes of watched states: position, previous and new state. - pub watched_writes: Vec<((i32, i32, i32), u16, u16)>, + pub watched_writes: Vec<((i32, i32, i32), u32, u32)>, /// `ChunkAccess.inhabitedTime` of resident chunks: ticks a player spent /// within spawning range (local difficulty). pub inhabited: HashMap<(i32, i32), i64>, @@ -198,12 +198,11 @@ impl World { if y < MIN_Y || y >= MIN_Y + (SECTIONS as i32) * 16 { return Err("write outside world height".into()); } - let previous = Arc::make_mut(chunk).set(x & 15, y, z & 15, state.0 as u16); - if u32::from(previous) != state.0 { - let watches = |id: u16| self.watched.get(usize::from(id)).copied().unwrap_or(false); - if watches(previous) || watches(state.0 as u16) { - self.watched_writes - .push(((x, y, z), previous, state.0 as u16)); + let previous = Arc::make_mut(chunk).set(x & 15, y, z & 15, state.0); + if previous != state.0 { + let watches = |id: u32| self.watched.get(id as usize).copied().unwrap_or(false); + if watches(previous) || watches(state.0) { + self.watched_writes.push(((x, y, z), previous, state.0)); } self.revision = self.revision.wrapping_add(1); if let Some(log) = &mut self.block_log { @@ -225,7 +224,7 @@ impl World { } let _ = sy; if self.chunks.get(&(x >> 4, z >> 4)).is_some_and(|c| c.lit) { - self.light_edits.push(((x, y, z), previous, state.0 as u16)); + self.light_edits.push(((x, y, z), previous, state.0)); } else { for dz in -1..=1 { for dx in -1..=1 { diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index 8672ba5a4..4d6cd4e86 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -38,7 +38,7 @@ fn resources() -> Option { root.join("items.json").exists().then_some(root) } -const STONE: u16 = 1; +const STONE: u32 = 1; fn flat_world() -> World { let mut world = World::new(BlockStateId(0), 0); @@ -163,7 +163,7 @@ struct Server { hub: Hub, world: World, next_entity: u32, - placed: Vec<(u32, [i32; 3], u16, i32)>, + placed: Vec<(u32, [i32; 3], u32, i32)>, } impl Server { fn tick(&mut self, entities: &[EntityState]) { @@ -193,6 +193,7 @@ impl Server { clock_rate: 1.0, tick_rate: 20.0, tick_frozen: false, + collision: None, }; let events = self.hub.tick(&mut ctx); for event in events { @@ -202,7 +203,7 @@ impl Server { if let S::UseItemOn(p) = *packet { let at = [p.pos[0], p.pos[1] + 1, p.pos[2]]; ctx.world - .set(at[0], at[1], at[2], BlockStateId(u32::from(STONE))) + .set(at[0], at[1], at[2], BlockStateId(STONE)) .unwrap(); self.placed.push((conn, at, STONE, p.sequence)); self.hub.ack(conn, p.sequence); @@ -346,7 +347,7 @@ fn status_and_join() { chunks += 1; let sections = l.chunk.sections(24, 16, 7).map_err(|e| e.to_string())?; // The floor is in the lowest section. - assert_eq!(sections[0].states.get(4 * 256), i32::from(STONE)); + assert_eq!(sections[0].states.get(4 * 256), STONE as i32); assert_eq!(sections[0].non_empty, 256); assert_eq!(sections[1].non_empty, 0); assert!(!l.light.sky.is_empty()); @@ -392,7 +393,7 @@ fn status_and_join() { assert!(chunks >= 9, "only {chunks} chunks"); assert_eq!( block_update, - Some(([9, MIN_Y + 5, 9], i32::from(STONE))), + Some(([9, MIN_Y + 5, 9], STONE as i32)), "placed block was not broadcast" ); Ok(bot.name) diff --git a/crates/horizon-client/tests/streaming_meshes.rs b/crates/horizon-client/tests/streaming_meshes.rs index 74edd5049..6804d197e 100644 --- a/crates/horizon-client/tests/streaming_meshes.rs +++ b/crates/horizon-client/tests/streaming_meshes.rs @@ -107,7 +107,7 @@ fn columns_loaded_past_the_render_distance_mesh_when_they_come_in_range() { /// A one-block cave under the sky: a stone floor at y 62 with a glowstone, /// and a roof at y 64 with holes, so that every light change in the cave is /// sampled by a face. -fn roofed(x: i32, z: i32, stone: u16, glowstone: u16) -> Chunk { +fn roofed(x: i32, z: i32, stone: u32, glowstone: u32) -> Chunk { let mut chunk = Chunk::empty(x, z); for lz in 0..16 { for lx in 0..16 { @@ -143,7 +143,7 @@ fn relit_columns_keep_every_mesh_current() { biomes: Arc::new(Biomes::load(&root).unwrap()), assets: assets.clone(), }); - let state = |name: &str| assets.registry.default_state(name).unwrap().0 as u16; + let state = |name: &str| assets.registry.default_state(name).unwrap().0; let (stone, glowstone, torch) = ( state("minecraft:stone"), state("minecraft:glowstone"), @@ -185,9 +185,7 @@ fn relit_columns_keep_every_mesh_current() { let (bx, bz) = (16 + lx, lz); world.set(bx, 64, bz, BlockStateId(0)).unwrap(); if i % 3 == 0 { - world - .set(bx, 63, bz, BlockStateId(u32::from(torch))) - .unwrap(); + world.set(bx, 63, bz, BlockStateId(torch)).unwrap(); } } } diff --git a/crates/horizon-client/tests/wide_states.rs b/crates/horizon-client/tests/wide_states.rs new file mode 100644 index 000000000..690732ceb --- /dev/null +++ b/crates/horizon-client/tests/wide_states.rs @@ -0,0 +1,40 @@ +//! Block states past vanilla's 16-bit global palette (docs/modpacks.md): +//! content mods can take the registry past 65,536 states. Its own test binary, +//! since the palette width is set once for the whole process. + +use horizon_client::chunk::{Chunk, Section, block_strategy, set_block_states}; + +#[test] +fn sections_hold_states_past_sixteen_bits() { + // Vanilla's width until the registry needs more (one test: the width is + // global to the process). + assert_eq!(block_strategy().global_bits, 16); + set_block_states(35_723); + assert_eq!(block_strategy().global_bits, 16); + set_block_states(100_000); + assert_eq!(block_strategy().global_bits, 17); + + // A few states past 65,536 stay in the section's own palette. + let mut chunk = Chunk::empty(0, 0); + chunk.set(1, 70, 2, 70_000); + chunk.set(3, 70, 4, 99_999); + assert_eq!(chunk.get(1, 70, 2), 70_000); + assert_eq!(chunk.get(3, 70, 4), 99_999); + assert_eq!(chunk.get(0, 70, 0), 0); + + // More than 256 distinct states take the global palette at 17 bits. + let mut values = [0u32; 4096]; + for (i, v) in values.iter_mut().enumerate() { + *v = 65_000 + (i as u32 % 1000) * 30; + } + let mut section = Section { + blocks: Section::from_blocks(&values), + ..Section::default() + }; + let mut out = [0u32; 4096]; + section.unpack(&mut out); + assert_eq!(out, values); + section.set(17, 99_998); + assert_eq!(section.get(17), 99_998); + assert_eq!(section.get(18), values[18]); +} diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs index 33d63411a..280f21582 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -789,7 +789,7 @@ fn build_with_gameplay( // Collision shapes. let collision_tag = nbt::read_named( &fs::read(root.join("cached-collision.nbt"))?, - Limits::default(), + Limits::tables(), ) .map_err(|e| invalid(e.to_string()))? .0 diff --git a/crates/horizon-world/src/nbt.rs b/crates/horizon-world/src/nbt.rs index 7e4d76a41..414767795 100644 --- a/crates/horizon-world/src/nbt.rs +++ b/crates/horizon-world/src/nbt.rs @@ -100,11 +100,13 @@ impl Default for Limits { impl Limits { /// The prepared per-state block tables (`cached-collision.nbt`, /// `block-properties.nbt`, ...): trusted files with a row per block - /// state, which content mods' states grow past the default caps. + /// state, which content mods' states grow past the default caps + /// (vanilla's 35,723 states fill about a tenth of these; ATM10's ported + /// mods, 193,762 states, about half). pub fn tables() -> Self { Self { - max_bytes: 1 << 28, - max_nodes: 16_000_000, + max_bytes: 1 << 30, + max_nodes: 128_000_000, max_depth: 512, } } diff --git a/crates/horizon-world/src/registry.rs b/crates/horizon-world/src/registry.rs index 30367e251..5ca2e994a 100644 --- a/crates/horizon-world/src/registry.rs +++ b/crates/horizon-world/src/registry.rs @@ -5,7 +5,8 @@ use crate::{DATA_VERSION, chunk::BlockState, compression::invalid, nbt::Tag}; pub use json::BlockStateJsonCodec; pub(crate) use json::java_integer; use std::{ - collections::{BTreeMap, BTreeSet}, + collections::{BTreeMap, BTreeSet, HashMap}, + hash::{DefaultHasher, Hash, Hasher}, io, }; @@ -14,9 +15,25 @@ pub struct BlockStateId(pub u32); pub struct BlockRegistry { states: Vec, - ids: BTreeMap, + /// Ids by a hash of their state, checked against `states`: 12 bytes per + /// state instead of a second copy of every name and property map (about + /// 125 MB for a registry of 190,000 states). + ids: HashMap, + /// States whose hash an earlier state already took (none in vanilla). + collided: BTreeMap, defaults: BTreeMap, } +/// The hash [`BlockRegistry`] indexes states by (fixed keys: the same in +/// every process). +fn state_key(state: &BlockState) -> u64 { + let mut hasher = DefaultHasher::new(); + state.name.hash(&mut hasher); + for (key, value) in &state.properties { + key.hash(&mut hasher); + value.hash(&mut hasher); + } + hasher.finish() +} impl BlockRegistry { pub fn from_nbt(tag: &Tag) -> io::Result { if tag.get("DataVersion") != Some(&Tag::Int(DATA_VERSION)) { @@ -33,18 +50,25 @@ impl BlockRegistry { } let mut result = Self { states: Vec::with_capacity(entries.len()), - ids: BTreeMap::new(), + ids: HashMap::with_capacity(entries.len()), + collided: BTreeMap::new(), defaults: BTreeMap::new(), }; for (i, entry) in entries.iter().enumerate() { let state = BlockState::from_nbt(entry)?; - if result - .ids - .insert(state.clone(), BlockStateId(i as u32)) - .is_some() - { + if result.id(&state).is_some() { return Err(invalid("duplicate block registry state")); } + match result.ids.entry(state_key(&state)) { + std::collections::hash_map::Entry::Vacant(slot) => { + slot.insert(i as u32); + } + std::collections::hash_map::Entry::Occupied(_) => { + result + .collided + .insert(state.clone(), BlockStateId(i as u32)); + } + } result.states.push(state); } for (name, id) in defaults { @@ -82,7 +106,10 @@ impl BlockRegistry { self.states.get(id.0 as usize) } pub fn id(&self, state: &BlockState) -> Option { - self.ids.get(state).copied() + match self.ids.get(&state_key(state)) { + Some(&id) if self.states[id as usize] == *state => Some(BlockStateId(id)), + _ => self.collided.get(state).copied(), + } } pub fn default_state(&self, name: &str) -> Option { self.defaults.get(name).copied() diff --git a/crates/horizon-world/src/worldgen/feature_catalog.rs b/crates/horizon-world/src/worldgen/feature_catalog.rs index 0b8d56cc4..4db251114 100644 --- a/crates/horizon-world/src/worldgen/feature_catalog.rs +++ b/crates/horizon-world/src/worldgen/feature_catalog.rs @@ -192,7 +192,7 @@ impl FeatureCatalog { if names.is_empty() { return Ok(serde_json::to_string(&format!("#{tag}"))?); } - if names.len() > 8192 { + if names.len() > super::state_provider::MAX_TAG_BLOCKS { return Err(DecodeError::Field("placed-feature tag size")); } names diff --git a/crates/horizon-world/src/worldgen/state_provider.rs b/crates/horizon-world/src/worldgen/state_provider.rs index 37e9c866b..098decdf1 100644 --- a/crates/horizon-world/src/worldgen/state_provider.rs +++ b/crates/horizon-world/src/worldgen/state_provider.rs @@ -93,7 +93,7 @@ impl<'r> StateProviderBindings<'r> { } let mut bound_tags = BTreeMap::new(); for (name, entries) in tags { - if entries.len() > 8192 { + if entries.len() > MAX_TAG_BLOCKS { return Err(DecodeError::Field("provider tag size")); } let values = entries @@ -558,6 +558,11 @@ impl BlockStateProvider { } } +/// Blocks a bound block tag may list (8,192 before content mods, vanilla's +/// tags fit well within it): content mods' blocks join the shared tags +/// (`mineable/pickaxe` takes every stone block of a pack). +pub(crate) const MAX_TAG_BLOCKS: usize = 1 << 20; + /// Bind the pinned registry's full-axis/full-facing/horizontal-facing property /// families. A five-way facing or two-axis property is a different property and /// is intentionally left unchanged. Unrelated properties retain their values. diff --git a/crates/horizon-world/tests/state_provider_bounds.rs b/crates/horizon-world/tests/state_provider_bounds.rs index 033d4675c..23553e6b7 100644 --- a/crates/horizon-world/tests/state_provider_bounds.rs +++ b/crates/horizon-world/tests/state_provider_bounds.rs @@ -41,7 +41,13 @@ fn bound_recursive_providers_and_registry_lists_before_sampling() { let branching = serde_json::json!({"if_true":{"type":"all_of","predicates":vec![serde_json::json!({"type":"true"});7]},"then":{"id":"stone"}}); let oversized = serde_json::json!({"type":"rule_based","rules":vec![branching;8192]}); assert!(BlockStateProvider::from_json(&oversized.to_string(), &bindings).is_err()); - let tags = BTreeMap::from([("horizon:oversized".into(), vec!["stone".into(); 8193])]); + // Content mods' blocks join shared tags: the cap is 2^20 blocks. + let tags = BTreeMap::from([("horizon:large".into(), vec!["stone".into(); 8193])]); + assert!(StateProviderBindings::new(®istry, BTreeSet::new(), &tags).is_ok()); + let tags = BTreeMap::from([( + "horizon:oversized".into(), + vec!["stone".into(); (1 << 20) + 1], + )]); assert!(StateProviderBindings::new(®istry, BTreeSet::new(), &tags).is_err()); let tags = BTreeMap::from([("tag".into(), vec![]), ("minecraft:tag".into(), vec![])]); assert!(StateProviderBindings::new(®istry, BTreeSet::new(), &tags).is_err()); diff --git a/docs/README.md b/docs/README.md index 7cf322042..9a5ea0483 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,7 +6,8 @@ To play, use [the launcher](../launcher/README.md); the project site is [playhor - [Build from source](../README.md#build-from-source): your own copy of the game, resource preparation, `cargo run`. - [Native client](native-client.md): options, controls, the dedicated server, `horizon-ctl` scripting, packaging, architecture. -- [Hosting a server](server.md): `horizon-server`, the design and the plan: install, `server.toml`, the CLI, the web panel, backups, services, Docker, and the bot benchmark against vanilla. +- [Host a server](hosting.md): install `horizon-server`, prepare the game files, first run, `server.toml`, the commands, the web panel, backups, services and Docker; what works today and what doesn't yet. +- [Hosting a server: design](server.md): `horizon-server`, the design and the plan: install, `server.toml`, the CLI, the web panel, backups, services, Docker, and the bot benchmark against vanilla. - [Agent control](agent-control.md): what AI agents can drive in the launcher and the game, and the design of the control socket, `horizon-ctl` and MCP. - [Graphics](graphics.md): the Simple and Advanced graphics settings, the graphics benchmark and what it measured. - [Benchmark](benchmark.md): Horizon against vanilla 26.3 and vanilla with performance mods, on the same machine, world, path and settings: what is measured, how it is kept fair, how to reproduce it. diff --git a/docs/graphics.md b/docs/graphics.md index a55313bea..7fa69577e 100644 --- a/docs/graphics.md +++ b/docs/graphics.md @@ -25,7 +25,7 @@ Every row has a one-line description and its cost in frame time (none, low, medi | Performance | battery mode, worker threads, upload budget per frame | `horizon-graphics.txt` | | Overlay | performance overlay: FPS, frame/CPU/GPU times, frame-time graph | `horizon-graphics.txt` | -`options.txt` keeps exactly vanilla's keys and values, so the options harness still compares it with vanilla; Horizon's settings live in `horizon-graphics.txt` beside it. Their defaults render as vanilla does: cave culling on, no upload budgets, sky, fog and weather on, 100% resolution, no FXAA, the present mode following VSync. Frame pacing defaults to Efficient: the limiter sleeps through the last half millisecond where vanilla spins, which changes timing, not pixels. +`options.txt` keeps exactly vanilla's keys and values, so the options harness still compares it with vanilla; Horizon's settings live in `horizon-graphics.txt` beside it. Their defaults render as vanilla does: cave culling on, no upload budgets, sky, fog and weather on, 100% resolution, no FXAA, the present mode following VSync. VSync on always waits for the display (Fifo), in a window and in fullscreen, as in vanilla; the present mode setting chooses how frames are shown only while VSync is off. Frame pacing defaults to Efficient: the limiter sleeps through the last half millisecond where vanilla spins, which changes timing, not pixels. **Battery mode** (Performance, off by default) is for laptops and handhelds: at most 60 frames per second in a world, 30 in menus without a world or while another window has focus, and half the automatic worker threads (chunks load slower). It changes only when frames are drawn: what they show and the game's 20 ticks per second stay as they are. diff --git a/docs/hosting.md b/docs/hosting.md new file mode 100644 index 000000000..f07983484 --- /dev/null +++ b/docs/hosting.md @@ -0,0 +1,326 @@ +# Host a server + +`horizon-server` hosts a Minecraft Java Edition 26.3 server with Horizon's own game as the engine: one native +program, no Java, one settings file, a command line, and a web panel. Vanilla 26.3 clients and Horizon clients +can join it. This page covers what works on `main` today and says plainly what doesn't yet. The design and the +plan are in [docs/server.md](https://github.com/ludovic111/horizon/blob/main/docs/server.md). + +## Before you start + +- **Online mode checks accounts** (release v2026.10.17.07 and newer). With `online_mode = true`, the + default, players who sign in with the official Minecraft launcher join with their own accounts, as on a + vanilla server. +- **Names you add are accounts** (release v2026.10.17.14 and newer). `init --player`, `horizon-server + whitelist add` and `op`, and the console's `whitelist add`, `op` and `ban` look a name up the way vanilla + does: players already seen (kept in `usercache.json`), then Mojang's profile service. In online mode a name + with no account is refused. So you can whitelist friends before they first join. +- **Horizon's own client can't sign in to a Microsoft account yet.** That needs an Azure app registration and + Mojang's approval, which the project doesn't have + ([docs/microsoft-account.md](https://github.com/ludovic111/horizon/blob/main/docs/microsoft-account.md)). + Until then Horizon players can join offline servers only (`online_mode = false`). An offline server never + checks accounts: anyone who reaches it can join under any name. Keep it on your LAN or a tailnet + (Tailscale, ZeroTier), or share it only with friends you trust. +- **No secure chat.** Chat isn't signed, and `enforce-secure-profile` has no effect. Vanilla clients show + chat from the server as not secure. +- **Nether and End:** the world follows a player through portals when they are alone on the server + (v2026.10.17.09 and newer). With several players online, portals don't move remote players yet. +- **Movement checks and chunk pacing** (release v2026.10.17.16 and newer). The server pulls back players who + move too fast ("moved too quickly"), as vanilla does, and sends chunks as fast as each client acknowledges + them. +- **No Docker image is published.** You build it yourself from the repository (below). Publishing an image + needs the project owner. +- Nothing of Mojang's is downloaded or shipped. The server reads the game files you prepare from your own copy + of Minecraft 26.3. + +## 1. Install + +Linux (x86-64) and macOS (Apple Silicon): + +```sh +curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.sh | sh +``` + +Windows (x64), in PowerShell: + +```powershell +irm https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.ps1 | iex +``` + +The script downloads the latest Horizon release for your computer from GitHub, checks it against the SHA-256 +GitHub publishes, and never asks for sudo or administrator rights. It installs: + +- the release in `~/.local/share/horizon/releases/` (Windows: `%LOCALAPPDATA%\Horizon`), with + `current` pointing at the one in use; +- `horizon-server` and `horizon-prepare` in `~/.local/bin` (Windows: added to your PATH); +- a `game-files` folder for the files you prepare, kept across updates. + +Options: `--version vX.Y.Z`, `--dir FOLDER`, `--bin FOLDER` (Windows: `-Version`, `-Dir`). Other systems, +such as Linux on ARM, build from source: `cargo build --release -p horizon-client --bin horizon-client -p +horizon-server` and keep both programs in one folder. + +The Horizon launcher also installs releases. Every release folder holds `horizon-server`, so you can run it +from there too. + +## 2. Prepare the game files + +Horizon reads Minecraft's data from your own copy of the game. You need Minecraft Java Edition 26.3, played +once from the official launcher on this computer, Java 25 (a JDK), and the 26.3 `server.jar`: it's the +`downloads.server.url` in your launcher's `versions/26.3/26.3.json`. Then: + +```sh +horizon-prepare --prepare --server-jar /path/to/server.jar +``` + +Add `--minecraft-dir PATH` if your launcher keeps the game elsewhere. The prepared files go to +`game-files`, which updates keep. + +**On a headless machine** (a VPS, a home server), prepare on your own computer instead, with the launcher or +`horizon-prepare`, and copy the prepared `26.3` folder to the server: into +`~/.local/share/horizon/game-files/horizon-client/26.3`, or into `resources/` in the server folder, or anywhere +`[engine] resources` in `server.toml` names. A folder copied this way needs release v2026.10.17.07 or +newer: older ones don't keep `registries.json` and `commands.json` with the prepared files, and the +server then stops with "registries.json not found next to the resources". Prepare again with a newer release. + +## 3. First run + +```sh +mkdir my-server && cd my-server +horizon-server init +``` + +`init` asks five things and writes `server.toml`: + +1. whether you agree to the [Minecraft EULA](https://aka.ms/MinecraftEULA): only a yes writes `eula=true`; +2. the world's name and an optional seed (an existing world or vanilla server folder is kept and its + `server.properties` imported); +3. the port, 25565 by default; +4. whether to use a whitelist (yes by default, as in vanilla) and who to add; +5. whether to make the first player an operator. + +It then tells you where it found the game and its files. Every question has a flag, so it also runs from a +script: + +```sh +horizon-server init --eula --world survival --seed 12345 --port 25565 --whitelist --player Alex --op Alex --yes +``` + +`--no-whitelist` turns the whitelist off, and `--offline` turns online mode off (see "Before you start"). +The players you add are looked up as Minecraft accounts in online mode, and get offline UUIDs on an offline +server, as vanilla does. + +Start the server in the foreground, with the console on your terminal (Ctrl-C stops it cleanly): + +```sh +horizon-server run +``` + +or in the background: + +```sh +horizon-server start +horizon-server status +``` + +```text +Running, up 29 s +TPS 20.0, MSPT 1.0 ms average, 3.1 ms P95 +0 of 20 players, 377 chunks loaded +RAM 1.42 GB, CPU 2 % of a core +``` + +Players join at your computer's address and the port (`192.168.1.20:25565`, or a tailnet name). Every +command takes `--dir FOLDER` to work on a server folder from elsewhere. + +## 4. Settings: `server.toml` + +You edit one file. The server writes vanilla's `server.properties` from it before every start, so the game +reads exactly what a vanilla server reads, and a vanilla server folder works as it is. + +```toml +[server] +motd = "A Minecraft Server" +port = 25565 +bind = "" # listen on every address, or only on this one (server-ip) +max_players = 20 +online_mode = true # check accounts with Mojang (see "Before you start") +whitelist = true +enforce_whitelist = false +view_distance = 10 +simulation_distance = 10 + +[world] +name = "world" +seed = "" # empty: a random seed on the first start +game_mode = "survival" +difficulty = "easy" +hardcore = false + +# Any other server.properties key, spelled as vanilla spells it: +[properties] +# spawn-protection = 16 + +[engine] +path = "" # the game program; empty: the one beside horizon-server +resources = "" # the prepared game files; empty: resources/ here, else the usual places +restart_on_crash = true + +[backups] +every = "6h" # 30m, 6h, 1d...; "0" turns automatic backups off +keep = 12 # automatic backups kept; backups made by hand are never deleted + +[panel] +bind = "127.0.0.1:8130" # this computer only, or a tailnet address (100.x); "" turns it off +allow_public = false +``` + +The defaults are vanilla 26.3's. Unknown keys and values vanilla would refuse are errors, so a typo stops the +start instead of being ignored. When the game changes a setting itself (`/whitelist on`), the change is copied +back into `server.toml` when it stops, and your comments are kept. Changes to the file apply at the next +restart: there is no live reload yet. + +Already have a vanilla server? Run `horizon-server init` in its folder, or `horizon-server import +server.properties` to write `server.toml` from it. The world, `ops.json`, `whitelist.json` and the ban lists +keep vanilla's names and formats, so going back to vanilla works too. + +## 5. Commands + +```text +horizon-server init first run +horizon-server run in the foreground, with the console; Ctrl-C stops it +horizon-server start | stop | restart in the background (its output goes to logs/supervisor.log) +horizon-server status [--json] up or not, TPS, MSPT, players, chunks, RAM, CPU +horizon-server cmd COMMAND... one console command, and what it answers +horizon-server logs [-f] [-n N] the log; -f follows it +horizon-server op|deop NAME +horizon-server whitelist on|off|list +horizon-server whitelist add|remove NAME +horizon-server backup [NAME] back up now +horizon-server backups list the backups +horizon-server restore BACKUP [--yes] +horizon-server service install|uninstall|print [--system] +horizon-server panel a one-time login link for the web panel +horizon-server import FILE server.toml from a vanilla server.properties +``` + +While the server runs, `op`, `whitelist` and `cmd` go to the game's console, so they act exactly as vanilla's +console commands do. While it's stopped, they edit vanilla's files directly. Any console command works through +`cmd`: `horizon-server cmd ban Griefer`, `horizon-server cmd say Restarting in 5 minutes`. + +The server restarts the game by itself if it crashes: after 5 s, then waiting longer each time, up to 5 +minutes. It keeps the crash report and gives up after 5 crashes in 10 minutes, and `status` says why. + +Coming: `update` and `rollback`, `console` (attach to a server running in the background), `ban` and +`pardon` as their own commands, and `mcp` (an MCP server so an AI assistant can run the server). + +## 6. Web panel + +The panel runs inside `horizon-server` while the server runs. It shows live TPS, MSPT, RAM and CPU graphs for +the last 10 minutes, the players with their ping (and a kick button), the console with a command line, and the +backups (back up now, restore with a confirmation), with Restart and Stop. + +```sh +horizon-server panel +``` + +prints a login link that works once, for 10 minutes. The panel listens on `127.0.0.1:8130`, this computer +only. To reach it from your other devices: + +- put your tailnet address in `[panel] bind` (for example `bind = "100.101.102.103:8130"`), or +- forward the port over SSH: `ssh -L 8130:127.0.0.1:8130 your-server`, then open the link on your computer. + +Any other address, such as `0.0.0.0` or a public IP, is refused unless you set `allow_public = true`, and +even then the panel warns at every start. It has no passwords to leak: whoever can read the server folder can +make a login link, and no one else can. Never put it on the open internet. + +## 7. Backups + +```sh +horizon-server backup before-the-update +horizon-server backups +horizon-server restore before-the-update +``` + +A backup zips the world, vanilla's files and `server.toml` into `backups/`. A running server saves first and +stays up: players don't notice. Automatic backups run on the `[backups] every` schedule while the server runs, +and the oldest automatic ones beyond `keep` are deleted. Backups you make by hand are never deleted. + +`restore` takes a backup's file name, a unique start of it, or the name you gave it. It moves the current +world aside to `backups/replaced-