diff --git a/.github/workflows/cancel-on-close.yml b/.github/workflows/cancel-on-close.yml new file mode 100644 index 000000000..9a6e44965 --- /dev/null +++ b/.github/workflows/cancel-on-close.yml @@ -0,0 +1,27 @@ +name: cancel-on-close +# A closed or merged pull request's queued and running checks free the runners at once. +# pull_request_target so the token can cancel runs of pull requests from forks too; +# it checks out nothing and runs no code from the pull request. +on: + pull_request_target: + types: [closed] +permissions: + actions: write +jobs: + cancel: + runs-on: ubuntu-latest + steps: + - name: Cancel the pull request's unfinished runs + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + BRANCH: ${{ github.event.pull_request.head.ref }} + SHA: ${{ github.event.pull_request.head.sha }} + run: | + for status in queued in_progress waiting pending requested; do + gh run list -R "$REPO" --branch "$BRANCH" --status "$status" --limit 100 \ + --json databaseId,event,headSha \ + -q ".[] | select(.event == \"pull_request\" and .headSha == \"$SHA\") | .databaseId" + done | sort -u | while read -r id; do + gh run cancel -R "$REPO" "$id" || true + done diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5d5e285c5..da23874b8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,6 +56,8 @@ jobs: run: | cargo +stable fmt --all -- --check cargo +stable clippy --workspace --all-targets -- -D warnings + # The server build (released as horizon-engine): the game without sound or controllers. + cargo +stable clippy -p horizon-client --all-targets --no-default-features -- -D warnings - name: Test Rust core and voxel kernel correctness if: steps.rust.outputs.required != 'false' run: cargo +stable test --workspace diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a4780c85b..bd916514b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -76,6 +76,9 @@ jobs: os: ubuntu-22.04 dir: horizon-linux-x86_64 asset: horizon-linux-x86_64.tar.gz + # The server build too: packaging/server/install.sh installs it on Linux. + server_dir: horizon-server-linux-x86_64 + server_asset: horizon-server-linux-x86_64.tar.gz - name: windows os: windows-latest dir: horizon-windows-x64 @@ -190,6 +193,29 @@ jobs: path: dist/${{ matrix.asset }} if-no-files-found: error retention-days: 3 + - name: The server build (the game without sound or controllers, as horizon-engine) + if: matrix.server_asset + run: | + set -euo pipefail + # After the client is packaged: target/release/horizon-client is rebuilt without the audio and + # controllers features, so it needs neither libasound nor libudev (minimal server images lack them). + cargo build --release --locked -p horizon-client --no-default-features --bin horizon-client + cargo run --locked -p xtask -- package-server target/release/horizon-client "dist/${{ matrix.server_dir }}" + folder="dist/${{ matrix.server_dir }}" + python3 tools/check_imports.py --server "$folder/horizon-engine" "$folder/horizon-server" "$folder/horizon-prepare" + "$folder/horizon-engine" --help | grep -q -- '--resources' + "$folder/horizon-server" --version + cd dist + rm -f "${{ matrix.server_asset }}" + tar czf "${{ matrix.server_asset }}" "${{ matrix.server_dir }}" + ls -l "${{ matrix.server_asset }}" + - uses: actions/upload-artifact@v4 + if: matrix.server_asset + with: + name: ${{ matrix.server_asset }} + path: dist/${{ matrix.server_asset }} + if-no-files-found: error + retention-days: 3 publish: needs: [decide, build] @@ -220,7 +246,7 @@ jobs: run: | gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \ --notes-file notes/body.md --latest dist/horizon-linux-x86_64.tar.gz dist/horizon-windows-x64.zip \ - dist/horizon-macos-arm64.zip + dist/horizon-macos-arm64.zip dist/horizon-server-linux-x86_64.tar.gz - name: Dry run, the release that would be published if: needs.decide.outputs.dry_run == 'true' run: | diff --git a/Cargo.lock b/Cargo.lock index 2f389dfef..94e2052e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1435,6 +1435,7 @@ dependencies = [ "naga", "png", "pollster", + "rustix 1.1.5", "serde", "serde_json", "sha2", @@ -1539,6 +1540,7 @@ dependencies = [ "horizon-world", "serde_json", "sha1", + "sha2", ] [[package]] @@ -1554,6 +1556,7 @@ dependencies = [ name = "horizon-server" version = "0.1.0" dependencies = [ + "chrono", "horizon-bench", "horizon-server-files", "libc", @@ -1569,6 +1572,7 @@ dependencies = [ name = "horizon-server-files" version = "0.1.0" dependencies = [ + "base64", "horizon-core", "horizon-protocol", "horizon-world", diff --git a/benchmarks/server-equal-mixed-2026-10-18/README.md b/benchmarks/server-equal-mixed-2026-10-18/README.md new file mode 100644 index 000000000..5849e72ba --- /dev/null +++ b/benchmarks/server-equal-mixed-2026-10-18/README.md @@ -0,0 +1,137 @@ +# Horizon's server against vanilla 26.3: mixed bots, equal work (2026-10-18) + +This reruns `../server-mixed-2026-10-18/` with the bots' load made the same on both servers. In that run the +`explore` bots flew as fast as each server sent them chunks. Horizon kept up and vanilla didn't, so Horizon +sent 2.9 to 5.9 times as many chunks a second, and vanilla's walking bots got a fifth of the chunks Horizon's +got. The comparison of tick times wasn't fair. + +## Summary + +- **The work was equal** at 1 and 10 bots. At 25 bots it was equal in chunks sent a second (158.6 against 157.6); + vanilla was still catching up on chunks its bots hadn't had yet, see "Equal work" below. Every bot joined, none + was dropped, no chunk was sent twice, and no bot ever waited for the chunk it stood in. +- **Tick time (MSPT), same work:** + - 1 bot: 1.8 ms on Horizon against 11.3 on vanilla; + - 10 bots: 4.7 against 34.3 ms; + - 25 bots: 11.7 against 50.5 ms. Vanilla dropped just under 20 TPS (19.8) and its worst 5-second P99 was + 1388 ms, against Horizon's 130; + - 50 bots: Horizon ran at 23.8 ms (20 TPS). Vanilla's watchdog stopped its server 30 s after the last bot + joined ("A single server tick took 60.01 seconds"). +- **Memory:** Horizon's RSS was 4.1 to 4.9 times smaller: 0.69 against 3.40 GB with one bot, 0.95 against + 3.87 GB with 25, and 1.03 GB with 50. Vanilla's heap is fixed at 4 GB, so its RSS is mostly that heap. +- **CPU** (100 % is one of the machine's 4 threads): 30 against 128 % at 10 bots, 58 against 192 % at 25. +- **What changed since the first run:** the first run's vanilla held 50 bots at 29.7 ms because its walking + bots got 640 to 1100 chunks each. With the explore bots paced, vanilla serves the walking bots in full + (5400 to 6100 chunks each, against Horizon's 6100 to 6600), and that is the load it can't carry at 50. + +## Results + +MSPT is milliseconds per tick from each server's own `/tick query` (50 is the limit for 20 TPS). P95 and P99 +are over the 300 measured seconds. "Worst P99" is the highest P99 of a single 5-second query. RSS and CPU +cover the server's process tree. "First-time chunks/s" counts chunks a bot hadn't received before (summed +over the bots). "Waited" is ticks a second that bots stood still waiting for their own chunk. "Pulled back" +counts position packets that moved a bot back. + +| Bots | Server | MSPT | P95 | P99 | Worst P99 | TPS | RSS (mean / max) | CPU | Start | Chunks/s | First-time chunks/s | Waited | Pulled back | +|---:|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| 1 | Horizon | **1.77** | 4.21 | 13.04 | 47.5 | 20 | **0.69 / 0.69 GB** | 28 % | 19.7 s | 9.94 | 0.01 | 0 | 0 | +| 1 | vanilla | 11.34 | 17.12 | 33.22 | 119.1 | 20 | 3.40 / 3.42 GB | 36 % | 20.4 s | 9.98 | 0.01 | 0 | 0 | +| 10 | Horizon | **4.74** | 10.48 | 19.69 | 120.1 | 20 | **0.86 / 0.88 GB** | 30 % | 19.5 s | 61.35 | 1.79 | 0 | 4159 | +| 10 | vanilla | 34.30 | 53.72 | 89.08 | 375.8 | 20 | 3.71 / 3.75 GB | 128 % | 19.9 s | 61.66 | 1.93 | 0 | 3976 | +| 25 | Horizon | **11.72** | 24.45 | 43.79 | 129.8 | 20 | **0.95 / 1.09 GB** | 58 % | 9.6 s | 158.57 | 5.78 | 0 | 3496 | +| 25 | vanilla | 50.45 | 74.09 | 191.21 | 1388.1 | 19.82 | 3.87 / 4.75 GB | 192 % | 37.8 s | 157.63 | 8.25 | 0 | 3629 | +| 50 | Horizon | **23.82** | 50.98 | 74.64 | 195.9 | 20 | **1.03 / 1.20 GB** | 98 % | 14.9 s | 302.81 | 10.96 | 0 | 7565 | +| 50 | vanilla | stopped by its watchdog | | | | | | | 11.2 s | | | | | + +Chunks each bot received over the whole run, by behaviour (mean): + +| Bots | Server | walk | explore | idle | +|---:|---|---:|---:|---:| +| 1 | Horizon | 6092 | | | +| 1 | vanilla | 6084 | | | +| 10 | Horizon | 6248 | 1165 | 473 | +| 10 | vanilla | 5729 | 1124 | 473 | +| 25 | Horizon | 6629 | 1267 | 473 | +| 25 | vanilla | 5387 | 1119 | 473 | +| 50 | Horizon | 6497 | 1256 | 473 | + +Both servers pulled bots back about as often (`moved too quickly` 20 and 296 times on vanilla at 10 and 25 +bots). + +## Equal work + +`tools/server_bench.py` now prints a work table after the runs. At each bot count it compares every server's +chunks sent a second and first-time chunks a second with the busiest server's. Work counts as equal when +both are within 10 % (or within a chunk a second when there are few). The report keeps the table as `work`. + +| Bots | Chunks/s (Horizon, vanilla) | First-time chunks/s (Horizon, vanilla) | Equal | +|---:|---|---|---| +| 1 | 9.94, 9.98 | 0.01, 0.01 | yes | +| 10 | 61.35, 61.66 | 1.79, 1.93 | yes | +| 25 | 158.57, 157.63 | 5.78, 8.25 | no: vanilla sent 2.5 more first-time chunks a second | + +Two settings made the load the same: + +- **Explore bots paced at 0.8 blocks a second** (`--explore-speed 0.8`), the rate the 2026-10-17 run showed + both servers keep up with. Every bot then follows the same path on both servers. The path is deterministic + per bot, and a bot only stops while the chunk it stands in hasn't arrived, which never happened here + (`Waited` 0). So both servers had the same chunks to send. +- **A 300-second warm-up** before the 300 measured seconds. A first pass with the old 60-second warm-up + (aborted after 10 bots) sent the same chunks a second on both (63.1 against 61.4). But vanilla was still + delivering the bots' first views during the measurement (12.9 first-time chunks a second against Horizon's + 4.1), so its window held more work than Horizon's. With 300 seconds both were in steady state at 1 and 10 + bots. At 25, vanilla still sent 2.5 more first-time chunks a second than Horizon: 1.6 % of all it sent, and + its walking bots ended the run with 19 % fewer chunks. Read the 25-bot tick times with that in mind: the + extra first-time chunks are work vanilla had still to do because it fell behind. + +## Method + +`tools/server_bench.py` ran 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`, white-list off; +- `gamerule respawn_radius 0`, and otherwise vanilla's default game rules (the locator bar on for both); +- the server waits for `Done`, the bots join one a second, warm up for 300 seconds and are measured for 300, + with `/tick query` every 5 seconds and RSS and CPU every second. + +The bots are `horizon-bots --behaviour mixed`: 60 % walk, 20 % explore and 20 % idle, each choice deterministic +per bot. All are creative and fly 24 blocks above spawn. `walk` flies to random points within 48 blocks at +5.6 blocks a second, `explore` flies straight out at 0.8 blocks a second, and `idle` hovers. + +**Machine.** The ThinkPad: Intel Core i7-7500U (2 cores, 4 threads), 32 GB, NixOS. The desktop (24 threads) +was meant to run it, but it didn't wake (`~/fleet/power wake desktop` timed out, as it did for the first run). +No other session ran on the ThinkPad during the runs (`load.txt`, a sample a minute). The servers ran under +`nice -n 19`. The bots ran on the Mac mini (M4 Pro, shared with other work at 70 to 90 % CPU) and reached the +ThinkPad over the tailnet. + +**What ran.** + +- Horizon: the server build from #916 (`horizon-client --no-default-features`, no sound or controllers) at + 519ec121, packaged with `xtask package-server` and installed with `install.sh --archive`, as Linux owners + will get it. `horizon-server` ran it as `horizon-engine`. The game files were prepared from the owner's own + Minecraft. `horizon-bots` and `server_bench.py` came from this PR. +- Vanilla: the pinned 26.3 server jar (the owner's own copy) on OpenJDK 25.0.4.1, `-Xms4g -Xmx4g`. + +`server_bench.py` stopped after vanilla's 50-bot server crashed and before it wrote its report. +`mixed-equal.json` holds the run lines it printed. The vanilla 50 entry and its error come from that server's +log, and the `work` table was computed with `server_bench.work`. `load.txt` is the fleet monitor's view of the +machines during the runs. + +## Reproduce + + curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.sh | sh + horizon-prepare --prepare --server-jar /path/to/server.jar # your own copy + cargo build --release -p horizon-bots # on the machine that runs the bots + # in a checkout whose .local/minecraft holds the pinned vanilla jars (tools/lab.py prepare): + HORIZON_BENCH_BIN=~/.local/share/horizon/current \ + python3 tools/server_bench.py --servers horizon,vanilla --bots 1,10,25,50 --behaviour mixed \ + --explore-speed 0.8 --warmup 300 --nice 19 \ + --bots-via 'ssh ' --bots-bin /path/to/horizon-bots --connect \ + --out mixed-equal.json + +## Next + +- One pass per configuration ran. Vanilla at 50 bots, in particular, needs a second pass, ideally on the + desktop (24 threads), where neither server is CPU-bound. +- 100 bots, and Paper and Fabric + Lithium (docs/server.md section 9). +- A longer warm-up, or measuring from when the first-time chunk rate settles, so the 25-bot work is equal too. diff --git a/benchmarks/server-equal-mixed-2026-10-18/load.txt b/benchmarks/server-equal-mixed-2026-10-18/load.txt new file mode 100644 index 000000000..2992b4a26 --- /dev/null +++ b/benchmarks/server-equal-mixed-2026-10-18/load.txt @@ -0,0 +1,702 @@ +2026-10-18T19:32:39Z +ludothinkpad ok: 27.2 GB free, 4 threads 17% busy, 0 sessions +desktop offline +macmini ok: 25.9 GB free, 14 threads 73% busy, 1 sessions +macbook offline + RAM 27.0 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 42% busy (agents 0.0, rest 1.6 cores) · 80°C · load 5.9 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:33:44Z +ludothinkpad ok: 26.7 GB free, 4 threads 19% busy, 0 sessions +desktop offline +macmini busy: 26.7 GB free, 14 threads 93% busy, 1 sessions +macbook offline + RAM 26.7 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 34% busy (agents 0.0, rest 1.7 cores) · 81°C · load 4.0 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:34:48Z +ludothinkpad ok: 26.4 GB free, 4 threads 56% busy, 0 sessions +desktop offline +macmini busy: 26.9 GB free, 14 threads 90% busy, 1 sessions +macbook offline + RAM 26.4 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 54% busy (agents 0.0, rest 2.2 cores) · 79°C · load 2.8 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:35:52Z +ludothinkpad ok: 26.7 GB free, 4 threads 27% busy, 0 sessions +desktop offline +macmini ok: 25.4 GB free, 14 threads 85% busy, 1 sessions +macbook offline + RAM 26.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 30% busy (agents 0.0, rest 1.1 cores) · 82°C · load 2.2 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:36:57Z +ludothinkpad ok: 26.7 GB free, 4 threads 25% busy, 0 sessions +desktop offline +macmini busy: 25.4 GB free, 14 threads 93% busy, 1 sessions +macbook offline + RAM 26.7 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 37% busy (agents 0.0, rest 1.2 cores) · 80°C · load 1.5 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:38:01Z +ludothinkpad ok: 26.6 GB free, 4 threads 54% busy, 0 sessions +desktop offline +macmini ok: 26.7 GB free, 14 threads 64% busy, 1 sessions +macbook offline + RAM 26.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 21% busy (agents 0.0, rest 1.2 cores) · 81°C · load 1.9 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:39:05Z +ludothinkpad ok: 26.7 GB free, 4 threads 20% busy, 0 sessions +desktop offline +macmini ok: 26.1 GB free, 14 threads 70% busy, 1 sessions +macbook offline + RAM 26.7 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 28% busy (agents 0.0, rest 1.0 cores) · 81°C · load 1.3 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:40:10Z +ludothinkpad ok: 26.7 GB free, 4 threads 39% busy, 0 sessions +desktop offline +macmini ok: 29.2 GB free, 14 threads 73% busy, 1 sessions +macbook offline + RAM 26.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 32% busy (agents 0.0, rest 1.7 cores) · 80°C · load 0.9 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:41:14Z +ludothinkpad ok: 26.7 GB free, 4 threads 31% busy, 0 sessions +desktop offline +macmini ok: 28.8 GB free, 14 threads 77% busy, 1 sessions +macbook offline + RAM 26.7 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 15% busy (agents 0.0, rest 1.1 cores) · 82°C · load 1.3 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:42:19Z +ludothinkpad ok: 26.5 GB free, 4 threads 26% busy, 0 sessions +desktop offline +macmini busy: 26.1 GB free, 14 threads 94% busy, 1 sessions +macbook offline + RAM 26.2 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 30% busy (agents 0.0, rest 1.3 cores) · 78°C · load 1.1 + · disk 289.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:43:23Z +ludothinkpad busy: 26.7 GB free, 4 threads 99% busy, 0 sessions +desktop offline +macmini ok: 28.2 GB free, 14 threads 83% busy, 1 sessions +macbook offline + RAM 26.3 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 99% busy (agents 0.0, rest 3.8 cores) · 86°C · load 2.4 + · disk 289.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:44:27Z +ludothinkpad busy: 25.2 GB free, 4 threads 98% busy, 0 sessions +desktop offline +macmini ok: 29.0 GB free, 14 threads 73% busy, 1 sessions +macbook offline + RAM 24.9 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 83% busy (agents 0.0, rest 3.7 cores) · 83°C · load 5.5 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:45:31Z +ludothinkpad ok: 24.5 GB free, 4 threads 39% busy, 0 sessions +desktop offline +macmini busy: 27.0 GB free, 14 threads 93% busy, 1 sessions +macbook offline + RAM 24.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 34% busy (agents 0.0, rest 1.5 cores) · 84°C · load 3.5 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:46:35Z +ludothinkpad ok: 23.7 GB free, 4 threads 69% busy, 0 sessions +desktop offline +macmini busy: 26.2 GB free, 14 threads 90% busy, 1 sessions +macbook offline + RAM 23.8 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 75% busy (agents 0.0, rest 2.8 cores) · 87°C · load 2.7 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:47:40Z +ludothinkpad ok: 23.8 GB free, 4 threads 66% busy, 0 sessions +desktop offline +macmini busy: 25.9 GB free, 14 threads 85% busy, 1 sessions +macbook offline + RAM 23.8 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 59% busy (agents 0.0, rest 2.5 cores) · 83°C · load 2.9 + · disk 291.7 GB free · battery 96% · Ludovic: away + +2026-10-18T19:48:44Z +ludothinkpad ok: 24.2 GB free, 4 threads 61% busy, 0 sessions +desktop offline +macmini busy: 29.0 GB free, 14 threads 90% busy, 1 sessions +macbook offline + RAM 24.3 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 62% busy (agents 0.0, rest 2.5 cores) · 84°C · load 3.2 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:49:48Z +ludothinkpad ok: 25.1 GB free, 4 threads 59% busy, 0 sessions +desktop offline +macmini ok: 31.1 GB free, 14 threads 81% busy, 1 sessions +macbook offline + RAM 25.1 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 57% busy (agents 0.0, rest 2.4 cores) · 85°C · load 2.9 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:50:52Z +ludothinkpad ok: 25.7 GB free, 4 threads 39% busy, 0 sessions +desktop offline +macmini busy: 28.4 GB free, 14 threads 88% busy, 2 sessions +macbook offline + RAM 25.8 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 18% busy (agents 0.0, rest 1.4 cores) · 67°C · load 2.4 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:51:57Z +ludothinkpad ok: 23.7 GB free, 4 threads 40% busy, 0 sessions +desktop offline +macmini ok: 27.9 GB free, 14 threads 83% busy, 1 sessions +macbook offline + RAM 23.7 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 23% busy (agents 0.0, rest 1.4 cores) · 81°C · load 1.8 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:53:01Z +ludothinkpad ok: 25.3 GB free, 4 threads 25% busy, 0 sessions +desktop offline +macmini ok: 27.1 GB free, 14 threads 84% busy, 1 sessions +macbook offline + RAM 25.1 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 31% busy (agents 0.0, rest 1.2 cores) · 80°C · load 1.8 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:54:05Z +ludothinkpad ok: 26.5 GB free, 4 threads 75% busy, 0 sessions +desktop offline +macmini busy: 27.1 GB free, 14 threads 91% busy, 1 sessions +macbook offline + RAM 26.5 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 69% busy (agents 0.0, rest 2.5 cores) · 78°C · load 2.3 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:55:09Z +ludothinkpad busy: 26.4 GB free, 4 threads 89% busy, 0 sessions +desktop offline +macmini busy: 26.3 GB free, 14 threads 86% busy, 1 sessions +macbook offline + RAM 26.3 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 32% busy (agents 0.0, rest 2.4 cores) · 79°C · load 2.9 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:56:14Z +ludothinkpad ok: 26.4 GB free, 4 threads 39% busy, 0 sessions +desktop offline +macmini ok: 27.1 GB free, 14 threads 68% busy, 1 sessions +macbook offline + RAM 26.4 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 63% busy (agents 0.0, rest 1.8 cores) · 82°C · load 2.3 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:57:18Z +ludothinkpad ok: 26.3 GB free, 4 threads 20% busy, 0 sessions +desktop offline +macmini busy: 29.2 GB free, 14 threads 85% busy, 1 sessions +macbook offline + RAM 26.3 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 19% busy (agents 0.0, rest 1.0 cores) · 80°C · load 1.8 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:58:22Z +ludothinkpad ok: 26.3 GB free, 4 threads 28% busy, 0 sessions +desktop offline +macmini busy: 27.3 GB free, 14 threads 88% busy, 1 sessions +macbook offline + RAM 26.1 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 93% busy (agents 0.0, rest 2.5 cores) · 80°C · load 2.0 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:59:27Z +ludothinkpad ok: 26.2 GB free, 4 threads 52% busy, 0 sessions +desktop offline +macmini ok: 35.0 GB free, 14 threads 85% busy, 1 sessions +macbook offline + RAM 26.2 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 22% busy (agents 0.0, rest 1.8 cores) · 80°C · load 3.6 + · disk 291.4 GB free · battery 96% · Ludovic: away + +2026-10-18T20:00:31Z +ludothinkpad busy: 25.8 GB free, 4 threads 87% busy, 0 sessions +desktop offline +macmini busy: 33.0 GB free, 14 threads 87% busy, 1 sessions +macbook offline + RAM 27.5 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 51% busy (agents 0.0, rest 2.9 cores) · 79°C · load 3.6 + · disk 291.5 GB free · battery 96% · Ludovic: away + +2026-10-18T20:01:35Z +ludothinkpad ok: 25.6 GB free, 4 threads 35% busy, 0 sessions +desktop offline +macmini ok: 32.4 GB free, 14 threads 81% busy, 1 sessions +macbook ok: 7.2 GB free, 12 threads 32% busy, 0 sessions + RAM 25.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 34% busy (agents 0.0, rest 1.3 cores) · 81°C · load 2.5 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T20:02:40Z +ludothinkpad ok: 26.6 GB free, 4 threads 35% busy, 0 sessions +desktop offline +macmini ok: 29.2 GB free, 14 threads 79% busy, 1 sessions +macbook ok: 6.5 GB free, 12 threads 39% busy, 0 sessions + RAM 26.5 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 33% busy (agents 0.0, rest 1.3 cores) · 81°C · load 2.7 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T20:03:44Z +ludothinkpad ok: 25.5 GB free, 4 threads 56% busy, 0 sessions +desktop offline +macmini busy: 31.1 GB free, 14 threads 89% busy, 1 sessions +macbook ok: 6.8 GB free, 12 threads 6% busy, 0 sessions + RAM 25.2 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 66% busy (agents 0.0, rest 2.5 cores) · 87°C · load 2.5 + · disk 291.3 GB free · battery 96% · Ludovic: away + +2026-10-18T20:04:48Z +ludothinkpad busy: 26.2 GB free, 4 threads 99% busy, 0 sessions +desktop offline +macmini busy: 30.0 GB free, 14 threads 89% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 31% busy, 0 sessions + RAM 25.8 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 84% busy (agents 0.0, rest 3.7 cores) · 85°C · load 3.4 + · disk 291.3 GB free · battery 96% · Ludovic: away + +2026-10-18T20:05:52Z +ludothinkpad busy: 24.5 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 34.1 GB free, 14 threads 89% busy, 1 sessions +macbook ok: 6.6 GB free, 12 threads 10% busy, 0 sessions + RAM 24.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 100% busy (agents 0.0, rest 4.0 cores) · 83°C · load 9.0 + · disk 291.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:06:57Z +ludothinkpad busy: 23.5 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 28.3 GB free, 14 threads 88% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 5% busy, 0 sessions + RAM 23.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 99% busy (agents 0.0, rest 4.0 cores) · 82°C · load 10.1 + · disk 309.2 GB free · battery 96% · Ludovic: away + +2026-10-18T20:08:01Z +ludothinkpad busy: 23.4 GB free, 4 threads 88% busy, 0 sessions +desktop offline +macmini ok: 29.6 GB free, 14 threads 83% busy, 1 sessions +macbook ok: 6.6 GB free, 12 threads 2% busy, 0 sessions + RAM 23.4 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 77% busy (agents 0.0, rest 3.4 cores) · 84°C · load 7.5 + · disk 309.2 GB free · battery 96% · Ludovic: away + +2026-10-18T20:09:05Z +ludothinkpad busy: 24.0 GB free, 4 threads 89% busy, 0 sessions +desktop offline +macmini ok: 25.9 GB free, 14 threads 83% busy, 1 sessions +macbook ok: 7.1 GB free, 12 threads 19% busy, 0 sessions + RAM 23.9 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 91% busy (agents 0.0, rest 3.6 cores) · 82°C · load 5.9 + · disk 309.1 GB free · battery 96% · Ludovic: away + +2026-10-18T20:10:09Z +ludothinkpad busy: 24.0 GB free, 4 threads 98% busy, 0 sessions +desktop offline +macmini busy: 27.1 GB free, 14 threads 88% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 19% busy, 0 sessions + RAM 24.0 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 92% busy (agents 0.0, rest 3.7 cores) · 84°C · load 6.6 + · disk 309.1 GB free · battery 96% · Ludovic: away + +2026-10-18T20:11:14Z +ludothinkpad busy: 24.3 GB free, 4 threads 92% busy, 0 sessions +desktop offline +macmini ok: 26.3 GB free, 14 threads 84% busy, 1 sessions +macbook ok: 6.6 GB free, 12 threads 18% busy, 0 sessions + RAM 24.4 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 99% busy (agents 0.0, rest 3.7 cores) · 85°C · load 6.5 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:12:18Z +ludothinkpad busy: 24.7 GB free, 4 threads 89% busy, 0 sessions +desktop offline +macmini ok: 28.6 GB free, 14 threads 78% busy, 1 sessions +macbook ok: 7.3 GB free, 12 threads 20% busy, 0 sessions + RAM 24.7 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 82% busy (agents 0.0, rest 3.4 cores) · 84°C · load 6.1 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:13:22Z +ludothinkpad ok: 23.4 GB free, 4 threads 53% busy, 0 sessions +desktop offline +macmini ok: 28.1 GB free, 14 threads 77% busy, 1 sessions +macbook ok: 7.3 GB free, 12 threads 20% busy, 0 sessions + RAM 23.4 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 48% busy (agents 0.0, rest 2.4 cores) · 80°C · load 4.2 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:14:27Z +ludothinkpad ok: 24.0 GB free, 4 threads 44% busy, 0 sessions +desktop offline +macmini ok: 28.0 GB free, 14 threads 71% busy, 1 sessions +macbook ok: 6.9 GB free, 12 threads 2% busy, 0 sessions + RAM 24.1 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 23% busy (agents 0.0, rest 2.0 cores) · 77°C · load 4.3 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:15:31Z +ludothinkpad ok: 22.7 GB free, 4 threads 31% busy, 0 sessions +desktop offline +macmini busy: 27.2 GB free, 14 threads 86% busy, 1 sessions +macbook ok: 6.9 GB free, 12 threads 19% busy, 0 sessions + RAM 22.5 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 30% busy (agents 0.0, rest 1.3 cores) · 77°C · load 2.6 + · disk 309.1 GB free · battery 96% · Ludovic: away + +2026-10-18T20:16:35Z +ludothinkpad ok: 26.8 GB free, 4 threads 37% busy, 0 sessions +desktop offline +macmini ok: 28.6 GB free, 14 threads 82% busy, 1 sessions +macbook ok: 6.8 GB free, 12 threads 9% busy, 0 sessions + RAM 26.8 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 42% busy (agents 0.0, rest 1.7 cores) · 81°C · load 2.3 + · disk 309.1 GB free · battery 96% · Ludovic: away + +2026-10-18T20:17:39Z +ludothinkpad ok: 26.3 GB free, 4 threads 63% busy, 0 sessions +desktop offline +macmini ok: 26.8 GB free, 14 threads 78% busy, 1 sessions +macbook ok: 7.0 GB free, 12 threads 19% busy, 0 sessions + RAM 26.4 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 64% busy (agents 0.0, rest 2.6 cores) · 87°C · load 1.9 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:18:43Z +ludothinkpad ok: 26.9 GB free, 4 threads 37% busy, 0 sessions +desktop offline +macmini busy: 32.2 GB free, 14 threads 87% busy, 1 sessions +macbook ok: 7.0 GB free, 12 threads 10% busy, 0 sessions + RAM 26.9 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 56% busy (agents 0.0, rest 1.9 cores) · 84°C · load 3.9 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:19:48Z +ludothinkpad ok: 26.0 GB free, 4 threads 77% busy, 0 sessions +desktop offline +macmini ok: 29.2 GB free, 14 threads 83% busy, 1 sessions +macbook ok: 7.0 GB free, 12 threads 10% busy, 0 sessions + RAM 26.0 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 66% busy (agents 0.0, rest 2.9 cores) · 86°C · load 3.2 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:20:52Z +ludothinkpad ok: 25.9 GB free, 4 threads 80% busy, 0 sessions +desktop offline +macmini ok: 26.8 GB free, 14 threads 84% busy, 1 sessions +macbook ok: 7.0 GB free, 12 threads 17% busy, 0 sessions + RAM 25.9 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 68% busy (agents 0.0, rest 3.2 cores) · 86°C · load 4.4 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:21:56Z +ludothinkpad ok: 26.3 GB free, 4 threads 63% busy, 0 sessions +desktop offline +macmini ok: 26.3 GB free, 14 threads 77% busy, 1 sessions +macbook ok: 6.8 GB free, 12 threads 14% busy, 0 sessions + RAM 26.3 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 66% busy (agents 0.0, rest 2.8 cores) · 84°C · load 3.1 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:23:00Z +ludothinkpad ok: 26.8 GB free, 4 threads 74% busy, 0 sessions +desktop offline +macmini ok: 26.1 GB free, 14 threads 82% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 11% busy, 0 sessions + RAM 26.7 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 65% busy (agents 0.0, rest 2.8 cores) · 84°C · load 5.0 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:24:05Z +ludothinkpad ok: 26.9 GB free, 4 threads 64% busy, 0 sessions +desktop offline +macmini busy: 28.3 GB free, 14 threads 90% busy, 1 sessions +macbook ok: 6.8 GB free, 12 threads 8% busy, 0 sessions + RAM 26.9 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 64% busy (agents 0.0, rest 2.7 cores) · 86°C · load 4.9 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:25:09Z +ludothinkpad ok: 26.0 GB free, 4 threads 56% busy, 0 sessions +desktop offline +macmini busy: 26.2 GB free, 14 threads 88% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 12% busy, 0 sessions + RAM 26.0 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 49% busy (agents 0.0, rest 2.1 cores) · 72°C · load 5.5 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:26:13Z +ludothinkpad ok: 25.8 GB free, 4 threads 47% busy, 0 sessions +desktop offline +macmini ok: 27.8 GB free, 14 threads 78% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 8% busy, 0 sessions + RAM 25.8 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 56% busy (agents 0.0, rest 2.1 cores) · 78°C · load 3.1 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:27:18Z +ludothinkpad busy: 25.5 GB free, 4 threads 94% busy, 0 sessions +desktop offline +macmini ok: 26.6 GB free, 14 threads 82% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 17% busy, 0 sessions + RAM 25.4 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 100% busy (agents 0.0, rest 3.9 cores) · 78°C · load 4.7 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:28:22Z +ludothinkpad busy: 24.6 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini ok: 26.4 GB free, 14 threads 80% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 8% busy, 0 sessions + RAM 24.2 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 99% busy (agents 0.0, rest 4.0 cores) · 77°C · load 10.5 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:29:27Z +ludothinkpad busy: 24.3 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini ok: 29.8 GB free, 14 threads 80% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 8% busy, 0 sessions + RAM 24.0 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 99% busy (agents 0.0, rest 4.0 cores) · 82°C · load 10.0 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:30:31Z +ludothinkpad busy: 23.7 GB free, 4 threads 91% busy, 0 sessions +desktop offline +macmini ok: 30.1 GB free, 14 threads 71% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 9% busy, 0 sessions + RAM 23.7 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 94% busy (agents 0.0, rest 3.8 cores) · 80°C · load 10.3 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:31:36Z +ludothinkpad busy: 23.6 GB free, 4 threads 93% busy, 0 sessions +desktop offline +macmini ok: 28.0 GB free, 14 threads 81% busy, 1 sessions +macbook ok: 6.6 GB free, 12 threads 14% busy, 0 sessions + RAM 23.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 95% busy (agents 0.0, rest 3.7 cores) · 80°C · load 10.7 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:32:40Z +ludothinkpad busy: 23.6 GB free, 4 threads 94% busy, 0 sessions +desktop offline +macmini ok: 26.9 GB free, 14 threads 76% busy, 1 sessions +macbook ok: 6.8 GB free, 12 threads 22% busy, 0 sessions + RAM 23.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 84% busy (agents 0.0, rest 3.5 cores) · 80°C · load 9.7 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:33:45Z +ludothinkpad ok: 25.2 GB free, 4 threads 51% busy, 0 sessions +desktop offline +macmini ok: 27.1 GB free, 14 threads 82% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 17% busy, 0 sessions + RAM 25.2 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 48% busy (agents 0.0, rest 2.1 cores) · 87°C · load 6.5 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:34:49Z +ludothinkpad ok: 25.1 GB free, 4 threads 56% busy, 0 sessions +desktop offline +macmini busy: 28.2 GB free, 14 threads 87% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 17% busy, 0 sessions + RAM 24.5 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 78% busy (agents 0.0, rest 2.7 cores) · 88°C · load 4.0 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:35:53Z +ludothinkpad busy: 23.6 GB free, 4 threads 86% busy, 0 sessions +desktop offline +macmini busy: 27.9 GB free, 14 threads 86% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 17% busy, 0 sessions + RAM 23.7 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 88% busy (agents 0.0, rest 3.3 cores) · 85°C · load 4.9 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:36:58Z +ludothinkpad ok: 23.6 GB free, 4 threads 75% busy, 0 sessions +desktop offline +macmini ok: 29.4 GB free, 14 threads 84% busy, 1 sessions +macbook ok: 6.5 GB free, 12 threads 18% busy, 0 sessions + RAM 23.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 85% busy (agents 0.0, rest 3.2 cores) · 85°C · load 5.1 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:38:02Z +ludothinkpad ok: 22.6 GB free, 4 threads 55% busy, 0 sessions +desktop offline +macmini ok: 26.5 GB free, 14 threads 80% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 10% busy, 0 sessions + RAM 22.3 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 54% busy (agents 0.0, rest 2.2 cores) · 85°C · load 4.5 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:39:06Z +ludothinkpad ok: 27.2 GB free, 4 threads 55% busy, 0 sessions +desktop offline +macmini busy: 29.5 GB free, 14 threads 85% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 9% busy, 0 sessions + RAM 27.3 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 48% busy (agents 0.0, rest 2.2 cores) · 87°C · load 4.0 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:40:10Z +ludothinkpad ok: 26.2 GB free, 4 threads 72% busy, 0 sessions +desktop offline +macmini ok: 27.7 GB free, 14 threads 84% busy, 1 sessions +macbook ok: 6.6 GB free, 12 threads 19% busy, 0 sessions + RAM 26.3 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 80% busy (agents 0.0, rest 3.1 cores) · 86°C · load 10.8 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:41:15Z +ludothinkpad busy: 26.4 GB free, 4 threads 86% busy, 0 sessions +desktop offline +macmini ok: 28.5 GB free, 14 threads 79% busy, 1 sessions +macbook ok: 6.6 GB free, 12 threads 10% busy, 0 sessions + RAM 26.4 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 90% busy (agents 0.0, rest 3.4 cores) · 86°C · load 12.8 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:42:19Z +ludothinkpad ok: 26.2 GB free, 4 threads 82% busy, 0 sessions +desktop offline +macmini ok: 26.9 GB free, 14 threads 78% busy, 1 sessions +macbook ok: 6.6 GB free, 12 threads 11% busy, 0 sessions + RAM 26.2 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 74% busy (agents 0.0, rest 3.3 cores) · 85°C · load 8.8 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:43:23Z +ludothinkpad busy: 26.7 GB free, 4 threads 93% busy, 0 sessions +desktop offline +macmini ok: 27.3 GB free, 14 threads 81% busy, 1 sessions +macbook ok: 6.6 GB free, 12 threads 10% busy, 0 sessions + RAM 26.7 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 88% busy (agents 0.0, rest 3.4 cores) · 85°C · load 5.4 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:44:27Z +ludothinkpad ok: 27.0 GB free, 4 threads 82% busy, 0 sessions +desktop offline +macmini busy: 26.9 GB free, 14 threads 87% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 13% busy, 0 sessions + RAM 27.0 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 75% busy (agents 0.0, rest 3.3 cores) · 82°C · load 9.8 + · disk 308.8 GB free · battery 96% · Ludovic: away + +2026-10-18T20:45:32Z +ludothinkpad ok: 27.2 GB free, 4 threads 76% busy, 0 sessions +desktop offline +macmini ok: 26.8 GB free, 14 threads 80% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 10% busy, 0 sessions + RAM 27.2 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 84% busy (agents 0.0, rest 3.2 cores) · 85°C · load 6.9 + · disk 308.8 GB free · battery 96% · Ludovic: away + +2026-10-18T20:46:36Z +ludothinkpad busy: 27.1 GB free, 4 threads 87% busy, 0 sessions +desktop offline +macmini busy: 26.8 GB free, 14 threads 92% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 9% busy, 0 sessions + RAM 26.8 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 85% busy (agents 0.0, rest 3.2 cores) · 82°C · load 4.4 + · disk 308.8 GB free · battery 96% · Ludovic: away + +2026-10-18T20:47:40Z +ludothinkpad busy: 25.3 GB free, 4 threads 86% busy, 0 sessions +desktop offline +macmini ok: 26.5 GB free, 14 threads 72% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 9% busy, 0 sessions + RAM 25.5 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 85% busy (agents 0.0, rest 3.4 cores) · 86°C · load 3.7 + · disk 308.8 GB free · battery 96% · Ludovic: away + +2026-10-18T20:48:45Z +ludothinkpad busy: 26.1 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini ok: 28.5 GB free, 14 threads 84% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 15% busy, 0 sessions + RAM 26.1 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 98% busy (agents 0.0, rest 3.9 cores) · 80°C · load 6.5 + · disk 308.8 GB free · battery 96% · Ludovic: away + +2026-10-18T20:49:50Z +ludothinkpad ok: 26.8 GB free, 4 threads 71% busy, 0 sessions +desktop offline +macmini busy: 27.7 GB free, 14 threads 93% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 10% busy, 0 sessions + RAM 26.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 92% busy (agents 0.0, rest 3.4 cores) · 81°C · load 5.2 + · disk 308.7 GB free · battery 96% · Ludovic: away + +2026-10-18T20:50:54Z +ludothinkpad busy: 25.8 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 31.3 GB free, 14 threads 95% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 11% busy, 0 sessions + RAM 25.8 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 99% busy (agents 0.0, rest 4.0 cores) · 82°C · load 8.1 + · disk 308.7 GB free · battery 96% · Ludovic: away + +2026-10-18T20:51:59Z +ludothinkpad ok: 27.2 GB free, 4 threads 12% busy, 0 sessions +desktop offline +macmini ok: 31.2 GB free, 14 threads 76% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 8% busy, 0 sessions + RAM 27.2 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 15% busy (agents 0.0, rest 1.3 cores) · 81°C · load 7.9 + · disk 308.7 GB free · battery 96% · Ludovic: away + +2026-10-18T20:53:03Z +ludothinkpad ok: 27.3 GB free, 4 threads 42% busy, 0 sessions +desktop offline +macmini busy: 27.8 GB free, 14 threads 87% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 9% busy, 0 sessions + RAM 27.2 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 14% busy (agents 0.0, rest 0.8 cores) · 82°C · load 3.1 + · disk 308.7 GB free · battery 96% · Ludovic: away + +2026-10-18T20:54:08Z +ludothinkpad ok: 28.9 GB free, 4 threads 4% busy, 0 sessions +desktop offline +macmini ok: 29.2 GB free, 14 threads 80% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 9% busy, 0 sessions + RAM 28.9 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 2% busy (agents 0.0, rest 0.3 cores) · 82°C · load 1.3 + · disk 308.7 GB free · battery 96% · Ludovic: away + +2026-10-18T20:55:12Z +ludothinkpad ok: 27.7 GB free, 4 threads 27% busy, 0 sessions +desktop offline +macmini ok: 31.2 GB free, 14 threads 70% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 10% busy, 0 sessions + RAM 27.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 26% busy (agents 0.0, rest 1.2 cores) · 69°C · load 1.0 + · disk 308.8 GB free · battery 96% · Ludovic: away + diff --git a/benchmarks/server-equal-mixed-2026-10-18/mixed-equal.json b/benchmarks/server-equal-mixed-2026-10-18/mixed-equal.json new file mode 100644 index 000000000..c494f3b24 --- /dev/null +++ b/benchmarks/server-equal-mixed-2026-10-18/mixed-equal.json @@ -0,0 +1,421 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-18T19:32:00+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4, + "name": "ThinkPad, Intel Core i7-7500U, 32 GB, NixOS" + }, + "commit": "f1d5bf520986b00a5b968a84d85809fca1a039fa", + "engine": "horizon-engine: the server build of #916 (horizon-client --no-default-features) at 519ec121, as install.sh --archive installed it", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon,vanilla", + "bots": "1,10,25,50", + "behaviour": "mixed", + "join_every": 1.0, + "warmup": 300, + "seconds": 300, + "seed": 12345, + "explore_speed": 0.8, + "gamerule": "", + "heap": "4g", + "nice": 19, + "bots_via": "ssh macmini", + "connect": "the ThinkPad's tailnet address", + "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" + } + }, + "note": "server_bench.py was stopped after vanilla's 50-bot server crashed, before it wrote this file; the runs are the lines it printed, and the vanilla 50 entry is taken from that server's log.", + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "mixed", + "start_seconds": 19.73, + "mspt": { + "average": 1.77, + "p50": 1.34, + "p95": 4.21, + "p99": 13.04 + }, + "mspt_worst_p99": 47.5, + "tps": 20.0, + "rss_mb": { + "mean": 686.54, + "max": 686.7 + }, + "cpu_percent": 27.92, + "chunks_per_second": 9.94, + "unique_per_second": 0.01, + "forgotten_per_second": 9.9, + "waited_ticks_per_second": 0.0, + "chunks_total": 6092, + "chunks_per_bot": { + "walk": 6092.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": 1, + "behaviour": "mixed", + "start_seconds": 20.45, + "mspt": { + "average": 11.34, + "p50": 10.6, + "p95": 17.12, + "p99": 33.22 + }, + "mspt_worst_p99": 119.1, + "tps": 20.0, + "rss_mb": { + "mean": 3404.16, + "max": 3416.3 + }, + "cpu_percent": 35.93, + "chunks_per_second": 9.98, + "unique_per_second": 0.01, + "forgotten_per_second": 9.93, + "waited_ticks_per_second": 0.0, + "chunks_total": 6084, + "chunks_per_bot": { + "walk": 6084.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": 59 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "mixed", + "start_seconds": 19.54, + "mspt": { + "average": 4.74, + "p50": 3.83, + "p95": 10.48, + "p99": 19.69 + }, + "mspt_worst_p99": 120.1, + "tps": 20.0, + "rss_mb": { + "mean": 855.26, + "max": 882.7 + }, + "cpu_percent": 29.78, + "chunks_per_second": 61.35, + "unique_per_second": 1.79, + "forgotten_per_second": 61.47, + "waited_ticks_per_second": 0.0, + "chunks_total": 40762, + "chunks_per_bot": { + "walk": 6247.67, + "explore": 1165.0, + "idle": 473.0 + }, + "unique_chunks_per_bot": { + "walk": 701.83, + "explore": 1086.0, + "idle": 473.0 + }, + "resent": 0, + "pulled_back": 4159, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "mixed", + "start_seconds": 19.95, + "mspt": { + "average": 34.3, + "p50": 32.2, + "p95": 53.72, + "p99": 89.08 + }, + "mspt_worst_p99": 375.8, + "tps": 20.0, + "rss_mb": { + "mean": 3713.5, + "max": 3754.9 + }, + "cpu_percent": 128.07, + "chunks_per_second": 61.66, + "unique_per_second": 1.93, + "forgotten_per_second": 61.71, + "waited_ticks_per_second": 0.0, + "chunks_total": 37568, + "chunks_per_bot": { + "walk": 5729.0, + "explore": 1124.0, + "idle": 473.0 + }, + "unique_chunks_per_bot": { + "walk": 701.17, + "explore": 1055.0, + "idle": 473.0 + }, + "resent": 0, + "pulled_back": 3976, + "moved_too_quickly": 20, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "mixed", + "start_seconds": 9.61, + "mspt": { + "average": 11.72, + "p50": 9.88, + "p95": 24.45, + "p99": 43.79 + }, + "mspt_worst_p99": 129.8, + "tps": 20.0, + "rss_mb": { + "mean": 947.35, + "max": 1086.1 + }, + "cpu_percent": 57.83, + "chunks_per_second": 158.57, + "unique_per_second": 5.78, + "forgotten_per_second": 158.45, + "waited_ticks_per_second": 0.0, + "chunks_total": 108126, + "chunks_per_bot": { + "walk": 6628.53, + "explore": 1266.6, + "idle": 473.0 + }, + "unique_chunks_per_bot": { + "walk": 704.67, + "explore": 1189.2, + "idle": 473.0 + }, + "resent": 0, + "pulled_back": 3496, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "mixed", + "start_seconds": 37.78, + "mspt": { + "average": 50.45, + "p50": 46.39, + "p95": 74.09, + "p99": 191.21 + }, + "mspt_worst_p99": 1388.1, + "tps": 19.82, + "rss_mb": { + "mean": 3866.18, + "max": 4745.0 + }, + "cpu_percent": 192.42, + "chunks_per_second": 157.63, + "unique_per_second": 8.25, + "forgotten_per_second": 156.12, + "waited_ticks_per_second": 0.0, + "chunks_total": 88763, + "chunks_per_bot": { + "walk": 5387.0, + "explore": 1118.6, + "idle": 473.0 + }, + "unique_chunks_per_bot": { + "walk": 699.0, + "explore": 1075.0, + "idle": 473.0 + }, + "resent": 2, + "pulled_back": 3629, + "moved_too_quickly": 296, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "mixed", + "start_seconds": 14.93, + "mspt": { + "average": 23.82, + "p50": 20.11, + "p95": 50.98, + "p99": 74.64 + }, + "mspt_worst_p99": 195.9, + "tps": 20.0, + "rss_mb": { + "mean": 1031.41, + "max": 1201.2 + }, + "cpu_percent": 98.21, + "chunks_per_second": 302.81, + "unique_per_second": 10.96, + "forgotten_per_second": 303.47, + "waited_ticks_per_second": 0.0, + "chunks_total": 212181, + "chunks_per_bot": { + "walk": 6496.53, + "explore": 1255.5, + "idle": 473.0 + }, + "unique_chunks_per_bot": { + "walk": 701.9, + "explore": 1184.7, + "idle": 473.0 + }, + "resent": 0, + "pulled_back": 7565, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "mixed", + "start_seconds": 11.16, + "error": "stopped by its watchdog 30 s after the last bot joined: \"A single server tick took 60.01 seconds (should be max 0.05)\" (Player.tick)" + } + ], + "work": [ + { + "behaviour": "mixed", + "bots": 1, + "servers": { + "horizon": { + "chunks_per_second": { + "value": 9.94, + "share": 0.996 + }, + "unique_per_second": { + "value": 0.01, + "share": 1.0 + }, + "waited_ticks_per_second": 0.0 + }, + "vanilla": { + "chunks_per_second": { + "value": 9.98, + "share": 1.0 + }, + "unique_per_second": { + "value": 0.01, + "share": 1.0 + }, + "waited_ticks_per_second": 0.0 + } + }, + "equal": true + }, + { + "behaviour": "mixed", + "bots": 10, + "servers": { + "horizon": { + "chunks_per_second": { + "value": 61.35, + "share": 0.995 + }, + "unique_per_second": { + "value": 1.79, + "share": 0.927 + }, + "waited_ticks_per_second": 0.0 + }, + "vanilla": { + "chunks_per_second": { + "value": 61.66, + "share": 1.0 + }, + "unique_per_second": { + "value": 1.93, + "share": 1.0 + }, + "waited_ticks_per_second": 0.0 + } + }, + "equal": true + }, + { + "behaviour": "mixed", + "bots": 25, + "servers": { + "horizon": { + "chunks_per_second": { + "value": 158.57, + "share": 1.0 + }, + "unique_per_second": { + "value": 5.78, + "share": 0.701 + }, + "waited_ticks_per_second": 0.0 + }, + "vanilla": { + "chunks_per_second": { + "value": 157.63, + "share": 0.994 + }, + "unique_per_second": { + "value": 8.25, + "share": 1.0 + }, + "waited_ticks_per_second": 0.0 + } + }, + "equal": false + } + ] +} diff --git a/benchmarks/server-mixed-2026-10-18/README.md b/benchmarks/server-mixed-2026-10-18/README.md new file mode 100644 index 000000000..3cbe3897f --- /dev/null +++ b/benchmarks/server-mixed-2026-10-18/README.md @@ -0,0 +1,125 @@ +# Horizon's server against vanilla 26.3: mixed bots (2026-10-18) + +The first benchmark from docs/server.md section 10 (item 4): the same bots on Horizon's dedicated server, as +`install.sh` installs it today, and on vanilla 26.3's, one server at a time on the same quiet machine. +There were 1, 10, 25 and 50 bots, all with the `mixed` behaviour. + +## Summary + +- **Both servers held 20 TPS in every run.** +- **Memory:** Horizon's RSS was 3.7 to 5.2 times smaller: 0.65 GB against 3.4 GB with one player, and + 1.0 GB against 4.0 GB with 50. Vanilla runs with the usual fixed heap (`-Xms4g -Xmx4g`), so its RSS + is mostly that heap. +- **Tick time (MSPT):** + - with 1, 10 and 25 players, Horizon's average tick was shorter (2.4 against 17.9 ms, 12.4 against 34.5, + 24.0 against 31.6); + - with 50, it was longer (35.2 against 29.7 ms); + - Horizon's P99 was lower at every count, and so were its worst 5-second windows (241 ms at most, + against 424 to 2320 ms for vanilla). +- **The work was not equal, and the difference counts against Horizon.** In `mixed`, 20 % of the bots + fly straight out at 22 blocks a second, as fast as each server sends them chunks. Horizon kept up: + - with 10 or more players it sent 2.9 to 5.9 times as many chunks a second, and generated 1.9 to 2.9 + times as much new terrain a second; + - its walking bots each received 3300 to 4000 chunks, against 640 to 1100 on vanilla once 10 or more + were online. + + So at 50 players Horizon's tick is 18 % longer while it generates twice the new terrain. The + equal-rate explore pass of `../server-equal-work-2026-10-17/` is the fair comparison for exploring. +- **Start (fresh world, to `Done`):** 10 to 20 s for Horizon, 14.5 to 28.6 s for vanilla. + +## Results + +MSPT is milliseconds per tick from each server's own `/tick query` (50 is the limit for 20 TPS). P95 and +P99 are over the whole run. "Worst P99" is the highest P99 of a single 5-second query. RSS and CPU cover +the server's whole process tree (100 % is one thread; the machine has 4). "New chunks/s" counts chunks +no bot had before. "Pulled back" counts position packets that moved a bot back. + +| Bots | Server | MSPT | P95 | P99 | Worst P99 | TPS | RSS (mean / max) | CPU | Start | Chunks/s | New chunks/s | Pulled back | +|---:|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| 1 | Horizon | **2.4** | 5.2 | 18.2 | 45.6 | 20 | **0.65 / 0.66 GB** | 25 % | 10.9 s | 9.9 | 0.3 | 0 | +| 1 | vanilla | 17.9 | 27.6 | 47.3 | 423.8 | 20 | 3.38 / 3.39 GB | 64 % | 14.8 s | 9.9 | 0.3 | 0 | +| 10 | Horizon | **12.4** | 36.0 | 65.9 | 117.1 | 20 | **0.94 / 1.01 GB** | 210 % | 10.2 s | 98.2 | 36.5 | 6267 | +| 10 | vanilla | 34.5 | 63.5 | 138.6 | 884.7 | 20 | 3.59 / 3.66 GB | 217 % | 14.5 s | 24.3 | 19.1 | 5500 | +| 25 | Horizon | **24.0** | 49.7 | 80.6 | 168.8 | 20 | **1.01 / 1.18 GB** | 192 % | 14.7 s | 178.2 | 31.9 | 5532 | +| 25 | vanilla | 31.6 | 70.0 | 222.7 | 2319.6 | 20 | 3.74 / 4.06 GB | 218 % | 28.6 s | 30.4 | 10.8 | 4524 | +| 50 | Horizon | 35.2 | 69.0 | 96.6 | 240.8 | 20 | **1.01 / 1.25 GB** | 218 % | 19.8 s | 273.2 | 34.6 | 8369 | +| 50 | vanilla | **29.7** | 62.3 | 137.4 | 489.3 | 20 | 4.00 / 4.60 GB | 294 % | 20.6 s | 94.4 | 17.8 | 12034 | + +Chunks each bot received, by behaviour (mean): + +| Bots | Server | walk | explore | idle | +|---:|---|---:|---:|---:| +| 10 | Horizon | 3992 | 7360 | 473 | +| 10 | vanilla | 680 | 2824 | 358 | +| 25 | Horizon | 3928 | 2475 | 473 | +| 25 | vanilla | 640 | 738 | 180 | +| 50 | Horizon | 3300 | 1192 | 460 | +| 50 | vanilla | 1105 | 629 | 220 | + +No bot failed to join or was dropped, and no chunk was sent twice (`resent` 0), on either server. Vanilla +also logged "moved too quickly" 12, 324 and 2193 times at 10, 25 and 50 bots. + +## Method + +`tools/server_bench.py`, unchanged, 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`, white-list off; +- `gamerule respawn_radius 0`, and otherwise vanilla's default game rules on both. The locator bar is on + for both: Horizon's server has run it since v2026.10.18.13. The 2026-10-17 runs turned it off on vanilla + because Horizon had none then; +- the server waits for `Done`, then the bots join one a second, warm up for 60 seconds, and are measured + for 300 seconds, with `/tick query` every 5 seconds and RSS and CPU every second. + +The bots are `horizon-bots --behaviour mixed`: 60 % walk, 20 % explore and 20 % idle, each choice +deterministic per bot. All are creative and fly 24 blocks above their spawn: + +- `walk`: random points within 48 blocks at 5.6 blocks a second; +- `explore`: straight out at up to 22 blocks a second, as fast as chunks come; +- `idle`: hovers. + +A bot doesn't move while the chunk it stands in hasn't arrived, and it acknowledges chunk batches as +vanilla's client does. + +**Machine.** The ThinkPad: Intel Core i7-7500U (2 cores, 4 threads), 32 GB, NixOS (Linux 6.18). No other +session ran on it (`load.txt`: the fleet monitor shows 0 sessions throughout). The busy periods are the +servers themselves, which used 2 to 3 of its 4 threads from 10 bots up, so both servers were CPU-bound +there. The servers ran under `nice -n 19`. The desktop was meant to run this (24 threads) but didn't +wake. The bots ran on the Mac mini (M4 Pro) and reached the ThinkPad over the tailnet, so they took none +of the servers' CPU. The Mac mini was shared with other work (70 to 90 % busy), which only affects the +bots' timing. + +**What ran.** + +- Horizon: the published v2026.10.18.15 release, `horizon-client` (the engine) at 6c078b28, as + `install.sh` installs it. Its game files were prepared from the owner's own Minecraft by the release's + `horizon-prepare`. `horizon-server` (the supervisor, which takes no part in the tick) came from #898 + (4ea2243e), because the release's copy can't find game files prepared without sounds (#893). + `horizon-bots` came from main. +- Vanilla: the pinned 26.3 server jar (the owner's own copy) on OpenJDK 25.0.4.1, `-Xms4g -Xmx4g`. + +On Linux the release's engine needs `libasound.so.2` and `libudev.so.1`. The ThinkPad has them only in +the Nix store, so the run set `LD_LIBRARY_PATH` to them (see #898). + +## Reproduce + + curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.sh | sh + horizon-prepare --prepare --server-jar /path/to/server.jar # your own copy + cargo build --release -p horizon-bots # on the machine that runs the bots + # in a checkout whose .local/minecraft holds the pinned vanilla jars (tools/lab.py prepare): + HORIZON_BENCH_BIN= \ + python3 tools/server_bench.py --servers horizon,vanilla --bots 1,10,25,50 --behaviour mixed --nice 19 \ + --bots-via 'ssh ' --bots-bin /path/to/horizon-bots --connect \ + --out mixed.json + +`mixed.json` is the report (`horizon-server-benchmark`: machine, versions, settings and every run), and +`load.txt` is the ThinkPad's load before and during the run. + +## Next + +- An equal-work `mixed` pass (`--explore-speed` at a rate both servers keep up with), then 100 bots. +- The same run on a bigger machine, so neither server is CPU-bound at 25 to 50 bots. +- Paper and Fabric + Lithium (docs/server.md section 9). +- At 50 players Horizon's tick is longer than vanilla's while it generates and sends far more. The + profile of the 2026-10-17 run (streaming and block entity ticks growing with players) is + perf-server's to take on. diff --git a/benchmarks/server-mixed-2026-10-18/load.txt b/benchmarks/server-mixed-2026-10-18/load.txt new file mode 100644 index 000000000..3468f9f86 --- /dev/null +++ b/benchmarks/server-mixed-2026-10-18/load.txt @@ -0,0 +1,286 @@ +ludothinkpad — OK + RAM 29.1 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 2% busy (agents 0.0, rest 0.1 cores) · 67°C · load 2.1 + · disk 295.5 GB free · battery 96% + +Sessions, most important first: + (finished session) 0.0 GB leftovers: node 0.0 GB + +Other machines (≤ 1 min old): desktop offline · macbook offline · macmini ok: 26.6 GB free, 14 threads 69% busy, 1 sessions + +# During the run, once a minute (uptime, then ~/fleet/load fleet) +18:25:30 + 18:25:30 up 8 days 3:08, 0 users, load average: 2.13, 1.53, 1.29 +ludothinkpad ok: 29.1 GB free, 4 threads 2% busy, 0 sessions +desktop offline +macmini busy: 27.6 GB free, 14 threads 87% busy, 1 sessions +18:26:34 + 18:26:34 up 8 days 3:09, 0 users, load average: 1.70, 1.56, 1.31 +ludothinkpad ok: 28.5 GB free, 4 threads 23% busy, 0 sessions +desktop offline +macmini busy: 26.4 GB free, 14 threads 85% busy, 1 sessions +18:27:38 + 18:27:38 up 8 days 3:10, 0 users, load average: 1.10, 1.43, 1.28 +ludothinkpad ok: 28.5 GB free, 4 threads 4% busy, 0 sessions +desktop offline +macmini ok: 27.7 GB free, 14 threads 80% busy, 1 sessions +18:28:42 + 18:28:42 up 8 days 3:11, 0 users, load average: 0.93, 1.29, 1.24 +ludothinkpad ok: 28.5 GB free, 4 threads 22% busy, 0 sessions +desktop offline +macmini ok: 26.0 GB free, 14 threads 82% busy, 1 sessions +18:29:46 + 18:29:46 up 8 days 3:12, 0 users, load average: 0.62, 1.12, 1.18 +ludothinkpad ok: 28.5 GB free, 4 threads 12% busy, 0 sessions +desktop offline +macmini ok: 25.7 GB free, 14 threads 81% busy, 1 sessions +18:30:50 + 18:30:51 up 8 days 3:13, 0 users, load average: 0.79, 1.05, 1.15 +ludothinkpad ok: 28.5 GB free, 4 threads 7% busy, 0 sessions +desktop offline +macmini busy: 27.0 GB free, 14 threads 88% busy, 1 sessions +18:31:55 + 18:31:55 up 8 days 3:14, 0 users, load average: 0.67, 0.96, 1.11 +ludothinkpad ok: 28.6 GB free, 4 threads 73% busy, 0 sessions +desktop offline +macmini ok: 27.3 GB free, 14 threads 79% busy, 1 sessions +18:32:59 + 18:32:59 up 8 days 3:15, 0 users, load average: 4.01, 1.91, 1.44 +ludothinkpad ok: 25.9 GB free, 4 threads 24% busy, 0 sessions +desktop offline +macmini ok: 26.4 GB free, 14 threads 85% busy, 1 sessions +18:34:03 + 18:34:03 up 8 days 3:16, 0 users, load average: 2.24, 1.84, 1.44 +ludothinkpad ok: 25.9 GB free, 4 threads 21% busy, 0 sessions +desktop offline +macmini busy: 29.2 GB free, 14 threads 86% busy, 1 sessions +18:35:07 + 18:35:07 up 8 days 3:17, 0 users, load average: 1.28, 1.63, 1.40 +ludothinkpad ok: 25.8 GB free, 4 threads 21% busy, 0 sessions +desktop offline +macmini busy: 31.0 GB free, 14 threads 86% busy, 1 sessions +18:36:11 + 18:36:11 up 8 days 3:18, 0 users, load average: 0.79, 1.41, 1.33 +ludothinkpad ok: 25.9 GB free, 4 threads 18% busy, 0 sessions +desktop offline +macmini busy: 26.3 GB free, 14 threads 93% busy, 1 sessions +18:37:15 + 18:37:15 up 8 days 3:20, 0 users, load average: 1.44, 1.47, 1.36 +ludothinkpad ok: 25.9 GB free, 4 threads 23% busy, 0 sessions +desktop offline +macmini busy: 26.8 GB free, 14 threads 86% busy, 1 sessions +18:38:19 + 18:38:19 up 8 days 3:21, 0 users, load average: 1.37, 1.45, 1.36 +ludothinkpad ok: 25.9 GB free, 4 threads 13% busy, 0 sessions +desktop offline +macmini busy: 26.7 GB free, 14 threads 86% busy, 1 sessions +18:39:24 + 18:39:24 up 8 days 3:22, 0 users, load average: 2.27, 1.66, 1.44 +ludothinkpad ok: 28.3 GB free, 4 threads 62% busy, 0 sessions +desktop offline +macmini ok: 27.1 GB free, 14 threads 70% busy, 1 sessions +18:40:28 + 18:40:28 up 8 days 3:23, 0 users, load average: 1.95, 1.72, 1.48 +ludothinkpad ok: 28.3 GB free, 4 threads 63% busy, 0 sessions +desktop offline +macmini ok: 26.7 GB free, 14 threads 84% busy, 1 sessions +18:41:32 + 18:41:32 up 8 days 3:24, 0 users, load average: 3.32, 2.22, 1.67 +ludothinkpad ok: 28.2 GB free, 4 threads 61% busy, 0 sessions +desktop offline +macmini busy: 26.8 GB free, 14 threads 85% busy, 1 sessions +18:42:36 + 18:42:36 up 8 days 3:25, 0 users, load average: 3.13, 2.33, 1.75 +ludothinkpad ok: 28.2 GB free, 4 threads 60% busy, 0 sessions +desktop offline +macmini busy: 27.1 GB free, 14 threads 91% busy, 1 sessions +18:43:40 + 18:43:40 up 8 days 3:26, 0 users, load average: 3.27, 2.48, 1.83 +ludothinkpad busy: 28.1 GB free, 4 threads 90% busy, 0 sessions +desktop offline +macmini busy: 28.3 GB free, 14 threads 92% busy, 1 sessions +18:44:44 + 18:44:44 up 8 days 3:27, 0 users, load average: 2.14, 2.32, 1.82 +ludothinkpad ok: 28.1 GB free, 4 threads 55% busy, 0 sessions +desktop offline +macmini busy: 30.4 GB free, 14 threads 88% busy, 1 sessions +18:45:48 + 18:45:48 up 8 days 3:28, 0 users, load average: 4.94, 3.06, 2.11 +ludothinkpad busy: 25.9 GB free, 4 threads 86% busy, 0 sessions +desktop offline +macmini ok: 28.7 GB free, 14 threads 84% busy, 1 sessions +18:46:53 + 18:46:53 up 8 days 3:29, 0 users, load average: 6.55, 3.92, 2.47 +ludothinkpad busy: 25.4 GB free, 4 threads 99% busy, 0 sessions +desktop offline +macmini ok: 29.3 GB free, 14 threads 81% busy, 1 sessions +18:47:57 + 18:47:57 up 8 days 3:30, 0 users, load average: 8.50, 4.96, 2.93 +ludothinkpad busy: 24.0 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 27.9 GB free, 14 threads 90% busy, 1 sessions +18:49:01 + 18:49:01 up 8 days 3:31, 0 users, load average: 8.59, 5.68, 3.31 +ludothinkpad busy: 22.7 GB free, 4 threads 99% busy, 0 sessions +desktop offline +macmini ok: 28.2 GB free, 14 threads 85% busy, 1 sessions +18:50:05 + 18:50:05 up 8 days 3:32, 0 users, load average: 7.81, 6.07, 3.61 +ludothinkpad busy: 24.5 GB free, 4 threads 90% busy, 0 sessions +desktop offline +macmini busy: 28.6 GB free, 14 threads 96% busy, 1 sessions +18:51:09 + 18:51:09 up 8 days 3:33, 0 users, load average: 8.29, 6.50, 3.93 +ludothinkpad busy: 24.3 GB free, 4 threads 92% busy, 0 sessions +desktop offline +macmini busy: 28.0 GB free, 14 threads 94% busy, 1 sessions +18:52:14 + 18:52:14 up 8 days 3:35, 0 users, load average: 5.58, 6.06, 3.95 +ludothinkpad busy: 26.0 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 26.3 GB free, 14 threads 87% busy, 1 sessions +18:53:18 + 18:53:18 up 8 days 3:36, 0 users, load average: 4.53, 5.69, 3.97 +ludothinkpad busy: 27.2 GB free, 4 threads 89% busy, 0 sessions +desktop offline +macmini busy: 26.8 GB free, 14 threads 87% busy, 1 sessions +18:54:22 + 18:54:22 up 8 days 3:37, 0 users, load average: 5.31, 5.64, 4.07 +ludothinkpad busy: 26.3 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 29.3 GB free, 14 threads 91% busy, 1 sessions +18:55:26 + 18:55:26 up 8 days 3:38, 0 users, load average: 10.47, 6.99, 4.63 +ludothinkpad busy: 26.1 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 26.7 GB free, 14 threads 90% busy, 1 sessions +18:56:30 + 18:56:30 up 8 days 3:39, 0 users, load average: 9.27, 7.45, 4.96 +ludothinkpad busy: 26.2 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 28.5 GB free, 14 threads 92% busy, 1 sessions +18:57:35 + 18:57:35 up 8 days 3:40, 0 users, load average: 7.79, 7.39, 5.10 +ludothinkpad busy: 26.1 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini ok: 27.1 GB free, 14 threads 80% busy, 1 sessions +18:58:39 + 18:58:39 up 8 days 3:41, 0 users, load average: 8.06, 7.55, 5.32 +ludothinkpad busy: 26.4 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 31.8 GB free, 14 threads 95% busy, 1 sessions +18:59:43 + 18:59:43 up 8 days 3:42, 0 users, load average: 8.44, 7.65, 5.50 +ludothinkpad busy: 26.2 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 31.4 GB free, 14 threads 94% busy, 1 sessions +19:00:47 + 19:00:47 up 8 days 3:43, 0 users, load average: 11.04, 8.66, 6.00 +ludothinkpad busy: 24.9 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 31.8 GB free, 14 threads 88% busy, 1 sessions +19:01:51 + 19:01:51 up 8 days 3:44, 0 users, load average: 11.91, 9.37, 6.41 +ludothinkpad busy: 24.4 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini ok: 32.9 GB free, 14 threads 77% busy, 1 sessions +19:02:56 + 19:02:56 up 8 days 3:45, 0 users, load average: 11.64, 9.85, 6.79 +ludothinkpad ok: 25.5 GB free, 4 threads 70% busy, 0 sessions +desktop offline +macmini busy: 30.9 GB free, 14 threads 91% busy, 1 sessions +19:04:00 + 19:04:00 up 8 days 3:46, 0 users, load average: 11.42, 10.06, 7.06 +ludothinkpad busy: 23.4 GB free, 4 threads 99% busy, 0 sessions +desktop offline +macmini busy: 28.4 GB free, 14 threads 94% busy, 1 sessions +19:05:04 + 19:05:04 up 8 days 3:47, 0 users, load average: 9.83, 9.96, 7.24 +ludothinkpad busy: 23.2 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini ok: 31.4 GB free, 14 threads 80% busy, 1 sessions +19:06:09 + 19:06:09 up 8 days 3:48, 0 users, load average: 8.38, 9.68, 7.34 +ludothinkpad ok: 22.7 GB free, 4 threads 17% busy, 0 sessions +desktop offline +macmini busy: 29.8 GB free, 14 threads 86% busy, 1 sessions +19:07:13 + 19:07:13 up 8 days 3:49, 0 users, load average: 4.51, 8.27, 7.00 +ludothinkpad ok: 25.7 GB free, 4 threads 75% busy, 0 sessions +desktop offline +macmini busy: 26.5 GB free, 14 threads 89% busy, 1 sessions +19:08:17 + 19:08:17 up 8 days 3:51, 0 users, load average: 6.77, 8.13, 7.04 +ludothinkpad busy: 25.8 GB free, 4 threads 95% busy, 0 sessions +desktop offline +macmini busy: 30.8 GB free, 14 threads 91% busy, 1 sessions +19:09:22 + 19:09:22 up 8 days 3:52, 0 users, load average: 8.27, 8.25, 7.14 +ludothinkpad busy: 25.2 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 28.3 GB free, 14 threads 91% busy, 1 sessions +19:10:26 + 19:10:26 up 8 days 3:53, 0 users, load average: 8.88, 8.57, 7.34 +ludothinkpad busy: 24.8 GB free, 4 threads 99% busy, 0 sessions +desktop offline +macmini ok: 32.4 GB free, 14 threads 72% busy, 1 sessions +19:11:30 + 19:11:30 up 8 days 3:54, 0 users, load average: 13.33, 10.05, 7.94 +ludothinkpad busy: 24.7 GB free, 4 threads 97% busy, 0 sessions +desktop offline +macmini busy: 30.1 GB free, 14 threads 87% busy, 1 sessions +19:12:35 + 19:12:35 up 8 days 3:55, 0 users, load average: 10.92, 10.13, 8.12 +ludothinkpad ok: 26.4 GB free, 4 threads 76% busy, 0 sessions +desktop offline +macmini busy: 29.3 GB free, 14 threads 86% busy, 1 sessions +19:13:39 + 19:13:39 up 8 days 3:56, 0 users, load average: 9.98, 9.89, 8.16 +ludothinkpad busy: 25.8 GB free, 4 threads 90% busy, 0 sessions +desktop offline +macmini busy: 28.8 GB free, 14 threads 93% busy, 1 sessions +19:14:43 + 19:14:43 up 8 days 3:57, 0 users, load average: 8.95, 9.63, 8.19 +ludothinkpad busy: 25.1 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini ok: 29.6 GB free, 14 threads 71% busy, 1 sessions +19:15:47 + 19:15:47 up 8 days 3:58, 0 users, load average: 12.02, 10.38, 8.55 +ludothinkpad busy: 24.5 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 28.1 GB free, 14 threads 93% busy, 1 sessions +19:16:52 + 19:16:52 up 8 days 3:59, 0 users, load average: 13.82, 11.21, 8.95 +ludothinkpad busy: 23.9 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini ok: 28.4 GB free, 14 threads 75% busy, 1 sessions +19:17:56 + 19:17:56 up 8 days 4:00, 0 users, load average: 11.95, 11.20, 9.10 +ludothinkpad busy: 25.0 GB free, 4 threads 99% busy, 0 sessions +desktop offline +macmini ok: 28.4 GB free, 14 threads 81% busy, 1 sessions +19:19:00 + 19:19:00 up 8 days 4:01, 0 users, load average: 11.46, 11.14, 9.22 +ludothinkpad busy: 24.6 GB free, 4 threads 95% busy, 0 sessions +desktop offline +macmini ok: 26.4 GB free, 14 threads 83% busy, 1 sessions +19:20:04 + 19:20:04 up 8 days 4:02, 0 users, load average: 11.11, 10.97, 9.28 +ludothinkpad busy: 24.6 GB free, 4 threads 93% busy, 0 sessions +desktop offline +macmini ok: 26.7 GB free, 14 threads 85% busy, 1 sessions +19:21:08 + 19:21:08 up 8 days 4:03, 0 users, load average: 9.81, 10.60, 9.27 +ludothinkpad busy: 24.4 GB free, 4 threads 91% busy, 0 sessions +desktop offline +macmini ok: 27.8 GB free, 14 threads 75% busy, 1 sessions +19:22:13 + 19:22:13 up 8 days 4:04, 0 users, load average: 5.98, 9.51, 9.00 +ludothinkpad ok: 23.8 GB free, 4 threads 18% busy, 0 sessions +desktop offline +macmini busy: 29.7 GB free, 14 threads 85% busy, 1 sessions +19:23:17 + 19:23:17 up 8 days 4:06, 0 users, load average: 4.01, 8.27, 8.60 +ludothinkpad ok: 23.1 GB free, 4 threads 56% busy, 0 sessions +desktop offline +macmini ok: 28.2 GB free, 14 threads 79% busy, 1 sessions diff --git a/benchmarks/server-mixed-2026-10-18/mixed.json b/benchmarks/server-mixed-2026-10-18/mixed.json new file mode 100644 index 000000000..36b21c327 --- /dev/null +++ b/benchmarks/server-mixed-2026-10-18/mixed.json @@ -0,0 +1,367 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-18T17:23:30+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4, + "note": "ThinkPad: Intel Core i7-7500U (2 cores, 4 threads), 32 GB, NixOS, Linux 6.18; the bots on the Mac mini (M4 Pro) over the tailnet" + }, + "commit": "4ea2243e4d1a44f910857bd759845db70e3690a8", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon,vanilla", + "bots": "1,10,25,50", + "behaviour": "mixed", + "join_every": 1.0, + "warmup": 60, + "seconds": 300, + "seed": 12345, + "explore_speed": 0, + "gamerule": "", + "heap": "4g", + "out": "mixed.json", + "nice": 19, + "bots_via": "ssh macmini", + "bots_bin": "horizon-bots (on the Mac mini)", + "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": "mixed", + "start_seconds": 10.92, + "mspt": { + "average": 2.38, + "p50": 1.97, + "p95": 5.17, + "p99": 18.2 + }, + "mspt_worst_p99": 45.6, + "tps": 20.0, + "rss_mb": { + "mean": 653.7, + "max": 659.2 + }, + "cpu_percent": 24.51, + "chunks_per_second": 9.9, + "unique_per_second": 0.3, + "forgotten_per_second": 9.93, + "waited_ticks_per_second": 0.0, + "chunks_total": 3951, + "chunks_per_bot": { + "walk": 3951.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": 1, + "behaviour": "mixed", + "start_seconds": 14.75, + "mspt": { + "average": 17.9, + "p50": 18.39, + "p95": 27.58, + "p99": 47.28 + }, + "mspt_worst_p99": 423.8, + "tps": 20.0, + "rss_mb": { + "mean": 3382.06, + "max": 3394.1 + }, + "cpu_percent": 64.02, + "chunks_per_second": 9.92, + "unique_per_second": 0.29, + "forgotten_per_second": 9.95, + "waited_ticks_per_second": 0.0, + "chunks_total": 3846, + "chunks_per_bot": { + "walk": 3846.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": "mixed", + "start_seconds": 10.22, + "mspt": { + "average": 12.39, + "p50": 8.33, + "p95": 35.99, + "p99": 65.9 + }, + "mspt_worst_p99": 117.1, + "tps": 20.0, + "rss_mb": { + "mean": 935.85, + "max": 1008.6 + }, + "cpu_percent": 210.37, + "chunks_per_second": 98.22, + "unique_per_second": 36.49, + "forgotten_per_second": 98.25, + "waited_ticks_per_second": 0.0, + "chunks_total": 39618, + "chunks_per_bot": { + "walk": 3992.17, + "explore": 7359.5, + "idle": 473.0 + }, + "unique_chunks_per_bot": { + "walk": 696.83, + "explore": 6869.0, + "idle": 473.0 + }, + "resent": 0, + "pulled_back": 6267, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "mixed", + "start_seconds": 14.54, + "mspt": { + "average": 34.47, + "p50": 29.67, + "p95": 63.52, + "p99": 138.58 + }, + "mspt_worst_p99": 884.7, + "tps": 20.0, + "rss_mb": { + "mean": 3594.26, + "max": 3661.7 + }, + "cpu_percent": 217.13, + "chunks_per_second": 24.34, + "unique_per_second": 19.13, + "forgotten_per_second": 20.12, + "waited_ticks_per_second": 0.62, + "chunks_total": 10443, + "chunks_per_bot": { + "walk": 679.83, + "explore": 2824.0, + "idle": 358.0 + }, + "unique_chunks_per_bot": { + "walk": 389.17, + "explore": 2824.0, + "idle": 358.0 + }, + "resent": 0, + "pulled_back": 5500, + "moved_too_quickly": 12, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "mixed", + "start_seconds": 14.73, + "mspt": { + "average": 24.0, + "p50": 21.07, + "p95": 49.72, + "p99": 80.57 + }, + "mspt_worst_p99": 168.8, + "tps": 20.0, + "rss_mb": { + "mean": 1013.07, + "max": 1179.4 + }, + "cpu_percent": 192.47, + "chunks_per_second": 178.23, + "unique_per_second": 31.85, + "forgotten_per_second": 177.93, + "waited_ticks_per_second": 60.59, + "chunks_total": 73657, + "chunks_per_bot": { + "walk": 3927.87, + "explore": 2474.8, + "idle": 473.0 + }, + "unique_chunks_per_bot": { + "walk": 691.73, + "explore": 2447.8, + "idle": 473.0 + }, + "resent": 0, + "pulled_back": 5532, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "mixed", + "start_seconds": 28.57, + "mspt": { + "average": 31.59, + "p50": 25.18, + "p95": 70.03, + "p99": 222.74 + }, + "mspt_worst_p99": 2319.6, + "tps": 20.0, + "rss_mb": { + "mean": 3742.51, + "max": 4055.0 + }, + "cpu_percent": 218.34, + "chunks_per_second": 30.37, + "unique_per_second": 10.84, + "forgotten_per_second": 29.44, + "waited_ticks_per_second": 50.91, + "chunks_total": 14193, + "chunks_per_bot": { + "walk": 640.2, + "explore": 738.0, + "idle": 180.0 + }, + "unique_chunks_per_bot": { + "walk": 211.33, + "explore": 737.6, + "idle": 180.0 + }, + "resent": 0, + "pulled_back": 4524, + "moved_too_quickly": 324, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 56 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "mixed", + "start_seconds": 19.84, + "mspt": { + "average": 35.2, + "p50": 32.12, + "p95": 69.04, + "p99": 96.56 + }, + "mspt_worst_p99": 240.8, + "tps": 20.0, + "rss_mb": { + "mean": 1013.2, + "max": 1249.1 + }, + "cpu_percent": 217.68, + "chunks_per_second": 273.18, + "unique_per_second": 34.58, + "forgotten_per_second": 268.19, + "waited_ticks_per_second": 138.29, + "chunks_total": 115527, + "chunks_per_bot": { + "walk": 3300.1, + "explore": 1192.4, + "idle": 460.0 + }, + "unique_chunks_per_bot": { + "walk": 632.67, + "explore": 1186.9, + "idle": 460.0 + }, + "resent": 0, + "pulled_back": 8369, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 57 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "mixed", + "start_seconds": 20.58, + "mspt": { + "average": 29.74, + "p50": 23.6, + "p95": 62.25, + "p99": 137.41 + }, + "mspt_worst_p99": 489.3, + "tps": 20.0, + "rss_mb": { + "mean": 3995.71, + "max": 4597.8 + }, + "cpu_percent": 294.31, + "chunks_per_second": 94.36, + "unique_per_second": 17.76, + "forgotten_per_second": 94.69, + "waited_ticks_per_second": 101.48, + "chunks_total": 41637, + "chunks_per_bot": { + "walk": 1104.97, + "explore": 628.8, + "idle": 220.0 + }, + "unique_chunks_per_bot": { + "walk": 279.4, + "explore": 626.4, + "idle": 220.0 + }, + "resent": 0, + "pulled_back": 12034, + "moved_too_quickly": 2193, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 57 + } + ], + "horizon_build": "v2026.10.18.15 release binaries (horizon-client, the engine, at 6c078b28); horizon-server from #898 (4ea2243e, the supervisor only)" +} \ No newline at end of file diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 29a02553f..82dca390d 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -31,31 +31,42 @@ toml = "1.1" naga = { version = "30.0.1", features = ["wgsl-in"] } # Java (OptiFine/Iris) shader packs, translated to WGSL. horizon-shaderpack = { path = "../horizon-shaderpack" } -cpal = "0.16" +# Sound (ALSA on Linux); the `audio` feature. +cpal = { version = "0.16", optional = true } symphonia = { version = "0.5", default-features = false, features = ["ogg", "vorbis"] } miniz_oxide = "0.8" ab_glyph = "0.2.32" log = "0.4" chrono = { version = "0.4.42", default-features = false, features = ["clock", "std"] } -flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] } +flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] } horizon-theme = { path = "../horizon-theme" } # Opt-in data collection: the game keeps, the launcher sends (docs/telemetry.md). horizon-telemetry = { path = "../horizon-telemetry", default-features = false } horizon-bench = { path = "../horizon-bench" } arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] } zip = { version = "2", default-features = false, features = ["deflate"] } -# Controllers (evdev + libudev on Linux, IOKit on macOS, Windows.Gaming.Input). -gilrs = "0.11" +# Controllers (evdev + libudev on Linux, IOKit on macOS, Windows.Gaming.Input); the `controllers` feature. +gilrs = { version = "0.11", optional = true } # The DualSense's rumble, adaptive triggers and lights over HID (gilrs only reads it). -horizon-dualsense = { path = "../horizon-dualsense" } +horizon-dualsense = { path = "../horizon-dualsense", optional = true } # HTTPS to the Minecraft services (online-mode session join). ureq = { version = "2", default-features = false, features = ["tls"] } +[target.'cfg(unix)'.dependencies] +# The server thread's CPU time per tick (`HORIZON_SPIKES`, spans.rs). +rustix = { version = "1", default-features = false, features = ["std", "time"] } + [target.'cfg(windows)'.build-dependencies] # The icon resource in the .exe (build.rs). winresource = "0.1" [features] +default = ["audio", "controllers"] +# Sound output. Without it (and `controllers`) the program links neither libasound nor libudev on +# Linux: the server build (`--no-default-features`, released as horizon-engine; docs/server.md). +audio = ["dep:cpal"] +# Controllers: gilrs, and the DualSense's own output. Without it only `horizon-ctl pad`'s virtual pad. +controllers = ["dep:gilrs", "dep:horizon-dualsense"] # Records the call sites of mob random draws (`mob_ai_probe` traces). rng-trace = ["horizon-core/rng-trace"] diff --git a/crates/horizon-client/examples/arrow_probe.rs b/crates/horizon-client/examples/arrow_probe.rs index 20c0883e3..63ff2df32 100644 --- a/crates/horizon-client/examples/arrow_probe.rs +++ b/crates/horizon-client/examples/arrow_probe.rs @@ -58,11 +58,12 @@ fn main() -> Result<()> { let root = PathBuf::from(&args[0]); let dir = PathBuf::from(&args[1]); let assets = Assets::load(&root)?; - let mut scene = World::test_scene(&assets, 1)?; + let render = assets.reload(&root)?; + let mut scene = World::test_scene(&assets, &render, 1)?; fs::write( dir.join("scene.json"), serde_json::to_vec( - &serde_json::json!({"radius":1,"resident_chunks":scene.chunks.len(),"model_gallery":assets.model_gallery}), + &serde_json::json!({"radius":1,"resident_chunks":scene.chunks.len(),"model_gallery":render.model_gallery}), )?, )?; if args[2] == "--describe" { diff --git a/crates/horizon-client/examples/auto_jump_probe.rs b/crates/horizon-client/examples/auto_jump_probe.rs index e4a9848e8..d8dee95df 100644 --- a/crates/horizon-client/examples/auto_jump_probe.rs +++ b/crates/horizon-client/examples/auto_jump_probe.rs @@ -31,13 +31,14 @@ fn main() -> Result<()> { }; let root = PathBuf::from(root); let assets = Assets::load(&root)?; - let mut scene = World::test_scene(&assets, 1)?; + let render = assets.reload(&root)?; + let mut scene = World::test_scene(&assets, &render, 1)?; let binding = collisions::load(&root, assets.registry)?; let resources = MotionResources::load(&root, &assets)?; fs::write( scene_json, serde_json::to_vec(&serde_json::json!({ - "radius": 1, "resident_chunks": scene.chunks.len(), "model_gallery": assets.model_gallery, + "radius": 1, "resident_chunks": scene.chunks.len(), "model_gallery": render.model_gallery, }))?, )?; let mut out = BufWriter::new(fs::File::create(output)?); diff --git a/crates/horizon-client/examples/block_entity_tickers_fixture.rs b/crates/horizon-client/examples/block_entity_tickers_fixture.rs new file mode 100644 index 000000000..f08c333f6 --- /dev/null +++ b/crates/horizon-client/examples/block_entity_tickers_fixture.rs @@ -0,0 +1,99 @@ +//! The Rust side of tools/test_block_entity_tickers_parity.py: the ops of +//! `VanillaBlockEntityTickerOracle` on `BlockEntities`, as `World` drives it +//! (a state write calls `state_changed`), printing the tick order. +use horizon_client::{ + block_entities::{BlockEntities, Pos, Ticking}, + containers::BlockEntity, +}; +use std::collections::HashMap; + +/// State ids of the fixture: 0 air, 1 a block whose block entity ticks, 2 a +/// jukebox without a record, 3 a block entity that never ticks (a chest). +fn state(name: &str) -> u32 { + match name { + "chest" | "barrel" => 3, + "jukebox" => 2, + _ => 1, + } +} + +fn entity(name: &str) -> BlockEntity { + if name.starts_with("jukebox") { + // The game makes a jukebox's block entity when a record goes in. + return BlockEntity::Jukebox(Default::default()); + } + BlockEntity::for_block(&format!("minecraft:{name}")) + .unwrap_or_else(|| panic!("no block entity for {name}")) +} + +fn main() { + let args: Vec = std::env::args().collect(); + let input = std::fs::read_to_string(&args[1]).expect("input"); + let mut out = String::new(); + let mut entities = BlockEntities::default(); + let mut states: HashMap = HashMap::new(); + let mut kinds: HashMap = HashMap::new(); + let table = vec![Ticking::No, Ticking::Yes, Ticking::Idle, Ticking::No]; + for line in input.lines() { + let w: Vec<&str> = line.split_whitespace().collect(); + let pos = |i: usize| -> Pos { + let n = |j: usize| w[i + j].parse::().expect("coordinate"); + (n(0), n(1), n(2)) + }; + match w[0] { + "reset" => { + entities = BlockEntities::default(); + entities.set_states(table.clone()); + states.clear(); + kinds.clear(); + } + "load" => { + let mut chunk = Vec::new(); + for i in (3..w.len()).step_by(4) { + let p = pos(i + 1); + states.insert(p, state(w[i])); + kinds.insert(p, w[i].to_owned()); + chunk.push((p, entity(w[i]))); + } + entities.load_chunk(chunk); + } + "place" => { + let p = pos(2); + // World::set, then the game adds the block entity. + let old = states.insert(p, state(w[1])).unwrap_or(0); + kinds.insert(p, w[1].to_owned()); + entities.state_changed(p, old, state(w[1])); + entities.insert(p, entity(w[1])); + } + "replace" => { + let p = pos(1); + entities.insert(p, entity(&kinds[&p])); + } + "remove" => { + let p = pos(1); + entities.remove(&p); + let old = states.insert(p, 0).unwrap_or(0); + entities.state_changed(p, old, 0); + } + "record" => { + let p = pos(1); + let s = if w[4] == "1" { 1 } else { 2 }; + let old = states.insert(p, s).unwrap_or(0); + entities.state_changed(p, old, s); + } + "unload" => { + let c = (w[1].parse::().unwrap(), w[2].parse::().unwrap()); + entities.retain(|p, _| (p.0 >> 4, p.2 >> 4) != c); + } + "tick" => { + out.push_str("tick"); + for (p, _) in entities.tickers(|p| states.get(&p).copied().unwrap_or(0)) { + out.push_str(&format!(" {},{},{}", p.0, p.1, p.2)); + } + out.push('\n'); + } + other => panic!("unknown op {other}"), + } + } + std::fs::write(&args[2], out).expect("output"); +} diff --git a/crates/horizon-client/examples/block_particles_fixture.rs b/crates/horizon-client/examples/block_particles_fixture.rs index e9c207a7e..63ef242b7 100644 --- a/crates/horizon-client/examples/block_particles_fixture.rs +++ b/crates/horizon-client/examples/block_particles_fixture.rs @@ -12,9 +12,11 @@ fn main() -> Result<(), Box> { let args: Vec<_> = std::env::args().collect(); let root = Path::new(&args[1]); let assets = Assets::load(root)?; + let render = assets.reload(root)?; let facts = BlockFacts::load(root, assets.registry)?; let tables = MeshTables::new( &assets, + &render, &facts, models::load_visibility(root, assets.registry)?, )?; diff --git a/crates/horizon-client/examples/breaking_fixture.rs b/crates/horizon-client/examples/breaking_fixture.rs index ec8f7a68b..2016fd613 100644 --- a/crates/horizon-client/examples/breaking_fixture.rs +++ b/crates/horizon-client/examples/breaking_fixture.rs @@ -18,9 +18,11 @@ fn main() -> Result<(), Box> { let args: Vec<_> = std::env::args().collect(); let root = Path::new(&args[1]); let assets = Assets::load(root)?; + let render = assets.reload(root)?; let facts = BlockFacts::load(root, assets.registry)?; let tables = MeshTables::new( &assets, + &render, &facts, models::load_visibility(root, assets.registry)?, )?; @@ -33,7 +35,7 @@ fn main() -> Result<(), Box> { let mut vertices = Vec::new(); let mut translucent = false; if facts.get(state).render_shape == RenderShape::Model { - let models = assets + let models = render .model_catalog .collect(state, BlockPos::new(p[0], p[1], p[2]))?; let offset = tables.offset(state, p[0], p[2]).unwrap_or([0.0; 3]); diff --git a/crates/horizon-client/examples/chunk_bench.rs b/crates/horizon-client/examples/chunk_bench.rs index 6ad2cbd99..be619245f 100644 --- a/crates/horizon-client/examples/chunk_bench.rs +++ b/crates/horizon-client/examples/chunk_bench.rs @@ -31,10 +31,12 @@ fn main() -> Result<()> { }; let (seed, size) = (flag("--seed", 12345), flag("--size", 8) as i32); let assets = Assets::load(&root)?; + let render = assets.reload(&root)?; let facts = BlockFacts::load(&root, assets.registry)?; let biomes = Biomes::load(&root)?; let tables = MeshTables::new( &assets, + &render, &facts, models::load_visibility(&root, assets.registry)?, )?; @@ -132,6 +134,7 @@ fn main() -> Result<()> { let mut mesher = Mesher { nether_shading: false, assets: &assets, + render: &render, tables: &tables, biomes: &biomes, visibility: tables.visibility.clone(), diff --git a/crates/horizon-client/examples/interaction_input_fixture.rs b/crates/horizon-client/examples/interaction_input_fixture.rs new file mode 100644 index 000000000..bb408dd88 --- /dev/null +++ b/crates/horizon-client/examples/interaction_input_fixture.rs @@ -0,0 +1,122 @@ +use horizon_client::interaction_input::{ + Button, InteractionInput, InteractionWorld, TargetUseWorld, use_on_target, +}; +use serde_json::Value; +use std::io::{BufRead, Write}; + +struct World { + using: bool, + destroying: bool, + entity: bool, + dig_on_attack: bool, + begin_using: bool, + delay: u32, + events: Vec, + passing: bool, +} +impl InteractionWorld for World { + fn using_item(&self) -> bool { + self.using + } + fn release_using(&mut self) { + self.events.push("release".into()); + self.using = false; + } + fn start_attack(&mut self) -> bool { + self.events.push("attack".into()); + if !self.entity { + self.destroying = self.dig_on_attack; + } + false + } + fn start_use(&mut self) { + if self.destroying { + return; + } + self.delay = 4; + let entity = self.entity; + use_on_target(self, entity); + } + fn pick(&mut self) { + self.events.push("pick".into()); + } + fn use_delay(&self) -> u32 { + self.delay + } + fn continue_attack(&mut self, down: bool) { + if self.using { + return; + } + let down = down && !self.entity; + self.events.push(format!("continue {down}")); + if !down { + self.destroying = false; + } + } +} + +impl TargetUseWorld for World { + fn use_entity(&mut self) -> bool { + self.events + .push(if self.passing { "entity" } else { "use" }.into()); + if self.passing { + false + } else { + self.using = self.begin_using; + true + } + } + fn use_block(&mut self) -> bool { + self.events + .push(if self.passing { "block" } else { "use" }.into()); + if self.passing { + false + } else { + self.using = self.begin_using; + true + } + } + fn use_item(&mut self) { + self.events.push("item".into()); + self.using = self.begin_using; + } +} + +fn main() -> Result<(), Box> { + let args: Vec<_> = std::env::args().collect(); + let input = std::io::BufReader::new(std::fs::File::open(&args[1])?); + let mut out = std::io::BufWriter::new(std::fs::File::create(&args[2])?); + for (i, line) in input.lines().enumerate() { + let row: Value = serde_json::from_str(&line?)?; + let flag = |key: &str| row[key].as_bool().unwrap(); + let mut world = World { + using: flag("using"), + destroying: flag("destroying"), + entity: flag("entity"), + dig_on_attack: flag("dig_on_attack"), + begin_using: flag("begin_using"), + delay: row["delay"].as_u64().unwrap() as u32, + events: vec![], + passing: row["passing"].as_bool().unwrap_or(false), + }; + let mut input = InteractionInput::default(); + for button in row["clicks"].as_array().unwrap() { + input.press(match button.as_u64().unwrap() { + 0 => Button::Attack, + 1 => Button::Use, + _ => Button::Pick, + }); + } + input.tick(&mut world, flag("attack_down"), flag("use_down")); + writeln!(out, "== {i}")?; + for event in world.events { + writeln!(out, "{event}")?; + } + writeln!( + out, + "state {} {} {}", + world.using, world.destroying, world.delay + )?; + } + Ok(()) +} diff --git a/crates/horizon-client/examples/lan_flat.rs b/crates/horizon-client/examples/lan_flat.rs index 4800f05fa..283c3a22b 100644 --- a/crates/horizon-client/examples/lan_flat.rs +++ b/crates/horizon-client/examples/lan_flat.rs @@ -101,6 +101,8 @@ fn main() -> Result<(), Box> { sprinting: false, equipment: Default::default(), health: 20.0, + attributes: Vec::new(), + living_flags: 0, }; loop { world.game_time += 1; @@ -128,7 +130,9 @@ fn main() -> Result<(), Box> { eprintln!("[lan] {packet:?}"); } } - HostEvent::Chat(line) | HostEvent::Warn(line) => println!("{line}"), + HostEvent::Chat { line, .. } | HostEvent::Warn(line) | HostEvent::Error(line) => { + println!("{line}") + } HostEvent::Left(_) => {} } } diff --git a/crates/horizon-client/examples/light_parity.rs b/crates/horizon-client/examples/light_parity.rs index 29488130e..f660189a2 100644 --- a/crates/horizon-client/examples/light_parity.rs +++ b/crates/horizon-client/examples/light_parity.rs @@ -206,7 +206,7 @@ fn incremental( sky_light: bool, edits: usize, ) { - use horizon_client::light::relight; + use horizon_client::light::{LightChanges, relight}; use std::sync::Arc; let mut world: HashMap<(i32, i32), Arc> = HashMap::new(); let inner: Vec<(i32, i32)> = { @@ -285,7 +285,14 @@ fn incremental( if old == state || !tables.differs(old, state) { continue; } - relight(&mut world, tables, sky_light, &[(x, y, z)], false); + relight( + &mut world, + tables, + sky_light, + &[(x, y, z)], + false, + &mut LightChanges::default(), + ); for dz in -1..=1 { for dx in -1..=1 { let (kx, kz) = (cx + dx, cz + dz); diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 087fd3edf..0b3adec31 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -999,6 +999,7 @@ fn main() -> horizon_client::Result<()> { hero: false, uuid: PLAYER_UUID, allies: Default::default(), + remote: false, } }); let mut scratch = LegacyRandom::new(0); diff --git a/crates/horizon-client/examples/model_library_bench.rs b/crates/horizon-client/examples/model_library_bench.rs index d3aba51e0..2089e39e1 100644 --- a/crates/horizon-client/examples/model_library_bench.rs +++ b/crates/horizon-client/examples/model_library_bench.rs @@ -56,10 +56,11 @@ fn main() -> horizon_client::Result<()> { let initial = LIVE.load(Relaxed); let start = Instant::now(); let assets = Assets::load(root)?; + let render = assets.reload(root)?; let block_ms = start.elapsed().as_secs_f64() * 1000.; let block_retained = LIVE.load(Relaxed) - initial; let start_items = Instant::now(); - let items = ItemRenderer::load_with_library(root, assets.model_library.clone())?; + let items = ItemRenderer::load_with_library(root, render.model_library.clone())?; let item_ms = start_items.elapsed().as_secs_f64() * 1000.; let total_ms = start.elapsed().as_secs_f64() * 1000.; let retained = LIVE.load(Relaxed) - initial; @@ -74,7 +75,7 @@ fn main() -> horizon_client::Result<()> { horizon_core::position::BlockPos::new(0, 0, 0), horizon_core::position::BlockPos::new(-17, 65, 31), ] { - if let Ok(selected) = assets.model_catalog.collect(id, pos) { + if let Ok(selected) = render.model_catalog.collect(id, pos) { for (variant, model) in selected { format!("{variant:?}").hash(&mut hash); model.ambient_occlusion.hash(&mut hash); diff --git a/crates/horizon-client/examples/player_sync_fixture.rs b/crates/horizon-client/examples/player_sync_fixture.rs new file mode 100644 index 000000000..b50a672af --- /dev/null +++ b/crates/horizon-client/examples/player_sync_fixture.rs @@ -0,0 +1,72 @@ +use horizon_client::player_sync::{PositionSender, teleport_velocity}; +use horizon_core::geometry::Vec3; +use horizon_protocol::packets::play::{PlayerPosition, Serverbound as S}; +use serde_json::Value; +use std::io::{BufRead, Write}; + +fn number(value: &Value) -> f64 { + f64::from_bits(u64::from_str_radix(value.as_str().unwrap(), 16).unwrap()) +} + +fn main() -> Result<(), Box> { + let args: Vec<_> = std::env::args().collect(); + let input = std::io::BufReader::new(std::fs::File::open(&args[1])?); + let mut out = std::io::BufWriter::new(std::fs::File::create(&args[2])?); + for line in input.lines() { + let row: Value = serde_json::from_str(&line?)?; + if row["kind"] == "movement" { + let mut sender = PositionSender::default(); + for op in row["ops"].as_array().unwrap() { + let pos = std::array::from_fn(|i| number(&op[i])); + let rot = (number(&op[3]) as f32, number(&op[4]) as f32); + if let Some(packet) = + sender.update(pos, rot, op[5].as_bool().unwrap(), op[6].as_bool().unwrap()) + { + let name = match packet { + S::MovePlayerPos(_) => "pos", + S::MovePlayerPosRot(_) => "posrot", + S::MovePlayerRot(_) => "rot", + S::MovePlayerStatus(_) => "status", + _ => unreachable!(), + }; + write!(out, "{name} ")?; + for byte in &packet.encode()[1..] { + write!(out, "{byte:02x}")?; + } + writeln!(out)?; + } else { + writeln!(out, "-")?; + } + } + } else { + let vector = |key: &str| { + Vec3::new( + number(&row[key][0]), + number(&row[key][1]), + number(&row[key][2]), + ) + }; + let rotation = |key: &str| (number(&row[key][0]) as f32, number(&row[key][1]) as f32); + let old = rotation("old"); + let new = rotation("new"); + let delta = vector("delta"); + let packet = PlayerPosition { + teleport: 0, + position: [0.0; 3], + delta: [delta.x, delta.y, delta.z], + yaw: new.0, + pitch: new.1, + relatives: row["flags"].as_i64().unwrap() as i32, + }; + let v = teleport_velocity(vector("velocity"), old, new, &packet); + writeln!( + out, + "{:016x} {:016x} {:016x}", + v.x.to_bits(), + v.y.to_bits(), + v.z.to_bits() + )?; + } + } + Ok(()) +} diff --git a/crates/horizon-client/examples/portal_scan_bench.rs b/crates/horizon-client/examples/portal_scan_bench.rs new file mode 100644 index 000000000..158b6a440 --- /dev/null +++ b/crates/horizon-client/examples/portal_scan_bench.rs @@ -0,0 +1,263 @@ +//! The `entity_portals` section scan only: `may_hold_portal` over synthetic +//! entity reaches, with the per-tick palette map against the resident cache. +//! Run with prepared client resources: +//! cargo run --profile fast -p horizon-client --example portal_scan_bench -- RESOURCES +use horizon_client::{ + blocks::BlockFacts, + chunk::{Chunk, MIN_Y, SECTIONS, Section}, + fast_hash::FxHashMap, + portal_sections::PortalSections, +}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + position::BlockPos, +}; +use horizon_world::{level::Behaviours, registry::BlockStateId}; +use std::{hint::black_box, path::Path, sync::Arc, time::Instant}; + +/// `Game::swept_portal`'s reach (`Entity.checkInsideBlocks`'s swept box). +fn reach(from: Vec3, to: Vec3, width: f32, height: f32) -> Aabb { + let half = f64::from(width) / 2.0; + let bounds = Aabb::new( + Vec3::new(to.x - half, to.y, to.z - half), + Vec3::new(to.x + half, to.y + f64::from(height), to.z + half), + ) + .deflate(Vec3::new(1.0e-5, 1.0e-5, 1.0e-5)); + bounds + .union_bounds(bounds.move_by(from.subtract(to))) + .inflate(Vec3::new(1.0, 1.0, 1.0)) +} + +fn sections(reach: Aabb) -> (i64, i32, i32, i32, i32, i32, i32) { + let (min, max) = (reach.min_position(), reach.max_position()); + let (min, max) = (BlockPos::containing(min), BlockPos::containing(max)); + let top = SECTIONS as i32 - 1; + let (x0, x1) = (min.x >> 4, max.x >> 4); + let (z0, z1) = (min.z >> 4, max.z >> 4); + let (y0, y1) = ( + ((min.y - MIN_Y) >> 4).clamp(0, top), + ((max.y - MIN_Y) >> 4).clamp(0, top), + ); + let count = (i64::from(x1) - i64::from(x0) + 1) + * (i64::from(y1) - i64::from(y0) + 1) + * (i64::from(z1) - i64::from(z0) + 1); + (count, x0, x1, y0, y1, z0, z1) +} + +/// The original `Game::may_hold_portal`: per-tick `seen`, palette per section. +fn may_hold_portal_baseline( + reach: Aabb, + world: &FxHashMap<(i32, i32), Arc>, + seen: &mut FxHashMap<(i32, i32, i32), bool>, + behaviours: &Behaviours, +) -> bool { + let (count, x0, x1, y0, y1, z0, z1) = sections(reach); + if count > 64 { + return true; + } + (x0..=x1).any(|cx| { + (z0..=z1).any(|cz| { + (y0..=y1).any(|sy| { + *seen.entry((cx, sy, cz)).or_insert_with(|| { + world + .get(&(cx, cz)) + .and_then(|c| c.sections.get(sy as usize)) + .is_some_and(|s| { + s.blocks + .maybe_has(|v| behaviours.portal_axis(BlockStateId(v)).is_some()) + }) + }) + }) + }) + }) +} + +/// The cached `Game::may_hold_portal`: one mask per resident chunk. +fn may_hold_portal_cached( + reach: Aabb, + world: &FxHashMap<(i32, i32), Arc>, + cache: &mut PortalSections, + behaviours: &Behaviours, +) -> bool { + let (count, x0, x1, y0, y1, z0, z1) = sections(reach); + if count > 64 { + return true; + } + let mut y_mask = 0u32; + for sy in y0..=y1 { + y_mask |= 1 << sy; + } + (x0..=x1).any(|cx| { + (z0..=z1).any(|cz| { + world.get(&(cx, cz)).is_some_and(|chunk| { + cache.get((cx, cz), chunk, |v| { + behaviours.portal_axis(BlockStateId(v)).is_some() + }) & y_mask + != 0 + }) + }) + }) +} + +fn main() -> horizon_client::Result<()> { + let root = std::env::args() + .nth(1) + .ok_or("expected prepared client resource directory")?; + let start = Instant::now(); + let registry = horizon_world::level::data::load_registry(Path::new(&root))?; + let (facts, behaviours) = BlockFacts::load_pair(Path::new(&root), ®istry)?; + println!( + "resource_load_ms={:.3}", + start.elapsed().as_secs_f64() * 1000.0 + ); + let len = registry.len() as u32; + let portal: Vec = (0..len) + .filter(|&id| behaviours.portal_axis(BlockStateId(id)).is_some()) + .collect(); + let inactive_states: Vec = (0..len) + .filter(|&id| behaviours.portal_axis(BlockStateId(id)).is_none()) + .collect(); + let _ = &facts; + let portal_state = *portal + .first() + .ok_or("no nether portal block state in the registry")?; + println!("portal_states={}", portal.len()); + + // 500 entities spread over a 17x17 chunk world. Their reaches touch 1-4 + // sections, as an item or a mob standing in or stepping into a portal does. + let grid = 17; + let base = -(grid / 2) * 16; + let entities: Vec<(Vec3, Vec3, f32, f32)> = (0..500) + .map(|i| { + let x = base + (i % grid) * 16 + (i % 5); + let z = base + (i / grid % grid) * 16 + (i % 7); + let y = 64 + (i % 3) * 16; + let from = Vec3::new(f64::from(x), f64::from(y), f64::from(z)); + let to = from.add_vector(Vec3::new(0.1, 0.0, 0.07)); + (from, to, 0.25, 0.25) + }) + .collect(); + let reaches: Vec = entities + .iter() + .map(|&(from, to, w, h)| reach(from, to, w, h)) + .collect(); + + for (name, palette, portals_every) in [ + ("sparse", 1usize, 0usize), + ("dense", 128, 0), + ("global", 300, 0), + ("dense_portal", 128, 5), + ] { + let start = Instant::now(); + let mut world: FxHashMap<(i32, i32), Arc> = FxHashMap::default(); + for czi in 0..grid { + for cxi in 0..grid { + let (cx, cz) = (-(grid / 2) + cxi, -(grid / 2) + czi); + let mut chunk = Chunk::empty(cx, cz); + for (i, section) in chunk.sections.iter_mut().enumerate() { + let values: [u32; 4096] = std::array::from_fn(|j| { + if portals_every > 0 && i % portals_every == 0 && j == 0 { + portal_state + } else { + inactive_states[(j * 7 + i) % palette.min(inactive_states.len())] + } + }); + Arc::make_mut(section).blocks = Section::from_blocks(&values); + } + world.insert((cx, cz), Arc::new(chunk)); + } + } + println!( + "{name} fixture_ms={:.3}", + start.elapsed().as_secs_f64() * 1000.0 + ); + let keys: Vec<_> = world.keys().copied().collect(); + let portal_chunks: Vec<(i32, i32)> = keys + .iter() + .copied() + .filter(|&(cx, cz)| { + world[&(cx, cz)] + .sections + .iter() + .any(|s| s.blocks.maybe_has(|v| v == portal_state)) + }) + .collect(); + println!("{name} portal_chunks={}", portal_chunks.len()); + // The global palette's maybe_has walks the whole ID range, so rescanning + // every chunk each tick (cold/reload/edit_all) is intractable; those rows + // are only meaningful for the palettes whose scans are bounded. + let workloads: &[(&str, usize)] = if name == "global" { + &[("steady", 0), ("edit_1pct", 3)] + } else { + &[ + ("steady", 0), + ("cold", 0), + ("reload", 0), + ("edit_1pct", 3), + ("edit_all", 289), + ] + }; + for &(workload, changed) in workloads { + let mut baseline = Vec::new(); + let mut candidate = Vec::new(); + let mut cache = PortalSections::default(); + let (mut base_hits, mut cand_hits) = (0u64, 0u64); + for sample in 0..8 { + for cached in if sample % 2 == 0 { + [false, true] + } else { + [true, false] + } { + let start = Instant::now(); + let mut result = 0u64; + for tick in 0..300 { + if cached && workload == "cold" { + cache = PortalSections::default(); + } + if cached && workload == "reload" { + cache.clear(); + } + for key in keys.iter().take(changed) { + Arc::make_mut(world.get_mut(key).unwrap()).set( + 0, + MIN_Y, + 0, + inactive_states[tick % inactive_states.len()], + ); + } + let mut seen = FxHashMap::default(); + for reach in &reaches { + let hit = if cached { + may_hold_portal_cached(*reach, &world, &mut cache, &behaviours) + } else { + may_hold_portal_baseline(*reach, &world, &mut seen, &behaviours) + }; + result += hit as u64; + } + } + if cached { + cache = PortalSections::default(); + cand_hits += black_box(result); + } else { + base_hits += black_box(result); + } + if sample > 0 { + let us = start.elapsed().as_secs_f64() * 1e6 / 300.0; + if cached { + candidate.push(us); + } else { + baseline.push(us); + } + } + } + } + assert_eq!( + base_hits, cand_hits, + "{name} {workload}: cached may_hold_portal diverged" + ); + println!("{name} {workload} baseline_us={baseline:.3?} candidate_us={candidate:.3?}"); + } + } + println!("chunk_wrapper_bytes={}", std::mem::size_of::()); + Ok(()) +} diff --git a/crates/horizon-client/examples/resource_memory.rs b/crates/horizon-client/examples/resource_memory.rs index 6deb5a9d4..0408b138b 100644 --- a/crates/horizon-client/examples/resource_memory.rs +++ b/crates/horizon-client/examples/resource_memory.rs @@ -94,12 +94,13 @@ fn main() -> Result<()> { drop(registry); step("registry dropped"); let assets = Assets::load(&root)?; + let render = assets.reload(&root)?; step("assets"); println!( " sprites: {} layers of {}px, {:.0} MB of pixels", - assets.texture_layers, - assets.sprite_size, - assets.pixels.len() as f64 / MB + render.texture_layers, + render.sprite_size, + render.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)?; @@ -114,28 +115,15 @@ fn main() -> Result<()> { step("light tables"); let tables = MeshTables::new( &assets, + &render, &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)?; + let motion = MotionResources::load_with_facts(&root, &assets, &facts)?; 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!( diff --git a/crates/horizon-client/examples/save_batch_bench.rs b/crates/horizon-client/examples/save_batch_bench.rs index 4ee5103de..d35ca8bbb 100644 --- a/crates/horizon-client/examples/save_batch_bench.rs +++ b/crates/horizon-client/examples/save_batch_bench.rs @@ -66,7 +66,6 @@ fn fixture(per_chunk: usize) -> (Vec>, Entities, Names) { for s in &mut template.sections[..8] { Arc::make_mut(s).blocks = PalettedContainer::new(block_strategy(), 1); } - template.heights = Arc::new([64; 256]); for i in 0..256 { let x = i % 16 - 8; let z = i / 16 - 8; diff --git a/crates/horizon-client/examples/save_bench.rs b/crates/horizon-client/examples/save_bench.rs new file mode 100644 index 000000000..2e3084290 --- /dev/null +++ b/crates/horizon-client/examples/save_bench.rs @@ -0,0 +1,128 @@ +//! The region writer on real chunks, without a window: how long a world's +//! chunks take to be encoded, compressed and written by `SaveDir`, against +//! the same encoding and compression done one chunk after another (what the +//! writer thread did alone before it had helpers). +//! +//! save_bench RESOURCES DIMENSION_DIR [--rounds N] +//! +//! DIMENSION_DIR is a saved dimension folder (`saves/W/dimensions/minecraft/ +//! overworld`); its chunks are read once, then each round saves them all into +//! a scratch folder with `save_later` + `flush`, and times the one-thread +//! baseline. The written chunks are checked byte for byte against the +//! baseline's compressed records. +use horizon_client::{ + assets::Assets, + biome::Biomes, + blocks::BlockFacts, + save::{SaveDir, SaveTables, encode_with}, +}; +use horizon_core::position::ChunkPos; +use horizon_world::{ + compression::Compression, + nbt::Limits, + region::{ChunkRecord, RegionFile}, +}; +use std::{path::PathBuf, sync::Arc, time::Instant}; + +type Result = std::result::Result>; + +fn main() -> Result<()> { + let args: Vec = std::env::args().skip(1).collect(); + let usage = "usage: save_bench RESOURCES DIMENSION_DIR [--rounds N]"; + let root = PathBuf::from(args.first().ok_or(usage)?); + let dimension = PathBuf::from(args.get(1).ok_or(usage)?); + let rounds: usize = args + .iter() + .position(|a| a == "--rounds") + .and_then(|i| args.get(i + 1)) + .and_then(|v| v.parse().ok()) + .unwrap_or(5); + + let assets = Assets::load(&root)?; + let facts = BlockFacts::load(&root, assets.registry)?; + let biomes = Arc::new(Biomes::load(&root)?); + let tables = Arc::new(SaveTables::new(&assets).with_block_entities(&facts)); + let registry = assets.registry; + + let source = SaveDir::new(dimension.clone()); + let _ = source.tables.set(tables.clone()); + let mut chunks = Vec::new(); + for entry in std::fs::read_dir(dimension.join("region"))? { + let path = entry?.path(); + if path.extension().is_none_or(|e| e != "mca") { + continue; + } + let region = RegionFile::open(&path)?; + for (pos, _) in region.chunks() { + if let Some(chunk) = source.load(pos.x, pos.z, registry, &biomes) { + chunks.push(Arc::new(chunk)); + } + } + } + chunks.sort_by_key(|c| (c.x, c.z)); + println!("{} chunks from {}", chunks.len(), dimension.display()); + + let scratch = std::env::temp_dir().join(format!("save_bench_{}", std::process::id())); + // Encoding and compressing on one thread (what the writer did alone), + // then SaveDir's writer with its helpers. + let mut times = [Vec::new(), Vec::new(), Vec::new()]; + let mut written = Vec::new(); + for round in 0..rounds { + let started = Instant::now(); + let tags: Vec<_> = chunks + .iter() + .map(|c| encode_with(c, registry, &biomes, Some(&tables), true)) + .collect(); + times[0].push(started.elapsed().as_secs_f64()); + let started = Instant::now(); + let baseline: Vec = tags + .iter() + .map(|tag| ChunkRecord::from_nbt(tag, Compression::Zlib, 0, Limits::default())) + .collect::>()?; + times[1].push(started.elapsed().as_secs_f64()); + drop(tags); + + let _ = std::fs::remove_dir_all(&scratch); + let save = SaveDir::new(scratch.clone()); + let _ = save.tables.set(tables.clone()); + let started = Instant::now(); + save.save_later(&chunks, registry, &biomes)?; + save.flush(); + times[2].push(started.elapsed().as_secs_f64()); + drop(save); + + if round == 0 { + for (chunk, want) in chunks.iter().zip(&baseline) { + let path = scratch.join(format!("region/r.{}.{}.mca", chunk.x >> 5, chunk.z >> 5)); + let got = RegionFile::open(&path)? + .read(ChunkPos::new(chunk.x, chunk.z))? + .ok_or("a saved chunk is missing")?; + if got.compressed != want.compressed { + return Err(format!("chunk {} {} differs", chunk.x, chunk.z).into()); + } + } + written = baseline.iter().map(|r| r.compressed.len()).collect(); + } + } + let _ = std::fs::remove_dir_all(&scratch); + println!( + "{} KiB compressed, identical to the one-thread records", + written.iter().sum::() / 1024 + ); + let per_chunk = 1000.0 / chunks.len() as f64; + let names = [ + "one thread: encode", + "one thread: compress", + "SaveDir (encode, compress, write)", + ]; + for (name, t) in names.iter().zip(&mut times) { + t.sort_by(f64::total_cmp); + println!( + "{name}: best {:.0} ms, median {:.0} ms of {rounds} ({:.3} ms per chunk at best)", + t[0] * 1000.0, + t[t.len() / 2] * 1000.0, + t[0] * per_chunk + ); + } + Ok(()) +} diff --git a/crates/horizon-client/examples/scene_collision_probe.rs b/crates/horizon-client/examples/scene_collision_probe.rs index c1a1e77ad..ec20eee74 100644 --- a/crates/horizon-client/examples/scene_collision_probe.rs +++ b/crates/horizon-client/examples/scene_collision_probe.rs @@ -40,7 +40,8 @@ fn main() -> Result<()> { return Err("radius must be 1..16".into()); } let assets = assets::Assets::load(&resources)?; - let world = world::World::test_scene(&assets, radius)?; + let render = assets.reload(&resources)?; + let world = world::World::test_scene(&assets, &render, radius)?; let binding = collisions::load(&resources, assets.registry)?; let mut scene = collisions::SceneCollisions { world: &world, @@ -50,7 +51,7 @@ fn main() -> Result<()> { fs::write( dir.join("scene.json"), serde_json::to_vec(&serde_json::json!({ - "radius":radius,"resident_chunks":world.chunks.len(),"model_gallery":assets.model_gallery, + "radius":radius,"resident_chunks":world.chunks.len(),"model_gallery":render.model_gallery, }))?, )?; let mut output = std::io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); diff --git a/crates/horizon-client/examples/scene_motion_probe.rs b/crates/horizon-client/examples/scene_motion_probe.rs index 6caa51463..f4ff07ebf 100644 --- a/crates/horizon-client/examples/scene_motion_probe.rs +++ b/crates/horizon-client/examples/scene_motion_probe.rs @@ -243,13 +243,14 @@ fn main() -> Result<()> { let root = PathBuf::from(&args[0]); let dir = PathBuf::from(&args[1]); let assets = Assets::load(&root)?; - let mut scene = World::test_scene(&assets, 1)?; + let render = assets.reload(&root)?; + let mut scene = World::test_scene(&assets, &render, 1)?; let binding = collisions::load(&root, assets.registry)?; let resources = MotionResources::load(&root, &assets)?; fs::write( dir.join("scene.json"), serde_json::to_vec( - &serde_json::json!({"radius":1,"resident_chunks":scene.chunks.len(),"model_gallery":assets.model_gallery}), + &serde_json::json!({"radius":1,"resident_chunks":scene.chunks.len(),"model_gallery":render.model_gallery}), )?, )?; if args[2] == "--describe" { diff --git a/crates/horizon-client/examples/section_mesh_fixture.rs b/crates/horizon-client/examples/section_mesh_fixture.rs index 6359f32d0..13f1a0f1a 100644 --- a/crates/horizon-client/examples/section_mesh_fixture.rs +++ b/crates/horizon-client/examples/section_mesh_fixture.rs @@ -3,7 +3,7 @@ //! the oracle's canonical form (vanilla ARGB colours and packed light coords). #![forbid(unsafe_code)] use horizon_client::{ - assets::Assets, + assets::{Assets, RenderAssets}, biome::{BiomeInfo, Biomes, GrassModifier}, blocks::BlockFacts, chunk::{Chunk, Light, MIN_Y, index}, @@ -48,6 +48,7 @@ fn chunk_index(x: i32, z: i32) -> Result { fn scene( row: &Value, assets: &Assets, + render: &RenderAssets, tables: &MeshTables, biomes: &mut Biomes, pristine: &[BiomeInfo], @@ -127,6 +128,7 @@ fn scene( let mut mesher = Mesher { nether_shading: row["nether"].as_bool().unwrap_or(false), assets, + render, tables, biomes: &*biomes, visibility: tables.visibility.clone(), @@ -159,15 +161,8 @@ fn scene( let vertices: Vec = quad .iter() .map(|v| { - json!([ - v.pos[0], - v.pos[1], - v.pos[2], - v.uv[0], - v.uv[1], - argb(v.color), - light_coords(v.light) - ]) + let ([x, y, z], [u, w]) = (v.pos, v.uv()); + json!([x, y, z, u, w, argb(v.color), light_coords(v.light)]) }) .collect(); quads.push(json!({"layer": layer, "sprite": sprite, "vertices": vertices})); @@ -184,11 +179,12 @@ fn main() -> Result<()> { } let root = PathBuf::from(&args[0]); let assets = Assets::load(&root)?; + let render = assets.reload(&root)?; let facts = BlockFacts::load(&root, assets.registry)?; let mut biomes = Biomes::load(&root)?; let visibility = models::load_visibility(&root, assets.registry)?; - let tables = MeshTables::new(&assets, &facts, visibility)?; - let names: BTreeMap = assets + let tables = MeshTables::new(&assets, &render, &facts, visibility)?; + let names: BTreeMap = render .sprite_layers .iter() .map(|(name, layer)| (*layer, name.as_str())) @@ -222,6 +218,7 @@ fn main() -> Result<()> { let result = scene( &row, &assets, + &render, &tables, &mut biomes, &pristine, diff --git a/crates/horizon-client/examples/streaming_bench.rs b/crates/horizon-client/examples/streaming_bench.rs index f99c594bb..9f8e99899 100644 --- a/crates/horizon-client/examples/streaming_bench.rs +++ b/crates/horizon-client/examples/streaming_bench.rs @@ -144,10 +144,12 @@ fn main() -> Result<()> { let hz = flag("--hz", 240.0); let assets = Arc::new(Assets::load(&root)?); + let render = Arc::new(assets.reload(&root)?); let facts = BlockFacts::load(&root, assets.registry)?; let biomes = Arc::new(Biomes::load(&root)?); let tables = Arc::new(MeshTables::new( &assets, + &render, &facts, models::load_visibility(&root, assets.registry)?, )?); @@ -160,6 +162,7 @@ fn main() -> Result<()> { )?); let context = Arc::new(WorkerContext { assets, + render: render.clone(), tables, biomes, light, diff --git a/crates/horizon-client/examples/tooltip_display_fixture.rs b/crates/horizon-client/examples/tooltip_display_fixture.rs new file mode 100644 index 000000000..ec61159cd --- /dev/null +++ b/crates/horizon-client/examples/tooltip_display_fixture.rs @@ -0,0 +1,40 @@ +//! Tooltip display visibility oracle companion for tools/test_tooltip_display_parity.py. +use horizon_client::{item_tooltip::TooltipDisplay, items::ItemStack}; +use horizon_world::nbt::Tag; +use std::{error::Error, fmt::Write}; + +fn main() -> Result<(), Box> { + let args: Vec = std::env::args().collect(); + let mut output = String::new(); + for line in std::fs::read_to_string(&args[1])?.lines() { + let fields: Vec<&str> = line.split('\t').collect(); + let hide_tooltip: bool = fields[0].parse()?; + let creative: bool = fields[1].parse()?; + let hide_attributes: bool = fields[2].parse()?; + let mut component = Vec::new(); + if hide_tooltip { + component.push(("hide_tooltip", Tag::Byte(1))); + } + if hide_attributes { + component.push(( + "hidden_components", + Tag::List(vec![Tag::String("minecraft:attribute_modifiers".into())]), + )); + } + let mut stack = ItemStack::new("minecraft:diamond_sword", 1); + if !component.is_empty() { + stack + .data_mut() + .set_other("minecraft:tooltip_display", Some(Tag::compound(component))); + } + let display = TooltipDisplay::for_stack(&stack); + writeln!( + output, + "{}\t{}", + display.name_visible(creative), + display.shows("minecraft:attribute_modifiers") + )?; + } + std::fs::write(&args[2], output)?; + Ok(()) +} diff --git a/crates/horizon-client/src/assets.rs b/crates/horizon-client/src/assets.rs index f278740f5..3e7c6e909 100644 --- a/crates/horizon-client/src/assets.rs +++ b/crates/horizon-client/src/assets.rs @@ -2,14 +2,13 @@ use crate::Result; use horizon_world::{ DATA_VERSION, heightmap::HeightmapState, - nbt::Tag, registry::{BlockRegistry, BlockStateId}, worldgen::{tags::TagDefinitions, terrain::TerrainBlockStates}, }; use serde_json::Value; use std::{ collections::BTreeSet, - fs::{self, File}, + fs::File, io::{self, BufReader}, path::Path, sync::Arc, @@ -49,11 +48,20 @@ impl TerrainBlockStates for Properties { self.0[id.0 as usize] } } +/// The block registry and the facts read from `facts.json` and the block tags: +/// everything world generation and collisions need, with none of the block +/// models or baked sprites. pub struct Assets { /// Leaked once per process: shared by world generation threads. pub registry: &'static BlockRegistry, pub properties: Properties, pub material_states: [BlockStateId; 6], + /// Block names in `#minecraft:blocks_fluid_flow` (fluid flow vectors). + pub blocks_fluid_flow: BTreeSet, +} +/// The block models and their baked sprites, read from the pack at `root` over +/// an existing block registry: everything the mesher and renderer need. +pub struct RenderAssets { pub sprite_size: u32, pub sprite_minimum_size: u32, pub pixels: Vec, @@ -68,30 +76,10 @@ pub struct Assets { pub translucent_layers: Vec, /// Each layer's `MipmapGenerator` settings. pub sprite_mips: Vec, - /// Block names in `#minecraft:blocks_fluid_flow` (fluid flow vectors). - pub blocks_fluid_flow: BTreeSet, } fn invalid(message: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) } -fn tag(value: &Value) -> Result { - Ok(match value { - Value::String(value) => Tag::String(value.as_str().into()), - Value::Number(value) => Tag::Int(i32::try_from( - value - .as_i64() - .ok_or_else(|| invalid("invalid registry number"))?, - )?), - Value::Array(values) => Tag::List(values.iter().map(tag).collect::>()?), - Value::Object(values) => Tag::Compound( - values - .iter() - .map(|(name, value)| Ok((name.as_str().into(), tag(value)?))) - .collect::>()?, - ), - _ => return Err(invalid("unsupported registry value").into()), - }) -} impl Assets { pub fn load(root: &Path) -> Result { let manifest: Value = serde_json::from_reader(BufReader::new(File::open( @@ -100,23 +88,8 @@ impl Assets { if manifest["data_version"].as_i64() != Some(i64::from(DATA_VERSION)) { return Err(invalid("resources do not match Horizon's pinned data version").into()); } - let facts: Value = serde_json::from_slice(&fs::read(root.join("facts.json"))?)?; - let states = facts["states"] - .as_array() - .ok_or_else(|| invalid("missing registry state facts"))?; - let registry = BlockRegistry::from_nbt(&Tag::compound([ - ("DataVersion", Tag::Int(DATA_VERSION)), - ( - "states", - Tag::List( - states - .iter() - .map(|state| tag(&state[4])) - .collect::>()?, - ), - ), - ("defaults", tag(&facts["defaults"])?), - ]))?; + let (registry, flags) = + BlockRegistry::from_facts_json_with_flags(File::open(root.join("facts.json"))?)?; let bundle: Value = serde_json::from_reader(BufReader::new(File::open(root.join("block-tags.json"))?))?; let mut definitions = TagDefinitions::default(); @@ -132,7 +105,7 @@ impl Assets { )?; } let built = - definitions.build(|name, _| facts["defaults"].get(name).map(|_| name.to_owned()))?; + definitions.build(|name, _| registry.default_state(name).map(|_| name.to_owned()))?; if !built.missing.is_empty() { return Err(invalid("unresolved block tags").into()); } @@ -158,27 +131,20 @@ impl Assets { .cloned() .collect(); let properties = Properties(Arc::new( - states + flags .iter() - .map(|state| { + .enumerate() + .map(|(i, &(air, fluid))| { + let name = ®istry + .state(BlockStateId(i as u32)) + .ok_or_else(|| invalid("missing registry state"))? + .name; Ok(StateFacts { - air: state[1] - .as_bool() - .ok_or_else(|| invalid("missing air fact"))?, - fluid: state[2] - .as_bool() - .ok_or_else(|| invalid("missing fluid fact"))?, - air_block: state[0].as_str() == Some("minecraft:air"), - motion: motion.contains( - state[0] - .as_str() - .ok_or_else(|| invalid("missing state name"))?, - ), - no_leaves: no_leaves.contains( - state[0] - .as_str() - .ok_or_else(|| invalid("missing state name"))?, - ), + air, + fluid, + air_block: name == "minecraft:air", + motion: motion.contains(name.as_str()), + no_leaves: no_leaves.contains(name.as_str()), }) }) .collect::>()?, @@ -193,33 +159,23 @@ impl Assets { // 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, + Ok(Self { registry, properties, material_states, blocks_fluid_flow, - ) + }) } - /// The same blocks with the models and sprites of another resource root + /// The models and sprites of another resource root over these blocks /// (resource packs changed): the registry and block facts come from the /// game data, which resource packs do not touch. - pub fn reload(&self, root: &Path) -> Result { - Self::with_models( - root, - self.registry, - self.properties.clone(), - self.material_states, - self.blocks_fluid_flow.clone(), - ) + pub fn reload(&self, root: &Path) -> Result { + RenderAssets::load(root, self) } - fn with_models( - root: &Path, - registry: &'static BlockRegistry, - properties: Properties, - material_states: [BlockStateId; 6], - blocks_fluid_flow: BTreeSet, - ) -> Result { +} +impl RenderAssets { + pub fn load(root: &Path, assets: &Assets) -> Result { + let registry = assets.registry; let mut sprites = crate::sprites::Sprites::default(); for name in MATERIALS { sprites.insert(root, &format!("minecraft:block/{name}"))?; @@ -243,9 +199,6 @@ impl Assets { } sprites.finish(); Ok(Self { - registry, - properties, - material_states, sprite_size: sprites.size, sprite_minimum_size: sprites.minimum_size, texture_layers: u32::try_from(sprites.count())?, @@ -258,7 +211,6 @@ impl Assets { sprite_layers: sprites.layers, translucent_layers: sprites.translucent, sprite_mips: sprites.mips, - blocks_fluid_flow, }) } } diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index 0c45fa934..250babf22 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -9,6 +9,7 @@ use crate::sound_engine::{ Sounds, TickContext, }; use crate::sound_events::{Sound, SoundRegistry}; +#[cfg(feature = "audio")] use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use horizon_core::random::{LegacyRandom, RandomSource}; use std::{ @@ -134,8 +135,14 @@ fn attach(mixer: &Mutex, channel: ChannelId, samples: Samples, looping: b c.looping |= looping; } } +/// The open output stream. A build without the `audio` feature (the server build, which must not +/// need libasound) never has one. +#[cfg(feature = "audio")] +type Stream = cpal::Stream; +#[cfg(not(feature = "audio"))] +type Stream = std::convert::Infallible; pub struct Audio { - _stream: Option, + _stream: Option, pub engine: SoundEngine, backend: MixerBackend, /// Record `Heard` sounds (the subtitle overlay is listening). @@ -333,6 +340,8 @@ fn distance_gain(linear: Option, distance: f32) -> f32 { Some(_) => 0.0, } } +// Only the output stream mixes; a build without one (no `audio` feature) never does. +#[cfg_attr(not(feature = "audio"), allow(dead_code))] fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { data.fill(0.0); let listener = mixer.listener; @@ -415,6 +424,7 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { /// `HORIZON_NO_AUDIO`, or a virtual screen (`vscreen`), where agents and /// harnesses run the game and must stay off the user's speakers. /// `HORIZON_AUDIO=1` opens the output anyway (testing into a null sink). +#[cfg(any(feature = "audio", test))] fn output_disabled(var: impl Fn(&str) -> Option) -> Option { if var("HORIZON_NO_AUDIO").is_some() { return Some("audio off: HORIZON_NO_AUDIO is set".into()); @@ -430,6 +440,7 @@ fn output_disabled(var: impl Fn(&str) -> Option) -> Option>, @@ -450,6 +461,7 @@ fn open_device( stream.play()?; Ok((stream, config)) } +#[cfg(feature = "audio")] fn build_stream>( device: &cpal::Device, config: &cpal::SupportedStreamConfig, @@ -523,7 +535,12 @@ impl Audio { capture: None, } } - fn open(mixer: Arc>) -> Result { + #[cfg(not(feature = "audio"))] + fn open(_: Arc>) -> Result { + Err("this build has no sound output (built without the `audio` feature)".into()) + } + #[cfg(feature = "audio")] + fn open(mixer: Arc>) -> Result { if let Some(reason) = output_disabled(|name| std::env::var_os(name)) { return Err(reason.into()); } diff --git a/crates/horizon-client/src/bin/horizon-ctl/commands.rs b/crates/horizon-client/src/bin/horizon-ctl/commands.rs index c5e716a03..8f64705c6 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/commands.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/commands.rs @@ -187,6 +187,10 @@ pub const COMMANDS: &[Cmd] = &[ &[opt("radius", Ty::Num, "search radius in blocks (default 32)"), opt("type", Ty::Str, "entity type filter")], mcp: true, local: false), cmd!("block", Observe, "block X Y Z", "the block state at a position", "", ["horizon-ctl block 10 64 -3"], &BLOCK_XYZ, mcp: true, local: false), + cmd!("light", Observe, "light X1 Y1 Z1 X2 Y2 Z2", "the stored sky and block light of a box", + "At most 32768 blocks per request. One hex digit per block in `sky` and `block`, x fastest, then z, then y; `.` where no chunk is loaded.", + ["horizon-ctl light 0 64 0 15 70 15"], + &[p("x1", Ty::Int, "corner X"), p("y1", Ty::Int, "corner Y"), p("z1", Ty::Int, "corner Z"), p("x2", Ty::Int, "opposite X"), p("y2", Ty::Int, "opposite Y"), p("z2", Ty::Int, "opposite Z")], mcp: true, local: false), cmd!("blocks", Observe, "blocks X1 Y1 Z1 X2 Y2 Z2", "the non-air blocks of a box, with counts per block", "At most 32768 blocks per request.", ["horizon-ctl blocks 0 60 0 15 70 15"], &[p("x1", Ty::Int, "corner X"), p("y1", Ty::Int, "corner Y"), p("z1", Ty::Int, "corner Z"), p("x2", Ty::Int, "opposite X"), p("y2", Ty::Int, "opposite Y"), p("z2", Ty::Int, "opposite Z")], mcp: true, local: false), @@ -339,7 +343,7 @@ pub const COMMANDS: &[Cmd] = &[ cmd!("bench", Scripting, "bench SECONDS", "reset frame stats, wait, reply with the summary", "", ["horizon-ctl bench 10"], &[], mcp: false, local: false), cmd!("stats", Scripting, "stats [reset]", "frame-time summary since the last reset", "", ["horizon-ctl stats"], &[], mcp: false, local: false), cmd!("fly", Scripting, "fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH [raw]]", "fly the camera along a line, then reply with the frame summary", - "With raw, the reply also lists every frame time in milliseconds (frame_ms).", + "The reply's tick_ms and tick_ms_max are the world's smoothed tick time over the flight (the server thread's when single player runs on one). With raw, the reply also lists every frame time in milliseconds (frame_ms).", ["horizon-ctl fly 0 100 0 500 100 0 20"], &[], mcp: false, local: false), ]; diff --git a/crates/horizon-client/src/bin/horizon-ctl/main.rs b/crates/horizon-client/src/bin/horizon-ctl/main.rs index 2e1b1bb56..27d9d5ba1 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/main.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/main.rs @@ -215,7 +215,12 @@ impl Session { let deadline = Instant::now() + Duration::from_secs_f64(limit.max(0.0)); loop { let status = self.game("status")?; - if !status["player"].is_null() && status["pending_chunks"] == 0 { + // On a server (single player's server thread too), also the + // level around the player. + if !status["player"].is_null() + && status["pending_chunks"] == 0 + && status["server"]["loaded"] != false + { return Ok(status); } if Instant::now() > deadline { diff --git a/crates/horizon-client/src/block_entities.rs b/crates/horizon-client/src/block_entities.rs new file mode 100644 index 000000000..93abb3711 --- /dev/null +++ b/crates/horizon-client/src/block_entities.rs @@ -0,0 +1,395 @@ +//! The world's block entities and the order they tick in: vanilla's +//! `Level.blockEntityTickers`, kept beside the block entity map so a tick +//! visits only the block entities that tick, in vanilla's order, instead of +//! scanning the whole map once per kind. +//! +//! The list follows `LevelChunk.updateBlockEntityTicker` and +//! `Level.tickBlockEntities`: +//! - a block entity whose block state has a ticker gets a slot at the end of +//! the list (through `pendingBlockEntityTickers`, so a slot made during a +//! tick first ticks on the next one); +//! - replacing the block entity at a position (`setBlockEntity`), or changing +//! its block state to another state with a ticker, keeps its slot +//! (`RebindableTickingBlockEntityWrapper.rebind`); +//! - removing it (`removeBlockEntity`), unloading its chunk +//! (`clearAllBlockEntities`) or changing its state to one without a ticker +//! (a jukebox losing its record) frees the slot; a later ticker there is +//! appended again; +//! - a loaded chunk's block entities are added in the iteration order of its +//! `Object2ObjectOpenHashMap` +//! (`registerAllBlockEntitiesAfterLevelLoad`), filled in the order the chunk +//! listed them. +//! +//! Which states tick is a table by state id, built by the game from the block +//! registry; whether a slot is made is decided when the slot is promoted at +//! the start of the next tick, from the block state then. +use crate::containers::BlockEntity; +use crate::fast_hash::{FxHashMap, FxHashSet}; +use std::collections::HashMap; + +pub type Pos = (i32, i32, i32); + +/// What a block state's block entity does each tick (`BlockState.getTicker`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Ticking { + /// No ticker, and the block has no block entity that could have one. + #[default] + No, + /// A ticker. + Yes, + /// The block's block entity, but this state has no ticker (a jukebox + /// without a record): a state change to it frees the slot. + Idle, +} + +#[derive(Default)] +pub struct BlockEntities { + map: HashMap, + /// `Level.blockEntityTickers`: positions and the slot each was given. + tickers: Vec<(Pos, u32)>, + /// `LevelChunk.tickersInLevel`: the live slot of each ticking position. + live: FxHashMap, + /// Positions that may need a slot, in the order vanilla would have made + /// it (`pendingBlockEntityTickers`), each with a token; decided at the + /// next promotion from the block state then. + added: Vec<(Pos, u32)>, + /// The token of each position's pending entry: an entry whose token is + /// not here any more was cancelled. + pending: FxHashMap, + next_slot: u32, + /// Whether a slot was freed since the list was last swept: otherwise + /// every slot in it is still live, unless its block entity is `out`. + freed: bool, + /// Positions whose block entity `take` took and `put` has not brought + /// back. + out: FxHashSet, + /// `Ticking` by block state id; empty until the game builds it. + states: Vec, +} + +impl std::ops::Deref for BlockEntities { + type Target = HashMap; + fn deref(&self) -> &Self::Target { + &self.map + } +} + +impl<'a> IntoIterator for &'a BlockEntities { + type Item = (&'a Pos, &'a BlockEntity); + type IntoIter = std::collections::hash_map::Iter<'a, Pos, BlockEntity>; + fn into_iter(self) -> Self::IntoIter { + self.map.iter() + } +} + +/// `Vec3i.hashCode`. +fn java_hash((x, y, z): Pos) -> i32 { + y.wrapping_add(z.wrapping_mul(31)) + .wrapping_mul(31) + .wrapping_add(x) +} +/// `HashCommon.mix`. +fn mix(x: i32) -> usize { + let h = (x as u32).wrapping_mul(0x9E37_79B9); + (h ^ (h >> 16)) as usize +} + +/// The order `values().forEach` visits a `new Object2ObjectOpenHashMap<>()` +/// keyed by these positions, put in this order (repeats keep their first +/// slot): open addressing with linear probing, a rehash to twice the size +/// past three quarters full, and iteration from the last slot down. +pub fn chunk_map_order(positions: impl IntoIterator) -> Vec { + // HashCommon.arraySize(16, .75f), and maxFill of each size. + let mut slots: Vec> = vec![None; 32]; + let max_fill = |n: usize| (n * 3).div_ceil(4).min(n - 1); + let mut size = 0; + for p in positions { + let mask = slots.len() - 1; + let mut at = mix(java_hash(p)) & mask; + let mut known = false; + while let Some(k) = slots[at] { + if k == p { + known = true; + break; + } + at = (at + 1) & mask; + } + if known { + continue; + } + slots[at] = Some(p); + // `if (size++ >= maxFill) rehash(arraySize(size + 1, f))`, which + // puts the keys back from the last slot down. + size += 1; + if size > max_fill(slots.len()) { + let n = ((size + 1) * 4).div_ceil(3).next_power_of_two(); + let old = std::mem::replace(&mut slots, vec![None; n]); + for k in old.into_iter().rev().flatten() { + let mut at = mix(java_hash(k)) & (n - 1); + while slots[at].is_some() { + at = (at + 1) & (n - 1); + } + slots[at] = Some(k); + } + } + } + slots.into_iter().rev().flatten().collect() +} + +impl BlockEntities { + /// Whether the ticking table has been built. + pub fn has_states(&self) -> bool { + !self.states.is_empty() + } + pub fn set_states(&mut self, states: Vec) { + self.states = states; + } + pub fn take_states(&mut self) -> Vec { + std::mem::take(&mut self.states) + } + pub fn ticking(&self, state: u32) -> Ticking { + self.states.get(state as usize).copied().unwrap_or_default() + } + + fn next(&mut self) -> u32 { + let n = self.next_slot; + self.next_slot = n.wrapping_add(1); + n + } + /// A ticker may be made for `pos` now (`updateBlockEntityTicker`). + fn add(&mut self, pos: Pos) { + let token = self.next(); + self.pending.insert(pos, token); + self.added.push((pos, token)); + } + /// `removeBlockEntityTicker`: no slot, made or pending. + fn cancel(&mut self, pos: &Pos) { + self.freed |= self.live.remove(pos).is_some(); + self.pending.remove(pos); + } + + pub fn get_mut(&mut self, pos: &Pos) -> Option<&mut BlockEntity> { + self.map.get_mut(pos) + } + pub fn iter_mut(&mut self) -> impl Iterator { + self.map.iter_mut() + } + pub fn values_mut(&mut self) -> impl Iterator { + self.map.values_mut() + } + /// `LevelChunk.setBlockEntity` (+ `addAndRegisterBlockEntity`): a new + /// block entity may get a slot; one replacing another keeps its slot. + pub fn insert(&mut self, pos: Pos, entity: BlockEntity) -> Option { + let old = self.map.insert(pos, entity); + if old.is_none() { + self.add(pos); + } + old + } + /// The block entity at `pos`, made by `make` when there is none. + pub fn get_or_insert_with( + &mut self, + pos: Pos, + make: impl FnOnce() -> BlockEntity, + ) -> &mut BlockEntity { + if !self.map.contains_key(&pos) { + self.add(pos); + } + self.map.entry(pos).or_insert_with(make) + } + /// `LevelChunk.removeBlockEntity`: the block entity and its slot. + pub fn remove(&mut self, pos: &Pos) -> Option { + self.cancel(pos); + self.map.remove(pos) + } + /// The block entity at `pos`, out of the map for a while: its slot stays + /// for `put` to bring it back (a tick working on it). + pub fn take(&mut self, pos: &Pos) -> Option { + let taken = self.map.remove(pos); + if taken.is_some() { + self.out.insert(*pos); + } + taken + } + /// Brings back what `take` took, in its slot. + pub fn put(&mut self, pos: Pos, entity: BlockEntity) { + self.out.remove(&pos); + if self.map.insert(pos, entity).is_none() + && !self.live.contains_key(&pos) + && !self.pending.contains_key(&pos) + { + self.add(pos); + } + } + /// Removes the block entities `keep` refuses, and their slots + /// (`clearAllBlockEntities` of unloaded chunks). + pub fn retain(&mut self, mut keep: impl FnMut(&Pos, &mut BlockEntity) -> bool) { + let (live, pending, freed) = (&mut self.live, &mut self.pending, &mut self.freed); + self.map.retain(|p, e| { + let kept = keep(p, e); + if !kept { + *freed |= live.remove(p).is_some(); + pending.remove(p); + } + kept + }); + } + pub fn clear(&mut self) { + self.map.clear(); + self.tickers.clear(); + self.live.clear(); + self.added.clear(); + self.pending.clear(); + self.out.clear(); + self.freed = false; + } + /// A loaded or generated chunk's block entities, in the order the chunk + /// lists them; they tick in its block entity map's order + /// (`registerAllBlockEntitiesAfterLevelLoad`). + pub fn load_chunk(&mut self, entities: Vec<(Pos, BlockEntity)>) { + let order = chunk_map_order(entities.iter().map(|(p, _)| *p)); + for (p, e) in entities { + self.map.insert(p, e); + } + for p in order { + self.add(p); + } + } + /// `LevelChunk.setBlockState` on a block entity's position, from state + /// `old` to `new`: a ticker made, kept or dropped. + pub fn state_changed(&mut self, pos: Pos, old: u32, new: u32) { + if self.states.is_empty() || !self.map.contains_key(&pos) { + return; + } + match self.ticking(new) { + // A new ticker, unless one was made or is pending (rebound). + Ticking::Yes => { + if self.ticking(old) != Ticking::Yes && !self.live.contains_key(&pos) { + self.add(pos); + } + } + Ticking::Idle => self.cancel(&pos), + // Another block: the game removes or replaces the block entity. + Ticking::No => {} + } + } + /// The start of `Level.tickBlockEntities`: pending slots join the list + /// and freed ones leave it. `state` reads the block state at a position. + /// Returns the slots to tick, in order; check each with `is_live` before + /// ticking it, as the ticks before it can free it. + pub fn tickers(&mut self, state: impl Fn(Pos) -> u32) -> Vec<(Pos, u32)> { + for (pos, token) in std::mem::take(&mut self.added) { + if self.pending.get(&pos) != Some(&token) { + continue; + } + self.pending.remove(&pos); + if self.live.contains_key(&pos) + || !self.map.contains_key(&pos) + || self.ticking(state(pos)) != Ticking::Yes + { + continue; + } + let slot = self.next(); + self.live.insert(pos, slot); + self.tickers.push((pos, slot)); + } + if !std::mem::take(&mut self.freed) && self.out.is_empty() { + return self.tickers.clone(); + } + self.out.clear(); + let (live, map) = (&mut self.live, &self.map); + self.tickers.retain(|(p, slot)| { + let mine = live.get(p) == Some(slot); + if mine && !map.contains_key(p) { + live.remove(p); + } + mine && map.contains_key(p) + }); + self.tickers.clone() + } + /// Whether a slot from `tickers` still ticks. + pub fn is_live(&self, (pos, slot): (Pos, u32)) -> bool { + self.live.get(&pos) == Some(&slot) && self.map.contains_key(&pos) + } + /// Frees the slot at `pos` (the block entity stays). + pub fn forget(&mut self, pos: &Pos) { + self.cancel(pos); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hopper() -> BlockEntity { + BlockEntity::Chest(vec![None; 5]) + } + /// States: 0 air, 1 ticks, 2 idle. + fn level() -> BlockEntities { + let mut b = BlockEntities::default(); + b.set_states(vec![Ticking::No, Ticking::Yes, Ticking::Idle]); + b + } + fn order(b: &mut BlockEntities, states: &HashMap) -> Vec { + b.tickers(|p| states.get(&p).copied().unwrap_or(0)) + .into_iter() + .map(|(p, _)| p) + .collect() + } + + #[test] + fn slots_follow_vanilla_lifecycle() { + let mut b = level(); + let mut s = HashMap::new(); + for p in [(0, 0, 0), (1, 0, 0), (2, 0, 0)] { + s.insert(p, 1); + b.insert(p, hopper()); + } + assert_eq!(order(&mut b, &s), [(0, 0, 0), (1, 0, 0), (2, 0, 0)]); + // Replacing keeps the slot; removing and placing again appends. + b.insert((0, 0, 0), hopper()); + b.remove(&(1, 0, 0)); + b.insert((1, 0, 0), hopper()); + assert_eq!(order(&mut b, &s), [(0, 0, 0), (2, 0, 0), (1, 0, 0)]); + // Take and put keep it; an idle state frees it, ticking again appends. + let e = b.take(&(0, 0, 0)).unwrap(); + b.put((0, 0, 0), e); + assert_eq!(order(&mut b, &s), [(0, 0, 0), (2, 0, 0), (1, 0, 0)]); + s.insert((2, 0, 0), 2); + b.state_changed((2, 0, 0), 1, 2); + assert_eq!(order(&mut b, &s), [(0, 0, 0), (1, 0, 0)]); + s.insert((2, 0, 0), 1); + b.state_changed((2, 0, 0), 2, 1); + assert_eq!(order(&mut b, &s), [(0, 0, 0), (1, 0, 0), (2, 0, 0)]); + // A slot freed during a tick is not live any more. + let slots = b.tickers(|p| s.get(&p).copied().unwrap_or(0)); + b.retain(|p, _| *p != (1, 0, 0)); + assert!(b.is_live(slots[0]) && !b.is_live(slots[1])); + // A block entity taken and never brought back loses its slot. + b.take(&(0, 0, 0)); + assert_eq!(order(&mut b, &s), [(2, 0, 0)]); + assert_eq!(order(&mut b, &s), [(2, 0, 0)]); + } + + #[test] + fn chunk_loads_in_open_hash_map_order() { + // A few keys: their mixed hashes over 32 slots, read from the top. + let positions = [ + (0, 64, 0), + (1, 64, 0), + (0, 64, 1), + (15, -64, 15), + (3, 70, 9), + ]; + let slot = |p: &Pos| mix(java_hash(*p)) & 31; + let mut expected = positions.to_vec(); + expected.sort_by_key(|p| std::cmp::Reverse(slot(p))); + let distinct: std::collections::HashSet = positions.iter().map(slot).collect(); + assert_eq!(distinct.len(), positions.len()); + assert_eq!(chunk_map_order(positions), expected); + // Past 24 keys the table doubles; every key stays, once. + let many: Vec = (0..100).map(|i| (i % 16, i / 16, 3)).collect(); + let order = chunk_map_order(many.iter().copied().chain(many.iter().copied())); + assert_eq!(order.len(), 100); + } +} diff --git a/crates/horizon-client/src/block_entity_anim.rs b/crates/horizon-client/src/block_entity_anim.rs index eefd1ba63..2a35c9835 100644 --- a/crates/horizon-client/src/block_entity_anim.rs +++ b/crates/horizon-client/src/block_entity_anim.rs @@ -12,11 +12,11 @@ //! (blocks, entities, game time) as closures, so the parity fixture can drive //! them with scripted inputs (`tools/test_block_entity_anim_parity.py`). use crate::block_entity_render::BlockAnim; +use crate::fast_hash::FxHashMap; use horizon_core::{ geometry::trig::{self, Mth}, random::{LegacyRandom, RandomSource}, }; -use std::collections::HashMap; /// `Direction` names by `get3DDataValue`. pub const DIRECTIONS: [&str; 6] = ["down", "up", "north", "south", "west", "east"]; @@ -832,38 +832,44 @@ pub fn ticker(name: &str, prop: impl Fn(&str) -> Option) -> Option, - pub books: HashMap<[i32; 3], EnchantingBook>, + pub chests: FxHashMap<[i32; 3], ChestLid>, + pub books: FxHashMap<[i32; 3], EnchantingBook>, /// `EnchantingTableBlockEntity.RANDOM`, shared by every table. pub book_random: LegacyRandom, - pub shulkers: HashMap<[i32; 3], Shulker>, - pub bells: HashMap<[i32; 3], Bell>, - pub conduits: HashMap<[i32; 3], Conduit>, - pub skulls: HashMap<[i32; 3], Skull>, - pub pots: HashMap<[i32; 3], PotWobble>, - pub gateways: HashMap<[i32; 3], EndGateway>, + pub shulkers: FxHashMap<[i32; 3], Shulker>, + pub bells: FxHashMap<[i32; 3], Bell>, + pub conduits: FxHashMap<[i32; 3], Conduit>, + pub skulls: FxHashMap<[i32; 3], Skull>, + pub pots: FxHashMap<[i32; 3], PotWobble>, + pub gateways: FxHashMap<[i32; 3], EndGateway>, /// The integrated server's copies of the gateways (`portalTick`). - pub gateway_servers: HashMap<[i32; 3], EndGateway>, + pub gateway_servers: FxHashMap<[i32; 3], EndGateway>, /// The client level's random (conduit particles). pub random: LegacyRandom, /// [`Ticker`] by block state id (see [`BlockEntityAnims::classify`]). pub kinds: Vec>, + /// The drawn block entities with a ticker, sorted by position, and the + /// renderer's block entity revision they were read at. + pub present: Vec<([i32; 3], Ticker)>, + pub present_revision: Option, } impl Default for BlockEntityAnims { fn default() -> Self { Self { - chests: HashMap::new(), - books: HashMap::new(), + chests: FxHashMap::default(), + books: FxHashMap::default(), book_random: LegacyRandom::new(0x626f6f6b), - shulkers: HashMap::new(), - bells: HashMap::new(), - conduits: HashMap::new(), - skulls: HashMap::new(), - pots: HashMap::new(), - gateways: HashMap::new(), - gateway_servers: HashMap::new(), + shulkers: FxHashMap::default(), + bells: FxHashMap::default(), + conduits: FxHashMap::default(), + skulls: FxHashMap::default(), + pots: FxHashMap::default(), + gateways: FxHashMap::default(), + gateway_servers: FxHashMap::default(), random: LegacyRandom::new(0x6c6576656c), kinds: Vec::new(), + present: Vec::new(), + present_revision: None, } } } @@ -877,15 +883,20 @@ impl BlockEntityAnims { .and_then(|s| ticker(&s.name, |k| s.properties.get(k).cloned())) }) .collect(); + self.present_revision = None; } /// The ticker of a block state. pub fn ticker(&self, state: u32) -> Option { self.kinds.get(state as usize).copied().flatten() } /// Drops the state of block entities that are gone or changed kind: - /// `present` maps the loaded block entities to their tickers. - pub fn retain_present(&mut self, present: &HashMap<[i32; 3], Ticker>) { - let is = |p: &[i32; 3], f: fn(&Ticker) -> bool| present.get(p).is_some_and(f); + /// `present` holds the loaded block entities' tickers, sorted by position. + pub fn retain_present(&mut self, present: &[([i32; 3], Ticker)]) { + let is = |p: &[i32; 3], f: fn(&Ticker) -> bool| { + present + .binary_search_by_key(p, |(q, _)| *q) + .is_ok_and(|i| f(&present[i].1)) + }; self.chests.retain(|p, _| is(p, |t| *t == Ticker::Lid)); self.books.retain(|p, _| is(p, |t| *t == Ticker::Book)); self.shulkers diff --git a/crates/horizon-client/src/chat.rs b/crates/horizon-client/src/chat.rs index 6156a041d..7c51a40f1 100644 --- a/crates/horizon-client/src/chat.rs +++ b/crates/horizon-client/src/chat.rs @@ -386,6 +386,12 @@ pub struct ChatScreen { parse: Option, /// The completions at the cursor (`pendingSuggestions`): range start (bytes) and list. pending: Option<(usize, Vec)>, + /// Completions waiting for the server's (an `ask_server` node at the + /// cursor): `pendingSuggestions` is not done until they come. + awaiting: Option, + /// The request to send (`ServerboundCommandSuggestionPacket`): id and + /// the command up to the cursor. + request: Option<(i32, String)>, suggestions: Option, usage: Vec, usage_position: i32, @@ -394,6 +400,16 @@ pub struct ChatScreen { keep_suggestions: bool, pub auto_suggestions: bool, } +/// Local completions waiting for the server's reply to request `id`. +struct Awaiting { + id: i32, + /// The command up to the cursor, as sent. + truncated: String, + local: Vec, +} +/// `ClientSuggestionProvider.pendingSuggestionsId`: one counter for the +/// connection, so a reply to an older request never matches. +static SUGGESTION_ID: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); /// `CommandSuggestions`' fill colour. const FILL: i32 = -805306368; fn byte_at(s: &str, chars: usize) -> usize { @@ -442,6 +458,8 @@ impl ChatScreen { history_pos: history_len, parse: None, pending: None, + awaiting: None, + request: None, suggestions: None, usage: Vec::new(), usage_position: 0, @@ -518,24 +536,84 @@ impl ChatScreen { } if cursor >= 1 && (self.suggestions.is_none() || !self.keep_suggestions) { let parse = self.parse.as_ref().expect("parsed above"); - let (range, list) = c - .dispatcher - .client_suggestions(parse, cursor_b, c.registries); - self.pending = Some((range.0, list)); - self.update_usage_info(m, c); + let (range, list, ask) = + c.dispatcher + .client_suggestions_asking(parse, cursor_b, c.registries); + if ask { + // ClientSuggestionProvider.customSuggestion: the + // suggestions are done when the server answers. + let id = SUGGESTION_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + let truncated = command[..cursor_b].to_owned(); + self.request = Some((id, truncated.clone())); + self.awaiting = Some(Awaiting { + id, + truncated, + local: list, + }); + self.pending = None; + } else { + self.awaiting = None; + self.pending = Some((range.0, list)); + self.update_usage_info(m, c); + } } } else if !command.chars().all(char::is_whitespace) { let partial = &command[..cursor_b]; let mut builder = SuggestionsBuilder::new(partial, last_word_index(partial)); builder.suggest_matching(c.registries.players.iter().map(String::as_str)); let (range, list) = merge_suggestions(partial, builder.out); + self.awaiting = None; self.pending = Some((range.0, list)); self.usage_width = 0; self.usage_position = 0; } else { + self.awaiting = None; self.pending = None; } } + /// The completion request to send to the server, if one is waiting. + pub fn take_request(&mut self) -> Option<(i32, String)> { + self.request.take() + } + /// `ClientSuggestionProvider.completeCustomSuggestions`: the server's + /// completions for request `id`, with `range` in UTF-16 units of the + /// command sent. They join the local ones (`Suggestions.merge`) and the + /// pending suggestions are done. + pub fn server_suggestions( + &mut self, + m: &Measure, + c: &Commands, + id: i32, + range: (usize, usize), + list: Vec<(String, Option)>, + ) { + let Some(awaiting) = self.awaiting.take_if(|a| a.id == id) else { + return; + }; + let input = &awaiting.truncated; + let byte = |units: usize| { + let mut n = 0; + input + .char_indices() + .find(|(_, ch)| { + let past = n >= units; + n += ch.len_utf16(); + past + }) + .map_or(input.len(), |(i, _)| i) + }; + let range = (byte(range.0), byte(range.0 + range.1)); + let mut all = awaiting.local; + all.extend(list.into_iter().map(|(text, tooltip)| Suggestion { + range, + text, + tooltip, + int_value: None, + })); + let (range, list) = merge_suggestions(input, all); + self.pending = Some((range.0, list)); + self.update_usage_info(m, c); + } /// `CommandSuggestions.updateUsageInfo`. fn update_usage_info(&mut self, m: &Measure, c: &Commands) { let Some(parse) = &self.parse else { return }; diff --git a/crates/horizon-client/src/chat_tests.rs b/crates/horizon-client/src/chat_tests.rs index 3cbac071b..e1bf2feda 100644 --- a/crates/horizon-client/src/chat_tests.rs +++ b/crates/horizon-client/src/chat_tests.rs @@ -230,3 +230,58 @@ fn mod_commands_are_coloured_and_complete_like_vanilla_ones() { screen.key(&m, &c, &[], winit::keyboard::KeyCode::Tab, false, false); assert_eq!(screen.value(), "/coords"); } + +#[test] +fn ask_server_nodes_wait_for_the_servers_completions() { + // ClientSuggestionProvider.customSuggestion: an `ask_server` node at the + // cursor sends the command so far, and the list is done with the reply. + let font = font(); + let m = Measure(&font); + let registries = Registries { + permission: 4, + ..Registries::default() + }; + let mut d = crate::command::vanilla::game_dispatcher().clone(); + let child = |d: &crate::command::Dispatcher, n: usize, name: &str| { + d.nodes[n] + .children + .iter() + .copied() + .find(|&c| d.nodes[c].name() == name) + .expect(name) + }; + let id = child(&d, child(&d, child(&d, 0, "bossbar"), "get"), "id"); + d.nodes[id].suggests = Some(crate::command::Suggests::AskServer); + let c = Commands { + dispatcher: &d, + registries: ®istries, + }; + let tab = |screen: &mut ChatScreen| { + screen.key(&m, &c, &[], winit::keyboard::KeyCode::Tab, false, false); + }; + let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360); + screen.type_text(&m, &c, "/bossbar get pt"); + let (request, sent) = screen.take_request().expect("the server is asked"); + assert_eq!(sent, "/bossbar get pt"); + assert_eq!(screen.take_request(), None); + // Nothing to complete until the reply. + tab(&mut screen); + assert_eq!(screen.value(), "/bossbar get pt"); + // A reply to an older request is dropped; the range is in UTF-16 units. + let reply = |text: &str| vec![(text.to_owned(), None)]; + screen.server_suggestions(&m, &c, request - 1, (13, 2), reply("pt6:old")); + tab(&mut screen); + assert_eq!(screen.value(), "/bossbar get pt"); + screen.server_suggestions(&m, &c, request, (13, 2), reply("pt6:check")); + tab(&mut screen); + assert_eq!(screen.value(), "/bossbar get pt6:check"); + // Without the server's provider the local list is done at once. + let local = crate::command::vanilla::game_dispatcher(); + let c = Commands { + dispatcher: local, + registries: ®istries, + }; + let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360); + screen.type_text(&m, &c, "/bossbar get pt"); + assert_eq!(screen.take_request(), None); +} diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs index ce2c4ea71..857372045 100644 --- a/crates/horizon-client/src/chunk.rs +++ b/crates/horizon-client/src/chunk.rs @@ -3,7 +3,7 @@ //! (copy-on-write through `Arc::make_mut`). use horizon_core::paletted::{PalettedContainer, Strategy}; use horizon_world::registry::BlockStateId; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; pub const MIN_Y: i32 = -64; pub const HEIGHT: i32 = 384; @@ -45,6 +45,10 @@ impl Light { } } #[inline] +fn column(x: i32, z: i32) -> usize { + ((z & 15) << 4 | (x & 15)) as usize +} +#[inline] pub fn index(x: i32, y: i32, z: i32) -> usize { ((y & 15) << 8 | (z & 15) << 4 | (x & 15)) as usize } @@ -118,8 +122,10 @@ pub struct Chunk { pub x: i32, pub z: i32, pub sections: Vec>, - /// Highest non-air, light-blocking-or-fluid Y per column (MOTION_BLOCKING-like), for rain/sky. - pub heights: Arc<[i16; 256]>, + /// `Heightmap.Types.WORLD_SURFACE` per column (`z << 4 | x`): one above + /// the highest non-air block, or `MIN_Y`. Built on the first read; a + /// `set` that can move a column's surface drops it. + surface: OnceLock>, pub lit: bool, /// Light read from a save with `isLightOn`: no light job is needed. pub light_loaded: bool, @@ -148,7 +154,7 @@ impl Chunk { sections: (0..SECTIONS) .map(|_| Arc::new(Section::default())) .collect(), - heights: Arc::new([MIN_Y as i16; 256]), + surface: OnceLock::new(), lit: false, light_loaded: false, fresh: false, @@ -190,7 +196,52 @@ impl Chunk { if !(0..SECTIONS as i32).contains(&s) { return v; } - Arc::make_mut(&mut self.sections[s as usize]).set(index(x, y, z), v) + let previous = Arc::make_mut(&mut self.sections[s as usize]).set(index(x, y, z), v); + // `Heightmap.update`: a write two or more below the surface can't + // move it. Any other change rebuilds the map on the next read. + if previous != v + && let Some(surface) = self.surface.get() + && y >= i32::from(surface[column(x, z)]) - 1 + { + self.surface = OnceLock::new(); + } + previous + } + /// `getHeight(Heightmap.Types.WORLD_SURFACE, x, z)` (`x`, `z` within the + /// chunk): one above the highest block that isn't `air`, or `MIN_Y`. + /// Sections must change only through `set` once this has been read. + pub fn world_surface(&self, x: i32, z: i32, air: impl Fn(u32) -> bool) -> i32 { + let surface = self.surface.get_or_init(|| self.prime_surface(air)); + i32::from(surface[column(x, z)]) + } + /// `Heightmap.primeHeightmaps` for WORLD_SURFACE: each section from the + /// top, skipping those of one air state, until every column is found. + fn prime_surface(&self, air: impl Fn(u32) -> bool) -> Box<[i16; 256]> { + let mut surface = Box::new([MIN_Y as i16; 256]); + let mut found = [false; 256]; + let mut left = 256; + let mut values = [0u32; 4096]; + for (s, section) in self.sections.iter().enumerate().rev() { + if left == 0 { + break; + } + if section.blocks.uniform().is_some_and(&air) { + continue; + } + section.unpack(&mut values); + let base = MIN_Y + s as i32 * 16; + for i in 0..256 { + if found[i] { + continue; + } + if let Some(dy) = (0..16).rev().find(|&dy| !air(values[dy << 8 | i])) { + surface[i] = (base + dy as i32 + 1) as i16; + found[i] = true; + left -= 1; + } + } + } + surface } #[inline] pub fn light(&self, x: i32, y: i32, z: i32) -> u8 { @@ -261,4 +312,50 @@ mod tests { ); assert_eq!(Chunk::empty(0, 0).highest(air, |_| unreachable!()), None); } + /// The kept WORLD_SURFACE heights match a scan of every column after + /// each of a few thousand writes (air, cave air, stone, whole sections). + #[test] + fn world_surface_follows_writes() { + let (air, cave_air, stone) = (0, 7, 1); + let is_air = |v: u32| v == air || v == cave_air; + let scan = |c: &Chunk, x: i32, z: i32| { + (MIN_Y..MIN_Y + HEIGHT) + .rev() + .find(|&y| !is_air(c.get(x, y, z))) + .map_or(MIN_Y, |y| y + 1) + }; + let mut chunk = Chunk::empty(0, 0); + assert_eq!(chunk.world_surface(5, 5, is_air), MIN_Y); + for y in MIN_Y..MIN_Y + 70 { + for i in 0..256 { + chunk.set(i & 15, y, i >> 4, stone); + } + } + for i in 0..4096 { + Arc::make_mut(&mut chunk.sections[8]).set(i, cave_air); + } + let mut random = horizon_core::random::LegacyRandom::new(9); + use horizon_core::random::RandomSource; + for step in 0..4000 { + let x = random.next_int_bound(16).unwrap(); + let z = random.next_int_bound(16).unwrap(); + let y = MIN_Y + 40 + random.next_int_bound(120).unwrap(); + let v = [air, cave_air, stone][random.next_int_bound(3).unwrap() as usize]; + chunk.set(x, y, z, v); + if step % 7 == 0 { + for i in 0..256 { + assert_eq!( + chunk.world_surface(i & 15, i >> 4, is_air), + scan(&chunk, i & 15, i >> 4) + ); + } + } + } + // Out-of-range writes and unchanged states keep the map. + let before = chunk.world_surface(3, 3, is_air); + chunk.set(3, MIN_Y + HEIGHT, 3, stone); + chunk.set(3, before - 1, 3, chunk.get(3, before - 1, 3)); + assert!(chunk.surface.get().is_some()); + assert_eq!(chunk.world_surface(3, 3, |_| unreachable!()), before); + } } diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index d3e00daca..a52f25ce7 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -15,24 +15,18 @@ use horizon_world::{ entity_obstruction::EntityIdentity, fluid::{FluidKind, FluidState}, liquid_collision::LiquidCollisionWorld, - nbt::{self, Limits}, powder_snow_collision::{PowderSnowEntity, PowderSnowWorld}, - registry::BlockRegistry, + registry::{BlockRegistry, BlockTableFile}, world_movement::{ CollisionCheckRequest, EntityMovementWorld, MovementRequest, no_world_collision, resolve_world_movement, }, }; -use std::{fs, io, path::Path, sync::Arc}; +use std::{io, path::Path, sync::Arc}; pub fn load<'r>(root: &Path, registry: &'r BlockRegistry) -> Result> { - let data = nbt::read_named( - &fs::read(root.join("cached-collision.nbt"))?, - Limits::tables(), - )? - .0 - .tag; - let cached = CachedCollisionRegistry::from_nbt(&data, registry)?; + let file = BlockTableFile::open(&root.join("cached-collision.nbt"), registry)?; + let cached = CachedCollisionRegistry::from_table(file.table("collision")?)?; if !cached.has_canonical_identities() { return Err("scene collisions require canonical shape identities".into()); } @@ -137,12 +131,25 @@ impl SceneCollisions<'_, '_> { movement: Vec3, max_step: f32, on_ground: bool, + ) -> Result { + self.resolve_with_context(bounds, movement, max_step, on_ground, self.context(bounds)) + } + /// Resolve movement with the entity's captured collision context. Most + /// callers only need the position context; entities such as falling blocks + /// also affect contextual block shapes (for example powder snow). + pub fn resolve_with_context( + &mut self, + bounds: Aabb, + movement: Vec3, + max_step: f32, + on_ground: bool, + context: CollisionContext<'_>, ) -> Result { Ok(resolve_world_movement( self, MovementRequest { entity: EntityIdentity(0), - context: self.context(bounds), + context, bounds, movement, max_step, diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs index 8fcb30830..e9aeaae51 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-client/src/command/mod.rs @@ -312,6 +312,9 @@ pub enum Suggests { /// ScoreboardCommand.suggestTriggers: trigger objectives some of the /// parsed `targets` have no score in, or a locked one. EnableTriggers, + /// SuggestionProviders.ASK_SERVER: the server completes the node + /// (ClientSuggestionProvider.customSuggestion); nothing locally. + AskServer, } impl Node { pub fn name(&self) -> &str { @@ -691,7 +694,7 @@ impl Suggests { Suggests::Triggers => { builder.suggest_matching(reg.trigger_objectives.iter().map(String::as_str)) } - Suggests::Nothing => {} + Suggests::Nothing | Suggests::AskServer => {} } } } @@ -955,7 +958,8 @@ impl Dispatcher { cursor: usize, reg: &Registries, ) -> (Range, Vec) { - self.suggestions_within(parse, cursor, reg, u8::MAX) + let (range, list, _) = self.suggestions_within(parse, cursor, reg, u8::MAX); + (range, list) } /// The suggestions the player's chat shows: the client's tree only holds /// the nodes the player may use (Commands.sendCommands prunes by canUse). @@ -965,6 +969,18 @@ impl Dispatcher { cursor: usize, reg: &Registries, ) -> (Range, Vec) { + let (range, list, _) = self.suggestions_within(parse, cursor, reg, reg.permission); + (range, list) + } + /// [`Self::client_suggestions`], and whether a node at the cursor asks + /// the server (`ask_server`): its completions come with the server's + /// reply, to be merged with these. + pub fn client_suggestions_asking( + &self, + parse: &ParseResults, + cursor: usize, + reg: &Registries, + ) -> (Range, Vec, bool) { self.suggestions_within(parse, cursor, reg, reg.permission) } fn suggestions_within( @@ -973,15 +989,17 @@ impl Dispatcher { cursor: usize, reg: &Registries, permission: u8, - ) -> (Range, Vec) { + ) -> (Range, Vec, bool) { let (parent, start, context) = parse.context.suggestion_context(cursor); let start = start.min(cursor); let truncated = &parse.input[..cursor.min(parse.input.len())]; let mut all = Vec::new(); + let mut ask = false; for &child in &self.nodes[parent].children { if self.nodes[child].permission > permission { continue; } + ask |= matches!(self.nodes[child].suggests, Some(Suggests::AskServer)); let mut builder = SuggestionsBuilder::new(truncated, start); match &self.nodes[child].kind { NodeKind::Literal(l) => { @@ -997,7 +1015,8 @@ impl Dispatcher { } all.extend(builder.out); } - merge_suggestions(truncated, all) + let (range, list) = merge_suggestions(truncated, all); + (range, list, ask) } fn smart_usage_of(&self, node: usize, optional: bool, deep: bool, level: u8) -> Option { let n = &self.nodes[node]; diff --git a/crates/horizon-client/src/command/network.rs b/crates/horizon-client/src/command/network.rs index 32f446f5c..8fed97db0 100644 --- a/crates/horizon-client/src/command/network.rs +++ b/crates/horizon-client/src/command/network.rs @@ -83,10 +83,9 @@ pub fn from_packet(packet: &Commands, local: &Dispatcher) -> Dispatcher { } _ => NodeKind::Root, }; - let suggests = match local_node { - Some(l) => l.suggests.clone(), - None => node.suggestions.as_deref().and_then(provider), - }; + // The server's providers, as the client knows them + // (ArgumentNodeStub.build): its own custom ones arrive as `ask_server`. + let suggests = node.suggestions.as_deref().and_then(provider); nodes[index(i)] = Some(Node { kind: if i == root { NodeKind::Root } else { kind }, children: node.children.iter().filter_map(valid).map(index).collect(), @@ -104,10 +103,10 @@ pub fn from_packet(packet: &Commands, local: &Dispatcher) -> Dispatcher { d } -/// SuggestionProviders by id (`ask_server` asks the server; the client's -/// own argument suggestions stand in for it). +/// SuggestionProviders by id (`SuggestionProviders.getProvider`). fn provider(id: &str) -> Option { match id { + "minecraft:ask_server" => Some(Suggests::AskServer), "minecraft:summonable_entities" => Some(Suggests::SummonableEntities), _ => None, } diff --git a/crates/horizon-client/src/effects.rs b/crates/horizon-client/src/effects.rs index a258ccf3a..17dce93ab 100644 --- a/crates/horizon-client/src/effects.rs +++ b/crates/horizon-client/src/effects.rs @@ -336,73 +336,8 @@ impl PlayerEffects { pub fn modifiers(&self) -> Vec<(&'static str, &'static str, f64, &'static str)> { let mut out = Vec::new(); for e in &self.list { - let level = f64::from(e.amplifier + 1); - let m = match e.id { - "speed" => Some(( - "minecraft:movement_speed", - "minecraft:effect.speed", - 0.2, - "add_multiplied_total", - )), - "slowness" => Some(( - "minecraft:movement_speed", - "minecraft:effect.slowness", - -0.15, - "add_multiplied_total", - )), - "haste" => Some(( - "minecraft:attack_speed", - "minecraft:effect.haste", - 0.1, - "add_multiplied_total", - )), - "mining_fatigue" => Some(( - "minecraft:attack_speed", - "minecraft:effect.mining_fatigue", - -0.1, - "add_multiplied_total", - )), - "strength" => Some(( - "minecraft:attack_damage", - "minecraft:effect.strength", - 3.0, - "add_value", - )), - "weakness" => Some(( - "minecraft:attack_damage", - "minecraft:effect.weakness", - -4.0, - "add_value", - )), - "jump_boost" => Some(( - "minecraft:safe_fall_distance", - "minecraft:effect.jump_boost", - 1.0, - "add_value", - )), - "health_boost" => Some(( - "minecraft:max_health", - "minecraft:effect.health_boost", - 4.0, - "add_value", - )), - "absorption" => Some(( - "minecraft:max_absorption", - "minecraft:effect.absorption", - 4.0, - "add_value", - )), - "luck" => Some(("minecraft:luck", "minecraft:effect.luck", 1.0, "add_value")), - "unluck" => Some(( - "minecraft:luck", - "minecraft:effect.unluck", - -1.0, - "add_value", - )), - _ => None, - }; - if let Some((a, id, amount, op)) = m { - out.push((a, id, amount * level, op)); + if let Some((a, id, amount, op)) = effect_modifier(e.id) { + out.push((a, id, amount * f64::from(e.amplifier + 1), op)); } } out @@ -445,6 +380,76 @@ impl StatusFlags { } } +/// The attribute modifier an effect adds at amplifier 0 +/// (`MobEffect.addAttributeModifier`): (attribute, id, amount, operation). +/// Each level multiplies the amount (`amplifier + 1`). +pub fn effect_modifier(effect: &str) -> Option<(&'static str, &'static str, f64, &'static str)> { + match effect { + "speed" => Some(( + "minecraft:movement_speed", + "minecraft:effect.speed", + 0.2, + "add_multiplied_total", + )), + "slowness" => Some(( + "minecraft:movement_speed", + "minecraft:effect.slowness", + -0.15, + "add_multiplied_total", + )), + "haste" => Some(( + "minecraft:attack_speed", + "minecraft:effect.haste", + 0.1, + "add_multiplied_total", + )), + "mining_fatigue" => Some(( + "minecraft:attack_speed", + "minecraft:effect.mining_fatigue", + -0.1, + "add_multiplied_total", + )), + "strength" => Some(( + "minecraft:attack_damage", + "minecraft:effect.strength", + 3.0, + "add_value", + )), + "weakness" => Some(( + "minecraft:attack_damage", + "minecraft:effect.weakness", + -4.0, + "add_value", + )), + "jump_boost" => Some(( + "minecraft:safe_fall_distance", + "minecraft:effect.jump_boost", + 1.0, + "add_value", + )), + "health_boost" => Some(( + "minecraft:max_health", + "minecraft:effect.health_boost", + 4.0, + "add_value", + )), + "absorption" => Some(( + "minecraft:max_absorption", + "minecraft:effect.absorption", + 4.0, + "add_value", + )), + "luck" => Some(("minecraft:luck", "minecraft:effect.luck", 1.0, "add_value")), + "unluck" => Some(( + "minecraft:luck", + "minecraft:effect.unluck", + -1.0, + "add_value", + )), + _ => None, + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index 3fa6e68a1..b9c8ee896 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -179,6 +179,8 @@ impl ItemEntity { /// ExperienceOrb: gravity 0.03, homing towards the player within 8 blocks. #[derive(Clone, Debug)] pub struct ExperienceOrb { + /// The entity id servers track it by. + pub id: u32, pub position: Vec3, pub previous: Vec3, pub velocity: Vec3, @@ -533,15 +535,16 @@ impl ArmorStand { Vec3::new(p.x + w, p.y + h, p.z + w), ) } - /// LivingEntity.travel with gravity 0.08 and 0.98 drag, falling until it - /// lands (armor stands have no other movement). + /// LivingEntity.travelInAir (armor stands have no other movement): move + /// by the velocity (a landing stops the fall, + /// `Block.updateEntityMovementAfterFallOn`), then gravity 0.08 and the + /// 0.98 drag, so a stand at rest on the ground keeps -0.0784 as vanilla's. pub fn tick(&mut self, scene: &mut crate::collisions::SceneCollisions) { if self.marker { return; } - let mut v = self.velocity; - v.y -= 0.08; - let wanted = v; + let wanted = self.velocity; + let mut y = wanted.y; if let Ok(moved) = scene.resolve(self.bounds(), wanted, 0.0, self.on_ground) { self.position = Vec3::new( self.position.x + moved.x, @@ -549,9 +552,11 @@ impl ArmorStand { self.position.z + moved.z, ); self.on_ground = wanted.y < 0.0 && moved.y > wanted.y; - v = Vec3::new(0.0, if moved.y != wanted.y { 0.0 } else { v.y * 0.98 }, 0.0); + if moved.y != wanted.y { + y = 0.0; + } } - self.velocity = v; + self.velocity = Vec3::new(0.0, (y - 0.08) * f64::from(0.98f32), 0.0); } } @@ -597,9 +602,10 @@ mod fire_environment_tests { return; } let assets = crate::assets::Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let facts = BlockFacts::load(&root, assets.registry).unwrap(); let items = crate::items::Items::load(&root, assets.registry, &facts).unwrap(); - let mut world = World::test_scene(&assets, 3).unwrap(); + let mut world = World::test_scene(&assets, &render, 3).unwrap(); let at = Vec3::new(20.5, 4.0, 20.5); world .set( diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index bf02f689f..ee86211a1 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -840,9 +840,12 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.species(), crate::mobs::Species::Slime | crate::mobs::Species::MagmaCube ) { - let health = m.health; + // AbstractCubeMob.readAdditionalSaveData: the size's attributes, then + // the saved health, the max health when there is none. crate::mobs::cube::set_size(&mut m, number(tag.get("Size")).unwrap_or(0) as i32 + 1); - m.health = health; + if let Some(h) = float(tag.get("Health")) { + m.health = h as f32; + } m.extra.flag2 = flag(tag, "wasOnGround"); } // Zombie, Piglin and Zoglin.readAdditionalSaveData: IsBaby (the baby @@ -943,6 +946,7 @@ pub fn orbs_from_nbt(tag: &Tag) -> Vec { }; let count = number(tag.get("Count")).unwrap_or(1).clamp(1, 64) as usize; let orb = ExperienceOrb { + id: 0, position, previous: position, velocity: motion(tag), @@ -1587,6 +1591,7 @@ mod tests { #[test] fn orbs_expand_their_count() { let o = ExperienceOrb { + id: 0, position: Vec3::new(1.0, 2.0, 3.0), previous: Vec3::ZERO, velocity: Vec3::ZERO, diff --git a/crates/horizon-client/src/fog.rs b/crates/horizon-client/src/fog.rs index 83f1a8bf5..4e29aeae9 100644 --- a/crates/horizon-client/src/fog.rs +++ b/crates/horizon-client/src/fog.rs @@ -32,6 +32,7 @@ pub struct FogData { } /// Per-biome water fog end multipliers (`visual/water_fog_end_distance`). +#[derive(Default)] pub struct FogTables { water_fog_end: Vec, } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 26709516f..2cbdabaa4 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -10,6 +10,7 @@ mod banners; mod beacon; mod beehives; mod block_entity_anims; +mod block_entity_ticks; mod block_items; mod blockctl; mod boats; @@ -24,6 +25,7 @@ mod command_blocks; mod command_harness; mod commands; mod composter; +mod consume; mod control; mod copper_golems; mod creaking; @@ -63,7 +65,10 @@ mod item_particles; mod jukebox; mod lan; mod lan_actions; +mod lan_attributes; +mod lan_chat; mod lan_crafting; +mod lan_entities; mod lan_mobs; mod lan_pvp; mod lan_screen; @@ -107,6 +112,8 @@ mod powder_snow; mod raids; mod recipe_book; mod remote; +mod remote_objects; +mod remote_projectiles; mod render_control; mod render_tick; mod respawn_anchor; @@ -121,6 +128,7 @@ mod sign_edit; mod sniffers; mod spawner; mod spill; +mod startup_menu; mod station_control; mod stations; mod stats; @@ -146,7 +154,7 @@ mod wither; mod zombie_villagers; use horizon_client::{ Result, - assets::Assets, + assets::{Assets, RenderAssets}, audio::Audio, biome::Biomes, blocks::{BlockFacts, Fluid}, @@ -188,6 +196,8 @@ use horizon_core::{ use horizon_core::{geometry::Vec3, random::RandomSource}; use horizon_world::{ block_collision::BlockCollisionRegistry, + collision_context::{CollisionContext, CollisionEntity, CollisionItem}, + entity_obstruction::{EntityIdentity, EntityObstructionWorld, ObstructionEntity}, level::{ Behaviours, Dimension as LevelDimension, EntityQuery, Landing, LevelAccess, LevelEvent, PlaceContext, PlaceOutcome, PlayerContext, PlayerEffect, Ticks, flags as level_flags, @@ -446,12 +456,16 @@ struct Hit { struct GameLevel<'w> { world: &'w mut World, facts: &'w BlockFacts, + collision: &'w BlockCollisionRegistry<'w>, events: &'w mut Vec, dimension: LevelDimension, darken: i32, raining: bool, thundering: bool, player_box: Option<([f64; 3], [f64; 3])>, + /// The LAN guests in this level who trigger blocks (not spectators). + guest_boxes: Vec<([f64; 3], [f64; 3])>, + player_collision: Option, /// Minecart boxes (detector rails). cart_boxes: Vec<([f64; 3], [f64; 3])>, biomes: &'w Biomes, @@ -466,6 +480,34 @@ struct GameLevel<'w> { rand_sequences: &'w mut horizon_client::random_sequences::RandomSequences, pending: &'w mut spill::Pending, spill: &'w mut spill::Spill, + /// Where the chunk tickets let blocks tick. + tickets: horizon_client::ticket_levels::Levels, +} +struct PlayerCollision { + y: f64, + descending: bool, + fall_distance: f64, + main_hand_item: Arc, + main_hand_count: i32, + leather_boots: bool, +} +struct PlayerObstruction(Aabb); +impl EntityObstructionWorld for PlayerObstruction { + type Error = std::convert::Infallible; + fn obstruction_candidates( + &mut self, + _excluded: Option, + _bounds: Aabb, + ) -> std::result::Result, Self::Error> { + Ok(vec![ObstructionEntity { + identity: EntityIdentity(0), + root_vehicle: EntityIdentity(0), + bounds: self.0, + removed: false, + spectator: false, + blocks_building: true, + }]) + } } impl LevelAccess for GameLevel<'_> { fn precipitation(&self, pos: BlockPos) -> Option { @@ -579,24 +621,71 @@ impl LevelAccess for GameLevel<'_> { fn dimension(&self) -> LevelDimension { self.dimension } - /// Level.isUnobstructed against the player for full-collision blocks. + /// `Level.isUnobstructed`: the placed state's collision shape against the player. fn is_unobstructed(&self, pos: BlockPos, state: BlockStateId) -> bool { let Some((lo, hi)) = self.player_box else { return true; }; - if !self.facts.get(state).full_collision { + let player = self.player_collision.as_ref(); + let context = player.map_or_else( + || CollisionContext::position(lo[1]), + |player| { + CollisionContext::for_entity( + CollisionEntity { + identity: EntityIdentity(0), + y: player.y, + descending: player.descending, + main_hand: Some(CollisionItem { + item: &player.main_hand_item, + count: player.main_hand_count, + }), + }, + false, + ) + }, + ); + let mut scene = collisions::SceneCollisions { + world: &*self.world, + binding: self.collision, + subject: player.map(|player| horizon_client::collisions::PowderSnowSubject { + fall_distance: player.fall_distance, + falling_block: false, + leather_boots: player.leather_boots, + walkable_type: false, + lava_walker: false, + }), + }; + let Ok(shape) = self + .collision + .collision_shape_with_context(&mut scene, state, pos, &context) + else { + return false; + }; + if shape.is_empty() { return true; } - let (x, y, z) = (f64::from(pos.x), f64::from(pos.y), f64::from(pos.z)); - !(x < hi[0] - 1e-7 - && x + 1.0 > lo[0] + 1e-7 - && y < hi[1] - 1e-7 - && y + 1.0 > lo[1] + 1e-7 - && z < hi[2] - 1e-7 - && z + 1.0 > lo[2] + 1e-7) + let shape = shape.moved(horizon_core::geometry::Vec3::new( + f64::from(pos.x), + f64::from(pos.y), + f64::from(pos.z), + )); + horizon_world::entity_obstruction::is_unobstructed( + &mut PlayerObstruction(Aabb::new( + horizon_core::geometry::Vec3::new(lo[0], lo[1], lo[2]), + horizon_core::geometry::Vec3::new(hi[0], hi[1], hi[2]), + )), + None, + &shape, + ) + .unwrap_or(false) + } + /// `ServerLevel.isPositionTickingWithEntitiesLoaded`: block ticking, and + /// a ticking chunk. + fn is_ticking_chunk(&self, chunk: horizon_core::position::ChunkPos) -> bool { + self.tickets.block_ticking(chunk.x, chunk.z) && ticking_chunk(self.world, chunk.x, chunk.z) } /// Entities that trigger pressure plates, tripwires and detector rails: - /// the player (a mob) and the minecarts. + /// the players (the host and the LAN guests, mobs) and the minecarts. fn count_entities(&self, area: Aabb, query: EntityQuery) -> usize { let hit = |(lo, hi): &([f64; 3], [f64; 3])| { area.intersects(Aabb::new( @@ -605,10 +694,17 @@ impl LevelAccess for GameLevel<'_> { )) }; let carts = || self.cart_boxes.iter().filter(|b| hit(b)).count(); + let players = || { + self.player_box + .iter() + .chain(&self.guest_boxes) + .filter(|b| hit(b)) + .count() + }; match query { EntityQuery::Minecart => carts(), - EntityQuery::Mobs => self.player_box.iter().filter(|b| hit(b)).count(), - EntityQuery::Everything => self.player_box.iter().filter(|b| hit(b)).count() + carts(), + EntityQuery::Mobs => players(), + EntityQuery::Everything => players() + carts(), } } fn emit(&mut self, event: LevelEvent) { @@ -647,6 +743,8 @@ impl LevelAccess for GameLevel<'_> { /// FallingBlockEntity carrying a block state. #[derive(Clone, Debug)] struct FallingBlock { + /// The entity id a server tracks it by (0 until it is tracked). + id: u32, state: BlockStateId, /// `DATA_START_POS`: spawn position used to select weighted block models. start_pos: BlockPos, @@ -669,12 +767,23 @@ struct FallingBlock { /// recipes, biomes, mobs, collision and motion. Read-only and `Send + Sync`, /// so the client and an integrated server thread can share one copy. pub struct Resources { + core: WorldCore, + rest: std::sync::OnceLock, +} + +struct WorldCore { facts: BlockFacts, + biomes: Arc, + environment: Environment, + collision: BlockCollisionRegistry<'static>, + motion: MotionResources, + threads: usize, +} + +struct WorldRest { items: Items, recipes: Recipes, transformers: horizon_client::block_transform::Transformers, - biomes: Arc, - environment: Environment, mob_types: HashMap>, mob_data: horizon_client::mobs::MobData, providers: Providers, @@ -686,14 +795,105 @@ pub struct Resources { nether_environment: Environment, end_environment: Environment, behaviours: Behaviours, - collision: BlockCollisionRegistry<'static>, - motion: MotionResources, - threads: usize, player_arm: Option, player_type: Option>, - /// Enchantments, workstation recipes and brewing (game/stations.rs). stations: horizon_client::stations::StationData, } + +impl Resources { + fn rest(&self) -> &WorldRest { + self.rest + .get() + .expect("world resources joined before entry") + } + fn facts(&self) -> &BlockFacts { + &self.core.facts + } + fn items(&self) -> &Items { + &self.rest().items + } + fn recipes(&self) -> &Recipes { + &self.rest().recipes + } + fn transformers(&self) -> &horizon_client::block_transform::Transformers { + &self.rest().transformers + } + fn biomes(&self) -> &Arc { + &self.core.biomes + } + fn environment(&self) -> &Environment { + &self.core.environment + } + fn mob_types(&self) -> &HashMap> { + &self.rest().mob_types + } + fn mob_data(&self) -> &horizon_client::mobs::MobData { + &self.rest().mob_data + } + fn providers(&self) -> &Providers { + &self.rest().providers + } + fn block_entity_render(&self) -> &horizon_client::block_entity_render::BlockEntityRenderer { + &self.rest().block_entity_render + } + fn animate(&self) -> &horizon_client::animate_tick::AnimateTables { + &self.rest().animate + } + fn fog(&self) -> &horizon_client::fog::FogTables { + &self.rest().fog + } + fn music(&self) -> &horizon_client::music::MusicTables { + &self.rest().music + } + fn ambient(&self) -> &horizon_client::ambience::AmbientTables { + &self.rest().ambient + } + fn nether_environment(&self) -> &Environment { + &self.rest().nether_environment + } + fn end_environment(&self) -> &Environment { + &self.rest().end_environment + } + fn behaviours(&self) -> &Behaviours { + &self.rest().behaviours + } + fn collision(&self) -> &BlockCollisionRegistry<'static> { + &self.core.collision + } + fn motion(&self) -> &MotionResources { + &self.core.motion + } + fn threads(&self) -> usize { + self.core.threads + } + fn player_arm(&self) -> &Option { + &self.rest().player_arm + } + fn player_type(&self) -> &Option> { + &self.rest().player_type + } + fn stations(&self) -> &horizon_client::stations::StationData { + &self.rest().stations + } +} + +/// Everything the title and menus draw: the GUI atlas with its font and the +/// title panorama. Kept apart from the world bundle so the title can appear +/// before the block sprites, models and gameplay tables are ready. +pub struct UiResources { + /// The GUI, font, particle, map and skin atlas. + pub atlas: HudAtlas, + /// The title screen's panorama faces. + pub panorama: Arc, +} +impl UiResources { + pub fn load(root: &std::path::Path) -> Result { + Ok(Self { + atlas: HudAtlas::build(root)?, + panorama: Arc::new(horizon_client::gfx::panorama::Faces::load(root)), + }) + } +} /// What a resource pack reload replaces (`Minecraft.reloadResourcePacks`): /// block models and sprites with their meshing tables, item models, /// translations and the textures read on the CPU. Each game holds its own; @@ -701,9 +901,9 @@ pub struct Resources { #[derive(Clone)] pub struct PackResources { assets: Arc, + render: Arc, context: Arc, layer_names: Arc>, - panorama: Arc, /// Item definitions, baked item models and special renderers. item_renderer: Arc, names: Arc, @@ -713,23 +913,25 @@ pub struct PackResources { forcefield: Arc<(u32, u32, Vec)>, } impl PackResources { - /// Everything a pack overlay at `root` provides, over `assets` loaded from it. + /// Everything a pack overlay at `root` provides, over `assets` and `render` + /// loaded from it. fn load( root: &std::path::Path, assets: Arc, + render: Arc, facts: &BlockFacts, biomes: Arc, light: Arc, ) -> Result { let visibility = models::load_visibility(root, assets.registry)?; - let tables = Arc::new(MeshTables::new(&assets, facts, visibility)?); + let tables = Arc::new(MeshTables::new(&assets, &render, facts, visibility)?); let item_renderer = horizon_client::item_render::ItemRenderer::load_with_library( root, - assets.model_library.clone(), + render.model_library.clone(), )?; Ok(Self { layer_names: Arc::new( - assets + render .sprite_layers .iter() .map(|(name, layer)| (*layer, name.trim_start_matches("minecraft:").to_owned())) @@ -737,12 +939,13 @@ impl PackResources { ), context: Arc::new(WorkerContext { assets: assets.clone(), + render: render.clone(), tables, biomes, light, }), assets, - panorama: Arc::new(horizon_client::gfx::panorama::Faces::load(root)), + render, item_renderer: Arc::new(item_renderer), names: Arc::new(Names::load(root)), clouds: Arc::new(load_clouds(root)), @@ -757,6 +960,12 @@ struct DragView { left: Option, } /// Ctrl+Q reads the physical keyboard, independently of sprint key mappings. +/// A chunk whose ticking future can complete (`ChunkMap.prepareTickingChunk`): +/// lit, with its neighbours loaded, as `postprocess_chunks` waits for. +fn ticking_chunk(world: &World, x: i32, z: i32) -> bool { + world.chunks.get(&(x, z)).is_some_and(|c| c.lit) + && (-1..=1).all(|dz| (-1..=1).all(|dx| world.chunks.contains_key(&(x + dx, z + dz)))) +} fn drop_whole_stack(physical_keys: &HashSet) -> bool { physical_keys.contains(&KeyCode::ControlLeft) || physical_keys.contains(&KeyCode::ControlRight) } @@ -775,12 +984,16 @@ fn select_creative_tab( struct Game<'a> { /// Shared with an integrated server; `collision` and `motion` borrow from it. res: Arc, + rest_loader: Option, + pending_entry: Option, + pending_pack_reload: bool, + world_renderer_ready: bool, collision: &'a BlockCollisionRegistry<'a>, motion: &'a MotionResources, /// This game's resource packs (`reload_packs` replaces them). pack: PackResources, - /// The GUI, font, particle, map and skin atlas. - atlas: HudAtlas, + /// The title and menu bundle (GUI atlas, font and panorama). + gui: UiResources, /// `FogRenderer`'s evolving state. fog: horizon_client::fog::FogState, screen_fx: horizon_client::screen_effects::ScreenEffects, @@ -984,6 +1197,8 @@ struct Game<'a> { /// A server's players on their way to another level, each waiting for /// the destination to load around them. server_trips: Vec, + /// Players a command sends to another level, once it has run. + level_teleports: 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 @@ -1003,6 +1218,7 @@ struct Game<'a> { end: end::EndState, block_ticks: Ticks, tick_chunks: horizon_client::tick_chunk_membership::TickChunkMembership, + tickets: horizon_client::ticket_levels::ChunkTickets, random_tick_sections: horizon_client::random_tick_sections::RandomTickSections, level_events: Vec, falling: Vec, @@ -1151,10 +1367,16 @@ struct Game<'a> { lan_acting_uuid: Option, /// Command feedback to forward to a guest. chat_capture: Option>, + /// Packets for the guest acting now, sent once its action returns. + guest_packets: Vec, /// `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)>, + /// The server console is running a command: whether its feedback goes to + /// the operators (`DedicatedServer.shouldInformAdmins`, + /// `broadcast-console-to-ops`). + console_broadcast: Option, /// State of `/spectate`, `/posteffect`, `/debug`, `/waypoint` and friends. cmds: commands::extra::CommandExtras, ui: chat::UiState, @@ -1203,6 +1425,21 @@ impl Dim { _ => Self::Overworld, } } + /// `Level.getMinY`: the dimension type's minimum y. + fn min_y(self) -> i32 { + match self { + Self::Overworld => MIN_Y, + Self::Nether | Self::End => 0, + } + } + /// `DimensionType.logicalHeight`. + fn logical_height(self) -> i32 { + match self { + Self::Overworld => HEIGHT, + Self::Nether => 128, + Self::End => 256, + } + } /// `Level.getMaxY`: the dimension type's minimum y plus height, less one. fn max_y(self) -> i32 { match self { @@ -1261,7 +1498,7 @@ impl Game<'_> { /// A block's outline boxes in world space (`getShape` plus the random offset). fn outline_boxes(&self, pos: [i32; 3]) -> Vec<[f64; 6]> { let state = self.world.block(pos[0], pos[1], pos[2]); - let f = self.res.facts.get(state); + let f = self.res.facts().get(state); let o = if f.outline_offset { self.pack .context @@ -1323,8 +1560,8 @@ impl Game<'_> { let mut t = 0.0; while t <= reach { let state = self.world.block(pos[0], pos[1], pos[2]); - let f = self.res.facts.get(state); - if !self.res.facts.is_air(state) + let f = self.res.facts().get(state); + if !self.res.facts().is_air(state) && !(f.fluid != Fluid::None && !f.waterlogged && &*f.name != "minecraft:kelp" @@ -1426,7 +1663,11 @@ impl Game<'_> { } /// Inventory.add: returns the stack that did not fit. fn give(&mut self, mut stack: ItemStack) -> Option { - let max = self.res.items.get(&stack.item).map_or(64, |i| i.max_stack); + let max = self + .res + .items() + .get(&stack.item) + .map_or(64, |i| i.max_stack); // Prefer the selected slot, then the hotbar, then the main inventory. let order: Vec = std::iter::once(self.selected) .chain((0..36).filter(|&i| i != self.selected)) @@ -1462,7 +1703,7 @@ impl Game<'_> { fn particle_sprite(&self, state: BlockStateId) -> Option<(String, u32)> { let models = self .pack - .assets + .render .model_catalog .collect(state, horizon_core::position::BlockPos::new(0, 0, 0)) .ok()?; @@ -1477,7 +1718,7 @@ impl Game<'_> { .or_else(|| models.iter().find_map(|(_, model)| model.particle))?; let name = self.pack.layer_names.get(&layer)?.clone(); let tint = if face.is_some_and(|face| face.quad.tint_index >= 0) { - let n = &self.res.facts.get(state).name; + let n = &self.res.facts().get(state).name; if n.contains("leaves") || n.contains("vine") { 0x48B518 } else { @@ -1489,7 +1730,7 @@ impl Game<'_> { Some((name, tint)) } fn particle_shape(&self, pos: [i32; 3], state: BlockStateId) -> Vec<[f64; 6]> { - let f = self.res.facts.get(state); + let f = self.res.facts().get(state); let offset = if f.outline_offset { self.pack .context @@ -1567,14 +1808,14 @@ impl Game<'_> { ) -> Vec { let registry = self.pack.assets.registry; let dynamic = self.pending.dynamic(pos); - match self.res.items.block_loot_sequence(registry, state) { + match self.res.items().block_loot_sequence(registry, state) { Some(sequence) => { let random = self.rand_sequences.get(&sequence, self.level.seed); self.res - .items + .items() .block_drops_with(registry, state, held, &dynamic, random) } - None => self.res.items.block_drops_with( + None => self.res.items().block_drops_with( registry, state, held, @@ -1644,14 +1885,14 @@ impl Game<'_> { ) { return true; } - if !item.tick(&self.world, &self.res.facts, self.collision) { + if !item.tick(&self.world, self.res.facts(), self.collision) { return false; } let environment = item.environment_tick( &self.world, - &self.res.facts, + self.res.facts(), self.pack.assets.registry, - &self.res.items, + self.res.items(), ); // shortcut: age is the fresh-drop clock; use entity ticks for saved/frozen-age phase parity. if environment.should_play_lava_hurt_sound(item.age) { @@ -1754,6 +1995,22 @@ impl Game<'_> { ], ) }); + let player_collision = self.player.as_ref().filter(|_| !spectator).map(|p| { + let main_hand = self.inventory.get(self.selected).and_then(Option::as_ref); + PlayerCollision { + y: p.position.y, + descending: p.velocity.y < 0.0, + fall_distance: p.fall_distance, + main_hand_item: main_hand.map_or_else( + || Arc::from("minecraft:air"), + |stack| Arc::clone(&stack.item), + ), + main_hand_count: main_hand.map_or(0, |stack| stack.count as i32), + leather_boots: self.armor[3] + .as_ref() + .is_some_and(|stack| stack.item.as_ref() == "minecraft:leather_boots"), + } + }); let cart_boxes = self .carts .iter() @@ -1765,6 +2022,7 @@ impl Game<'_> { ) }) .collect(); + let guest_boxes = self.lan_block_trigger_boxes(); let dimension = match self.dim { Dim::Overworld => LevelDimension::Overworld, Dim::Nether => LevelDimension::Nether, @@ -1774,25 +2032,29 @@ impl Game<'_> { let mut level = GameLevel { cart_boxes, world: &mut self.world, - facts: &self.res.facts, + facts: self.res.facts(), + collision: self.collision, events: &mut self.level_events, dimension, darken, raining: rain > 0.2, thundering: thunder > 0.9, player_box, - biomes: &self.res.biomes, + guest_boxes, + player_collision, + biomes: self.res.biomes(), seed: self.level.seed, - behaviours: &self.res.behaviours, - items: &self.res.items, + behaviours: self.res.behaviours(), + items: self.res.items(), loot: horizon_client::structure_blocks::loot_data(&self.options.resources), registry: self.pack.assets.registry, rules, rand_sequences: &mut self.rand_sequences, pending: &mut self.pending, spill: &mut self.spill, + tickets: self.tickets.levels(), }; - let result = f(&self.res.behaviours, &mut level, &mut self.block_ticks); + let result = f(self.res.behaviours(), &mut level, &mut self.block_ticks); self.flush_spill(); result } @@ -1827,27 +2089,68 @@ impl Game<'_> { } for &key in self.tick_chunks.removed() { self.random_tick_sections.remove(&key); + self.portals.sections.remove(&key); self.block_ticks .remove_chunk(horizon_core::position::ChunkPos::new(key.0, key.1)); } self.tick_chunks.recycle_added(added); } - /// ServerLevel.tick block phases: scheduled ticks, random ticks within the - /// simulation distance, block events and moving pistons. + /// `DistanceManager`'s tickets of the level in place, from every player in + /// it (the local player, LAN guests, a server's players) and its forced + /// chunks. A game with neither a server nor a player (the headless + /// fixtures) ticks everywhere. + fn update_chunk_tickets(&mut self) { + let mut players: Vec<(i32, i32)> = self.lan.as_ref().map_or_else(Vec::new, |h| { + h.hub + .guests + .iter() + .filter(|g| h.hub.here(g)) + .map(|g| g.chunk()) + .collect() + }); + if let Some(p) = &self.player { + players.push(( + (p.position.x.floor() as i32) >> 4, + (p.position.z.floor() as i32) >> 4, + )); + } + let sources = (self.options.dedicated.is_some() || !players.is_empty()).then(|| { + horizon_client::ticket_levels::Sources { + players, + forced: self.streaming.forced.iter().copied().collect(), + view_distance: self.settings.render_distance.clamp(2, 32), + simulation_distance: self.settings.simulation_distance.max(2), + } + }); + self.tickets.update(sources); + } + /// `ServerLevel.startTickingChunk`: a loaded chunk's saved ticks are + /// scheduled from the game time at which it becomes a ticking chunk + /// (block ticking, with its neighbours loaded). Chunks become ticking + /// between ticks in vanilla: before this tick's clock advanced. + fn start_ticking_chunks(&mut self) { + let levels = self.tickets.levels(); + let world = &self.world; + let started = self + .tick_chunks + .start_ticking(|(x, z)| levels.loaded_ticking(x, z) && ticking_chunk(world, x, z)); + let time = self.world.game_time - 1; + for (x, z) in started { + let pos = horizon_core::position::ChunkPos::new(x, z); + self.block_ticks.blocks.unpack_chunk(pos, time); + self.block_ticks.fluids.unpack_chunk(pos, time); + } + } + /// ServerLevel.tick block phases: scheduled ticks, random ticks in the + /// chunks the tickets simulate, block events and moving pistons. fn tick_blocks(&mut self) -> Result<()> { self.sync_tick_chunks(); - let Some(p) = self.player.as_ref() else { - return Ok(()); - }; - let (pcx, pcz) = ( - (p.position.x.floor() as i32) >> 4, - (p.position.z.floor() as i32) >> 4, - ); - let simulation = self.settings.render_distance.min(8); + self.start_ticking_chunks(); + let levels = self.tickets.levels(); let mut ticking = Vec::new(); - let facts = &self.res.facts; + let facts = self.res.facts(); for (&(x, z), chunk) in &self.world.chunks { - if (x - pcx).abs() > simulation || (z - pcz).abs() > simulation || !chunk.lit { + if !levels.random_ticking(x, z) || !ticking_chunk(&self.world, x, z) { continue; } // Capture eligibility before inside-block and scheduled updates, as @@ -1857,8 +2160,9 @@ impl Game<'_> { ticking.push((x, z, sections)); } // Entity.checkInsideBlocks for the plates, tripwires and detector rails - // under the player and the minecarts. + // under the players (the host and the LAN guests) and the minecarts. let mut inside = Vec::new(); + let guests = self.lan_block_trigger_boxes(); let boxes = self .player .iter() @@ -1877,7 +2181,8 @@ impl Game<'_> { [p.x - 0.49, p.y, p.z - 0.49], [p.x + 0.49, p.y + 0.7, p.z + 0.49], ) - })); + })) + .chain(guests); for (lo, hi) in boxes { for x in (lo[0] + 1e-7).floor() as i32..=(hi[0] - 1e-7).floor() as i32 { for y in (lo[1] + 1e-7).floor() as i32..=(hi[1] - 1e-7).floor() as i32 { @@ -1947,10 +2252,10 @@ impl Game<'_> { let state = BlockStateId(data as u32); let p = [pos.x, pos.y, pos.z]; self.destroy_particles(p, state); - if self.res.facts.is_air(state) { + if self.res.facts().is_air(state) { continue; } - let sounds = self.res.facts.get(state).sounds.clone(); + let sounds = self.res.facts().get(state).sounds.clone(); let c = [ f64::from(pos.x) + 0.5, f64::from(pos.y) + 0.5, @@ -1977,6 +2282,11 @@ impl Game<'_> { pos, data, } => self.dragon_egg_particles([pos.x, pos.y, pos.z], data), + LevelEvent::LevelEvent { + id: 2017, + pos, + data, + } => self.consume_teleport_particles([pos.x, pos.y, pos.z], data), LevelEvent::LevelEvent { id: 2013, pos, @@ -2052,6 +2362,7 @@ impl Game<'_> { f64::from(pos.z) + 0.5, ); self.falling.push(FallingBlock { + id: 0, state, start_pos: pos, position: p, @@ -2061,7 +2372,7 @@ impl Game<'_> { no_gravity: false, drop_item: true, fall_distance: 0.0, - damage: if self.res.facts.get(state).name.ends_with("anvil") { + damage: if self.res.facts().get(state).name.ends_with("anvil") { horizon_client::falling_block::Damage::anvil() } else { Default::default() @@ -2174,7 +2485,7 @@ impl Game<'_> { fn open_menu(&mut self, pos: [i32; 3]) { let name = self .res - .facts + .facts() .get(self.world.block(pos[0], pos[1], pos[2])) .name .clone(); @@ -2201,13 +2512,13 @@ impl Game<'_> { self.audio .play("minecraft:block.ender_chest.open", Some(at), 0.5, pitch); } else if &*name == "minecraft:beacon" && self.open_station(pos, &name) { - self.world.block_entities.entry(key).or_insert_with(|| { + self.world.block_entities.get_or_insert_with(key, || { BlockEntity::for_block(&name).unwrap_or(BlockEntity::Chest(Vec::new())) }); } else if storage::is_shulker_box(&name) && !self.shulker_can_open(pos) { // ShulkerBoxBlock.canOpen: the lid has no room; nothing opens. } else if let Some(entity) = BlockEntity::for_block(&name) { - self.world.block_entities.entry(key).or_insert(entity); + self.world.block_entities.get_or_insert_with(key, || entity); let centre = [ f64::from(key.0) + 0.5, f64::from(key.1) + 0.5, @@ -2281,65 +2592,87 @@ impl Game<'_> { let mut falling = std::mem::take(&mut self.falling); let mut landed = Vec::new(); let mut dropped = Vec::new(); + let mut collision_error = None; let entity_drops = self.ui.rules.bool("entity_drops"); falling.retain_mut(|f| { + let original = f.clone(); f.previous = f.position; f.age = f.age.wrapping_add(1); if !f.no_gravity { f.velocity.y -= 0.04; } + let wanted = f.velocity; + let mut scene = collisions::SceneCollisions { + world: &self.world, + binding: self.collision, + subject: Some(collisions::PowderSnowSubject { + fall_distance: f.fall_distance, + falling_block: true, + ..Default::default() + }), + }; + let context = CollisionContext::for_entity( + CollisionEntity { + identity: EntityIdentity(0), + y: f.position.y, + descending: wanted.y < 0.0, + main_hand: None, + }, + false, + ); + let movement = match scene.resolve_with_context( + horizon_client::falling_block::bounds(f.position), + wanted, + 0.0, + false, + context, + ) { + Ok(movement) => movement, + Err(error) => { + *f = original; + collision_error.get_or_insert(error); + return true; + } + }; let next = Vec3::new( - f.position.x + f.velocity.x, - f.position.y + f.velocity.y, - f.position.z + f.velocity.z, + f.position.x + movement.x, + f.position.y + movement.y, + f.position.z + movement.z, ); - let below = self.world.block( - next.x.floor() as i32, - next.y.floor() as i32, - next.z.floor() as i32, - ); - let below_facts = self.res.facts.get(below); - // PowderSnowBlock.getCollisionShape for a FallingBlockEntity: the - // whole block, or 0.9 high after a fall of more than 2.5 blocks, - // where the block it rests in is the snow itself. - let powder_snow = &*below_facts.name == "minecraft:powder_snow"; - let sunk = powder_snow - && f.fall_distance > 2.5 - && next.y - next.y.floor() < f64::from(0.9_f32); - let solid = - (below_facts.full_collision || powder_snow && f.fall_distance <= 2.5 || sunk) - && f.velocity.y < 0.0; + let on_ground = wanted.y < 0.0 && movement.y != wanted.y; // FallingBlockEntity.tick: off the ground, it gives up after 600 // ticks (100 outside the world) and drops itself as an item. let y = next.y.floor() as i32; let outside = y <= horizon_client::chunk::MIN_Y || y >= horizon_client::chunk::MIN_Y + 384; - if !solid && (f.age > 100 && outside || f.age > 600) { + if !on_ground && (f.age > 100 && outside || f.age > 600) { if f.drop_item && entity_drops { dropped.push((f.state, next)); } return false; } - if solid { - let pos = [ - next.x.floor() as i32, - next.y.floor() as i32 + i32::from(!sunk), - next.z.floor() as i32, - ]; - let landing_y = if sunk { - next.y.floor() + f64::from(0.9_f32) - } else { - f64::from(pos[1]) - }; - f.fall_distance += (f.position.y - landing_y).max(0.0); - f.position = Vec3::new(next.x, landing_y, next.z); - landed.push((f.clone(), pos)); - return false; - } if next.y < f.position.y { f.fall_distance += f.position.y - next.y; } f.position = next; + if on_ground { + let pos = [ + f.position.x.floor() as i32, + f.position.y.floor() as i32, + f.position.z.floor() as i32, + ]; + landed.push((f.clone(), pos)); + return false; + } + if movement.x != wanted.x { + f.velocity.x = 0.0; + } + if movement.y != wanted.y { + f.velocity.y = 0.0; + } + if movement.z != wanted.z { + f.velocity.z = 0.0; + } f.velocity = Vec3::new( f.velocity.x * 0.98, f.velocity.y * 0.98, @@ -2350,7 +2683,7 @@ impl Game<'_> { self.falling = falling; for (state, at) in dropped { // Entity.spawnAtLocation: an item entity where the block was. - let item = self.res.facts.get(state).item.clone(); + let item = self.res.facts().get(state).item.clone(); if &*item != "minecraft:air" { let r = &mut self.world.random; let v = [ @@ -2370,7 +2703,80 @@ impl Game<'_> { for (block, pos) in landed { self.finish_falling_block(block, pos); } - self.process_level_events() + self.process_level_events()?; + if let Some(error) = collision_error { + return Err(error); + } + Ok(()) + } + /// `DecoratedPotBlock.playerWillDestroy`: a pot mined with an item in + /// `breaks_decorated_pots`, unless an enchantment prevents shattering, is + /// cracked first (flags 260), so it shatters into its sherds. + fn crack_mined_pot(&mut self, pos: [i32; 3], state: BlockStateId) -> BlockStateId { + let registry = &self.pack.assets.registry; + let Some(mut pot) = registry + .state(state) + .filter(|s| s.name == "minecraft:decorated_pot") + .cloned() + else { + return state; + }; + let Some(held) = self.held() else { + return state; + }; + let breaks = self + .res + .items() + .item_tags + .get("minecraft:breaks_decorated_pots") + .is_some_and(|t| t.contains(&*held.item)); + let enchantments = &self.res.stations().enchantments; + let kept = held + .enchantments() + .iter() + .any(|(e, _)| enchantments.in_tag("minecraft:prevents_decorated_pot_shattering", e)); + if !breaks || kept { + return state; + } + pot.properties.insert("cracked".into(), "true".into()); + let Ok(cracked) = registry.resolve(&pot) else { + return state; + }; + let at = BlockPos::new(pos[0], pos[1], pos[2]); + self.with_level(|b, level, ticks| b.set_block(level, ticks, at, cracked, 260)); + cracked + } + /// `ItemStack.mineBlock` for the held stack once a survival player has + /// mined the block `name`: an item with a `tool` component counts as used + /// and loses its `damage_per_block` on a block that doesn't break + /// instantly (`ShearsItem`: on any block but fire). + fn mine_block_with_held(&mut self, name: &str, hardness: f32) { + let Some(stack) = self.inventory[self.selected].clone() else { + return; + }; + let Some((per_block, max)) = self + .res + .items() + .get(&stack.item) + .and_then(|i| Some((i.tool_damage_per_block?, i.max_damage))) + else { + return; + }; + let wears = if &*stack.item == "minecraft:shears" { + !self.res.items().block_in_tag("minecraft:fire", name) + } else { + hardness != 0.0 + }; + if wears && per_block > 0 && max > 0 { + let loss = self.durability_loss(&stack, per_block); + if let Some(held) = self.inventory[self.selected].as_mut() { + held.damage += loss; + if held.damage >= max { + self.inventory[self.selected] = None; + } + } + } + self.stats.add("used", &stack.item, 1); } fn break_block(&mut self, pos: [i32; 3]) -> Result<()> { self.with_player_actor(|game| game.break_block_as_player(pos)) @@ -2379,7 +2785,8 @@ impl Game<'_> { self.pad_rumble(horizon_client::gamepad::Rumble::BlockBroken); // ServerPlayerGameMode.destroyBlock. let state = self.world.block(pos[0], pos[1], pos[2]); - let facts = self.res.facts.get(state).clone(); + let facts = self.res.facts().get(state).clone(); + let state = self.crack_mined_pot(pos, state); // Block.playerWillDestroy: mining their gold angers all nearby piglins. if self.guarded_by_piglins(&facts.name) { self.anger_piglins(false); @@ -2411,26 +2818,12 @@ impl Game<'_> { }); if removed && !creative { let held = self.held().cloned(); - // ItemStack.mineBlock: tools lose durability on blocks with nonzero hardness. - if facts.hardness > 0.0 - && let Some(stack) = self.inventory[self.selected].clone() - && let Some(max) = self - .res - .items - .get(&stack.item) - .filter(|i| i.max_damage > 0 && !i.tool.is_empty()) - .map(|i| i.max_damage) - { - let loss = self.durability_loss(&stack, 1); - if let Some(stack) = self.inventory[self.selected].as_mut() { - stack.damage += loss; - if stack.damage >= max { - self.inventory[self.selected] = None; - } - } - } + self.mine_block_with_held(&facts.name, facts.hardness); let harvest = !facts.requires_tool - || self.res.items.correct_for_drops(held.as_ref(), &facts.name); + || self + .res + .items() + .correct_for_drops(held.as_ref(), &facts.name); if harvest { // Block.playerDestroy: the mined statistic, the exhaustion and the drops. self.stats.add("mined", &facts.name, 1); @@ -2601,7 +2994,7 @@ impl Game<'_> { let Some(stack) = self.held().cloned() else { return Ok(false); }; - let Some(info) = self.res.items.get(&stack.item).cloned() else { + let Some(info) = self.res.items().get(&stack.item).cloned() else { return Ok(false); }; if block_hit.is_some() && (self.use_bone_meal(&stack)? || self.ignite_tnt(&stack)?) { @@ -2712,7 +3105,7 @@ impl Game<'_> { return Ok(true); }; let target = [pos.x, pos.y, pos.z]; - if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) { + if let Some(entity) = BlockEntity::for_block(&self.res.facts().get(state).name) { let key = (target[0], target[1], target[2]); self.world.block_entities.insert(key, entity); let game_master = self.can_use_game_master_blocks(); @@ -2756,15 +3149,15 @@ impl Game<'_> { } Ok(true) } - /// `Consumable.startConsuming` for held food the player can eat - /// (`Player.canEat`): the right click is held for `consume_seconds`. + /// `Consumable.startConsuming` for a held consumable: food needs + /// `Player.canEat` (`Consumable.canConsume`), anything else is always + /// consumed. The right click is held for `consume_seconds`. fn start_eating(&mut self, info: &horizon_client::items::ItemInfo) -> bool { - if !info.consumable - || info.food.is_none() - || !self - .player - .as_ref() - .is_some_and(|p| info.can_always_eat || p.health.food.food < 20 || self.creative) + if info.consumable.is_none() + || (info.food.is_some() + && !self.player.as_ref().is_some_and(|p| { + info.can_always_eat || p.health.food.food < 20 || self.creative + })) { return false; } @@ -2773,18 +3166,17 @@ impl Game<'_> { } true } - fn apply_consume_effect( - &mut self, - effect: &horizon_client::items::ConsumeEffect, - eye: [f64; 3], - ) { + fn apply_consume_effect(&mut self, effect: &horizon_client::items::ConsumeEffect) { use horizon_client::items::ConsumeEffect; match effect { ConsumeEffect::ApplyEffects { effects, probability, } => { - if *probability >= 1.0 || self.world.random.next_float() <= *probability { + // ApplyStatusEffectsConsumeEffect.apply: the user's random + // (the level's stands in, as for every player draw) is drawn + // even at probability 1. + if self.world.random.next_float() < *probability { for eff in effects { if let Some(def) = horizon_client::brewing::effect(&eff.id) { if def.instant { @@ -2817,9 +3209,14 @@ impl Game<'_> { } self.apply_effect_status(); } - ConsumeEffect::TeleportRandomly => {} + ConsumeEffect::TeleportRandomly(teleport) => self.teleport_randomly(teleport), ConsumeEffect::PlaySound(sound) => { - self.audio.play(sound, Some(eye), 1.0, 1.0); + // PlaySoundConsumeEffect: at the user's block position. + let at = self.player.as_ref().map(|p| { + let b = horizon_core::position::BlockPos::containing(p.position); + [b.x, b.y, b.z].map(|v| f64::from(v) + 0.5) + }); + self.audio.play(sound, at, 1.0, 1.0); } } } @@ -2867,7 +3264,7 @@ impl Game<'_> { self.using = None; return; } - let Some(info) = self.res.items.get(&stack.item).cloned() else { + let Some(info) = self.res.items().get(&stack.item).cloned() else { self.using = None; return; }; @@ -2901,49 +3298,21 @@ impl Game<'_> { } return; } - let duration = 32; - // Consumable.shouldEmitParticlesAndSounds(useItemRemainingTicks), with - // the remaining ticks before this tick counts down: every 4 ticks once - // more than 21.875% of the time has passed (none on the last tick). + let Some(consumable) = info.consumable.as_ref() else { + self.using = None; + return; + }; + // ItemStack.onUseTick: Consumable.shouldEmitParticlesAndSounds with + // the remaining ticks before this tick counts them down. + let duration = consumable.ticks().max(0) as u32; let remaining = duration - ticks.min(duration); let ticks = ticks + 1; - let eye = self.eye_position().unwrap_or_default(); - if duration - remaining > (duration as f32 * 0.21875) as u32 && remaining % 4 == 0 { - let pitch = - (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 1.0; - self.audio.play( - "minecraft:entity.generic.eat", - Some(eye), - 0.5 + 0.5 * self.world.random.next_int_bound(2).unwrap_or(0) as f32, - pitch, - ); - self.eat_particles(&stack, 5); + if consumable.should_emit(remaining as i32) { + self.emit_consume(consumable, &stack, 5); } if ticks >= duration { self.using = None; - // Consumable.onConsume: emitParticlesAndSounds(..., 16). - self.eat_particles(&stack, 16); - // Consumable.onConsume. - self.post_entity_event("minecraft:eat", horizon_client::mobs::Who::Player); - if let Some((nutrition, saturation)) = info.food { - if let Some(p) = self.player.as_mut() { - // FoodData.eat(nutrition, saturation) - let food = &mut p.health.food; - food.food = (food.food + nutrition as i32).clamp(0, 20); - food.saturation = (food.saturation + saturation).clamp(0.0, food.food as f32); - } - self.audio.play( - "minecraft:entity.player.burp", - Some(eye), - 0.5, - self.world.random.next_float() * 0.1 + 0.9, - ); - for effect in &info.consume_effects { - self.apply_consume_effect(effect, eye); - } - self.trigger_item("minecraft:consume_item", &stack); - self.consume_held(); - } + self.finish_consuming(&info, consumable, &stack); } else { self.using = Some((slot, ticks)); } @@ -2984,13 +3353,13 @@ impl Game<'_> { }); } let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); - let facts = self.res.facts.get(state); + let facts = self.res.facts().get(state); if facts.hardness < 0.0 { return Ok(()); } // Player.getDestroySpeed / BlockBehaviour.getDestroyProgress. let held = self.held(); - let mut speed = self.res.items.mining_speed(held, &facts.name); + let mut speed = self.res.items().mining_speed(held, &facts.name); speed = self.modify_destroy_speed(speed); let player = self.player.as_ref().ok_or("no player")?; if !player.ground.on_ground { @@ -2999,7 +3368,7 @@ impl Game<'_> { let eye = self.eye_position().unwrap_or_default(); if self .res - .facts + .facts() .get(self.world.block( eye[0].floor() as i32, eye[1].floor() as i32, @@ -3010,7 +3379,7 @@ impl Game<'_> { { speed *= self.submerged_mining_speed(); } - let harvest = !facts.requires_tool || self.res.items.correct_for_drops(held, &facts.name); + let harvest = !facts.requires_tool || self.res.items().correct_for_drops(held, &facts.name); let progress = if facts.hardness == 0.0 { 1.0 } else { @@ -3050,11 +3419,11 @@ impl Game<'_> { if self.dim == Dim::Nether { // Below the bedrock ceiling: a solid floor with two air blocks above. for y in (32..120).rev() { - let floor = self.res.facts.get(self.world.block(x, y - 1, z)); + let floor = self.res.facts().get(self.world.block(x, y - 1, z)); if floor.full_collision && floor.fluid == Fluid::None - && self.res.facts.is_air(self.world.block(x, y, z)) - && self.res.facts.is_air(self.world.block(x, y + 1, z)) + && self.res.facts().is_air(self.world.block(x, y, z)) + && self.res.facts().is_air(self.world.block(x, y + 1, z)) { return Some(y); } @@ -3064,8 +3433,8 @@ impl Game<'_> { let mut y = MIN_Y + HEIGHT - 1; while y > MIN_Y { let s = self.world.block(x, y, z); - if !self.res.facts.is_air(s) { - let f = self.res.facts.get(s); + if !self.res.facts().is_air(s) { + let f = self.res.facts().get(s); let ok = f.full_collision && f.fluid == Fluid::None && !f.name.contains("leaves") @@ -3156,6 +3525,11 @@ impl Game<'_> { player.may_fly = self.creative || spectator; player.invulnerable = self.creative || spectator; player.spectator = spectator; + if spectator { + player.flying = true; + } else if !player.may_fly { + player.flying = false; + } player.respiration = self.armor[0] .as_ref() .map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32); @@ -3163,7 +3537,7 @@ impl Game<'_> { // LivingEntity.canGlideUsing: a glider in its slot that will not break next. player.glider = self.armor[1].as_ref().is_some_and(|s| { self.res - .items + .items() .get(&s.item) .is_some_and(|i| i.glider && (i.max_damage == 0 || s.damage + 1 < i.max_damage)) }); @@ -3287,7 +3661,7 @@ impl Game<'_> { // LivingEntity.canGlideUsing: a glider in its slot that will not break next. player.glider = self.armor[1].as_ref().is_some_and(|s| { self.res - .items + .items() .get(&s.item) .is_some_and(|i| i.glider && (i.max_damage == 0 || s.damage + 1 < i.max_damage)) }); @@ -3301,7 +3675,7 @@ impl Game<'_> { self.inventory.get(slot)?.as_ref() } }) - .and_then(|s| self.res.items.get(&s.item)) + .and_then(|s| self.res.items().get(&s.item)) .map(|i| i.use_speed); // PowderSnowBlock.canEntityWalkOnPowderSnow and LivingEntity.canFreeze. player.leather_boots = self.armor[3] @@ -3309,7 +3683,7 @@ impl Game<'_> { .is_some_and(|s| &*s.item == "minecraft:leather_boots"); let immune = self .res - .items + .items() .item_tags .get("minecraft:freeze_immune_wearables"); player.freeze_immune = self @@ -3366,7 +3740,7 @@ impl Game<'_> { MotionEvent::Emission { state, in_water, .. } if !crouching => { - let sounds = self.res.facts.get(state).sounds.clone(); + let sounds = self.res.facts().get(state).sounds.clone(); // Entity.playStepSound: the block's step sound at 0.15 volume, // muffled under the swim sound in water. let (volume, pitch) = if in_water { @@ -3541,6 +3915,10 @@ impl Game<'_> { } self.audio .play("minecraft:entity.player.death", Some(at), 1.0, 1.0); + // LivingEntity.die: the LAN guests see the host's death animation. + if let Some(host) = &self.lan { + host.hub.entity_event(host.host_entity, 3, feet); + } self.screen = Screen::Dead; self.capture(false); } @@ -3549,6 +3927,7 @@ impl Game<'_> { /// What the tick runs after the local player's own update: effects, the /// world's entities and blocks, and the network hub. fn tick_world(&mut self, running: bool) -> Result<()> { + self.update_chunk_tickets(); horizon_client::spans::time("tick_effects", || self.tick_effects()); horizon_client::spans::time("tick_using", || self.tick_using()); horizon_client::spans::time("tick_hud", || self.tick_hud()); @@ -3609,7 +3988,6 @@ impl Game<'_> { horizon_client::spans::time("tick_block_entities", || self.tick_block_entities())?; horizon_client::spans::time("tick_sculk_entities", || self.tick_sculk_entities()); horizon_client::spans::time("tick_sculk_blocks", || self.tick_sculk_blocks())?; - horizon_client::spans::time("tick_brewing_stands", || self.tick_brewing_stands())?; } if running { // ClientLevel.tickBlockEntities (not while paused or frozen): @@ -3806,7 +4184,7 @@ impl Game<'_> { let (stack, capped) = match drag.and_then(|d| d.slots.get(&slot)) { Some(None) => return, Some(Some((count, capped))) => { - batch.fill(&self.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); + batch.fill(&self.gui.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); let carried = self .carried .clone() @@ -3885,7 +4263,7 @@ impl Game<'_> { // moved to (x, y). Horizon tracks no item cooldowns to shade yet. let max_damage = self .res - .items + .items() .get(&stack.item) .map_or(0, |info| info.max_damage as i32); let decorations = hud_overlays::ItemDecorations { @@ -3901,10 +4279,10 @@ impl Game<'_> { 0, 0, &decorations, - &self.atlas.font, + &self.gui.atlas.font, )); draws.push(hud_layout::GuiDraw::Pop); - hud_layout::paint(batch, &self.atlas, &draws); + hud_layout::paint(batch, &self.gui.atlas, &draws); } fn hud(&mut self, size: [u32; 2]) -> HudBatch { let mut batch = self.hud_layers(size); @@ -3912,7 +4290,7 @@ impl Game<'_> { // and the toasts, so it is over everything, menus included. self.draw_debug_overlay(&mut batch, size); self.frame_graph - .draw(self.settings.horizon.overlay, &mut batch, &self.atlas); + .draw(self.settings.horizon.overlay, &mut batch, &self.gui.atlas); self.draw_pad_cursor(&mut batch); batch } @@ -3933,12 +4311,12 @@ impl Game<'_> { if horizon_client::ui_theme::horizon() { let fade = self.backdrop_fade(); let mut ui = - horizon_client::ui_theme::Ui::new(&self.atlas, &mut batch, self.cursor); + horizon_client::ui_theme::Ui::new(&self.gui.atlas, &mut batch, self.cursor); title.draw_horizon(&mut ui, fade); ui.finish(); } else { title.draw( - &self.atlas, + &self.gui.atlas, &mut batch, self.cursor, self.settings.file.bool("hideSplashTexts"), @@ -3946,7 +4324,7 @@ impl Game<'_> { } return batch; } - let atlas_ptr: *const HudAtlas = &self.atlas; + let atlas_ptr: *const HudAtlas = &self.gui.atlas; let _ = atlas_ptr; if self.remote_overlay(&mut batch) { return batch; @@ -3977,7 +4355,7 @@ impl Game<'_> { hud_layout::full_attack_indicator(a, delay, self.crosshair_living()) }); let draws = hud_layout::crosshair(wi, hi, attack, full); - hud_layout::paint(&mut batch, &self.atlas, &draws); + hud_layout::paint(&mut batch, &self.gui.atlas, &draws); } if !spectator { let inputs = hud_layout::HotbarInputs { @@ -3989,7 +4367,7 @@ impl Game<'_> { attack: (indicator == 2).then_some(strength), }; let draws = hud_layout::hotbar(wi, hi, &inputs); - hud_layout::paint(&mut batch, &self.atlas, &draws); + hud_layout::paint(&mut batch, &self.gui.atlas, &draws); for d in &draws { if let hud_layout::GuiDraw::Item { slot, x, y, .. } = *d { let stack = if slot == 40 { @@ -4019,7 +4397,7 @@ impl Game<'_> { && !spectator && let Some(p) = &mut self.player { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let width = |s: &str| HudBatch::text_width(atlas, s) as i32; let draws = hud_layout::experience( wi, @@ -4043,7 +4421,7 @@ impl Game<'_> { let eye = p.position.y + f64::from(p.dimensions.eye_height); let under_water = self .res - .facts + .facts() .get(self.world.block( p.position.x.floor() as i32, eye.floor() as i32, @@ -4082,13 +4460,13 @@ impl Game<'_> { } // Hud.extractSleepOverlay: over all health/food bars, under titles and chat. let draws = hud_overlays::sleep_overlay(wi, hi, self.sleep_timer as i32); - hud_layout::paint(&mut batch, &self.atlas, &draws); + hud_layout::paint(&mut batch, &self.gui.atlas, &draws); if show_hud { self.draw_titles(&mut batch); self.draw_scoreboard(&mut batch); self.draw_subtitles(&mut batch); } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; if show_hud && let Some((text, at)) = &self.message && at.elapsed() < Duration::from_secs(3) @@ -4105,9 +4483,9 @@ impl Game<'_> { // PauseScreen(false): only its title, at the top. Screen::Paused => { let title = self.translate("menu.paused", "Game Paused"); - let tw = HudBatch::text_width(&self.atlas, &title); + let tw = HudBatch::text_width(&self.gui.atlas, &title); batch.text( - &self.atlas, + &self.gui.atlas, &title, ((batch.width / 2.0).floor() - (tw / 2.0).floor()).floor(), 10.0, @@ -4306,7 +4684,7 @@ impl Game<'_> { /// `RecipeCraftingHolder.awardUsedRecipes`: a crafted recipe becomes known /// (special ones never do). fn award_crafted(&mut self, recipes: &[String]) { - let index = &self.res.stations.recipe_index; + let index = &self.res.stations().recipe_index; let (_, unlocked) = self.level.recipe_book.add_recipes(index, recipes); self.recipe_unlocked(&unlocked); } @@ -4315,7 +4693,7 @@ impl Game<'_> { let grid: Vec> = (0..n * n).map(|i| self.craft_grid[i].clone()).collect(); let scale = |id: i32| self.maps.data.get(&id).map(|m| m.scale); self.res - .recipes + .recipes() .find_with(&grid, n, &scale) .map(|(name, result)| (name.to_owned(), result)) } @@ -4325,7 +4703,7 @@ impl Game<'_> { let (sx, sy) = self.slot_position(i); if i == 504 && self.offhand.is_none() { batch.sprite( - &self.atlas, + &self.gui.atlas, "gui/sprites/container/slot/shield", ox + sx, oy + sy, @@ -4334,7 +4712,7 @@ impl Game<'_> { if (500..504).contains(&i) && self.armor[i - 500].is_none() { let icon = ["helmet", "chestplate", "leggings", "boots"][i - 500]; batch.sprite( - &self.atlas, + &self.gui.atlas, &format!("gui/sprites/container/slot/{icon}"), ox + sx, oy + sy, @@ -4350,7 +4728,7 @@ impl Game<'_> { } let (ox, oy) = self.inventory_origin(batch); { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; batch.fill( atlas, 0.0, @@ -4474,7 +4852,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); batch.fill( - &self.atlas, + &self.gui.atlas, ox + sx, oy + sy, 16.0, @@ -4515,7 +4893,7 @@ impl Game<'_> { ); let name = self .res - .facts + .facts() .get(self.world.block(key.0, key.1, key.2)) .name .clone(); @@ -4588,7 +4966,7 @@ impl Game<'_> { let items = self.creative_screen.items(&self.pack.names); let first = self.creative_screen.first_row(&self.pack.names); let shown = items.get(first * 9 + slot - Creative::DISPLAY); - let catalog = &self.res.items; + let catalog = self.res.items(); let max = |s: &ItemStack| catalog.get(&s.item).map_or(64, |i| i.max_stack); match click_display(&mut self.carried, shown, max, button, input) { DisplayClick::Hotbar(i, stack) => self.inventory[i] = Some(stack), @@ -4599,6 +4977,10 @@ impl Game<'_> { /// Several clicks on one menu instance (a quick craft drag is three). fn menu_ops(&mut self, ops: &[(Option, i32, horizon_client::menu::Input)]) -> bool { use horizon_client::menu::Input; + if self.remote.is_some() && self.screen == Screen::Inventory { + // On a server the clicks are the server's: predicted and sent. + return self.remote_menu_ops(ops); + } if let [(Some(slot), button, input)] = ops { self.crafter_slot_clicked(*slot, *button, *input); } @@ -4744,7 +5126,7 @@ impl Game<'_> { Some(BlockEntity::Chest(_)) => { let shulker = self.container.is_some_and(|k| { let id = self.world.block(k.0, k.1, k.2); - storage::is_shulker_box(&self.res.facts.get(id).name) + storage::is_shulker_box(&self.res.facts().get(id).name) }); let kind = match size { 5 => Kind::Hopper, @@ -4754,6 +5136,9 @@ impl Game<'_> { }; (kind, size) } + // A server's BrewingStandMenu; a local stand's clicks are the + // station screen's. + Some(BlockEntity::Brewing(_)) if self.remote.is_some() => (Kind::Brewing, 5), Some(BlockEntity::Furnace(f)) => ( Kind::Furnace( match f.kind.recipe_type().trim_start_matches("minecraft:") { @@ -4773,7 +5158,7 @@ impl Game<'_> { plain: false, }; (kind, map) - } else if self.station.is_none() && !self.mount_active() && self.remote.is_none() { + } else if self.station.is_none() && !self.mount_active() { let table = self.craft_size == 3; let map = Map { container: 0, @@ -4837,15 +5222,15 @@ impl Game<'_> { next_id: std::cell::Cell::new(next_map), }; let trade_env = horizon_client::merchant::TradeEnv { - trades: &self.res.stations.trades, - enchantments: &self.res.stations.enchantments, + trades: &self.res.stations().trades, + enchantments: &self.res.stations().enchantments, maps: Some(&maps), }; let env = Env { - items: &self.res.items, - recipes: &self.res.recipes, - brewing: &self.res.stations.brewing, - banners: &self.res.stations.banners, + items: self.res.items(), + recipes: self.res.recipes(), + brewing: &self.res.stations().brewing, + banners: &self.res.stations().banners, trade: Some(&trade_env), }; menu.creative = creative; @@ -4886,7 +5271,12 @@ impl Game<'_> { Some(false) => return true, Some(true) => {} } - self.register_exploration_maps(made); + // On a server the clicks only predict: the server drops, crafts and + // makes maps itself. + let predicting = self.remote.is_some(); + if !predicting { + self.register_exploration_maps(made); + } if let Some(s) = menu.merchant.take() { self.merchant_sync_out(s); } @@ -4904,10 +5294,12 @@ impl Game<'_> { if !offhand_mapped { self.offhand = menu.player_item(40).cloned(); } - for stack in dropped { - self.player_drop(stack); + if !predicting { + for stack in dropped { + self.player_drop(stack); + } + self.award_crafted(&crafted); } - self.award_crafted(&crafted); if kind == Kind::Loom { if let Some(s) = self.station.as_mut() { s.loom.selected = usize::try_from(menu.data[0]).ok(); @@ -4933,7 +5325,7 @@ impl Game<'_> { .and_then(|k| self.world.block_entities.get_mut(&k)) { // AbstractFurnaceBlockEntity.setItem: only a new input restarts cooking. - f.input_clicked(&self.res.recipes, before[0].clone()); + f.input_clicked(self.res.recipes(), before[0].clone()); } self.apply_equipment(); true @@ -5039,9 +5431,13 @@ impl Game<'_> { return; } if let Some(moved) = self.last_quick_moved.clone() { - self.menu_session(|menu, env, to_menu| { - Some(menu.quick_move_all(env, to_menu(slot)?, &moved).is_ok()) - }); + if self.remote.is_some() { + self.remote_quick_move_all(slot, &moved); + } else { + self.menu_session(|menu, env, to_menu| { + Some(menu.quick_move_all(env, to_menu(slot)?, &moved).is_ok()) + }); + } } self.last_inv_click = None; self.inv_clicks.skip_release(); @@ -5332,7 +5728,7 @@ impl Game<'_> { None => self.carried = Some(result), Some(c) if c.item == result.item - && c.count + result.count <= max(&self.res.items, c) => + && c.count + result.count <= max(self.res.items(), c) => { c.count += result.count } @@ -5348,7 +5744,7 @@ impl Game<'_> { while let Some((recipe, result)) = self.craft_recipe() { let made = (result.item.clone(), result.count); let cells = self.craft_size * self.craft_size; - let remainders = self.res.recipes.remainders( + let remainders = self.res.recipes().remainders( &recipe, &self.craft_grid[..cells], self.craft_size, @@ -5362,7 +5758,7 @@ impl Game<'_> { None => self.carried = Some(result), Some(c) if c.item == result.item - && c.count + result.count <= max(&self.res.items, c) => + && c.count + result.count <= max(self.res.items(), c) => { c.count += result.count } @@ -5404,7 +5800,7 @@ impl Game<'_> { let wanted = ["head", "chest", "legs", "feet"][slot - 500]; let fits = self.carried.as_ref().is_none_or(|c| { self.res - .items + .items() .get(&c.item) .and_then(|i| i.equip_slot.as_deref()) == Some(wanted) @@ -5418,7 +5814,7 @@ impl Game<'_> { } let carried = self.carried.take(); let current = self.slot_mut(slot).take(); - let items = &self.res.items; + let items = self.res.items(); let (new_slot, new_carried) = match (carried, current) { (None, Some(mut s)) if right => { let half = s.count.div_ceil(2); @@ -5459,7 +5855,7 @@ impl Game<'_> { .container .and_then(|k| self.world.block_entities.get_mut(&k)) { - f.input_clicked(&self.res.recipes, before); + f.input_clicked(self.res.recipes(), before); } } /// `Camera.setRotation`: the camera's orientation, turned round in @@ -5500,7 +5896,7 @@ impl Game<'_> { m.height(), camera, fire_yaw, - &self.atlas.sprites, + &self.gui.atlas.sprites, self.world.light( at.x.floor() as i32, at.y.floor() as i32, @@ -5522,7 +5918,7 @@ impl Game<'_> { p.dimensions.height, camera, fire_yaw, - &self.atlas.sprites, + &self.gui.atlas.sprites, self.world.light( feet.x.floor() as i32, feet.y.floor() as i32, @@ -5535,7 +5931,7 @@ impl Game<'_> { if item.fire_ticks > 0 && !self .res - .items + .items() .resists_fire(&item.stack, "minecraft:in_fire") { let at = item.previous.lerp(item.position, alpha); @@ -5545,7 +5941,7 @@ impl Game<'_> { 0.25, camera, fire_yaw, - &self.atlas.sprites, + &self.gui.atlas.sprites, self.world.light( at.x.floor() as i32, at.y.floor() as i32, @@ -5564,7 +5960,7 @@ impl Game<'_> { 1.975 * scale, camera, fire_yaw, - &self.atlas.sprites, + &self.gui.atlas.sprites, self.world.light( stand.position.x.floor() as i32, stand.position.y.floor() as i32, @@ -5589,7 +5985,7 @@ impl Game<'_> { self.name_tag_geometry(camera, alpha, &mut out, &mut see_through); self.see_through_vertices = see_through; // Entity shadows (EntityRenderer.extractShadow). - if let Some(sprite) = self.atlas.sprites.get("misc/shadow").copied() { + if let Some(sprite) = self.gui.atlas.sprites.get("misc/shadow").copied() { let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 }; let darken = self.sky_darken(); let a = alpha; @@ -5619,7 +6015,7 @@ impl Game<'_> { let (radius, strength) = horizon_client::shadows::shadow_params(id); horizon_client::shadows::shadow( &self.world, - &self.res.facts, + self.res.facts(), sprite, camera, pos, @@ -5644,7 +6040,7 @@ impl Game<'_> { game_time: self.world.game_time, max_y: self.dim.max_y(), world: &self.world, - sprites: &self.atlas.sprites, + sprites: &self.gui.atlas.sprites, nether: self.dim == Dim::Nether, lid: &lid, sign: &|p| match self.world.block_entities.get(&(p[0], p[1], p[2])) { @@ -5652,7 +6048,7 @@ impl Game<'_> { _ => None, }, banner: &|p| self.banner_layers_at(p), - glyph: &|c| self.atlas.glyph_cell(c), + glyph: &|c| self.gui.atlas.glyph_cell(c), }; // Block entities outside the view frustum are skipped (with a // block of margin for models larger than their block). @@ -5660,7 +6056,7 @@ impl Game<'_> { // Beams and structure outlines reach far outside their block // (BlockEntityRenderer.shouldRenderOffScreen): never culled. let off_screen = |state: u32| { - let name = &*self.res.facts.get(BlockStateId(state)).name; + let name = &*self.res.facts().get(BlockStateId(state)).name; matches!( name, "minecraft:beacon" @@ -5670,7 +6066,7 @@ impl Game<'_> { ) }; let visible = r.block_entities().filter(|(p, state)| { - if !self.res.block_entity_render.renders(*state) { + if !self.res.block_entity_render().renders(*state) { return false; } off_screen(*state) @@ -5686,7 +6082,7 @@ impl Game<'_> { for block in visible { let start = out.len(); self.res - .block_entity_render + .block_entity_render() .render(&scene, std::iter::once(block), &mut out); if !off_screen(block.1) { self.cull_entity_vertices(&mut out, start); @@ -5694,12 +6090,12 @@ impl Game<'_> { } } else { self.res - .block_entity_render + .block_entity_render() .render(&scene, visible, &mut out); } if let Some(mining) = &self.mining && mining.progress > 0.0 - && self.atlas.sprites.contains_key(&format!( + && self.gui.atlas.sprites.contains_key(&format!( "block/destroy_stage_{}", ((mining.progress * 10.0) as u32).min(9) )) @@ -5708,12 +6104,13 @@ impl Game<'_> { .world .block(mining.pos[0], mining.pos[1], mining.pos[2]); self.res - .block_entity_render + .block_entity_render() .render_breaking(&scene, mining.pos, state.0, &mut out); } } // Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet. if let Some(r) = self + .gui .atlas .sprites .get("entity/experience/experience_orb") @@ -5826,7 +6223,7 @@ impl Game<'_> { &|b| world.light(b[0], b[1], b[2]), &mut out, ); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; // Breaking progress overlay (destroy_stage_0..9). if let Some(m) = &self.mining && m.progress > 0.0 @@ -5843,11 +6240,11 @@ impl Game<'_> { ) - camera) .as_vec3(); let state = self.world.block(m.pos[0], m.pos[1], m.pos[2]); - if self.res.facts.get(state).render_shape + if self.res.facts().get(state).render_shape == horizon_client::blocks::RenderShape::Model && let Ok(models) = self .pack - .assets + .render .model_catalog .collect(state, BlockPos::new(m.pos[0], m.pos[1], m.pos[2])) { @@ -5877,7 +6274,7 @@ impl Game<'_> { if self.dim == Dim::End { let sky = self .res - .end_environment + .end_environment() .sample(self.world.day_time, None, None); return (15.0 - 15.0 * sky.sky_light_level).round() as i32; } @@ -5889,7 +6286,10 @@ impl Game<'_> { { return darken; } - let mut sky = self.res.environment.sample(self.world.day_time, None, None); + let mut sky = self + .res + .environment() + .sample(self.world.day_time, None, None); horizon_client::environment::apply_weather(&mut sky, rain, thunder); // Level.updateSkyBrightness: darkening from the sky light level. let darken = (15.0 - 15.0 * sky.sky_light_level).round() as i32; @@ -5921,7 +6321,7 @@ impl Game<'_> { let hand_damage = 1.0 + self .held() - .and_then(|h| self.res.items.get(&h.item)) + .and_then(|h| self.res.items().get(&h.item)) .map_or(0.0, |i| i.attack_damage); let damage = hand_damage + self.effect_attack_bonus(); let scale = self.attack_strength_scale(); @@ -5944,7 +6344,7 @@ impl Game<'_> { fn attack_strength_scale(&self) -> f32 { let speed = self .held() - .and_then(|h| self.res.items.get(&h.item)) + .and_then(|h| self.res.items().get(&h.item)) .map_or(0.0, |i| i.attack_speed); let delay = 20.0 / (4.0 + speed).max(0.1); ((self.attack_ticks as f32 + 0.5) / delay).clamp(0.0, 1.0) @@ -5954,7 +6354,7 @@ impl Game<'_> { let p = self.player.as_ref()?; let sword = self.held().is_some_and(|s| { self.res - .items + .items() .item_tags .get("minecraft:swords") .is_some_and(|tag| tag.contains(&*s.item)) @@ -6026,7 +6426,7 @@ impl Game<'_> { let hand_damage = 1.0 + self .held() - .and_then(|h| self.res.items.get(&h.item)) + .and_then(|h| self.res.items().get(&h.item)) .map_or(0.0, |i| i.attack_damage); if self.attack_frame() || self.attack_armor_stand() @@ -6145,38 +6545,6 @@ impl Game<'_> { false, ) } - fn tick_block_entities(&mut self) -> Result<()> { - self.tick_hoppers()?; - self.tick_crafters(); - self.tick_mount_menu(); - self.tick_jukeboxes(); - self.tick_beacons(); - self.tick_creaking_hearts()?; - self.tick_spawners()?; - self.tick_trial_spawners()?; - self.tick_vaults()?; - self.tick_beehives(); - let mut lit_changes = Vec::new(); - for (pos, entity) in self.world.block_entities.iter_mut() { - if let BlockEntity::Furnace(f) = entity - && let Some(lit) = f.tick(&self.res.recipes, &self.res.items, &self.res.providers) - { - lit_changes.push((*pos, lit)); - } - } - for ((x, y, z), lit) in lit_changes { - let state = self.world.block(x, y, z); - if let Some(mut s) = self.pack.assets.registry.state(state).cloned() - && s.properties.contains_key("lit") - { - s.properties.insert("lit".into(), lit.to_string()); - if let Ok(id) = self.pack.assets.registry.resolve(&s) { - self.world.set(x, y, z, id)?; - } - } - } - Ok(()) - } /// Copies of a save batch carrying its live block entities and save data. fn with_entities<'a>( &self, @@ -6211,7 +6579,7 @@ impl Game<'_> { /// SkyRenderer.renderSunMoonAndStars: bodies on a frame rotated Y -90 then X by angle. fn celestial_geometry(&self, sky: &horizon_client::environment::Sky) -> Vec { let mut out = Vec::new(); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let frame = |angle: f32| { glam::Mat4::from_rotation_y((-90.0f32).to_radians()) * glam::Mat4::from_rotation_x(angle.to_radians()) @@ -6308,6 +6676,16 @@ impl Game<'_> { creative: bool, create: Option<&horizon_client::title::WorldOptions>, ) -> Result<()> { + if self.defer_world_entry(PendingWorldEntry::Local { + folder: folder.to_owned(), + name: name.map(str::to_owned), + seed, + creative, + create: create.cloned().map(Box::new), + })? { + return Ok(()); + } + self.join_world_rest()?; let save_root = std::env::current_dir()?.join("saves").join(folder); if integrated::wanted(&self.options, &save_root) { return self.open_integrated(folder, name, seed, creative, create); @@ -6369,7 +6747,7 @@ impl Game<'_> { let dim = Dim::from_id(&level.dimension); let (mut streaming, save) = self.make_streaming(&save_root, dim, level.seed)?; streaming.radius = self.settings.render_distance; - let mut world = World::new(self.res.facts.air, level.seed); + let mut world = World::new(self.res.facts().air, level.seed); world.fast_lava = dim == Dim::Nether; world.game_time = level.time; world.day_time = self.options.time.unwrap_or(level.day_time); @@ -6447,7 +6825,7 @@ impl Game<'_> { self.save = save; self.level = level; // ServerRecipeBook.loadUntrusted: recipes the manager does not have are dropped. - let index = &self.res.stations.recipe_index; + let index = &self.res.stations().recipe_index; let book = &mut self.level.recipe_book; book.recipes.retain(|r| index.contains(r)); book.to_be_displayed.retain(|r| index.contains(r)); @@ -6527,7 +6905,7 @@ impl Game<'_> { horizon_client::flatgen::FlatTerrain::from_settings( &s, pack.assets.registry, - &res.biomes, + res.biomes(), ) }); let mut streaming = if let Some(inner) = flat { @@ -6536,25 +6914,28 @@ impl Game<'_> { inner: Arc::new(inner), save: save.clone(), registry: pack.assets.clone(), - biomes: res.biomes.clone(), + biomes: res.biomes().clone(), }), pack.context.clone(), - res.threads, + res.threads(), ) } else if self.options.test_terrain && dim == Dim::Overworld { - let inner = Arc::new(TestTerrain::new(pack.assets.registry, &res.biomes)?); + let inner = Arc::new(TestTerrain::new(pack.assets.registry, res.biomes())?); Streaming::new( Arc::new(Persistent { inner, save: save.clone(), registry: pack.assets.clone(), - biomes: res.biomes.clone(), + biomes: res.biomes().clone(), }), pack.context.clone(), - res.threads, + res.threads(), ) } else { - let inner = Arc::new(VanillaTerrain::for_dimension(&self.options.resources.join("worldgen"), pack.assets.registry, &res.biomes, seed, dim.id()).map_err(|e| { + // WorldOptions.generateStructures, from the world's settings. + let structures = + horizon_client::save::WorldGen::read(world_root).is_none_or(|w| w.structures); + let inner = Arc::new(VanillaTerrain::for_world(&self.options.resources.join("worldgen"), pack.assets.registry, res.biomes(), seed, dim.id(), structures).map_err(|e| { format!("{e}\nPrepare the worldgen bundle with the launcher, or: horizon-prepare --prepare") })?); self.end.set_locator(Some(inner.clone())); @@ -6563,10 +6944,10 @@ impl Game<'_> { inner, save: save.clone(), registry: pack.assets.clone(), - biomes: res.biomes.clone(), + biomes: res.biomes().clone(), }), pack.context.clone(), - res.threads, + res.threads(), ) }; streaming.radius = self.settings.render_distance; @@ -6577,8 +6958,9 @@ impl Game<'_> { streaming.biome_zoom = BiomeZoom::new(obfuscate_seed(seed)); streaming.sky_light = dim != Dim::Nether; streaming.nether_shading = dim == Dim::Nether; - // The integrated server draws nothing (the dedicated server keeps its behaviour). - streaming.mesh = !self.options.integrated; + // A server draws nothing: neither the integrated server nor the + // dedicated one meshes sections. + streaming.mesh = !self.options.integrated && self.options.dedicated.is_none(); Ok((streaming, save)) } /// Change dimension through a portal (Entity.changeDimension with @@ -6603,7 +6985,7 @@ impl Game<'_> { let keys: Vec<_> = self.world.modified.drain().collect(); let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k))); self.save - .save(&chunks, self.pack.assets.registry, &self.res.biomes)?; + .save(&chunks, self.pack.assets.registry, self.res.biomes())?; self.save_dimension_entities()?; // Coordinates scale by 8 between the Overworld and the Nether. let scale = match (self.dim, target) { @@ -6619,13 +7001,14 @@ impl Game<'_> { )); let (streaming, save) = self.make_streaming(&self.world_root.clone(), target, self.level.seed)?; - let mut world = World::new(self.res.facts.air, self.level.seed); + let mut world = World::new(self.res.facts().air, self.level.seed); world.fast_lava = target == Dim::Nether; world.game_time = self.world.game_time; world.day_time = self.world.day_time; world.weather = self.world.weather; // An open hub keeps hearing the new level's block changes. world.block_log = self.world.block_log.as_ref().map(|_| Vec::new()); + world.light_log = self.world.light_log.as_ref().map(|_| Default::default()); // The sculk tables' watched blocks are built once per game. world.watched = std::mem::take(&mut self.world.watched); self.streaming = streaming; @@ -6654,7 +7037,7 @@ impl Game<'_> { fn portal_shape(&self, start: [i32; 3], x_axis: bool) -> Option<([i32; 3], i32, i32)> { let name = |p: [i32; 3]| { self.res - .facts + .facts() .get(self.world.block(p[0], p[1], p[2])) .name .clone() @@ -6816,7 +7199,7 @@ impl Game<'_> { horizon_client::crash::clear_detail("World"); self.debug_charts.reset(); self.streaming.paused = true; - self.world = World::new(self.res.facts.air, 0); + self.world = World::new(self.res.facts().air, 0); self.player = None; self.sleeping = None; self.sleep_timer = 0; @@ -6879,7 +7262,7 @@ impl Game<'_> { .collect(); equipped.push((self.inventory[self.selected].as_ref(), "mainhand")); for (stack, slot) in equipped { - let Some(info) = stack.and_then(|s| self.res.items.get(&s.item)) else { + let Some(info) = stack.and_then(|s| self.res.items().get(&s.item)) else { continue; }; for (attribute, id, amount, op, group) in &info.modifiers { @@ -6914,7 +7297,7 @@ impl Game<'_> { .collect(); for (slot, amount) in self.armor.iter_mut().zip(losses) { if let Some(stack) = slot.as_mut() - && let Some(info) = self.res.items.get(&stack.item) + && let Some(info) = self.res.items().get(&stack.item) && info.max_damage > 0 { stack.damage += amount; @@ -6951,7 +7334,7 @@ impl Game<'_> { let b = p.map(|v| v.floor() as i32); if b != last { let state = self.world.block(b[0], b[1], b[2]); - let f = self.res.facts.get(state); + let f = self.res.facts().get(state); let face = [last[0] - b[0], last[1] - b[1], last[2] - b[2]]; if f.fluid != Fluid::None && f.fluid_level == 8 @@ -6965,7 +7348,7 @@ impl Game<'_> { point: p, }); } - if !self.res.facts.is_air(state) && f.fluid == Fluid::None { + if !self.res.facts().is_air(state) && f.fluid == Fluid::None { return Some(Hit { pos: b, face, @@ -7022,7 +7405,7 @@ impl Game<'_> { let Some(held) = self.held() else { return Ok(false); }; - let removes_dye = cauldron::removes_dye(&self.res.items, &held.item); + let removes_dye = cauldron::removes_dye(self.res.items(), &held.item); let above = self.world.block(pos[0], pos[1] + 1, pos[2]); let under_water = registry .state(above) @@ -7078,7 +7461,7 @@ impl Game<'_> { } let Some(id) = self .res - .items + .items() .get(&stack.item) .and_then(|i| i.block_transformer.clone()) else { @@ -7089,7 +7472,7 @@ impl Game<'_> { let shield = self .offhand .as_ref() - .and_then(|s| self.res.items.get(&s.item)) + .and_then(|s| self.res.items().get(&s.item)) .is_some_and(|i| i.blocks_attacks.is_some()); if shield && !self.keys.contains(&KeyCode::ShiftLeft) { return Ok(false); @@ -7111,8 +7494,8 @@ impl Game<'_> { }; let Some((_, t, state)) = self.res - .transformers - .apply(&self.res.items, registry, &id, face_name, &around) + .transformers() + .apply(self.res.items(), registry, &id, face_name, &around) else { return Ok(false); }; @@ -7183,7 +7566,7 @@ impl Game<'_> { }; let max = self .held() - .and_then(|s| self.res.items.get(&s.item)) + .and_then(|s| self.res.items().get(&s.item)) .map_or(0, |i| i.max_damage); let cell = self.held_mut(); if let Some(stack) = cell.as_mut() @@ -7248,7 +7631,7 @@ impl Game<'_> { return Ok(UseResult::Pass); }; let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); - let f = self.res.facts.get(state).clone(); + let f = self.res.facts().get(state).clone(); if f.fluid == Fluid::None || f.fluid_level != 8 || f.fluid_falling { return Ok(UseResult::Pass); } @@ -7296,7 +7679,7 @@ impl Game<'_> { if !self.may_build() { return Ok(UseResult::Fail); } - let target = if self.res.facts.get(clicked).replaceable { + let target = if self.res.facts().get(clicked).replaceable { hit.pos } else { [ @@ -7338,7 +7721,7 @@ impl Game<'_> { if item == "honeycomb" { let registry = self.pack.assets.registry; let old = registry.state(clicked).cloned(); - if let Some(waxed) = old.and_then(|old| self.res.transformers.waxed(registry, &old)) + if let Some(waxed) = old.and_then(|old| self.res.transformers().waxed(registry, &old)) && let Ok(state) = registry.resolve(&waxed) { self.level_set(hit.pos, state)?; @@ -7359,7 +7742,7 @@ impl Game<'_> { if !self.may_build() { return Ok(UseResult::Fail); } - let name = self.res.facts.get(clicked).name.clone(); + let name = self.res.facts().get(clicked).name.clone(); if self.can_light(clicked, &name) { let registry = self.pack.assets.registry; let mut state = registry @@ -7431,7 +7814,9 @@ impl Game<'_> { let mut r = dispenser::entity_random(); let _yaw = r.next_float(); let p = Vec3::new(at[0], at[1], at[2]); + self.next_entity += 1; self.orbs.push(ExperienceOrb { + id: self.next_entity, position: p, previous: p, velocity: Vec3::new( @@ -7495,13 +7880,29 @@ impl Game<'_> { .player .as_ref() .filter(|p| !p.health.dead_or_dying() && !spectator); - let target = player.map(|p| { - [ - p.position.x, - p.position.y + f64::from(p.dimensions.eye_height) / 2.0, - p.position.z, - ] - }); + // ExperienceOrb.followNearbyPlayer: each orb goes for the nearest + // living player within 8 blocks, the host's own or a guest. + let mut followed: Vec<([f64; 3], [f64; 3])> = player + .map(|p| { + let feet = [p.position.x, p.position.y, p.position.z]; + let eye = f64::from(p.dimensions.eye_height); + (feet, [feet[0], feet[1] + eye / 2.0, feet[2]]) + }) + .into_iter() + .collect(); + if let Some(host) = self.lan.as_ref() { + followed.extend( + host.hub + .guests + .iter() + .filter(|g| g.placed && g.loaded && !g.dead && g.health > 0.0) + .filter(|g| !g.spectator()) + .map(|g| { + let p = g.position; + (p, [p[0], p[1] + g.eye_height() / 2.0, p[2]]) + }), + ); + } let bounds = player.map(|p| { let w = f64::from(p.dimensions.width) / 2.0; ( @@ -7514,7 +7915,19 @@ impl Game<'_> { ) }); let mut orbs = std::mem::take(&mut self.orbs); - orbs.retain_mut(|o| o.tick(&self.world, &self.res.facts, self.collision, target)); + orbs.retain_mut(|o| { + let distance = |feet: &[f64; 3]| -> f64 { + (feet[0] - o.position.x).powi(2) + + (feet[1] - o.position.y).powi(2) + + (feet[2] - o.position.z).powi(2) + }; + let target = followed + .iter() + .filter(|(feet, _)| distance(feet) < 64.0) + .min_by(|a, b| distance(&a.0).total_cmp(&distance(&b.0))) + .map(|(_, target)| *target); + o.tick(&self.world, self.res.facts(), self.collision, target) + }); let mut gained = 0; let mut taken = Vec::new(); if let Some((min, max)) = bounds { @@ -7548,19 +7961,25 @@ impl Game<'_> { (self.world.random.next_float() - self.world.random.next_float()) * 0.35 + 0.9; self.audio .play("minecraft:entity.experience_orb.pickup", at, 0.1, pitch); - if self.experience.give(gained as i32) - && self.experience.level % 5 == 0 - && self.ticks > self.last_level_up + 100 - { - self.last_level_up = self.ticks; - let volume = if self.experience.level > 30 { - 1.0 - } else { - self.experience.level as f32 / 30.0 - }; - self.audio - .play("minecraft:entity.player.levelup", at, volume * 0.75, 1.0); - } + self.give_orb_points(gained); + } + } + /// `Player.giveExperiencePoints`, and `giveExperienceLevels`' level-up + /// sound every fifth level (at most every 100 ticks). + pub(super) fn give_orb_points(&mut self, gained: u32) { + let at = self.eye_position(); + if self.experience.give(gained as i32) + && self.experience.level % 5 == 0 + && self.ticks > self.last_level_up + 100 + { + self.last_level_up = self.ticks; + let volume = if self.experience.level > 30 { + 1.0 + } else { + self.experience.level as f32 / 30.0 + }; + self.audio + .play("minecraft:entity.player.levelup", at, volume * 0.75, 1.0); } } /// BowItem.releaseUsing: power from charge time, arrows at power * 3. @@ -7708,10 +8127,16 @@ impl Game<'_> { if hand == Hand::Off { continue; } - let Some(arm) = self.res.player_arm.clone() else { + let Some(arm) = self.res.player_arm().clone() else { continue; }; - let Some(r) = self.atlas.sprites.get("entity/player/wide/steve").copied() else { + let Some(r) = self + .gui + .atlas + .sprites + .get("entity/player/wide/steve") + .copied() + else { continue; }; // renderPlayerArm (right arm) @@ -7835,22 +8260,22 @@ impl Game<'_> { } out } - /// The renderer for the window, with the current block sprites, shared + /// The renderer for the window, with the current block sprites, GUI /// atlas and world border texture. fn new_renderer(&self, window: Arc) -> Result { - self.renderer_for(window, &self.pack, &self.atlas) + self.renderer_for(window, &self.pack, &self.gui) } fn renderer_for( &self, window: Arc, pack: &PackResources, - atlas: &HudAtlas, + gui: &UiResources, ) -> Result { build_renderer( window, self.options.offscreen, pack, - atlas, + gui, self.renderer.as_ref(), ) } @@ -7900,7 +8325,7 @@ impl Game<'_> { /// base temperature lowered above y 80) or none (no precipitation). fn precipitation(&self, x: i32, y: i32, z: i32) -> Option { let chunk = self.world.chunks.get(&(x >> 4, z >> 4))?; - let b = self.res.biomes.get(chunk.biome(x, y, z)); + let b = self.res.biomes().get(chunk.biome(x, y, z)); if !b.precipitation { return None; } @@ -7916,7 +8341,7 @@ impl Game<'_> { let mut y = from; while y > MIN_Y { let s = self.world.block(x, y, z); - let f = self.res.facts.get(s); + let f = self.res.facts().get(s); if f.full_collision || f.fluid != Fluid::None || f.name.contains("leaves") { return y + 1; } @@ -7967,7 +8392,7 @@ impl Game<'_> { if intensity <= 0.0 { return; } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (Some(rain_tex), Some(snow_tex)) = ( atlas.sprites.get("environment/rain").copied(), atlas.sprites.get("environment/snow").copied(), @@ -8122,40 +8547,48 @@ impl Game<'_> { self.stats.reset("custom", "minecraft:time_since_rest"); } fn wake_up(&mut self) { + if self.remote.is_some() { + // InBedChatScreen.sendWakeUp: the server wakes the player. + self.remote_stop_sleeping(); + return; + } self.sleeping = None; self.sleep_timer = 100; } fn tick_sleep(&mut self) { self.sleep_timer = tick_sleep_timer(self.sleep_timer, self.sleeping.is_some()); - let Some(head) = self.sleeping else { - return; - }; - if self.keys.contains(&KeyCode::ShiftLeft) - || self - .player - .as_ref() - .is_none_or(|p| p.health.dead_or_dying()) - { - self.wake_up(); - return; + if let Some(head) = self.sleeping { + if self.keys.contains(&KeyCode::ShiftLeft) + || self + .player + .as_ref() + .is_none_or(|p| p.health.dead_or_dying()) + { + self.wake_up(); + return; + } + if let Some(p) = self.player.as_mut() { + p.position = Vec3::new( + f64::from(head[0]) + 0.5, + f64::from(head[1]) + 0.5625, + f64::from(head[2]) + 0.5, + ); + p.velocity = Vec3::ZERO; + } } - if let Some(p) = self.player.as_mut() { - p.position = Vec3::new( - f64::from(head[0]) + 0.5, - f64::from(head[1]) + 0.5625, - f64::from(head[2]) + 0.5, - ); - p.velocity = Vec3::ZERO; - } - // ServerLevel: once everyone has slept 100 ticks, skip to morning and clear weather. - if self.sleep_timer >= 100 { + // ServerLevel.tick: once enough of the players have slept 100 ticks, + // skip to morning, clear the weather and wake everyone. + if self.enough_slept() { let t = self.world.day_time; self.world.day_time = t + 24000 - t.rem_euclid(24000); self.world.weather.raining = false; self.world.weather.thundering = false; self.world.weather.rain_time = 0; self.world.weather.thunder_time = 0; - self.wake_up(); + if self.sleeping.is_some() { + self.wake_up(); + } + self.wake_guests(); } } fn creative_origin(batch: &HudBatch) -> (f32, f32) { @@ -8163,7 +8596,7 @@ impl Game<'_> { } /// Vanilla tooltip: dark box with a purple gradient border. fn tooltip(&self, batch: &mut HudBatch, text: &str, x: f32, y: f32) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let w = HudBatch::text_width(atlas, text); let (x, y) = (x + 12.0, y - 12.0); batch.fill(atlas, x - 3.0, y - 4.0, w + 6.0, 16.0, rgba(16, 0, 16, 240)); @@ -8185,7 +8618,7 @@ impl Game<'_> { ) }; batch.fill( - &self.atlas, + &self.gui.atlas, 0.0, 0.0, batch.width, @@ -8196,7 +8629,7 @@ impl Game<'_> { for (i, t) in tabs.iter().enumerate() { if i != selected { let (tx, ty) = Creative::tab_position(t); - batch.sprite(&self.atlas, &tab_sprite(t, false), ox + tx, oy + ty); + batch.sprite(&self.gui.atlas, &tab_sprite(t, false), ox + tx, oy + ty); } } let background = if tab.search { @@ -8206,13 +8639,13 @@ impl Game<'_> { } else { "gui/container/creative_inventory/tab_items" }; - if let Some(mut r) = self.atlas.sprites.get(background).copied() { + if let Some(mut r) = self.gui.atlas.sprites.get(background).copied() { r.u1 = r.u0 + (r.u1 - r.u0) * Creative::WIDTH / r.w as f32; r.v1 = r.v0 + (r.v1 - r.v0) * Creative::HEIGHT / r.h as f32; batch.rect_uv(ox, oy, Creative::WIDTH, Creative::HEIGHT, r, u32::MAX); } let (tx, ty) = Creative::tab_position(&tab); - batch.sprite(&self.atlas, &tab_sprite(&tab, true), ox + tx, oy + ty); + batch.sprite(&self.gui.atlas, &tab_sprite(&tab, true), ox + tx, oy + ty); for t in &tabs { let (tx, ty) = Creative::tab_position(t); let stack = ItemStack { @@ -8228,7 +8661,7 @@ impl Game<'_> { oy + ty + if t.top { 9.0 } else { 7.0 }, ); } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; if !tab.inventory { batch.text( atlas, @@ -8270,7 +8703,7 @@ impl Game<'_> { if Self::creative_trash_hovered(batch, self.cursor) { let (x, y) = Creative::TRASH_POSITION; batch.fill( - &self.atlas, + &self.gui.atlas, ox + x, oy + y, 16.0, @@ -8281,7 +8714,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (x, y) = self.slot_position(slot); batch.fill( - &self.atlas, + &self.gui.atlas, ox + x, oy + y, 16.0, @@ -8304,7 +8737,7 @@ impl Game<'_> { && self.cursor.1 >= y && self.cursor.1 < y + 16.0 { - batch.fill(&self.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); + batch.fill(&self.gui.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); hovered = Some(stack.clone()); } } @@ -8330,7 +8763,7 @@ impl Game<'_> { "gui/sprites/container/creative_inventory/scroller_disabled" }; batch.sprite( - &self.atlas, + &self.gui.atlas, scroller, ox + Creative::SCROLL_X, oy + Creative::SCROLL_Y + self.creative_screen.scroller_offset(), @@ -8458,6 +8891,7 @@ impl Game<'_> { level.food = p.health.food.food; level.saturation = p.health.food.saturation; + level.flying = p.flying; } level.inventory = self .inventory @@ -8539,7 +8973,7 @@ impl Game<'_> { let keys: Vec<_> = self.world.modified.drain().collect(); let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k))); self.save - .save_later(&chunks, self.pack.assets.registry, &self.res.biomes)?; + .save_later(&chunks, self.pack.assets.registry, self.res.biomes())?; if wait { self.save.flush(); } @@ -8548,6 +8982,19 @@ impl Game<'_> { Ok(()) } fn render(&mut self) -> Result { + if self.pending_entry.is_some() { + if let (Some(renderer), Some(loader)) = (&mut self.renderer, &self.rest_loader) { + let mut hud = HudBatch::new([renderer.config.width, renderer.config.height]); + horizon_client::level_loading::draw_progress( + &mut hud, + &self.gui.atlas, + loader.progress.line(), + loader.progress.fraction(), + ); + return renderer.render(&loading_frame(&hud)); + } + return Ok(false); + } self.poll_shader_pack(); let Some(size) = self .renderer @@ -8568,7 +9015,7 @@ impl Game<'_> { let s = self.world .block(c.x.floor() as i32, c.y.floor() as i32, c.z.floor() as i32); - (c, self.res.facts.get(s).fluid == Fluid::Water, yaw, pitch) + (c, self.res.facts().get(s).fluid == Fluid::Water, yaw, pitch) } None => ( glam::DVec3::new(0.5, 100.0, 0.5), @@ -8584,13 +9031,29 @@ impl Game<'_> { camera.y.floor() as i32, camera.z.floor() as i32, ]; + // The camera inside an opaque block sees nothing through it: disable. + let cave_culling = self.settings.horizon.cave_culling + && !self + .res + .facts() + .get(self.world.block(block[0], block[1], block[2])) + .solid_render; + // The cave culling search runs on its worker while the frame is prepared. + if cave_culling + && self.title.is_none() + && let Some(renderer) = self.renderer.as_mut() + { + horizon_client::spans::time("occlusion", || { + renderer.start_occlusion(camera, (self.streaming.radius * 16) as f32) + }); + } let biome = self .world .chunks .get(&(block[0] >> 4, block[2] >> 4)) .map(|c| c.biome(block[0], block[1], block[2])) .unwrap_or(0); - let info = self.res.biomes.get(biome).clone(); + let info = self.res.biomes().get(biome).clone(); let environment = self.dim_environment(); let mut sky = environment.sample(self.world.day_time, info.sky, info.fog); let (rain, thunder) = if self.dim == Dim::Overworld { @@ -8631,10 +9094,10 @@ impl Game<'_> { self.pick() .map(|h| { let state = self.world.block(h.pos[0], h.pos[1], h.pos[2]); - let f = self.res.facts.get(state); + let f = self.res.facts().get(state); outline_after_terrain = self .pack - .assets + .render .model_catalog .collect(state, BlockPos::new(h.pos[0], h.pos[1], h.pos[2])) .is_ok_and(|models| { @@ -8772,13 +9235,7 @@ impl Game<'_> { skybox: self.dim == Dim::Overworld && self.settings.horizon.sky, end_sky: self.dim == Dim::End && self.settings.horizon.sky, environment_fog: (self.dim == Dim::Nether).then_some((sky.fog_start, sky.fog_end)), - // The camera inside an opaque block sees nothing through it: disable. - cave_culling: self.settings.horizon.cave_culling - && !self - .res - .facts - .get(self.world.block(block[0], block[1], block[2])) - .solid_render, + cave_culling, water_fog, fog: Some({ let mut fog = self.frame_fog(camera, &sky, biome); @@ -8799,7 +9256,7 @@ impl Game<'_> { clouds: ((!title || live) && self.dim == Dim::Overworld && horizon_client::clouds::visible(&self.settings.clouds, sky.cloud_color[3])) - .then(|| self.atlas.sprites.get("horizon/white")) + .then(|| self.gui.atlas.sprites.get("horizon/white")) .flatten() .map(|white| horizon_client::clouds::Input { texture: &self.pack.clouds, @@ -8829,14 +9286,15 @@ impl Game<'_> { .mining .as_ref() .and_then(|m| { - self.atlas.sprites.get(&format!( + self.gui.atlas.sprites.get(&format!( "block/destroy_stage_{}", ((m.progress * 10.0) as u32).min(9) )) }) .map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0]), end_portal_sprites: ["environment/end_sky", "entity/end_portal/end_portal"].map(|n| { - self.atlas + self.gui + .atlas .sprites .get(n) .map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0]) @@ -8896,7 +9354,7 @@ impl Game<'_> { reason: horizon_client::level_loading::Reason, ) { use horizon_client::level_loading::{self, Reason, STATUS_RADIUS}; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); match reason { // The panorama and its blur are drawn by the renderer. @@ -9189,7 +9647,7 @@ impl Game<'_> { if !modified.is_empty() && let Err(e) = horizon_client::spans::time("save_chunks", || { self.save - .save_later(&modified, self.pack.assets.registry, &self.res.biomes) + .save_later(&modified, self.pack.assets.registry, self.res.biomes()) }) { log::warn!("Horizon: failed to save unloaded chunks: {e}"); @@ -9276,7 +9734,10 @@ impl ApplicationHandler for Game<'_> { } }; match self.new_renderer(window.clone()) { - Ok(r) => self.renderer = Some(r), + Ok(r) => { + self.renderer = Some(r); + self.world_renderer_ready = true; + } Err(e) => { self.error = Some(e); event_loop.exit(); @@ -9325,7 +9786,6 @@ impl ApplicationHandler for Game<'_> { event: key_event, .. } = &event && let PhysicalKey::Code(key) = key_event.physical_key - && self.title.is_none() { use horizon_client::debug_keys::KeyAction; let action = match (key_event.state, key_event.repeat) { @@ -9355,6 +9815,25 @@ impl ApplicationHandler for Game<'_> { // The press state of Horizon-style buttons. horizon_client::ui_theme::set_pressed(*state == ElementState::Pressed); } + if self.pending_entry.is_some() + && matches!(&event, WindowEvent::KeyboardInput { event, .. } + if event.state == ElementState::Pressed + && event.physical_key == PhysicalKey::Code(KeyCode::Escape)) + { + self.pending_entry = None; + self.perf.cancel_world_opening(); + return; + } + if self.pending_entry.is_some() + && !matches!( + &event, + WindowEvent::CloseRequested + | WindowEvent::Resized(_) + | WindowEvent::RedrawRequested + ) + { + return; + } let result: Result<()> = (|| { match event { WindowEvent::CloseRequested => { @@ -9407,7 +9886,7 @@ impl ApplicationHandler for Game<'_> { && !horizon_client::ui_theme::horizon() { title.drag(self.cursor, (b.width, b.height)); - title.drag_field(&self.atlas, self.cursor.0); + title.drag_field(&self.gui.atlas, self.cursor.0); } if self.dragging && self.screen == Screen::Options { let _ = b; @@ -9512,7 +9991,7 @@ impl ApplicationHandler for Game<'_> { .map(|r| [r.config.width, r.config.height]) .unwrap_or([1, 1]); let mut b = HudBatch::new(size); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let shift = self.has_shift_down(); let (action, sound) = self.title.as_mut().map_or((Action::None, false), |t| { if horizon_client::ui_theme::horizon() { @@ -9917,6 +10396,10 @@ impl ApplicationHandler for Game<'_> { self.pause = self.pauses_game(); if let Some(server) = &self.integrated { server.set_paused(self.pause); + server.set_distances( + self.settings.render_distance, + self.settings.simulation_distance, + ); } self.clock.end_frame(self.pause); let finished = self @@ -9997,6 +10480,11 @@ impl ApplicationHandler for Game<'_> { } } fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + if let Err(error) = self.resume_world_entry() { + self.error = Some(error); + event_loop.exit(); + return; + } self.poll_control(event_loop); self.poll_pads(event_loop); if self.options.frames.is_some() && self.started.elapsed() > self.options.timeout { @@ -10052,7 +10540,7 @@ impl<'a> Game<'a> { fn new( res: &'a Arc, pack: PackResources, - atlas: HudAtlas, + gui: UiResources, options: Options, settings: Settings, audio: Audio, @@ -10061,7 +10549,7 @@ impl<'a> Game<'a> { let registry = pack.assets.registry; // Until a world is opened the streamer is idle. let mut streaming = Streaming::new( - Arc::new(TestTerrain::new(registry, &res.biomes)?), + Arc::new(TestTerrain::new(registry, res.biomes())?), pack.context.clone(), 1, ); @@ -10081,18 +10569,22 @@ impl<'a> Game<'a> { minecarts::CartModels::load(document.as_ref()), ) }; - let world = World::new(res.facts.air, 0); + let world = World::new(res.facts().air, 0); let creative = options.creative; let inventory = vec![None; 36]; let now = Instant::now(); let look = options.look; - let particles = horizon_client::particles::ParticleEngine::new(&root, &atlas.sprites); + let particles = horizon_client::particles::ParticleEngine::new(&root, &gui.atlas.sprites); Ok(Game { res: res.clone(), - collision: &res.collision, - motion: &res.motion, + rest_loader: None, + pending_entry: None, + pending_pack_reload: false, + world_renderer_ready: false, + collision: res.collision(), + motion: res.motion(), pack, - atlas, + gui, fog: Default::default(), screen_fx: Default::default(), world, @@ -10236,6 +10728,7 @@ impl<'a> Game<'a> { world_root: PathBuf::new(), travelling: None, server_trips: Vec::new(), + level_teleports: Vec::new(), levels: Default::default(), level_pass: Default::default(), portals: Default::default(), @@ -10246,6 +10739,7 @@ impl<'a> Game<'a> { end: Default::default(), block_ticks: Ticks::new(0), tick_chunks: Default::default(), + tickets: Default::default(), random_tick_sections: Default::default(), level_events: Vec::new(), falling: Vec::new(), @@ -10340,10 +10834,12 @@ impl<'a> Game<'a> { lan_entity_events: Vec::new(), lid_openers: HashMap::new(), lan_acting: None, + guest_packets: Vec::new(), lan_acting_name: None, lan_acting_uuid: None, chat_capture: None, admin_feedback: Vec::new(), + console_broadcast: None, cmds: Default::default(), ui: Default::default(), combat: Default::default(), @@ -10374,23 +10870,146 @@ impl<'a> Game<'a> { struct Loaded { root: PathBuf, pack_error: Option, - resources: Resources, + resources: Arc, + rest_loader: Option, pack: PackResources, - atlas: HudAtlas, + /// The menu bundle, for the synchronous launch; the loading screen receives + /// it earlier through its own channel. + gui: Option, } -/// The loader's checkpoints, in order; the loading screen reports them. -const STAGES: u32 = 9; -const STAGE_LINES: [&str; 9] = [ +/// What the background loader publishes: the menu bundle as soon as it is +/// ready, then the core bundle with a handle to the rest worker. +enum LoaderMsg { + Ui(UiResources, PathBuf), + Done(std::result::Result), +} + +enum PendingWorldEntry { + Local { + folder: String, + name: Option, + seed: Option, + creative: bool, + create: Option>, + }, + Server { + address: String, + name: String, + }, +} + +struct WorldRestLoader { + progress: Progress, + handle: JoinHandle>, +} + +impl WorldRestLoader { + fn ready(&self) -> Result { + // No time limit: the title stays usable while this loads, and a slow + // disk or a debug build can take minutes. A failure ends the thread + // and is reported by `finish`. + Ok(self.handle.is_finished()) + } + + fn finish(self) -> Result<()> { + self.handle + .join() + .map_err(|_| "world resource loader panicked")? + .map_err(Into::into) + } +} + +impl Game<'_> { + fn defer_world_entry(&mut self, entry: PendingWorldEntry) -> Result { + self.poll_world_rest()?; + if self.rest_loader.is_none() { + return Ok(false); + } + self.perf.world_opening(); + if self.title.is_none() { + self.title = Some(Title::new( + std::env::current_dir()?.join("saves"), + &self.options.resources, + )); + } + self.pending_entry = Some(entry); + log::info!("Horizon: world entry waiting for world resources"); + Ok(true) + } + + fn resume_world_entry(&mut self) -> Result<()> { + self.poll_world_rest()?; + if self.rest_loader.is_some() { + return Ok(()); + } + if std::mem::take(&mut self.pending_pack_reload) { + self.reload_packs(); + } + match self.pending_entry.take() { + Some(PendingWorldEntry::Local { + folder, + name, + seed, + creative, + create, + }) => { + self.open_world(&folder, name.as_deref(), seed, creative, create.as_deref())?; + } + Some(PendingWorldEntry::Server { address, name }) => { + self.connect_server(&address, &name)?; + } + None => {} + } + Ok(()) + } + + fn poll_world_rest(&mut self) -> Result<()> { + if let Some(loader) = &self.rest_loader + && loader.ready()? + { + self.rest_loader + .take() + .ok_or("missing world loader")? + .finish()?; + } + Ok(()) + } + + fn join_world_rest(&mut self) -> Result<()> { + if self.rest_loader.is_some() { + let waited = Instant::now(); + log::info!("Horizon: waiting for world resources"); + while self.rest_loader.is_some() { + self.poll_world_rest()?; + if self.rest_loader.is_some() { + std::thread::sleep(Duration::from_millis(10)); + } + } + log::info!( + "Horizon: world resources joined after {} ms", + waited.elapsed().as_millis() + ); + } + if self.res.rest.get().is_none() { + return Err("world resources are unavailable".into()); + } + Ok(()) + } +} + +const STAGES: u32 = 10; +const STAGE_LINES: [&str; 10] = [ + "Loading menu", "Loading assets", "Loading block facts", - "Loading items", "Loading biomes", "Loading pack tables", - "Loading atlas", "Loading collision", - "Loading resources", - "Starting audio", + "Loading items", + "Loading recipes", + "Loading world resources", + "World resources ready", ]; /// The background loader's checkpoint, read by the loading screen each frame. @@ -10427,26 +11046,53 @@ fn synchronous_startup(options: &Options) -> bool { || std::env::var_os("HORIZON_NET_REPORT").is_some() } -/// The current loading sequence, unchanged, as a function so the synchronous -/// launch can run it on the main thread and an ordinary launch on a worker. -/// `on_stage` reports [`STAGES`] checkpoints to the loading screen. +/// The synchronous launch loads both phases; an ordinary launch returns the +/// core bundle while the rest worker keeps loading. fn load_resources( mut root: PathBuf, vanilla_root: &std::path::Path, settings: &Settings, started: Instant, - on_stage: &(dyn Fn(u32) + Sync), + menu: bool, + progress: &Progress, + publish: &mut dyn FnMut(UiResources, &std::path::Path), ) -> Result { + let requested_root = root.clone(); + let threads = settings.horizon.worker_threads(); + // Stage A: the menu bundle (atlas and panorama). With a loading screen it is + // published at once so the title backdrop can appear while the world bundle + // loads; the synchronous launch instead carries it in `Loaded`. + let mut loaded_gui = None; + let mut ui_ready = false; + if let Ok(ui) = UiResources::load(&root) { + if menu { + horizon_client::telemetry::mark_ui_ready(); + log::info!( + "Horizon: UI bundle ready after {} ms", + started.elapsed().as_millis() + ); + publish(ui, &root); + } else { + loaded_gui = Some(ui); + } + ui_ready = true; + } + progress.set(0); let mut pack_error = None; - let assets = match Assets::load(&root) { - Ok(assets) => assets, + let (assets, render) = match Assets::load(&root).and_then(|assets| { + let render = assets.reload(&root)?; + Ok((assets, render)) + }) { + Ok(bundle) => bundle, // Minecraft.rollbackResourcePacks: the packs break loading, start // with the game's own resources. Err(e) if root != vanilla_root => { log::warn!("Horizon: resource packs failed to load ({e}); using the default resources"); pack_error = Some(e.to_string()); root = vanilla_root.to_path_buf(); - Assets::load(vanilla_root)? + let assets = Assets::load(vanilla_root)?; + let render = assets.reload(vanilla_root)?; + (assets, render) } Err(e) => { return Err(format!( @@ -10456,47 +11102,177 @@ fn load_resources( } }; let assets = Arc::new(assets); + let render = Arc::new(render); + // The menu bundle must come from the same root as the world bundle. + if !ui_ready || root != requested_root { + let ui = UiResources::load(&root)?; + if menu { + horizon_client::telemetry::mark_ui_ready(); + log::info!( + "Horizon: UI bundle ready after {} ms", + started.elapsed().as_millis() + ); + publish(ui, &root); + } else { + loaded_gui = Some(ui); + } + } log::info!("load assets: {:.2}s", started.elapsed().as_secs_f32()); - on_stage(0); + progress.set(1); let behaviour_json: serde_json::Value = serde_json::from_reader(std::io::BufReader::new( std::fs::File::open(root.join("block-behaviours.json"))?, ))?; + // The block facts, the biomes and the environment are independent reads: + // run them together, within the worker budget the settings allow. + let registry = assets.registry; + let load_facts = || { + BlockFacts::load_with_projection(&root, registry, &behaviour_json) + .map_err(|e| e.to_string()) + }; + let load_biomes = || Biomes::load(&root).map_err(|e| e.to_string()); + let load_environment = || Environment::load(&root).map_err(|e| e.to_string()); + let (facts, biomes, environment) = if threads > 1 { + std::thread::scope(|scope| { + let facts = scope.spawn(load_facts); + let biomes = scope.spawn(load_biomes); + let environment = scope.spawn(load_environment); + ( + facts.join().unwrap(), + biomes.join().unwrap(), + environment.join().unwrap(), + ) + }) + } else { + (load_facts(), load_biomes(), load_environment()) + }; let (facts, gameplay_projection) = - BlockFacts::load_with_projection(&root, assets.registry, &behaviour_json)?; - let mob_data = horizon_client::mobs::MobData::load(&root, &facts); - horizon_client::mobs::trial_spawner::load_registry(&root); + facts.map_err(|e| -> Box { e.into() })?; + let biomes = Arc::new(biomes.map_err(|e| -> Box { e.into() })?); + let environment = environment.map_err(|e| -> Box { e.into() })?; log::info!("load facts: {:.2}s", started.elapsed().as_secs_f32()); - on_stage(1); - let items = Items::load(&root, assets.registry, &facts)?; - log::info!("load items: {:.2}s", started.elapsed().as_secs_f32()); - on_stage(2); - let recipes = Recipes::load(&root, &items)?; - let transformers = horizon_client::block_transform::Transformers::load(&root, assets.registry)?; - let biomes = Arc::new(Biomes::load(&root)?); - let environment = Environment::load(&root)?; + progress.set(2); log::info!("load biomes+env: {:.2}s", started.elapsed().as_secs_f32()); - on_stage(3); + progress.set(3); let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?); - let pack = PackResources::load(&root, assets.clone(), &facts, biomes.clone(), light)?; + let pack = PackResources::load(&root, assets.clone(), render, &facts, biomes.clone(), light)?; log::info!("load pack tables: {:.2}s", started.elapsed().as_secs_f32()); - on_stage(4); - let atlas = HudAtlas::build(&root)?; - horizon_client::ui::load_metadata(&root); - horizon_client::lang::set(horizon_client::lang::Language::load( - &[&root], - &settings.language, - )); - log::info!("load atlas: {:.2}s", started.elapsed().as_secs_f32()); - on_stage(5); + progress.set(4); + if !menu { + horizon_client::ui::load_metadata(&root); + horizon_client::lang::set(horizon_client::lang::Language::load( + &[&root], + &settings.language, + )); + } let registry_owner = assets.clone(); let collision = collisions::load(&root, registry_owner.registry)?; - let motion = MotionResources::load(&root, ®istry_owner)?; + let motion = MotionResources::load_with_facts(&root, ®istry_owner, &facts)?; log::info!( "load collision+motion: {:.2}s", started.elapsed().as_secs_f32() ); - on_stage(6); - let threads = settings.horizon.worker_threads(); + progress.set(5); + let resources = Resources { + core: WorldCore { + facts, + biomes: biomes.clone(), + environment, + collision, + motion, + threads, + }, + rest: std::sync::OnceLock::new(), + }; + let resources = Arc::new(resources); + if menu { + horizon_client::telemetry::mark_core_ready(); + log::info!( + "Horizon: core-ready after {} ms", + started.elapsed().as_millis() + ); + } + let rest_loader = if menu { + let resources = resources.clone(); + let root = root.clone(); + let rest_progress = progress.clone(); + let progress = progress.clone(); + let handle = std::thread::Builder::new() + .name("world-rest-loader".into()) + .spawn(move || { + let rest = load_world_rest( + &root, + &resources, + &assets, + &behaviour_json, + &gameplay_projection, + &progress, + started, + ) + .map_err(|error| error.to_string())?; + resources + .rest + .set(rest) + .map_err(|_| "world resources already loaded".to_owned())?; + progress.set(9); + horizon_client::telemetry::mark_rest_ready(); + log::info!( + "Horizon: rest-ready after {} ms", + started.elapsed().as_millis() + ); + Ok(()) + })?; + Some(WorldRestLoader { + progress: rest_progress, + handle, + }) + } else { + let rest = load_world_rest( + &root, + &resources, + &assets, + &behaviour_json, + &gameplay_projection, + progress, + started, + )?; + resources + .rest + .set(rest) + .map_err(|_| "world resources already loaded")?; + None + }; + Ok(Loaded { + root, + pack_error, + resources, + rest_loader, + pack, + gui: loaded_gui, + }) +} + +fn load_world_rest( + root: &std::path::Path, + resources: &Resources, + assets: &Assets, + behaviour_json: &serde_json::Value, + gameplay_projection: &[horizon_client::blocks::GameplayProjection], + progress: &Progress, + started: Instant, +) -> Result { + let facts = resources.facts(); + let biomes = resources.biomes(); + let threads = resources.threads(); + let registry_owner = assets; + progress.set(6); + let mob_data = horizon_client::mobs::MobData::load(root, facts); + horizon_client::mobs::trial_spawner::load_registry(root); + + let items = Items::load(root, assets.registry, facts)?; + log::info!("load items: {:.2}s", started.elapsed().as_secs_f32()); + progress.set(7); + let recipes = Recipes::load(root, &items)?; + let transformers = horizon_client::block_transform::Transformers::load(root, assets.registry)?; log::info!( "Horizon: resources loaded in {:.1}s; {} block states, {} items, {} biomes; {} worker threads", started.elapsed().as_secs_f32(), @@ -10505,59 +11281,42 @@ fn load_resources( biomes.list.len(), threads ); - let stations = horizon_client::stations::StationData::load(&root, &items); + progress.set(8); + let stations = horizon_client::stations::StationData::load(root, &items); let animate = - horizon_client::animate_tick::AnimateTables::load(&root, registry_owner.registry, &biomes)?; - let fog = horizon_client::fog::FogTables::load(&root, &biomes); - let resources = Resources { + horizon_client::animate_tick::AnimateTables::load(root, registry_owner.registry, biomes)?; + let fog = horizon_client::fog::FogTables::load(root, biomes); + Ok(WorldRest { stations, - facts, items, recipes, transformers, - biomes, - environment, - collision, - motion, - providers: Providers::load(&root), + providers: Providers::load(root), block_entity_render: horizon_client::block_entity_render::BlockEntityRenderer::load( - &root, + root, registry_owner.registry, )?, animate, fog, - music: horizon_client::music::MusicTables::load(&root), - ambient: horizon_client::ambience::AmbientTables::load(&root), - nether_environment: Environment::load_dimension(&root, "the_nether", false)?, - end_environment: Environment::load_dimension(&root, "the_end", false)?, + music: horizon_client::music::MusicTables::load(root), + ambient: horizon_client::ambience::AmbientTables::load(root), + nether_environment: Environment::load_dimension(root, "the_nether", false)?, + end_environment: Environment::load_dimension(root, "the_end", false)?, behaviours: Behaviours::load_with_gameplay( registry_owner.registry, - &root, - &behaviour_json, - &gameplay_projection, + root, + behaviour_json, + gameplay_projection, )?, - mob_types: MobTypes::load(&root)? + mob_types: MobTypes::load(root)? .types .into_iter() .map(|(k, v)| (k, Arc::new(v))) .collect(), mob_data, - threads, - player_type: perspective::player_type(&root), - player_arm: horizon_client::mobs::load_model(&root, "minecraft:player#main") + player_type: perspective::player_type(root), + player_arm: horizon_client::mobs::load_model(root, "minecraft:player#main") .and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")), - }; - // Both inputs are needed only while constructing the behaviour tables. - // Release their owned JSON/Arc buffers before entering the long-lived game loop. - drop(gameplay_projection); - drop(behaviour_json); - on_stage(7); - Ok(Loaded { - root, - pack_error, - resources, - pack, - atlas, }) } @@ -10567,10 +11326,11 @@ fn build_renderer( window: Arc, offscreen: bool, pack: &PackResources, - atlas: &HudAtlas, + gui: &UiResources, previous: Option<&Renderer>, ) -> Result { - let assets = &pack.assets; + let assets = &pack.render; + let atlas = &gui.atlas; let mut renderer = pollster::block_on(Renderer::new( window, offscreen, @@ -10582,7 +11342,7 @@ fn build_renderer( &assets.animations, (&atlas.pixels, atlas.width, atlas.height), (&pack.forcefield.2, pack.forcefield.0), - &pack.panorama, + &gui.panorama, previous, ))?; renderer.hud.fire_animations = atlas @@ -10594,18 +11354,22 @@ fn build_renderer( } /// The loading screen's renderer: the real HUD atlas and font over one opaque -/// white block-sprite layer, an empty border texture and an empty panorama. +/// white block-sprite layer, an empty border texture and the title panorama +/// once the menu bundle is ready. fn loading_renderer( window: Arc, offscreen: bool, - atlas: Option<&HudAtlas>, + gui: Option<&UiResources>, + previous: Option<&Renderer>, ) -> Result { static FORCEFIELD: [u8; 4] = [0; 4]; static EMPTY_HUD: [u8; 4] = [0, 0, 0, 255]; - let panorama = horizon_client::gfx::panorama::Faces { + let empty_panorama = horizon_client::gfx::panorama::Faces { size: 1, pixels: [0u8; 4].repeat(6), }; + let panorama = gui.map_or(&empty_panorama, |gui| gui.panorama.as_ref()); + let atlas = gui.map(|gui| &gui.atlas); let (pixels, width, height) = match atlas { Some(atlas) => (atlas.pixels.as_slice(), atlas.width, atlas.height), None => (EMPTY_HUD.as_slice(), 1, 1), @@ -10621,8 +11385,8 @@ fn loading_renderer( &[], (pixels, width, height), (&FORCEFIELD[..], 1), - &panorama, - None, + panorama, + previous, ))?; if let Some(atlas) = atlas { renderer.hud.fire_animations = atlas @@ -10692,12 +11456,13 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> { fn start_game<'a>( res: &'a Arc, pack: PackResources, - atlas: HudAtlas, + gui: UiResources, options: Options, pack_error: Option, audio: Audio, vanilla_root: PathBuf, started: Instant, + rest_loader: Option, ) -> Result>> { let mut settings = Settings::load(&std::env::current_dir()?.join("options.txt")); horizon_client::ui_theme::load_preferences(&std::env::current_dir()?); @@ -10711,7 +11476,8 @@ fn start_game<'a>( if let Some(d) = options.distance_override { settings.render_distance = d; } - let mut game = Game::new(res, pack, atlas, options, settings, audio)?; + let mut game = Game::new(res, pack, gui, options, settings, audio)?; + game.rest_loader = rest_loader; game.ui.vanilla_root = vanilla_root; if let Some(error) = pack_error { game.open_options_at(true, horizon_client::options_ui::Page::Packs); @@ -10842,7 +11608,7 @@ fn run_event_loop(mut game: Game<'_>) -> Result<()> { struct Loading { window: Option>, renderer: Option, - atlas: Option, + gui: Option, settings: Settings, fullscreen: horizon_client::window::FullscreenState, options: Option, @@ -10850,10 +11616,11 @@ struct Loading { pack_error: Option, started: Instant, progress: Progress, - receiver: Receiver>, + receiver: Receiver, loaded: Option>, handle: Option>, shown: bool, + menu: startup_menu::StartupMenu, error: Option>, } impl Loading { @@ -10885,7 +11652,7 @@ impl Loading { } }; let offscreen = self.options.as_ref().is_some_and(|o| o.offscreen); - match loading_renderer(window.clone(), offscreen, self.atlas.as_ref()) { + match loading_renderer(window.clone(), offscreen, self.gui.as_ref(), None) { Ok(r) => self.renderer = Some(r), Err(e) => { self.error = Some(e); @@ -10904,31 +11671,44 @@ impl Loading { if self.window.as_ref().is_none_or(|w| w.id() != id) { return; } - match event { - WindowEvent::CloseRequested => event_loop.exit(), - WindowEvent::Resized(size) => { - if let Some(r) = &mut self.renderer { - r.resize(size.width, size.height); - } + if let Err(error) = self.menu_event(event_loop, event) { + self.error = Some(error); + event_loop.exit(); + } + } + /// The menu bundle arrived: rebuild the loading screen with the real atlas + /// and title panorama. + fn set_ui(&mut self, gui: UiResources, root: PathBuf) { + log::info!( + "Horizon: loading the title artwork after {} ms", + self.started.elapsed().as_millis() + ); + self.menu.set_root(root, &self.settings); + self.gui = Some(gui); + horizon_client::ui_theme::reset_atlas(); + self.apply_menu_settings(); + let Some(window) = self.window.clone() else { + return; + }; + let offscreen = self.options.as_ref().is_some_and(|o| o.offscreen); + if let Some(renderer) = &mut self.renderer { + renderer.release_surface(); + } + match loading_renderer(window, offscreen, self.gui.as_ref(), self.renderer.as_ref()) { + Ok(r) => { + self.settings + .clamp_gui_scale([r.config.width as i32, r.config.height as i32]); + horizon_client::hud::GUI_SCALE.store(self.settings.gui_scale, Ordering::Relaxed); + self.renderer = Some(r); } - WindowEvent::RedrawRequested => self.draw(), - _ => {} + Err(e) => self.error = Some(e), } } fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { - if self.loaded.is_none() { - match self.receiver.try_recv() { - Ok(result) => self.loaded = Some(result), - Err(TryRecvError::Disconnected) => { - if let Some(handle) = self.handle.take() { - let _ = handle.join(); - } - self.error = Some("resource loader stopped before finishing".into()); - event_loop.exit(); - return; - } - Err(TryRecvError::Empty) => {} - } + if let Err(error) = self.poll_menu_resources() { + self.error = Some(error); + event_loop.exit(); + return; } if let Some(w) = &self.window { if self.options.as_ref().is_some_and(|o| o.offscreen) { @@ -10940,22 +11720,24 @@ impl Loading { event_loop.set_control_flow(ControlFlow::Poll); } fn draw(&mut self) { - let Some(renderer) = self.renderer.as_mut() else { + let Some(size) = self + .renderer + .as_ref() + .map(|r| [r.config.width, r.config.height]) + else { return; }; - let size = [renderer.config.width, renderer.config.height]; let mut batch = HudBatch::new(size); - if let Some(atlas) = &self.atlas { - horizon_client::level_loading::draw_progress( - &mut batch, - atlas, - self.progress.line(), - self.progress.fraction(), - ); - } + self.draw_menu(&mut batch); let frame = loading_frame(&batch); - if let Err(e) = renderer.render(&frame) { - log::warn!("Horizon: loading screen frame failed: {e}"); + if let Some(renderer) = &mut self.renderer { + match renderer.render(&frame) { + Ok(true) if self.gui.is_some() && self.menu.pending.is_none() => { + self.menu.perf.title_shown() + } + Ok(_) => {} + Err(e) => log::warn!("Horizon: loading screen frame failed: {e}"), + } } if !self.shown { self.shown = true; @@ -10968,13 +11750,10 @@ impl Loading { fn finish(&mut self, loaded: Loaded) -> Result>> { let mut options = self.options.take().ok_or("loading already finished")?; options.resources = loaded.root.clone(); - self.progress.set(STAGES - 1); - // Audio is created on the main thread, after the join. - let audio = if options.dedicated.is_some() { - Audio::silent(&options.resources) - } else { - Audio::new(&options.resources) - }; + // StartupMenu owns world selection until it can hand it to Game. + options.world = None; + options.server = None; + let gui = self.gui.take().ok_or("missing menu bundle")?; let window = self.window.clone().ok_or("window closed")?; // Keep the loader's device and swap in the real textures in one step. if let Some(renderer) = &mut self.renderer { @@ -10984,29 +11763,43 @@ impl Loading { window.clone(), options.offscreen, &loaded.pack, - &loaded.atlas, + &gui, self.renderer.as_ref(), )?; + log::info!( + "Horizon: world renderer ready after {} ms", + self.started.elapsed().as_millis() + ); + // Audio is created on the main thread, after the core is ready. + let audio = if options.dedicated.is_some() { + Audio::silent(&options.resources) + } else { + Audio::new(&options.resources) + }; let pack_error = loaded.pack_error.or_else(|| self.pack_error.take()); // The game borrows its shared resources for the process's lifetime, // like the single copy an integrated server would share. - let res: &'static Arc = Box::leak(Box::new(Arc::new(loaded.resources))); + let res: &'static Arc = Box::leak(Box::new(loaded.resources)); let Some(mut game) = start_game( res, loaded.pack, - loaded.atlas, + gui, options, pack_error, audio, self.vanilla_root.clone(), self.started, + loaded.rest_loader, )? else { return Ok(None); }; game.window = Some(window); game.renderer = Some(renderer); + game.world_renderer_ready = true; game.fullscreen = self.fullscreen; + self.menu.handoff(&mut game); + game.settings = self.settings.clone(); game.apply_settings(); game.previous = Instant::now(); Ok(Some(game)) @@ -11055,7 +11848,11 @@ impl ApplicationHandler for App { event_loop.exit(); return; } - match loading.loaded.take() { + match if loading.menu.reload_packs { + None + } else { + loading.loaded.take() + } { None => Step::Waiting, Some(Err(e)) => Step::Failed(e.into()), Some(Ok(loaded)) => match loading.finish(loaded) { @@ -11094,28 +11891,15 @@ fn run_loading( pack_error: Option, started: Instant, ) -> Result<()> { + horizon_client::ui_theme::load_preferences(&std::env::current_dir()?); let progress = Progress::new(); - let (sender, receiver) = std::sync::mpsc::channel(); - let loader = { - let progress = progress.clone(); - let settings = settings.clone(); - let vanilla_root = vanilla_root.clone(); - let root = options.resources.clone(); - std::thread::Builder::new() - .name("resource-loader".into()) - .spawn(move || { - let result = load_resources(root, &vanilla_root, &settings, started, &|stage| { - progress.set(stage) - }) - .map_err(|e| e.to_string()); - let _ = sender.send(result); - })? - }; - let atlas = HudAtlas::build(&options.resources).ok(); + let (receiver, loader) = + startup_menu::spawn_loader(&options, &settings, &vanilla_root, started, &progress)?; + let menu = startup_menu::StartupMenu::new(&options, pack_error.as_deref())?; let loading = Loading { window: None, renderer: None, - atlas, + gui: None, settings, fullscreen: horizon_client::window::FullscreenState::new(false), options: Some(options), @@ -11127,6 +11911,7 @@ fn run_loading( loaded: None, handle: Some(loader), shown: false, + menu, error: None, }; let mut app = App::Loading(Box::new(loading)); @@ -11161,6 +11946,9 @@ pub fn run() -> Result<()> { // Snapshots of derived tables live in the game folder, never beside the // shared resources. Behaviours::set_cache_dir(std::env::current_dir()?.join(".horizon-cache")); + if !synchronous_startup(&options) { + return run_loading(options, early_settings, vanilla_root, None, started); + } let mut pack_error = None; options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs) .unwrap_or_else(|e| { @@ -11173,34 +11961,33 @@ pub fn run() -> Result<()> { &early_settings.mods.enabled, &options.dev_mods, ); - // Harnesses and dedicated runs stay synchronous; a normal launch enters - // the event loop at once and loads the resources on a worker. - if !synchronous_startup(&options) { - return run_loading(options, early_settings, vanilla_root, pack_error, started); - } let loaded = load_resources( options.resources.clone(), &vanilla_root, &early_settings, started, - &|_| {}, + false, + &Progress::new(), + &mut |_, _| {}, )?; + let gui = loaded.gui.ok_or("missing menu bundle")?; options.resources = loaded.root.clone(); let audio = if options.dedicated.is_some() { Audio::silent(&options.resources) } else { Audio::new(&options.resources) }; - let resources = Arc::new(loaded.resources); + let resources = loaded.resources; let game = start_game( &resources, loaded.pack, - loaded.atlas, + gui, options, loaded.pack_error.or(pack_error), audio, vanilla_root, started, + loaded.rest_loader, )?; if let Some(game) = game { run_event_loop(game)?; @@ -11282,6 +12069,64 @@ mod tests { assert!(hud_overlays::sleep_overlay(320, 240, timer as i32).is_empty()); } + #[test] + fn world_rest_poll_does_not_wait_for_a_blocked_worker() { + let (release, wait) = std::sync::mpsc::channel(); + let loader = WorldRestLoader { + progress: Progress::new(), + handle: std::thread::spawn(move || { + wait.recv().unwrap(); + Ok(()) + }), + }; + assert!(!loader.ready().unwrap()); + release.send(()).unwrap(); + loader.finish().unwrap(); + } + + #[test] + fn world_rest_poll_waits_for_a_slow_worker() { + let (release, wait) = std::sync::mpsc::channel(); + let loader = WorldRestLoader { + progress: Progress::new(), + handle: std::thread::spawn(move || { + wait.recv().unwrap(); + Ok(()) + }), + }; + // However long it takes, a worker still loading is not an error. + assert!(!loader.ready().unwrap()); + release.send(()).unwrap(); + while !loader.ready().unwrap() { + std::thread::sleep(Duration::from_millis(1)); + } + loader.finish().unwrap(); + } + + #[test] + fn world_rest_worker_failure_reaches_the_client() { + let loader = WorldRestLoader { + progress: Progress::new(), + handle: std::thread::spawn(|| Err("missing world table".to_owned())), + }; + assert_eq!( + loader.finish().unwrap_err().to_string(), + "missing world table" + ); + } + + #[test] + fn world_rest_worker_panic_reaches_the_client() { + let loader = WorldRestLoader { + progress: Progress::new(), + handle: std::thread::spawn(|| panic!("broken loader")), + }; + assert_eq!( + loader.finish().unwrap_err().to_string(), + "world resource loader panicked" + ); + } + /// An integrated server thread shares the loaded resources with the client. #[test] fn shared_resources_can_cross_threads() { diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 882b5cc93..d13ed6b13 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -106,7 +106,7 @@ impl adv::World for View<'_, '_> { .map(|c| { self.0 .res - .biomes + .biomes() .get(c.biome(p[0], p[1], p[2])) .name .clone() @@ -118,7 +118,7 @@ impl adv::World for View<'_, '_> { } fn block(&self, p: [i32; 3]) -> (String, BTreeMap) { let state = self.0.world.block(p[0], p[1], p[2]); - let name = self.0.res.facts.get(state).name.to_string(); + let name = self.0.res.facts().get(state).name.to_string(); let props = self .0 .pack @@ -138,7 +138,7 @@ impl adv::World for View<'_, '_> { match self .0 .res - .facts + .facts() .get(self.0.world.block(p[0], p[1], p[2])) .fluid { @@ -152,7 +152,7 @@ impl adv::World for View<'_, '_> { !self .0 .res - .facts + .facts() .get(self.0.world.block(p[0], y, p[2])) .full_collision }) @@ -165,19 +165,19 @@ impl adv::World for View<'_, '_> { (1..=5).any(|d| { self.0 .res - .facts + .facts() .get(self.0.world.block(p[0], p[1] - d, p[2])) .name .ends_with("campfire") }) } fn in_tag(&self, registry: &str, tag: &str, id: &str) -> bool { - let items = &self.0.res.items; + let items = &self.0.res.items(); match registry { "item" => items.item_tags.get(tag).is_some_and(|t| t.contains(id)), "block" => items.block_tags.get(tag).is_some_and(|t| t.contains(id)), - "entity_type" => self.0.res.mob_data.entity_has(tag, id), - "worldgen/biome" => self.0.res.mob_data.biome_has(tag, id), + "entity_type" => self.0.res.mob_data().entity_has(tag, id), + "worldgen/biome" => self.0.res.mob_data().biome_has(tag, id), _ => false, } } @@ -408,6 +408,9 @@ impl Game<'_> { } } } + if hits.is_empty() { + return; + } let date = now_text(); for (ai, ci) in hits { let a = &tree.list[ai]; @@ -454,17 +457,17 @@ impl Game<'_> { .rewards .recipes .iter() - .filter(|r| self.res.stations.recipe_index.contains(r)) + .filter(|r| self.res.stations().recipe_index.contains(r)) .cloned() .collect(); let (_, unlocked) = self .level .recipe_book - .add_recipes(&self.res.stations.recipe_index, &rewards); + .add_recipes(&self.res.stations().recipe_index, &rewards); for table in &a.rewards.loot { let items = self .res - .items + .items() .loot_table(table, false, None, &mut self.world.random); for s in items { if let Some(rest) = self.give(s) @@ -497,10 +500,13 @@ impl Game<'_> { // PlayerList.broadcastSystemMessage: everyone hears of a // network player's advancement. match self.lan_acting_name.clone() { - Some(player) => self - .adv - .announced - .push(Text::translate(key, &[Text::literal(&player), name])), + // Player.getDisplayName. + Some(_) => { + let player = self.target_name(super::commands::Target::Player); + self.adv + .announced + .push(Text::translate(key, &[player, name])); + } None => self.system_message(Text::translate( key, &[Text::literal(super::chat::PLAYER_NAME), name], @@ -549,7 +555,7 @@ impl Game<'_> { .filter_map(|s| s.as_ref()) .filter(|s| { self.res - .items + .items() .get(&s.item) .is_some_and(|i| s.count >= i.max_stack) }) @@ -790,11 +796,11 @@ impl Game<'_> { if let Some((station, item)) = recipe { // RecipeToast: black description under a purple title, the // station at 0.6 scale in the corner over the cycling result. - let atlas = &self.atlas; + let atlas = &self.gui.atlas; batch.sprite(atlas, "gui/sprites/toast/recipe", x, 0.0); let title = self.translate("recipe.toast.title", "New Recipe(s) Unlocked!"); let description = self.translate("recipe.toast.description", "Check your recipe book"); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; batch.text(atlas, &title, x + 30.0, 7.0, 0xFF50_0050, false); batch.text(atlas, &description, x + 30.0, 18.0, 0xFF00_0000, false); let start = batch.vertices.len(); @@ -803,7 +809,7 @@ impl Game<'_> { self.draw_item_model(batch, &item, x + 8.0, 8.0); return; } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; batch.sprite(atlas, "gui/sprites/toast/advancement", x, 0.0); let (key, color) = match frame { Frame::Task => ("advancements.toast.task", 0xFF00_FFFF), @@ -832,18 +838,25 @@ pub(super) fn adv_name(a: &adv::Advancement) -> Text { Frame::Challenge => text::DARK_PURPLE, _ => text::GREEN, }; - let tooltip = text_of(&d.title) - .with_color(color) + // Advancement.decorateName: the title in the frame's colour (styles + // merged into it), a new line and the description. + let coloured = text_of(&d.title).with_color(color); + let mut component = coloured.component(); + if let Some(o) = component.as_object_mut() { + o.insert( + "extra".into(), + serde_json::json!(["\n", text_of(&d.description).component()]), + ); + } + let tooltip = coloured .append("\n") - .append(text_of(&d.description)); + .append(text_of(&d.description)) + .with_component(component); let title = text_of(&d.title).with_style(&Style { hover: Some(Box::new(tooltip)), ..Style::default() }); - Text::literal("[") - .append(title) - .append("]") - .with_color(color) + Text::translate("chat.square_brackets", &[title]).with_color(color) } impl Game<'_> { /// `AdvancementCommands.Action.GRANT` on one advancement (or one of diff --git a/crates/horizon-client/src/game/advancements_screen.rs b/crates/horizon-client/src/game/advancements_screen.rs index 759588887..211bab362 100644 --- a/crates/horizon-client/src/game/advancements_screen.rs +++ b/crates/horizon-client/src/game/advancements_screen.rs @@ -269,7 +269,7 @@ impl Game<'_> { } /// `AdvancementWidget`'s title lines, description lines and width. fn adv_widget_text(&self, i: usize) -> (Vec, Vec, f32) { - let font = &self.atlas.font; + let font = &self.gui.atlas.font; let a = &self.adv.tree.list[i]; let Some(d) = &a.display else { return (Vec::new(), Vec::new(), 0.0); @@ -332,7 +332,7 @@ impl Game<'_> { let (sx, sy) = self.adv_ui.scroll.unwrap_or_default(); let (sx, sy) = (sx.floor() as i32, sy.floor() as i32); self.adv_tick_hover(&view, sx, sy, left, top); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); let title = Text::translate("gui.advancements", &[]); let tw = atlas.font.width_text(&title); @@ -444,7 +444,7 @@ impl Game<'_> { } let (x, y) = pos(i); let (x, y) = ((ox + x) as f32, (oy + y) as f32); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; batch.sprite_scaled( atlas, frame_sprite(d.frame, done), @@ -461,7 +461,7 @@ impl Game<'_> { } } // The window, tabs and title. - let atlas = &self.atlas; + let atlas = &self.gui.atlas; batch.sprite_region( atlas, "gui/advancements/window", @@ -475,7 +475,7 @@ impl Game<'_> { let (x, y) = tab_pos(ty, i); let sprite = tab_sprite(ty, i, ty.3, Some(t) == tab); batch.sprite_scaled( - &self.atlas, + &self.gui.atlas, &sprite, left + x, top + y, @@ -494,7 +494,7 @@ impl Game<'_> { } } } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let title = tab.and_then(|t| tree.list[t].display.as_ref()).map_or_else( || Text::translate("gui.advancements", &[]), |d| text_of(&d.title), @@ -509,7 +509,7 @@ impl Game<'_> { } } // Done. - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (bx, by) = ((w / 2.0 - 100.0).floor(), h - FOOTER + 6.0); let hover = ui::hovered(self.cursor, bx, by, 200.0, 20.0); ui::button( @@ -532,7 +532,7 @@ impl Game<'_> { let (cx, cy) = self.cursor; if cx > x && cx < x + ty.1 && cy > y && cy < y + ty.2 { if let Some(d) = &tree.list[t].display { - ui::tooltip(batch, &self.atlas, &[text_of(&d.title)], self.cursor); + ui::tooltip(batch, &self.gui.atlas, &[text_of(&d.title)], self.cursor); } break; } @@ -616,7 +616,7 @@ impl Game<'_> { ], ) }); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let progress_w = progress.as_ref().map_or(0.0, |t| atlas.font.width_text(t)) as i32; let top_side = title_bottom + desc_h >= INSIDE_H; let amount = if a.criteria.is_empty() || total == 0 { diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 8e956373e..5d7d294dd 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -4,7 +4,13 @@ //! take time run as a task advanced every frame and reply when they finish or //! time out, so `horizon-ctl break 10 64 3` returns what the block dropped. use super::{Game, Screen}; -use horizon_client::{Result, block_entity_anim::Ticker, items::ItemStack, widgets}; +use horizon_client::{ + Result, + block_entity_anim::Ticker, + chunk::{MIN_Y, SECTIONS}, + items::ItemStack, + widgets, +}; use horizon_core::geometry::Vec3; use horizon_world::registry::BlockStateId; use serde_json::{Value, json}; @@ -27,6 +33,7 @@ pub(super) const HELP: &[&str] = &[ "entities [RADIUS] [TYPE] mobs, dropped items and orbs near the player, nearest first", "block X Y Z the block state at a position", "blocks X1 Y1 Z1 X2 Y2 Z2 the non-air blocks of a box (at most 32768 blocks)", + "light X1 Y1 Z1 X2 Y2 Z2 the stored sky and block light of a box (at most 32768 blocks)", "find-block BLOCK [RADIUS] the nearest loaded blocks of a kind (default radius 32)", "inventory hotbar, main inventory, armor, offhand and carried stack", "screen the open screen or menu, its slots and its buttons", @@ -318,7 +325,7 @@ impl Game<'_> { let state = self.world.block(pos[0], pos[1], pos[2]); let mut v = json!({ "pos": pos, - "block": &*self.res.facts.get(state).name, + "block": &*self.res.facts().get(state).name, "state": self.state_string(state), "loaded": self.world.chunks.contains_key(&(pos[0] >> 4, pos[2] >> 4)), }); @@ -466,6 +473,12 @@ impl Game<'_> { }), "dimension": self.dim.id(), "gamemode": format!("{:?}", self.mode).to_lowercase(), + // The bed (its head) the player sleeps in. + "sleeping": self.sleeping, + // The item in use: its slot and for how many ticks. + "using": self.using.map(|(slot, ticks)| json!({ "slot": slot, "ticks": ticks })), + // The arm swings started (LivingEntity.swing). + "swings": self.swings_started, "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, @@ -568,7 +581,7 @@ impl Game<'_> { push( [m.position.x, m.position.y, m.position.z], m.kind.id.as_ref(), - json!({ "id": m.id, "kind": "mob", "health": m.health, "baby": m.is_baby() }), + json!({ "id": m.id, "kind": "mob", "health": m.health, "baby": m.is_baby(), "hurt_time": m.hurt_time }), ); } for item in &self.dropped { @@ -666,17 +679,25 @@ impl Game<'_> { /// Whether a block stops movement, for the path finder. fn blocks_motion(&self, pos: [i32; 3]) -> bool { - let f = self.res.facts.get(self.world.block(pos[0], pos[1], pos[2])); + let f = self + .res + .facts() + .get(self.world.block(pos[0], pos[1], pos[2])); f.full_collision || f.legacy_solid } fn walkable(&self, n: Node) -> bool { let below = self.world.block(n[0], n[1] - 1, n[2]); let lava = |p: [i32; 3]| { - &*self.res.facts.get(self.world.block(p[0], p[1], p[2])).name == "minecraft:lava" + &*self + .res + .facts() + .get(self.world.block(p[0], p[1], p[2])) + .name + == "minecraft:lava" }; self.world.chunks.contains_key(&(n[0] >> 4, n[2] >> 4)) && (self.blocks_motion([n[0], n[1] - 1, n[2]]) - || self.res.facts.get(below).fluid != horizon_client::blocks::Fluid::None) + || self.res.facts().get(below).fluid != horizon_client::blocks::Fluid::None) && !self.blocks_motion(n) && !self.blocks_motion([n[0], n[1] + 1, n[2]]) && !lava(n) @@ -737,7 +758,11 @@ impl Game<'_> { if !clear || !self.walkable(m) { continue; } - let water = self.res.facts.get(self.world.block(m[0], m[1], m[2])).fluid + let water = self + .res + .facts() + .get(self.world.block(m[0], m[1], m[2])) + .fluid != horizon_client::blocks::Fluid::None; let step = 10 + if dy != 0 { 5 } else { 0 } + if water { 30 } else { 0 }; let c = base + step; @@ -947,10 +972,10 @@ impl Game<'_> { for z in lo[2]..=hi[2] { for x in lo[0]..=hi[0] { let state = self.world.block(x, y, z); - if self.res.facts.is_air(state) { + if self.res.facts().is_air(state) { continue; } - let name = self.res.facts.get(state).name.to_string(); + let name = self.res.facts().get(state).name.to_string(); *census.entry(name).or_insert(0) += 1; list.push(json!([x, y, z, self.state_string(state)])); } @@ -958,6 +983,35 @@ impl Game<'_> { } ok(json!({ "from": lo, "to": hi, "counts": census, "blocks": list })) } + "light" => { + self.need_world()?; + let (p, q) = (a.block_pos(0)?, a.block_pos(3)?); + let lo = [0, 1, 2].map(|i| p[i].min(q[i])); + let hi = [0, 1, 2].map(|i| p[i].max(q[i])); + let volume: i64 = (0..3).map(|i| i64::from(hi[i] - lo[i] + 1)).product(); + if volume > 32768 { + return Err(format!("{volume} blocks; at most 32768 per request").into()); + } + // One hex digit per block, x fastest, then z, then y; `.` + // outside the loaded chunks. + let (mut sky, mut block) = (String::new(), String::new()); + for y in lo[1]..=hi[1] { + for z in lo[2]..=hi[2] { + for x in lo[0]..=hi[0] { + let packed = self + .world + .chunks + .get(&(x >> 4, z >> 4)) + .filter(|_| (MIN_Y..MIN_Y + SECTIONS as i32 * 16).contains(&y)) + .map(|c| c.light(x & 15, y, z & 15)); + let digit = |v: u8| char::from_digit(u32::from(v), 16).unwrap_or('.'); + sky.push(packed.map_or('.', |v| digit(v >> 4))); + block.push(packed.map_or('.', |v| digit(v & 15))); + } + } + } + ok(json!({ "from": lo, "to": hi, "sky": sky, "block": block })) + } "find-block" => { self.need_world()?; let want = namespaced(a.get(0, "BLOCK")?); @@ -973,7 +1027,7 @@ impl Game<'_> { for z in c[2] - radius..=c[2] + radius { for x in c[0] - radius..=c[0] + radius { let state = self.world.block(x, y, z); - if *self.res.facts.get(state).name == *want { + if *self.res.facts().get(state).name == *want { let d = dist(eye, [x, y, z].map(|v| f64::from(v) + 0.5)); found.push((d, [x, y, z])); } @@ -1181,7 +1235,7 @@ impl Game<'_> { self.playing()?; let pos = a.block_pos(0)?; let before = self.world.block(pos[0], pos[1], pos[2]); - if self.res.facts.is_air(before) { + if self.res.facts().is_air(before) { return Err(format!("there is no block at {pos:?}").into()); } self.aim_block(pos, None)?; @@ -1210,24 +1264,24 @@ impl Game<'_> { .ok_or("nothing in hand to place; select an item")?; let held = held.item.clone(); let before = self.world.block(pos[0], pos[1], pos[2]); - if !self.res.facts.get(before).replaceable && !self.res.facts.is_air(before) { + if !self.res.facts().get(before).replaceable && !self.res.facts().is_air(before) { return Err(format!( "{pos:?} holds {}; break it first", - self.res.facts.get(before).name + self.res.facts().get(before).name ) .into()); } // A replaceable block there (grass, snow) is clicked itself, as // a player would; otherwise the face of a neighbour touching it. - let mut aimed = !self.res.facts.is_air(before) - && !self.res.facts.get(before).outline.is_empty() + let mut aimed = !self.res.facts().is_air(before) + && !self.res.facts().get(before).outline.is_empty() && self.aim_block(pos, None).is_ok(); for (_, d) in FACES.iter().filter(|_| !aimed) { let d = *d; let support = add(pos, d); let state = self.world.block(support[0], support[1], support[2]); - let f = self.res.facts.get(state); - if self.res.facts.is_air(state) + let f = self.res.facts().get(state); + if self.res.facts().is_air(state) || f.replaceable || f.fluid != horizon_client::blocks::Fluid::None && !f.waterlogged { @@ -1494,6 +1548,13 @@ impl Game<'_> { return Err("command TEXT".into()); } let command = format!("/{text}"); + // Single player's console is its server thread's. + if let Some(server) = &self.integrated { + let chat = server + .call(move |g| g.owner_console_command(&command)) + .ok_or("the integrated server stopped")?; + return ok(json!({ "ok": true, "chat": chat })); + } if self.remote.is_some() { self.send_chat(&command); return ok(json!({ "ok": true })); @@ -1893,7 +1954,10 @@ impl Game<'_> { // Step up onto the next block, or out of water. let in_water = { let b = p.map(|v| v.floor() as i32); - self.res.facts.get(self.world.block(b[0], b[1], b[2])).fluid + self.res + .facts() + .get(self.world.block(b[0], b[1], b[2])) + .fluid != horizon_client::blocks::Fluid::None }; if aim[1] > p[1] + 0.5 && horizontal(p, aim) < 1.6 && on_ground { diff --git a/crates/horizon-client/src/game/allays.rs b/crates/horizon-client/src/game/allays.rs index a2a5842b5..52dfa7e1c 100644 --- a/crates/horizon-client/src/game/allays.rs +++ b/crates/horizon-client/src/game/allays.rs @@ -29,7 +29,11 @@ impl Game<'_> { continue; }; let carried = self.mobs[i].extra.ints[1]; - let max = self.res.items.get(&held).map_or(64, |i| i.max_stack as i32); + let max = self + .res + .items() + .get(&held) + .map_or(64, |i| i.max_stack as i32); // GoToWantedItem / wantsToPickUp: the same item within 32. let wanted = if griefing && carried < max && self.mobs[i].extra.ints[3] <= 0 { self.dropped diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index 80e42169d..6ff5c7c15 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -111,7 +111,12 @@ impl Game<'_> { let Some(item) = item else { continue; }; - let Some(asset) = self.res.items.get(item).and_then(|i| i.equip_asset.clone()) else { + let Some(asset) = self + .res + .items() + .get(item) + .and_then(|i| i.equip_asset.clone()) + else { continue; }; let kind = if layer == "leggings" { @@ -124,7 +129,7 @@ impl Game<'_> { continue; }; let (Some(r), Some(part)) = ( - self.atlas.sprites.get(texture.as_str()), + self.gui.atlas.sprites.get(texture.as_str()), assets.player.get(layer), ) else { continue; @@ -144,7 +149,7 @@ impl Game<'_> { // BlockPlaceContext: a replaceable clicked block is replaced. let clicked = self .res - .facts + .facts() .get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2])); let pos = if clicked.replaceable { hit.pos @@ -230,7 +235,7 @@ impl Game<'_> { fn equipment_slot(&self, stack: &ItemStack) -> usize { match self .res - .items + .items() .get(&stack.item) .and_then(|i| i.equip_slot.as_deref()) { @@ -379,7 +384,7 @@ impl Game<'_> { let mut dead = Vec::new(); for (i, a) in self.armor_stands.iter_mut().enumerate() { a.tick(&mut scene); - if !a.environment_tick(&self.world, &self.res.facts, self.pack.assets.registry) { + if !a.environment_tick(&self.world, self.res.facts(), self.pack.assets.registry) { dead.push(i); } } @@ -403,7 +408,7 @@ impl Game<'_> { out: &mut Vec, ) { let assets = &self.armor_stand_assets; - let sprites = &self.atlas.sprites; + let sprites = &self.gui.atlas.sprites; let uv_of = |name: &str| sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); let Some(wood) = uv_of("entity/armorstand/armorstand") else { return; @@ -413,6 +418,32 @@ impl Game<'_> { if a.invisible { continue; } + // ArmorStand.shouldRenderAtSqrDistance: 256 times the box's mean + // edge (4 for a marker's empty box), whatever the entity distance. + // LivingEntityRenderer grows the culling box by 0.5 for a dragon head. + let (width, height) = match (a.marker, a.small) { + (true, _) => (0.0, 0.0), + (false, true) => (0.25, 0.9875), + (false, false) => (0.5, 1.975), + }; + let edge = (width + height + width) / 3.0 * 4.0; + let range = if edge == 0.0 { 4.0 } else { edge } * 64.0; + let dragon = a.equipment[5] + .as_ref() + .is_some_and(|i| &*i.item == "minecraft:dragon_head"); + let position = super::entity_culling::at(a.position); + if !self.standing_entity_in_view( + camera, + position, + position, + alpha, + width, + height, + range, + if dragon { 0.5 } else { 0.0 }, + ) { + continue; + } let Some(model) = (if a.small { &assets.small } else { &assets.main }) else { continue; }; @@ -490,7 +521,7 @@ impl Game<'_> { }; let Some(asset) = self .res - .items + .items() .get(&stack.item) .and_then(|i| i.equip_asset.clone()) else { @@ -542,7 +573,7 @@ impl Game<'_> { /// `Equippable.swapWithEquipmentSlot`: right-clicking armor swaps it into /// its slot (the worn piece comes back to the hand). pub(super) fn equip_from_hand(&mut self, stack: &ItemStack) -> bool { - let Some(info) = self.res.items.get(&stack.item) else { + let Some(info) = self.res.items().get(&stack.item) else { return false; }; let index = match info.equip_slot.as_deref() { @@ -673,7 +704,7 @@ impl Game<'_> { &serde_json::Value::Null, false, pose, - &self.atlas.sprites, + &self.gui.atlas.sprites, &self.item_host(), &mut sink, ); @@ -683,7 +714,7 @@ impl Game<'_> { if let Some(stack) = &a.equipment[5] && self .res - .items + .items() .get(&stack.item) .is_none_or(|i| i.equip_asset.is_none()) && let Some(head) = part_matrix(model, base, poses, "head", 0.0) diff --git a/crates/horizon-client/src/game/backdrop.rs b/crates/horizon-client/src/game/backdrop.rs index 149cddefa..3a5ec81d6 100644 --- a/crates/horizon-client/src/game/backdrop.rs +++ b/crates/horizon-client/src/game/backdrop.rs @@ -71,8 +71,10 @@ impl Game<'_> { } /// Called every frame while the title is up. pub(super) fn update_backdrop(&mut self) -> Result<()> { - let wanted = self.title.is_some() + let wanted = self.pending_entry.is_none() + && self.title.is_some() && horizon_client::ui_theme::horizon() + && self.world_renderer_ready && self.renderer.is_some() && self.options.frames.is_none(); if !wanted { @@ -127,6 +129,10 @@ impl Game<'_> { .is_some_and(|r| r.section_count() > 40) { self.backdrop.ready = Some(Instant::now()); + log::info!( + "Horizon: title backdrop ready; world rest ready: {}", + self.res.rest.get().is_some() + ); } Ok(()) } @@ -139,10 +145,14 @@ impl Game<'_> { } } fn surface_y(&self, x: i32, z: i32) -> Option { - let air = self.res.facts.air; + let air = self.res.facts().air; (-60..320).rev().find(|&y| self.world.block(x, y, z) != air) } fn start_backdrop(&mut self) -> Result<()> { + log::info!( + "Horizon: starting title backdrop after {} ms", + self.started.elapsed().as_millis() + ); let seed = seed(); let root = std::env::current_dir()? .join("saves") @@ -155,7 +165,7 @@ impl Game<'_> { VanillaTerrain::new( &self.options.resources.join("worldgen"), pack.assets.registry, - &res.biomes, + res.biomes(), seed, ) .map_err(|e| format!("title backdrop: {e}"))?, @@ -165,10 +175,10 @@ impl Game<'_> { inner: inner.clone(), save: save.clone(), registry: pack.assets.clone(), - biomes: res.biomes.clone(), + biomes: res.biomes().clone(), }), pack.context.clone(), - res.threads.min(6), + res.threads().min(6), ); streaming.radius = self.settings.render_distance.clamp(4, 10); streaming.biome_blend = self.settings.biome_blend; @@ -179,7 +189,7 @@ impl Game<'_> { streaming.paused = true; self.streaming = streaming; self.save = save; - let mut world = World::new(self.res.facts.air, seed); + let mut world = World::new(self.res.facts().air, seed); world.day_time = DAY_TIME; world.game_time = 6000; // Light snow: the weather renders as snow in frozen biomes. @@ -237,7 +247,7 @@ impl Game<'_> { } fn stop_backdrop(&mut self) { self.streaming.paused = true; - self.world = World::new(self.res.facts.air, 0); + self.world = World::new(self.res.facts().air, 0); if let Some(r) = self.renderer.as_mut() { r.clear_sections(); } diff --git a/crates/horizon-client/src/game/banners.rs b/crates/horizon-client/src/game/banners.rs index 6875fcb7f..05beda3f8 100644 --- a/crates/horizon-client/src/game/banners.rs +++ b/crates/horizon-client/src/game/banners.rs @@ -14,7 +14,7 @@ impl Game<'_> { else { return Vec::new(); }; - layer_textures(&self.res.stations.banners, &b.layers) + layer_textures(&self.res.stations().banners, &b.layers) } } diff --git a/crates/horizon-client/src/game/beacon.rs b/crates/horizon-client/src/game/beacon.rs index c8c437965..79cf14541 100644 --- a/crates/horizon-client/src/game/beacon.rs +++ b/crates/horizon-client/src/game/beacon.rs @@ -99,30 +99,16 @@ impl Game<'_> { } /// `getHeight(WORLD_SURFACE)`: above the highest non-air block. pub(super) fn world_surface(&self, x: i32, z: i32) -> i32 { - let (min, max) = (super::MIN_Y, super::MIN_Y + super::HEIGHT); - (min..max) - .rev() - .find(|&y| !self.res.facts.is_air(self.world.block(x, y, z))) - .map_or(min, |y| y + 1) + self.world + .world_surface(x, z, |id| self.res.facts().is_air(id)) } - /// `BeaconBlockEntity.tick` for every beacon. - pub(super) fn tick_beacons(&mut self) { - let keys: Vec<(i32, i32, i32)> = self - .world - .block_entities - .iter() - .filter(|(_, e)| matches!(e, BlockEntity::Beacon(_))) - .map(|(k, _)| *k) - .collect(); - for key in keys { - let Some(BlockEntity::Beacon(mut b)) = self.world.block_entities.remove(&key) else { - continue; - }; - self.tick_beacon(key, &mut b); - self.world - .block_entities - .insert(key, BlockEntity::Beacon(b)); - } + /// `BeaconBlockEntity.tick` of the beacon at `key`. + pub(super) fn tick_beacon_at(&mut self, key: (i32, i32, i32)) { + let Some(BlockEntity::Beacon(mut b)) = self.world.block_entities.take(&key) else { + return; + }; + self.tick_beacon(key, &mut b); + self.world.block_entities.put(key, BlockEntity::Beacon(b)); } fn tick_beacon(&mut self, (x, y, z): (i32, i32, i32), b: &mut Beacon) { let mut check = if b.last_check_y < y { @@ -136,7 +122,7 @@ impl Game<'_> { let mut i = 0; while i < 10 && check <= surface { let state = self.world.block(x, check, z); - let f = self.res.facts.get(state); + let f = self.res.facts().get(state); if let Some(color) = self.beam_color(&f.name) { if b.checking.len() <= 1 { b.checking.push((color, 1)); @@ -197,7 +183,7 @@ impl Game<'_> { fn beacon_base(&self, x: i32, y: i32, z: i32) -> i32 { let base = self .res - .items + .items() .block_tags .get("minecraft:beacon_base_blocks"); let mut levels = 0; @@ -208,7 +194,7 @@ impl Game<'_> { } let ok = (x - step..=x + step).all(|lx| { (z - step..=z + step).all(|lz| { - let name = &self.res.facts.get(self.world.block(lx, ly, lz)).name; + let name = &self.res.facts().get(self.world.block(lx, ly, lz)).name; base.is_some_and(|t| t.contains(&**name)) }) }); @@ -389,7 +375,7 @@ impl Game<'_> { let levels = self.beacon_levels(); let sel = self.station.as_ref().map_or([None; 2], |s| s.beacon); let paid = self.station.as_ref().is_some_and(|s| s.inputs[0].is_some()); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; batch.fill( atlas, 0.0, @@ -410,7 +396,7 @@ impl Game<'_> { ("block.minecraft.beacon.secondary", "Secondary Power", 169.0), ] { let text = self.translate(key, fallback); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let w = HudBatch::text_width(atlas, &text); batch.text( atlas, @@ -425,7 +411,7 @@ impl Game<'_> { let x = [20.0, 41.0, 63.0, 86.0, 108.0][i]; self.draw_item(batch, &ItemStack::new(item, 1), bx + x, by + 109.0); } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let mut tooltip = None; let button = |batch: &mut HudBatch, x: f32, y: f32, active: bool, selected: bool, icon: &str| { @@ -507,7 +493,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); batch.fill( - &self.atlas, + &self.gui.atlas, ox + sx, oy + sy, 16.0, @@ -528,7 +514,13 @@ impl Game<'_> { } /// `BeaconRenderer`: each section's rotating solid beam and its glow. pub(super) fn beacon_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { - let Some(s) = self.atlas.sprites.get("entity/beacon/beacon_beam").copied() else { + let Some(s) = self + .gui + .atlas + .sprites + .get("entity/beacon/beacon_beam") + .copied() + else { return; }; let time = (self.world.game_time.rem_euclid(40)) as f32 + alpha as f32; diff --git a/crates/horizon-client/src/game/beehives.rs b/crates/horizon-client/src/game/beehives.rs index 0520e4367..b7f7efb1a 100644 --- a/crates/horizon-client/src/game/beehives.rs +++ b/crates/horizon-client/src/game/beehives.rs @@ -41,7 +41,7 @@ impl HiveHost for GameHive<'_, '_> { if !self .game .res - .mob_data + .mob_data() .entity_has("minecraft:beehive_inhabitors", &kind) { return None; @@ -72,10 +72,10 @@ impl Game<'_> { /// The hive's honey level and front, from its block state. pub(super) fn hive_state(&self, at: [i32; 3]) -> Option<(Option, [i32; 2])> { let state = self.world.block(at[0], at[1], at[2]); - let name = &self.res.facts.get(state).name; + let name = &self.res.facts().get(state).name; if !self .res - .items + .items() .block_tags .get("minecraft:beehives") .is_some_and(|t| t.contains(&**name)) @@ -87,48 +87,37 @@ impl Game<'_> { let facing = beehive::facing_step(props.get("facing").map(String::as_str)); Some((honey, facing)) } - /// `BeehiveBlockEntity.serverTick` for every hive, after an emergency - /// exit for those with fire beside them (`BeehiveBlock.updateShape`). - pub(super) fn tick_beehives(&mut self) { - let mut keys: Vec<(i32, i32, i32)> = self - .world - .block_entities - .iter() - .filter(|(_, e)| matches!(e, BlockEntity::Beehive(_))) - .map(|(k, _)| *k) - .collect(); - keys.sort_unstable(); - for key in keys { - let at = [key.0, key.1, key.2]; - let Some((honey, facing)) = self.hive_state(at) else { - continue; - }; - let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key) - else { - continue; - }; - let fire = [ - [1, 0, 0], - [-1, 0, 0], - [0, 1, 0], - [0, -1, 0], - [0, 0, 1], - [0, 0, -1], - ] - .iter() - .any(|d| { - let state = self.world.block(at[0] + d[0], at[1] + d[1], at[2] + d[2]); - &*self.res.facts.get(state).name == "minecraft:fire" - }); - let mut host = GameHive { game: self }; - if fire && !hive.bees.is_empty() { - hive.release_all(at, facing, honey, Release::Emergency, &mut host); - } - hive.server_tick(at, facing, honey, &mut host); - self.world - .block_entities - .insert(key, BlockEntity::Beehive(hive)); + /// `BeehiveBlockEntity.serverTick` of the hive at `key`, after an + /// emergency exit if fire is beside it (`BeehiveBlock.updateShape`). + pub(super) fn tick_beehive(&mut self, key: (i32, i32, i32)) { + let at = [key.0, key.1, key.2]; + let Some((honey, facing)) = self.hive_state(at) else { + return; + }; + let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.take(&key) else { + return; + }; + let fire = [ + [1, 0, 0], + [-1, 0, 0], + [0, 1, 0], + [0, -1, 0], + [0, 0, 1], + [0, 0, -1], + ] + .iter() + .any(|d| { + let state = self.world.block(at[0] + d[0], at[1] + d[1], at[2] + d[2]); + &*self.res.facts().get(state).name == "minecraft:fire" + }); + let mut host = GameHive { game: self }; + if fire && !hive.bees.is_empty() { + hive.release_all(at, facing, honey, Release::Emergency, &mut host); } + hive.server_tick(at, facing, honey, &mut host); + self.world + .block_entities + .put(key, BlockEntity::Beehive(hive)); } /// `BeehiveBlockEntity.addOccupant` for a bee its `BeeEnterHiveGoal` /// sent in: off its lead, its tag stored, the bee gone. @@ -152,13 +141,13 @@ impl Game<'_> { self.mobs[i].extra.mount = None; let tag = self.mob_tree_nbt(i); let flower = bee::get(&self.mobs[i]).and_then(|b| b.flower); - let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key) else { + let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.take(&key) else { return; }; let stored = hive.add_occupant(at, tag, flower, &mut GameHive { game: self }); self.world .block_entities - .insert(key, BlockEntity::Beehive(hive)); + .put(key, BlockEntity::Beehive(hive)); if stored && let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { m.removed = true; } @@ -166,13 +155,13 @@ impl Game<'_> { /// `BeehiveBlockEntity.emptyAllLivingFromHive` with no player about. pub(super) fn empty_hive(&mut self, at: [i32; 3], facing: [i32; 2], status: Release) { let key = (at[0], at[1], at[2]); - let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key) else { + let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.take(&key) else { return; }; hive.release_all(at, facing, None, status, &mut GameHive { game: self }); self.world .block_entities - .insert(key, BlockEntity::Beehive(hive)); + .put(key, BlockEntity::Beehive(hive)); } /// `BeehiveBlock.playerDestroy` without silk touch: the bees come out /// angry at the player unless smoke calms them, then diff --git a/crates/horizon-client/src/game/block_entity_anims.rs b/crates/horizon-client/src/game/block_entity_anims.rs index d377aeb45..619fcd009 100644 --- a/crates/horizon-client/src/game/block_entity_anims.rs +++ b/crates/horizon-client/src/game/block_entity_anims.rs @@ -13,7 +13,6 @@ use horizon_client::{ }; use horizon_core::geometry::{Aabb, Vec3}; use horizon_world::nbt::Tag; -use std::collections::HashMap; /// The handle of the local player among a bell's gathered entities. const PLAYER: u64 = u64::MAX; @@ -174,18 +173,27 @@ impl Game<'_> { let Some(r) = &self.renderer else { return; }; - let present: HashMap<[i32; 3], Ticker> = r - .block_entities() - .filter_map(|(p, s)| Some((*p, self.be_anims.ticker(*s)?))) - .collect(); - self.be_anims.retain_present(&present); + // Sorted by position: the order they tick in, and a quick lookup. + // Read again only when the drawn block entities changed. + let revision = r.block_entity_revision(); + if self.be_anims.present_revision != Some(revision) { + let mut present: Vec<([i32; 3], Ticker)> = r + .block_entities() + .filter_map(|(p, s)| Some((*p, self.be_anims.ticker(*s)?))) + .collect(); + present.sort_unstable_by_key(|(p, _)| *p); + self.be_anims.retain_present(&present); + self.be_anims.present = present; + self.be_anims.present_revision = Some(revision); + } + let positions = std::mem::take(&mut self.be_anims.present); let players: Vec<[f64; 3]> = match &self.player { Some(p) if !self.spectator() => vec![[p.position.x, p.position.y, p.position.z]], _ => Vec::new(), }; let raiders = self .res - .stations + .stations() .enchantments .entity_tags .get("minecraft:raiders") @@ -193,14 +201,12 @@ impl Game<'_> { .unwrap_or_default(); let frames = self .res - .items + .items() .block_tags .get("minecraft:conduit_effect_block") .cloned() .unwrap_or_default(); - let mut positions: Vec<([i32; 3], Ticker)> = present.into_iter().collect(); - positions.sort_unstable_by_key(|(p, _)| *p); - for (pos, ticker) in positions { + for &(pos, ticker) in &positions { match ticker { Ticker::Lid => self.be_anims.chests.entry(pos).or_default().tick(), Ticker::Book => { @@ -279,7 +285,7 @@ impl Game<'_> { } Ticker::Conduit => { let world = &self.world; - let facts = &self.res.facts; + let facts = self.res.facts(); let registry = self.pack.assets.registry; let is_water = |p: [i32; 3]| { facts.get(world.block(p[0], p[1], p[2])).fluid @@ -322,6 +328,7 @@ impl Game<'_> { } } } + self.be_anims.present = positions; } /// `EndGatewayBlock.entityInside` on the server: whether the gateway at /// `pos` let the entity in (`triggerCooldown`, with its block event). @@ -365,7 +372,7 @@ impl Game<'_> { /// pot's saved `sherds` (back, left, right, front). pub(super) fn block_anim(&self, pos: [i32; 3], partial: f32) -> BlockAnim { let state = self.world.block(pos[0], pos[1], pos[2]); - let sherds = if &*self.res.facts.get(state).name == "minecraft:decorated_pot" { + let sherds = if &*self.res.facts().get(state).name == "minecraft:decorated_pot" { let sherds = self.saved_tag(pos).and_then(|t| t.get("sherds")); ["back", "left", "right", "front"].map(|side| match sherds.and_then(|s| s.get(side)) { // An item id, or the item stack the processed templates hold. diff --git a/crates/horizon-client/src/game/block_entity_ticks.rs b/crates/horizon-client/src/game/block_entity_ticks.rs new file mode 100644 index 000000000..bb1cadd15 --- /dev/null +++ b/crates/horizon-client/src/game/block_entity_ticks.rs @@ -0,0 +1,131 @@ +//! `Level.tickBlockEntities` for the block entities ticked together here +//! (hoppers, crafters, jukeboxes, beacons, creaking hearts, spawners, trial +//! spawners, vaults, beehives and furnaces): only those whose state has a +//! ticker, in vanilla's list order (`horizon_client::block_entities`), in +//! chunks that tick blocks. Sculk, brewing stands and pistons tick in their +//! own passes. +use super::Game; +use horizon_client::{ + Result, + block_entities::{Pos, Ticking}, + containers::{BlockEntity, FurnaceKind, HOPPER_SLOTS}, +}; +use horizon_world::registry::BlockStateId; + +impl Game<'_> { + pub(super) fn tick_block_entities(&mut self) -> Result<()> { + self.tick_mount_menu(); + self.load_entity_types(); + if !self.world.block_entities.has_states() { + let states = self.ticking_states(); + self.world.block_entities.set_states(states); + } + self.forget_gone_hoppers(); + let ticking = self.block_ticking_area(); + let mut spawners = Vec::new(); + let mut trial_spawners = Vec::new(); + for slot in self.world.block_entity_tickers() { + let pos = slot.0; + // Ticks before this one can remove it (`TickingBlockEntity.isRemoved`). + if !self.world.block_entities.is_live(slot) + || !ticking(pos.0, pos.2) + || !self.border.contains(f64::from(pos.0), f64::from(pos.2)) + { + continue; + } + match self.world.block_entities.get(&pos) { + Some(BlockEntity::Chest(items)) if items.len() == HOPPER_SLOTS => { + self.tick_hopper(pos) + } + Some(BlockEntity::Crafter(_)) => self.tick_crafter(pos), + Some(BlockEntity::Jukebox(_)) => self.tick_jukebox(pos), + Some(BlockEntity::Beacon(_)) => self.tick_beacon_at(pos), + Some(BlockEntity::CreakingHeart(_)) => self.tick_creaking_heart(pos)?, + Some(BlockEntity::Spawner(_)) => { + self.tick_spawner(pos)?; + spawners.push(pos); + } + Some(BlockEntity::TrialSpawner(_)) => { + self.tick_trial_spawner(pos)?; + trial_spawners.push(pos); + } + Some(BlockEntity::Vault(_)) => self.tick_vault(pos)?, + Some(BlockEntity::Beehive(_)) => self.tick_beehive(pos), + Some(BlockEntity::Furnace(_)) => self.tick_furnace(pos)?, + Some(BlockEntity::Brewing(_)) => self.tick_brewing_stand(pos)?, + _ => {} + } + } + self.update_song_volumes(); + self.scan_for_hearts(); + // The client ticks (particles, sounds, the turning mob) are for a + // window; a dedicated or integrated server has none. + if self.options.dedicated.is_none() { + self.client_tick_spawners(&spawners); + for key in trial_spawners { + self.client_tick_trial_spawner(key); + } + } + Ok(()) + } + /// `BlockState.getTicker` of every state, for the block entities ticked + /// here. A creaking heart keeps its slot while uprooted (see + /// `tick_creaking_heart`). + fn ticking_states(&self) -> Vec { + let registry = self.pack.assets.registry; + (0..registry.len()) + .map(|i| { + let state = BlockStateId(i as u32); + let name: &str = &self.res.facts().get(state).name; + match name { + "minecraft:hopper" + | "minecraft:crafter" + | "minecraft:beacon" + | "minecraft:creaking_heart" + | "minecraft:spawner" + | "minecraft:trial_spawner" + | "minecraft:vault" + | "minecraft:beehive" + | "minecraft:bee_nest" + | "minecraft:brewing_stand" => Ticking::Yes, + "minecraft:jukebox" => { + let record = registry + .state(state) + .and_then(|s| s.properties.get("has_record")) + .is_some_and(|v| v == "true"); + if record { Ticking::Yes } else { Ticking::Idle } + } + n if FurnaceKind::from_block(n).is_some() => Ticking::Yes, + _ => Ticking::No, + } + }) + .collect() + } + /// `ServerLevel.shouldTickBlocksAt` in a block-ticking chunk + /// (`LevelChunk.isTicking`, block coordinates), from every player's + /// tickets (`update_chunk_tickets`). + fn block_ticking_area(&self) -> impl Fn(i32, i32) -> bool + use<> { + let levels = self.tickets.levels(); + move |x, z| levels.block_ticking_at(x, z) + } + /// `AbstractFurnaceBlockEntity.serverTick` of the furnace at `pos`, and + /// its block's `lit` following it. + fn tick_furnace(&mut self, pos: Pos) -> Result<()> { + let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get_mut(&pos) else { + return Ok(()); + }; + let Some(lit) = f.tick(self.res.recipes(), self.res.items(), self.res.providers()) else { + return Ok(()); + }; + let state = self.world.block(pos.0, pos.1, pos.2); + if let Some(mut s) = self.pack.assets.registry.state(state).cloned() + && s.properties.contains_key("lit") + { + s.properties.insert("lit".into(), lit.to_string()); + if let Ok(id) = self.pack.assets.registry.resolve(&s) { + self.world.set(pos.0, pos.1, pos.2, id)?; + } + } + Ok(()) + } +} diff --git a/crates/horizon-client/src/game/block_items.rs b/crates/horizon-client/src/game/block_items.rs index b8012cce1..199c39a78 100644 --- a/crates/horizon-client/src/game/block_items.rs +++ b/crates/horizon-client/src/game/block_items.rs @@ -22,7 +22,7 @@ impl Game<'_> { let entity = self.world.block_entities.get(&key)?; let block = &self .res - .facts + .facts() .get(self.world.block(key.0, key.1, key.2)) .name; let mut tag = save::encode_block_entity(key, entity, block); @@ -37,7 +37,7 @@ impl Game<'_> { pub(super) fn picked_stack(&self, pos: [i32; 3], include_data: bool) -> Option { let key = (pos[0], pos[1], pos[2]); let state = self.world.block(pos[0], pos[1], pos[2]); - let facts = self.res.facts.get(state); + let facts = self.res.facts().get(state); if &*facts.item == "minecraft:air" { return None; } diff --git a/crates/horizon-client/src/game/blockctl.rs b/crates/horizon-client/src/game/blockctl.rs index 993e0789e..719ce8dd2 100644 --- a/crates/horizon-client/src/game/blockctl.rs +++ b/crates/horizon-client/src/game/blockctl.rs @@ -47,7 +47,7 @@ impl Game<'_> { format!("{}[{}]", s.name, props.join(",")) } fn put_block(&mut self, pos: [i32; 3], state: BlockStateId) -> Result<()> { - let name = self.res.facts.get(state).name.clone(); + let name = self.res.facts().get(state).name.clone(); self.world.block_entities.remove(&(pos[0], pos[1], pos[2])); self.level_set(pos, state)?; if let Some(entity) = BlockEntity::for_block(&name) { diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index a5a609cac..1d1a6b628 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -2,7 +2,7 @@ //! paddling controls, collisions, riding (`positionRider`, `clampRotation`, //! dismounting), `BoatItem` placement, `VehicleEntity.hurtServer` breaking, //! saving and `AbstractBoatRenderer` with animated paddles. -use super::{Game, Keys, view_vector}; +use super::{Game, Keys, entity_culling::at, view_vector}; use horizon_client::{ blocks::Fluid, collisions::SceneCollisions, @@ -180,11 +180,11 @@ impl BoatModels { } impl Game<'_> { fn fluid_height(&self, x: i32, y: i32, z: i32) -> Option<(f32, bool)> { - let f = self.res.facts.get(self.world.block(x, y, z)); + let f = self.res.facts().get(self.world.block(x, y, z)); if f.fluid != Fluid::Water { return None; } - let above = self.res.facts.get(self.world.block(x, y + 1, z)); + let above = self.res.facts().get(self.world.block(x, y + 1, z)); // FluidState.getHeight: 1 under the same fluid, else amount / 9. let height = if above.fluid == Fluid::Water { 1.0 @@ -277,7 +277,7 @@ impl Game<'_> { && f64::from(x + 1) > lo.x && f64::from(z) < hi.z && f64::from(z + 1) > lo.z; - let f = self.res.facts.get(self.world.block(x, y0, z)); + let f = self.res.facts().get(self.world.block(x, y0, z)); if inside && (f.full_collision || f.legacy_solid) && !f.has_class("LilyPadBlock") { friction += f.friction; count += 1; @@ -495,8 +495,8 @@ impl Game<'_> { ); let top = b.bounds().max_position().y; let (bx, by, bz) = (x.floor() as i32, top.floor() as i32, z.floor() as i32); - let below = self.res.facts.get(self.world.block(bx, by - 1, bz)); - let here = self.res.facts.get(self.world.block(bx, by, bz)); + let below = self.res.facts().get(self.world.block(bx, by - 1, bz)); + let here = self.res.facts().get(self.world.block(bx, by, bz)); let target = if below.fluid != Fluid::Water && !here.full_collision && (below.full_collision || below.legacy_solid) @@ -700,8 +700,19 @@ impl Game<'_> { /// AbstractBoatRenderer. pub(super) fn boat_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let a = alpha as f32; + let range = super::entity_culling::default_range( + glam::DVec3::new(WIDTH, HEIGHT, WIDTH), + self.settings.entity_distance, + ); for b in &self.boats { let entity_start = out.len(); + // EntityRenderer.shouldRender. + let (previous, position) = (at(b.previous), at(b.position)); + if !self.standing_entity_in_view( + camera, previous, position, alpha, WIDTH, HEIGHT, range, 0.0, + ) { + continue; + } let models = if b.chest { &self.boat_models.chest_models } else { @@ -712,6 +723,7 @@ impl Game<'_> { }; let folder = if b.chest { "chest_boat" } else { "boat" }; let Some(uv) = self + .gui .atlas .sprites .get(&format!("entity/{folder}/{}", b.wood)) diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index 5603e8369..8745c6f35 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -45,7 +45,7 @@ pub(super) enum BookScreen { } impl Game<'_> { fn book_lines(&self, page: &str) -> Vec { - self.atlas.font.split(&Text::literal(page), 114.0) + self.gui.atlas.font.split(&Text::literal(page), 114.0) } /// `WritableBookItem.use` / `WrittenBookItem.use`. pub(super) fn use_book(&mut self, stack: &ItemStack) -> bool { @@ -242,7 +242,7 @@ impl Game<'_> { /// the page (`MultilineTextField.insertText`: line breaks kept, cut to /// the 1024 characters left, rejected when it overflows the 14 lines). fn book_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) { - let font = &self.atlas.font; + let font = &self.gui.atlas.font; match self.book.as_mut() { Some(BookScreen::Edit { signing: true, @@ -397,7 +397,7 @@ impl Game<'_> { let key = (pos[0], pos[1], pos[2]); if &*self .res - .facts + .facts() .get(self.world.block(pos[0], pos[1], pos[2])) .name != "minecraft:lectern" @@ -549,7 +549,7 @@ impl Game<'_> { } pub(super) fn draw_book(&self, batch: &mut HudBatch) { let Some(book) = &self.book else { return }; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); let (mx, my) = self.cursor; let hover = diff --git a/crates/horizon-client/src/game/breezes.rs b/crates/horizon-client/src/game/breezes.rs index 52e3b36a9..466469110 100644 --- a/crates/horizon-client/src/game/breezes.rs +++ b/crates/horizon-client/src/game/breezes.rs @@ -40,7 +40,7 @@ impl Game<'_> { m.position.z.floor() as i32, ); let mut state = self.world.block(x, y, z); - if self.res.facts.is_air(state) { + if self.res.facts().is_air(state) { state = self.world.block(x, (m.position.y - 0.2).floor() as i32, z); } let Some((sprite, tint)) = self.particle_sprite(state) else { diff --git a/crates/horizon-client/src/game/cartography.rs b/crates/horizon-client/src/game/cartography.rs index 86d5d5395..4a5738f6e 100644 --- a/crates/horizon-client/src/game/cartography.rs +++ b/crates/horizon-client/src/game/cartography.rs @@ -89,17 +89,17 @@ impl Game<'_> { if is_locked { locked = true; if scaling || locking { - batch.sprite(&self.atlas, error, ox + 35.0, oy + 31.0); + batch.sprite(&self.gui.atlas, error, ox + 35.0, oy + 31.0); } } if scaling && scale >= 4 { locked = true; - batch.sprite(&self.atlas, error, ox + 35.0, oy + 31.0); + batch.sprite(&self.gui.atlas, error, ox + 35.0, oy + 31.0); } } let sprite = |batch: &mut HudBatch, game: &Self, name: &str, x: f32, y: f32| { batch.sprite( - &game.atlas, + &game.gui.atlas, &format!("gui/sprites/container/cartography_table/{name}"), ox + x, oy + y, diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index b19cd9d01..20aeeb7fd 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -219,12 +219,18 @@ impl Game<'_> { .map(|a| format!("minecraft:{a}")) .collect(); let reg = &mut self.ui.registries; - let mut items: Vec = self.res.items.order.iter().map(|s| s.to_string()).collect(); + let mut items: Vec = self + .res + .items() + .order + .iter() + .map(|s| s.to_string()) + .collect(); items.sort(); reg.items = items; reg.item_tags = self .res - .items + .items() .item_tags .keys() .map(|k| horizon_client::command::args::normalize(k)) @@ -232,7 +238,7 @@ impl Game<'_> { reg.item_tags.sort(); reg.block_tags = self .res - .items + .items() .block_tags .keys() .map(|k| horizon_client::command::args::normalize(k)) @@ -259,7 +265,7 @@ impl Game<'_> { .collect(); let mut summonable: Vec = self .res - .mob_types + .mob_types() .keys() .map(|k| horizon_client::command::args::normalize(k)) .collect(); @@ -405,7 +411,7 @@ impl Game<'_> { .as_ref() .map_or([1280, 720], |r| [r.config.width, r.config.height]); let b = HudBatch::new(size); - let m = Measure(&self.atlas.font); + let m = Measure(&self.gui.atlas.font); let c = Commands { dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, @@ -450,7 +456,7 @@ impl Game<'_> { let focused = self.screen == Screen::Chat; let heard = self.mods.mods.is_running().then(|| text.plain()); self.ui.chat.add( - &self.atlas, + &self.gui.atlas, text, Some(SYSTEM_INDICATOR), self.ticks, @@ -463,7 +469,7 @@ impl Game<'_> { /// Keys while the chat screen is open. pub(super) fn chat_key(&mut self, event: &KeyEvent) { if let Some(shortcut) = self.edit_shortcut(event) { - let m = Measure(&self.atlas.font); + let m = Measure(&self.gui.atlas.font); let c = Commands { dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, @@ -509,7 +515,7 @@ impl Game<'_> { let Some(mut screen) = self.ui.chat_screen.take() else { return; }; - let m = Measure(&self.atlas.font); + let m = Measure(&self.gui.atlas.font); let c = Commands { dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, @@ -533,9 +539,26 @@ impl Game<'_> { } } } + /// The server's completions for an `ask_server` request + /// (ClientPacketListener.handleCommandSuggestions). + pub(super) fn chat_server_suggestions( + &mut self, + id: i32, + range: (usize, usize), + list: Vec<(String, Option)>, + ) { + let m = Measure(&self.gui.atlas.font); + let c = Commands { + dispatcher: chat_tree(&self.remote, &self.mods), + registries: &self.ui.registries, + }; + if let Some(screen) = self.ui.chat_screen.as_mut() { + screen.server_suggestions(&m, &c, id, range, list); + } + } /// Text typed into the chat box (control socket `chat`). pub(super) fn chat_type(&mut self, text: &str) { - let m = Measure(&self.atlas.font); + let m = Measure(&self.gui.atlas.font); let c = Commands { dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, @@ -563,7 +586,7 @@ impl Game<'_> { let heard = self.mods.mods.is_running().then(|| line.plain()); self.ui .chat - .add(&self.atlas, line, None, self.ticks, focused); + .add(&self.gui.atlas, line, None, self.ticks, focused); if let Some(line) = heard { self.mods_chat(&line); } @@ -591,7 +614,7 @@ impl Game<'_> { let height = self.renderer.as_ref().map_or(720.0, |r| { HudBatch::new([r.config.width, r.config.height]).height }); - let m = Measure(&self.atlas.font); + let m = Measure(&self.gui.atlas.font); let c = Commands { dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, @@ -604,7 +627,7 @@ impl Game<'_> { return; } match self.ui.chat.click_at( - &self.atlas.font, + &self.gui.atlas.font, height as i32, cursor.0 as f64, cursor.1 as f64, @@ -630,13 +653,15 @@ impl Game<'_> { if self.ui.hide_gui && !focused { return; } - self.ui.chat.draw(batch, &self.atlas, self.ticks, focused); + self.ui + .chat + .draw(batch, &self.gui.atlas, self.ticks, focused); } pub(super) fn draw_chat_screen(&mut self, batch: &mut HudBatch) { let Some(mut screen) = self.ui.chat_screen.take() else { return; }; - let m = Measure(&self.atlas.font); + let m = Measure(&self.gui.atlas.font); let c = Commands { dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, @@ -654,7 +679,7 @@ impl Game<'_> { .chat_opened .map_or(0, |t| t.elapsed().as_millis() as u64); let draws = screen.draw(&m, mouse, blink, background); - horizon_client::screen_draw::paint(batch, &self.atlas, &draws); + horizon_client::screen_draw::paint(batch, &self.gui.atlas, &draws); self.ui.chat_screen = Some(screen); } /// Advance the overworld clock (ServerClockManager.tick) when @@ -672,6 +697,16 @@ impl Game<'_> { c.partial -= whole; self.world.day_time += whole as i64; } + /// `ServerClockInstance.packNetworkState`: the rate players' clients + /// advance the overworld clock at, 0 while it is paused (`/time pause`) + /// or `advance_time` is off. + pub(super) fn network_clock_rate(&self) -> f32 { + if self.ui.rules.bool("advance_time") && !self.ui.clock.paused { + self.ui.clock.rate + } else { + 0.0 + } + } /// The engine-side rule values (block behaviour and health). pub(super) fn level_rules(&self) -> horizon_world::level::GameRules { let r = &self.ui.rules; @@ -846,11 +881,11 @@ impl Game<'_> { let focused = self.screen == Screen::Chat; self.ui .chat - .add(&self.atlas, message, None, self.ticks, focused); + .add(&self.gui.atlas, message, None, self.ticks, focused); } #[allow(dead_code)] fn chat_debug_fill(&self, batch: &mut HudBatch) { - batch.fill(&self.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0)); + batch.fill(&self.gui.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0)); } } /// `yyyy-MM-dd_HH.mm.ss[_n].png` (Util.getFilenameFormattedDateTime, local time diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index abe67c6c6..da3851d9a 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -114,7 +114,7 @@ impl Game<'_> { let location = if let Some(c) = p.last_climbable { let name = self .res - .facts + .facts() .get(self.world.block(c.x, c.y, c.z)) .name .clone(); @@ -127,7 +127,7 @@ impl Game<'_> { _ => "other_climbable", }) } else { - let f = self.res.facts.get(self.world.block( + let f = self.res.facts().get(self.world.block( p.position.x.floor() as i32, (p.position.y + 0.1).floor() as i32, p.position.z.floor() as i32, diff --git a/crates/horizon-client/src/game/command_blocks.rs b/crates/horizon-client/src/game/command_blocks.rs index 434c72e72..76fc6d48c 100644 --- a/crates/horizon-client/src/game/command_blocks.rs +++ b/crates/horizon-client/src/game/command_blocks.rs @@ -357,6 +357,7 @@ impl Game<'_> { silent: false, store: None, dimension: self.dim, + level: None, block: Some(pos), }; // performPrefixedCommand: a leading slash is allowed. @@ -458,7 +459,7 @@ impl Game<'_> { self.close_command_block(); return; } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); let mid = (w / 2.0).floor(); ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); @@ -598,13 +599,13 @@ impl Game<'_> { if let Ok(id) = registry.resolve(&wanted) && wanted != *current { - let entity = self.world.block_entities.remove(&pos); + let entity = self.world.block_entities.take(&pos); let at = BlockPos::new(pos.0, pos.1, pos.2); self.with_level(|b, level, ticks| { b.set_block(level, ticks, at, id, flags::UPDATE_CLIENTS) }); if let Some(entity) = entity { - self.world.block_entities.insert(pos, entity); + self.world.block_entities.put(pos, entity); } let _ = self.process_level_events(); } diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index aca4d3002..b970414a6 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -9,6 +9,7 @@ pub(super) mod extra; mod items; mod misc; mod place; +mod players; mod raid; mod terrain_cmds; mod text_commands; @@ -33,7 +34,11 @@ pub(super) type R = Result; /// An entity a selector found. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub(super) enum Target { + /// The player in place: the host's, or the guest whose turn it is. Player, + /// Another player of a hosted world or server: a guest by connection + /// (game/commands/players.rs). + Guest(u32), Mob(u32), Item(u32), Orb(usize), @@ -165,14 +170,20 @@ impl Game<'_> { } 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() + /// CommandSourceStack.broadcastToAdmins (`sendSuccess` with `broadcast`) + /// for a guest's command, the host's in a world open to LAN and the + /// dedicated server console's when `broadcast-console-to-ops` is on: + /// `[name: message]`, gray and italic, for the other operators when + /// `send_command_feedback`, and for a player's command on a dedicated + /// server the console when `log_admin_commands`. Queued while the + /// command runs; `send_admin_feedback` sends it. + pub(super) fn broadcast_to_admins(&mut self, message: Text) { + let informs = match self.console_broadcast { + Some(broadcast) => broadcast, + // While a guest acts the host's LanHost is out of `self.lan`. + None => self.lan_acting.is_some() || self.lan.is_some(), + }; + if !informs || message .translation_key() .is_some_and(|k| admin::QUIET.contains(&k)) @@ -180,29 +191,62 @@ impl Game<'_> { return; } let ops = self.ui.rules.bool("send_command_feedback"); - let console = self.ui.rules.bool("log_admin_commands"); + // MinecraftServer.sendSystemMessage, unless the server is the source. + let console = self.console_broadcast.is_none() + && self.lan_acting.is_some() + && self.options.dedicated.is_some() + && 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]) + // getDisplayName: the entity the command runs as (`execute as`), or + // the server's own source, "Server". + let who = match self.command_source.and_then(|s| s.entity) { + Some(entity) => self.target_name(entity), + None if self.console_broadcast.is_some() => Text::literal("Server".to_owned()), + None => self.player_display_name(), + }; + let line = Text::translate("chat.type.admin", &[who, message]) .with_color(text::GRAY) .italic(); self.admin_feedback.push((line, ops, console)); } + /// Player.getDisplayName: the name (team-formatted), suggesting a + /// `/tell`, showing the player on hover, inserting the name. + fn player_display_name(&self) -> Text { + let name = self.acting_player_name().to_owned(); + let Some(uuid) = self.lan_acting_uuid else { + return self.target_name(Target::Player); + }; + self.target_name(Target::Player).with_component_fields(vec![ + ( + "click_event".into(), + serde_json::json!({"action": "suggest_command", "command": format!("/tell {name} ")}), + ), + ( + "hover_event".into(), + serde_json::json!({"action": "show_entity", "id": "minecraft:player", + "uuid": horizon_protocol::crypto::uuid_string(uuid), "name": name}), + ), + ("insertion".into(), name.into()), + ]) + } fn source_position(&self) -> [f64; 3] { if let Some(s) = &self.command_source { return s.pos; } match &self.player { Some(p) => [p.position.x, p.position.y, p.position.z], - None => self.spawn.map_or([0.0, 64.0, 0.0], |s| [s.x, s.y, s.z]), + None => self.server_position(), } } + /// MinecraftServer.createCommandSourceStack's position: the corner of + /// the respawn block (`Vec3.atLowerCornerOf`). + pub(super) fn server_position(&self) -> [f64; 3] { + self.spawn.map_or([0.0, 64.0, 0.0], |s| { + [s.x.floor(), s.y.floor(), s.z.floor()] + }) + } fn source_rotation(&self) -> [f32; 2] { self.command_source .map_or([self.yaw, self.pitch], |s| s.rot) @@ -256,6 +300,7 @@ impl Game<'_> { .player .as_ref() .map(|p| [p.position.x, p.position.y, p.position.z]), + Target::Guest(conn) => self.command_guest(conn).map(|g| g.position), Target::Mob(id) => self .mobs .iter() @@ -315,7 +360,7 @@ impl Game<'_> { } pub(super) fn target_type(&self, t: Target) -> String { match t { - Target::Player => "minecraft:player".into(), + Target::Player | Target::Guest(_) => "minecraft:player".into(), Target::Mob(id) => self .mobs .iter() @@ -362,12 +407,19 @@ impl Game<'_> { match t { Target::Player => { let name = self.acting_player_name(); + if let Some(uuid) = self.lan_acting_uuid { + return self.player_text(name, uuid); + } match self.score.board.players_team(name) { // PlayerTeam.formatNameForTeam. Some(team) => team.formatted_name(Text::literal(name)), None => Text::literal(name), } } + Target::Guest(conn) => match self.command_guest(conn) { + Some(g) => self.player_text(&g.name, g.uuid), + None => Text::empty(), + }, Target::Item(id) => { let item = self .dropped @@ -414,11 +466,10 @@ impl Game<'_> { /// EntitySelector.findEntities. pub(super) fn select(&mut self, s: &Selector) -> Vec { if let Some(name) = &s.player_name { - return if name.eq_ignore_ascii_case(PLAYER_NAME) && self.player.is_some() { - vec![Target::Player] - } else { - Vec::new() - }; + return self.player_named(name).into_iter().collect(); + } + if let Some(uuid) = s.uuid { + return self.target_by_uuid(uuid).into_iter().collect(); } let origin = { let p = self.source_position(); @@ -432,10 +483,15 @@ impl Game<'_> { match (s.kind, self.command_source) { // @s: the executing entity (none for a server source). ('s', Some(source)) => candidates.extend(source.entity), - _ if self.player.is_some() => candidates.push(Target::Player), + ('s', None) => candidates.extend(self.source_entity()), + // A guest in place is among the players, in join order. + _ if self.player.is_some() && self.lan_acting.is_none() => { + candidates.push(Target::Player); + } _ => {} } if s.kind != 's' { + candidates.extend(self.player_candidates(s)); candidates.extend( self.mobs .iter() @@ -479,7 +535,7 @@ impl Game<'_> { } } if !s.include_entities - && t != Target::Player + && !t.is_player() && s.types.iter().all(|(w, n)| *n || w != &ty) && s.kind != 'e' && s.kind != 'n' @@ -495,16 +551,20 @@ impl Game<'_> { if !passing.contains(&t) { return None; } + let player = match t { + Target::Player => Some((level, if creative { "creative" } else { "survival" })), + Target::Guest(conn) => self.guest_level_and_mode(conn), + _ => None, + }; if let Some((lo, hi)) = s.level - && (t != Target::Player - || lo.is_some_and(|l| level < l) - || hi.is_some_and(|h| level > h)) + && player.is_none_or(|(level, _)| { + lo.is_some_and(|l| level < l) || hi.is_some_and(|h| level > h) + }) { return None; } for (mode, neg) in &s.gamemodes { - let current = if creative { "creative" } else { "survival" }; - if t != Target::Player || (current == mode) == *neg { + if player.is_none_or(|(_, current)| (current == mode) == *neg) { return None; } } @@ -563,12 +623,12 @@ impl Game<'_> { /// EntityArgument.getEntities / getPlayers / getEntity / getPlayer. pub(super) fn entities(&mut self, ctx: &Context, name: &str, players: bool) -> R> { let Some(Arg::Entity(s)) = ctx.get(name).cloned() else { - return Ok(vec![Target::Player]); + return Ok(vec![self.implied_player()]); }; let found: Vec = self .select(&s) .into_iter() - .filter(|t| !players || *t == Target::Player) + .filter(|t| !players || t.is_player()) .collect(); if found.is_empty() { return Err(err( @@ -774,63 +834,63 @@ impl Game<'_> { let targets = if ctx.get("target").is_some() { self.entities(ctx, "target", true)? } else { - vec![Target::Player] + vec![self.implied_player()] }; let mut count = 0; for t in targets { - if t != Target::Player || !self.set_game_mode(mode) { + let mode_name = Text::translate(&format!("gameMode.{}", mode.name()), &[]); + // GameModeCommand.logGamemodeChange: the source's own entity. + let own = self.source_entity() == Some(t); + let told = !own && self.ui.rules.bool("send_command_feedback"); + let changed = self.for_player(t, |g| { + if !g.set_game_mode(mode) { + return false; + } + if told { + g.system_message(Text::translate( + "gameMode.changed", + std::slice::from_ref(&mode_name), + )); + } + true + }); + if changed != Some(true) { continue; } count += 1; - let mode_name = Text::translate(&format!("gameMode.{}", mode.name()), &[]); - // GameModeCommand.logGamemodeChange: the source's own entity. - let own = match self.command_source { - None => true, - Some(s) => s.entity == Some(t), - }; if own { self.feedback(Text::translate( "commands.gamemode.success.self", &[mode_name], )); } else { - if self.ui.rules.bool("send_command_feedback") { - self.system_message(Text::translate( - "gameMode.changed", - std::slice::from_ref(&mode_name), - )); - } self.feedback(Text::translate( "commands.gamemode.success.other", - &[Text::literal(self.acting_player_name()), mode_name], + &[self.target_name(t), mode_name], )); } } Ok(count) } - /// ItemStack.getDisplayName: "[Name]" in the rarity colour. + /// ItemStack.getDisplayName of one `item` with no components. pub(super) fn item_display_name(&self, item: &str) -> Text { - let rarity = self.item_rarity(item); - let color = match rarity.as_str() { - "uncommon" => text::YELLOW, - "rare" => text::AQUA, - "epic" => text::LIGHT_PURPLE, - _ => text::WHITE, - }; - Text::literal("[") - .append(Text::literal(self.pack.names.item(item))) - .append("]") - .with_color(color) + self.stack_display_name(&ItemStack { + item: item.into(), + count: 1, + damage: 0, + extra: None, + }) } /// `ItemStack.getDisplayName`: the hover name (custom name in italics, - /// a written book's title, a potion's effect name...) in brackets, in the - /// rarity colour unless the stack is empty. + /// a written book's title, a potion's effect name, else the item's + /// translated name) in brackets, in the rarity colour and showing the + /// stack on hover unless it is empty. pub(super) fn stack_display_name(&self, s: &ItemStack) -> Text { let item = &*s.item; let empty = item == "minecraft:air" || s.count == 0; let custom = s.custom_name(); let hover = if let Some(c) = custom { - Text::literal(c).italic() + Text::literal(c) } else if let Some(title) = s .data() .and_then(|d| d.written.as_ref()) @@ -851,9 +911,22 @@ impl Game<'_> { &[], ) } else { - Text::literal(self.pack.names.item(item)) + // Item.getDescriptionId: a block item's is the block's. + let (namespace, path) = item.split_once(':').unwrap_or(("minecraft", item)); + let key = format!("item.{namespace}.{path}"); + let key = if self.pack.names.get(&key).is_some() { + key + } else { + format!("block.{namespace}.{path}") + }; + Text::translate(&key, &[]) }; - let wrapped = Text::translate("chat.square_brackets", &[hover]); + // Component.empty().append(getHoverName()), italic for a custom name. + let mut name = Text::empty().append(hover); + if custom.is_some() { + name = name.italic(); + } + let wrapped = Text::translate("chat.square_brackets", &[name]); if empty { return wrapped; } @@ -871,7 +944,14 @@ impl Game<'_> { "epic" => text::LIGHT_PURPLE, _ => text::WHITE, }; - wrapped.with_color(color) + // HoverEvent.ShowItem: the count only when it is not one. + let mut shown = serde_json::json!({"action": "show_item", "id": item}); + if s.count != 1 { + shown["count"] = s.count.into(); + } + wrapped + .with_color(color) + .with_component_fields(vec![("hover_event".into(), shown)]) } pub(super) fn item_rarity(&self, item: &str) -> String { static RARITY: std::sync::OnceLock> = @@ -909,7 +989,7 @@ impl Game<'_> { }; let count = Self::int(ctx, "count").unwrap_or(1); let targets = self.entities(ctx, "targets", true)?; - let max_stack = self.res.items.get(&id).map_or(64, |i| i.max_stack) as i32; + let max_stack = self.res.items().get(&id).map_or(64, |i| i.max_stack) as i32; if count > max_stack * 100 { return Err(CommandError::new(Text::translate( "commands.give.failed.toomanyitems", @@ -921,33 +1001,38 @@ impl Game<'_> { } // An air stack is empty: nothing is given (but the message still is). let empty = id == "minecraft:air"; - for _ in targets.iter().filter(|_| !empty) { - let mut remaining = count; - while remaining > 0 { - let size = remaining.min(max_stack); - remaining -= size; - let left = self.give(ItemStack { - item: id.as_str().into(), - count: size as u32, - damage, - extra: extra.clone(), - }); - if let Some(rest) = left { - // Inventory full: drop the rest at the player's feet without pickup delay. - let p = self.source_position(); - self.spawn_item(rest, [p[0], p[1] + 1.32, p[2]], [0.0, 0.0, 0.0], 0); - } else { - let r = &mut self.world.random; - let pitch = ((r.next_float() - r.next_float()) * 0.7 + 1.0) * 2.0; - let p = self.source_position(); - self.audio - .play("minecraft:entity.item.pickup", Some(p), 0.2, pitch); + for &t in targets.iter().filter(|_| !empty) { + self.for_player(t, |g| { + let mut remaining = count; + while remaining > 0 { + let size = remaining.min(max_stack); + remaining -= size; + let left = g.give(ItemStack { + item: id.as_str().into(), + count: size as u32, + damage, + extra: extra.clone(), + }); + // At the player who gets them. + let p = g + .target_position(Target::Player) + .unwrap_or(g.source_position()); + if let Some(rest) = left { + // Inventory full: drop the rest at the player's feet without pickup delay. + g.spawn_item(rest, [p[0], p[1] + 1.32, p[2]], [0.0, 0.0, 0.0], 0); + } else { + let r = &mut g.world.random; + let pitch = ((r.next_float() - r.next_float()) * 0.7 + 1.0) * 2.0; + g.audio + .play("minecraft:entity.item.pickup", Some(p), 0.2, pitch); + } } - } + }); } + // The prototype stack: one item. let name = self.stack_display_name(&ItemStack { item: id.as_str().into(), - count: count.max(1) as u32, + count: 1, damage, extra: extra.clone(), }); @@ -957,7 +1042,7 @@ impl Game<'_> { &[ Text::literal(count.to_string()), name, - Text::literal(self.acting_player_name()), + self.target_name(targets[0]), ], ) } else { @@ -976,6 +1061,9 @@ impl Game<'_> { fn teleport_to(&mut self, t: Target, pos: [f64; 3], rotation: Option<[f32; 2]>) { let v = Vec3::new(pos[0], pos[1], pos[2]); match t { + Target::Guest(_) => { + self.for_player(t, |g| g.teleport_to(Target::Player, pos, rotation)); + } Target::Player => { if let Some(p) = self.player.as_mut() { p.position = v; @@ -1092,17 +1180,60 @@ impl Game<'_> { self.end_portal_travel = false; Ok(()) } + + /// A server's player teleported into another level than theirs + /// (ServerPlayer.teleport): queued to move after the command. False + /// when `t` is not a player in another level. + fn teleport_across( + &mut self, + t: Target, + level: super::Dim, + pos: [f64; 3], + rotation: Option<[f32; 2]>, + ) -> bool { + let (conn, at) = match t { + Target::Player => (self.lan_acting, self.dim), + Target::Guest(conn) => ( + Some(conn), + self.command_guest(conn) + .map_or(self.dim, |g| super::Dim::from_id(&g.dimension)), + ), + _ => (None, self.dim), + }; + let Some(conn) = conn.filter(|_| at != level && self.options.dedicated.is_some()) else { + return false; + }; + self.level_teleports + .push(super::server_travel::LevelTeleport { + conn, + dim: level, + at: pos, + rotation, + }); + true + } fn cmd_teleport(&mut self, id: &str, ctx: &Context) -> R { let targets = if id.starts_with("teleport.targets") { self.entities(ctx, "targets", false)? } else { - vec![Target::Player] + vec![self.implied_player()] }; if id.ends_with("destination") { let dest = self.entities(ctx, "destination", false)?[0]; let pos = self.target_position(dest).unwrap_or(self.source_position()); + // Into the destination's level. + let level = match dest { + Target::Guest(conn) => self + .command_guest(conn) + .map_or(self.dim, |g| super::Dim::from_id(&g.dimension)), + _ => self.dim, + }; + // TeleportCommand.teleportToEntity: the destination's rotation too. + let rotation = Some(self.target_rotation(dest)); for &t in &targets { - self.teleport_to(t, pos, None); + if !self.teleport_across(t, level, pos, rotation) { + self.teleport_to(t, pos, rotation); + } } let message = if targets.len() == 1 { Text::translate( @@ -1160,7 +1291,18 @@ impl Game<'_> { (-(dy.atan2(horizontal).to_degrees())) as f32, ]); } + // A server's player in another level than the source's (`execute + // in`, the console's Overworld) moves there (ServerPlayer.teleport + // into another level), after the command. + let source_level = match self.command_source.and_then(|s| s.level) { + Some(level) => level, + None if self.source_entity().is_none() => super::Dim::Overworld, + None => self.dim, + }; for &t in &targets { + if self.teleport_across(t, source_level, pos, rotation) { + continue; + } let dimension = self.command_source.map_or(self.dim, |s| s.dimension); if t == Target::Player && dimension != self.dim { self.teleport_player_to_dimension(dimension, pos, rotation)?; @@ -1366,6 +1508,9 @@ impl Game<'_> { } fn kill_target(&mut self, t: Target) { match t { + Target::Guest(_) => { + self.for_player(t, |g| g.kill_target(Target::Player)); + } Target::Player => { if let Some(p) = self.player.as_mut() { let _ = p.set_health(0.0, false); @@ -1408,7 +1553,7 @@ impl Game<'_> { let targets = if ctx.get("targets").is_some() { self.entities(ctx, "targets", false)? } else { - vec![Target::Player] + vec![self.implied_player()] }; let names: Vec = targets.iter().map(|&t| self.target_name(t)).collect(); // Remove indexed entities from the back so earlier indices stay valid. @@ -1461,7 +1606,7 @@ impl Game<'_> { if self.ui.difficulty == 0 && self .res - .mob_types + .mob_types() .get(&format!("minecraft:{short}")) .is_some_and(|t| t.category == "monster") { @@ -1478,7 +1623,7 @@ impl Game<'_> { let name; if let Some(t) = self .res - .mob_types + .mob_types() .get(&format!("minecraft:{short}")) .cloned() { @@ -1494,7 +1639,9 @@ impl Game<'_> { return Err(err("commands.summon.failed", &[])); } "experience_orb" => { + self.next_entity += 1; self.orbs.push(horizon_client::entities::ExperienceOrb { + id: self.next_entity, position: Vec3::new(pos[0], pos[1], pos[2]), previous: Vec3::new(pos[0], pos[1], pos[2]), velocity: Vec3::new(0.0, 0.0, 0.0), @@ -1520,7 +1667,13 @@ impl Game<'_> { self.carts.push(cart); name = Text::translate(&format!("entity.minecraft.{k}"), &[]); } - _ => return Err(err("commands.summon.failed", &[])), + // SummonCommand.createEntity: any other type from an empty compound. + _ => { + let Some(target) = self.summon_with_nbt(&kind, pos, "{}")? else { + return Err(err("commands.summon.failed", &[])); + }; + name = self.target_name(target); + } } } self.feedback(Text::translate("commands.summon.success", &[name])); @@ -1546,10 +1699,10 @@ impl Game<'_> { let name_ok = if b.tag { let tag = b.id.trim_start_matches("minecraft:"); self.res - .items + .items() .block_tags .get(tag) - .or_else(|| self.res.items.block_tags.get(&b.id)) + .or_else(|| self.res.items().block_tags.get(&b.id)) .is_some_and(|set| { set.contains(&s.name) || set.contains(s.name.trim_start_matches("minecraft:")) }) @@ -1574,8 +1727,8 @@ impl Game<'_> { } // A different block replaces the block entity (Level.setBlock). let (old, new) = ( - self.res.facts.get(previous).name.clone(), - self.res.facts.get(state).name.clone(), + self.res.facts().get(previous).name.clone(), + self.res.facts().get(state).name.clone(), ); // The command clears the old block entity without its side effects // (UPDATE_SKIP_BLOCK_ENTITY_SIDEEFFECTS); the new block gets a fresh one. @@ -2169,10 +2322,10 @@ impl Game<'_> { let tag = predicate.id.trim_start_matches("minecraft:"); return self .res - .items + .items() .item_tags .get(tag) - .or_else(|| self.res.items.item_tags.get(&predicate.id)) + .or_else(|| self.res.items().item_tags.get(&predicate.id)) .is_some_and(|s| { s.contains(item) || s.contains(item.trim_start_matches("minecraft:")) }); @@ -2618,7 +2771,7 @@ impl Game<'_> { let focused = self.screen == Screen::Chat; self.ui .chat - .add(&self.atlas, line, None, self.ticks, focused); + .add(&self.gui.atlas, line, None, self.ticks, focused); Ok(1) } /// MessageArgument: `@p`-style selectors in a message become names. diff --git a/crates/horizon-client/src/game/commands/compute.rs b/crates/horizon-client/src/game/commands/compute.rs index 24552011d..c7b2355e3 100644 --- a/crates/horizon-client/src/game/commands/compute.rs +++ b/crates/horizon-client/src/game/commands/compute.rs @@ -502,7 +502,7 @@ impl Game<'_> { Some(Value::String(b)) => match b.strip_prefix('#') { Some(tag) => self .res - .items + .items() .block_tags .get(tag.trim_start_matches("minecraft:")) .is_some_and(|set| { diff --git a/crates/horizon-client/src/game/commands/data.rs b/crates/horizon-client/src/game/commands/data.rs index 1d2321a1a..bbb388deb 100644 --- a/crates/horizon-client/src/game/commands/data.rs +++ b/crates/horizon-client/src/game/commands/data.rs @@ -35,6 +35,11 @@ impl Game<'_> { pub(in crate::game) fn entity_nbt(&mut self, t: Target) -> Option { let player_uuid = self.level.player_uuid; Some(match t { + Target::Guest(_) => { + return self + .for_player(t, |g| g.entity_nbt(Target::Player)) + .flatten(); + } Target::Player => { self.player.as_ref()?; self.sync_level(); @@ -142,7 +147,7 @@ impl Game<'_> { set_key(&mut tag, "id", Tag::String(k.as_str().into())); } let new = - entity_nbt::mob_from_nbt(&tag, &self.res.mob_types, id).ok_or_else(stale)?; + entity_nbt::mob_from_nbt(&tag, self.res.mob_types(), id).ok_or_else(stale)?; if let Some(slot) = self.mobs.iter_mut().find(|m| m.id == id) { // Runtime-only state (AI, animation) carries over. let old = std::mem::replace(slot, new); diff --git a/crates/horizon-client/src/game/commands/effects.rs b/crates/horizon-client/src/game/commands/effects.rs index 86726fed9..65d6592f7 100644 --- a/crates/horizon-client/src/game/commands/effects.rs +++ b/crates/horizon-client/src/game/commands/effects.rs @@ -59,7 +59,7 @@ impl Game<'_> { if ctx.get("targets").is_some() { self.entities(ctx, "targets", false) } else { - Ok(vec![Target::Player]) + Ok(vec![self.implied_player()]) } } /// `EffectCommands.giveEffect`. @@ -83,10 +83,11 @@ impl Game<'_> { let mut tracker = Tracker::default(); for t in self.living_targets(ctx)? { let changed = match t { - Target::Player => { + Target::Player | Target::Guest(_) => { let mut instance = EffectInstance::new(effect.id, duration, amplifier); instance.visible = particles; - self.add_player_effect(instance) + self.for_player(t, |g| g.add_player_effect(instance)) + .unwrap_or(false) } Target::Mob(id) => match self.mobs.iter_mut().find(|m| m.id == id) { Some(m) => { @@ -131,18 +132,22 @@ impl Game<'_> { let mut tracker = Tracker::default(); for t in self.living_targets(ctx)? { let changed = match (t, effect) { - (Target::Player, None) => { - let any = !self.potions.effects.list.is_empty(); - self.potions.effects.clear(); - self.apply_effect_status(); - any - } - (Target::Player, Some(e)) => { - let before = self.potions.effects.list.len(); - self.potions.effects.list.retain(|x| x.id != e.id); - self.apply_effect_status(); - self.potions.effects.list.len() != before - } + (Target::Player | Target::Guest(_), None) => self + .for_player(t, |g| { + let any = !g.potions.effects.list.is_empty(); + g.potions.effects.clear(); + g.apply_effect_status(); + any + }) + .unwrap_or(false), + (Target::Player | Target::Guest(_), Some(e)) => self + .for_player(t, |g| { + let before = g.potions.effects.list.len(); + g.potions.effects.list.retain(|x| x.id != e.id); + g.apply_effect_status(); + g.potions.effects.list.len() != before + }) + .unwrap_or(false), (Target::Mob(id), e) => match self.mobs.iter_mut().find(|m| m.id == id) { Some(m) => { let before = m.extra.effects.len(); @@ -187,7 +192,7 @@ impl Game<'_> { return Ok(0); }; let level = Self::int(ctx, "level").unwrap_or(1); - let enchantments = &self.res.stations.enchantments; + let enchantments = &self.res.stations().enchantments; let Some(def) = enchantments.get(&id) else { return Err(err( "argument.resource.not_found", @@ -213,8 +218,8 @@ impl Game<'_> { } continue; }; - let e = &self.res.stations.enchantments; - let compatible = e.can_enchant(&self.res.items, &id, &stack.item) + let e = &self.res.stations().enchantments; + let compatible = e.can_enchant(self.res.items(), &id, &stack.item) && stack .crafting_enchantments() .iter() @@ -265,7 +270,7 @@ impl Game<'_> { } let (name, curse) = self .res - .stations + .stations() .enchantments .full_name(&id, level.max(0) as u32); let style = Style { diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index 9db5654d6..221ebb238 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -26,6 +26,9 @@ pub(in crate::game) struct Source { /// The level this command source uses. Horizon has only this dimension's /// chunks loaded in the single-player client. pub dimension: Dim, + /// The dimension `execute in` named, if any: a server teleports its + /// players there (`TeleportCommand` into the source's level). + pub level: Option, /// The command block whose output this source is /// (`BaseCommandBlock.CloseableCommandBlockSource`). pub block: Option<(i32, i32, i32)>, @@ -70,13 +73,15 @@ impl Game<'_> { /// The source a command typed by the player starts from. pub(in crate::game) fn player_source(&self) -> Source { Source { - entity: Some(Target::Player), + // The server console has no entity (CommandSourceStack of the server). + entity: self.player.is_some().then_some(Target::Player), pos: self.source_position(), rot: self.source_rotation(), eyes: false, silent: false, store: None, dimension: self.dim, + level: None, block: None, } } @@ -84,18 +89,22 @@ impl Game<'_> { pub(in crate::game) fn server_source(&self) -> Source { Source { entity: None, - pos: self.spawn.map_or([0.0, 64.0, 0.0], |s| [s.x, s.y, s.z]), + pos: self.server_position(), rot: [0.0, 0.0], eyes: false, silent: true, store: None, dimension: self.dim, + level: None, block: None, } } pub(super) fn target_rotation(&self, t: Target) -> [f32; 2] { match t { Target::Player => [self.yaw, self.pitch], + Target::Guest(conn) => self + .command_guest(conn) + .map_or([0.0; 2], |g| [g.yaw, g.pitch]), Target::Mob(id) => self .mobs .iter() @@ -130,6 +139,7 @@ impl Game<'_> { .player .as_ref() .map_or(1.62, |p| f64::from(p.dimensions.eye_height)), + Target::Guest(conn) => self.command_guest(conn).map_or(1.62, |g| g.eye_height()), Target::Mob(id) => self .mobs .iter() @@ -441,6 +451,7 @@ impl Game<'_> { pos: self.target_position(t)?, rot: self.target_rotation(t), dimension: self.dim, + level: None, ..s }) }) @@ -548,6 +559,7 @@ impl Game<'_> { vec![Source { pos: [s.pos[0] * scale, s.pos[1], s.pos[2] * scale], dimension, + level: Some(super::super::Dim::from_id(dim)), ..s }] } @@ -630,7 +642,7 @@ impl Game<'_> { }) .collect() } - fn target_with_uuid(&self, uuid: [i32; 4]) -> Option { + pub(super) fn target_with_uuid(&self, uuid: [i32; 4]) -> Option { if Some(uuid) == self.level.player_uuid { return Some(Target::Player); } @@ -653,7 +665,7 @@ impl Game<'_> { if state == self.world.air { continue; } - let facts = self.res.facts.get(state); + let facts = self.res.facts().get(state); let blocks = facts.legacy_solid || facts.fluid != horizon_client::blocks::Fluid::None; let leaves = self .pack @@ -947,7 +959,7 @@ impl Game<'_> { let chunk = self.world.chunks.get(&(p[0] >> 4, p[2] >> 4))?; Some( self.res - .biomes + .biomes() .get(chunk.biome(p[0], p[1], p[2])) .name .clone(), @@ -970,7 +982,7 @@ impl Game<'_> { .resources .join(format!("data/{ns}/tags/worldgen/biome/{path}.json")); let Ok(bytes) = std::fs::read(file) else { - return self.res.mob_data.biome_has(tag, biome); + return self.res.mob_data().biome_has(tag, biome); }; let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap_or_default(); v["values"].as_array().is_some_and(|a| { diff --git a/crates/horizon-client/src/game/commands/extra.rs b/crates/horizon-client/src/game/commands/extra.rs index a90648043..7a4accb0d 100644 --- a/crates/horizon-client/src/game/commands/extra.rs +++ b/crates/horizon-client/src/game/commands/extra.rs @@ -586,7 +586,7 @@ impl Game<'_> { ); let hit = traverse_blocks(eye, end, 256, |b: BlockPos| { let state = self.world.block(b.x, b.y, b.z); - (!self.res.facts.is_air(state)).then_some([b.x, b.y, b.z]) + (!self.res.facts().is_air(state)).then_some([b.x, b.y, b.z]) }); hit.ok().flatten().unwrap_or([ end.x.floor() as i32, diff --git a/crates/horizon-client/src/game/commands/items.rs b/crates/horizon-client/src/game/commands/items.rs index c71eebc68..fde97764d 100644 --- a/crates/horizon-client/src/game/commands/items.rs +++ b/crates/horizon-client/src/game/commands/items.rs @@ -375,7 +375,11 @@ impl Game<'_> { } else { 0 }; - let max = self.res.items.get(&stack.item).map_or(64, |i| i.max_stack); + let max = self + .res + .items() + .get(&stack.item) + .map_or(64, |i| i.max_stack); stack.count = (base + n).clamp(0, max as i32) as u32; } "minecraft:limit_count" => { @@ -389,7 +393,11 @@ impl Game<'_> { } } "minecraft:set_damage" => { - let max = self.res.items.get(&stack.item).map_or(0, |i| i.max_damage); + let max = self + .res + .items() + .get(&stack.item) + .map_or(0, |i| i.max_damage); if max > 0 { let f = match m["damage"].as_f64() { Some(f) => f as f32, @@ -587,7 +595,7 @@ impl Game<'_> { if let Some(Tag::Int(n)) = s.data().and_then(|d| d.other("minecraft:max_stack_size")) { return (*n).clamp(1, 99) as u32; } - self.res.items.get(&s.item).map_or(64, |i| i.max_stack) + self.res.items().get(&s.item).map_or(64, |i| i.max_stack) } /// `ResourceOrIdArgument.getItemModifier`: an inline modifier (SNBT) or /// a registered one. diff --git a/crates/horizon-client/src/game/commands/place.rs b/crates/horizon-client/src/game/commands/place.rs index 9037304b0..016f6e2fe 100644 --- a/crates/horizon-client/src/game/commands/place.rs +++ b/crates/horizon-client/src/game/commands/place.rs @@ -53,13 +53,7 @@ impl Game<'_> { let Ok(raw) = Compression::Gzip.decode(&bytes, 1 << 28) else { continue; }; - let Ok((named, _)) = nbt::read_named( - &raw, - Limits { - max_bytes: 1 << 28, - ..Limits::default() - }, - ) else { + let Ok((named, _)) = nbt::read_named(&raw, Limits::templates()) else { continue; }; return Some(Arc::new(StructureTemplate::from_nbt( diff --git a/crates/horizon-client/src/game/commands/players.rs b/crates/horizon-client/src/game/commands/players.rs new file mode 100644 index 000000000..d71c219a8 --- /dev/null +++ b/crates/horizon-client/src/game/commands/players.rs @@ -0,0 +1,210 @@ +//! Commands acting on the other players of a hosted world or a server +//! (EntitySelector.findPlayers and EntityArgument's player targets). The +//! player in place (the host's, or the guest whose turn it is) is +//! `Target::Player`; every other guest is `Target::Guest`, found by name, +//! UUID or selector, and what a command does to them runs with their state +//! swapped in (`for_player`), as their own turn, what it tells them going to +//! their chat. +use super::{Game, Target}; +use horizon_client::{command::args::Selector, lan::guest::Guest, text::Text}; +use horizon_protocol::packets::play::{self, Clientbound as C}; + +impl Target { + /// A player, in place or not (`instanceof ServerPlayer`). + pub(in crate::game) fn is_player(self) -> bool { + matches!(self, Target::Player | Target::Guest(_)) + } +} + +/// GameType.getName for a guest's game mode id. +fn mode_name(id: i32) -> &'static str { + match id { + 1 => "creative", + 2 => "adventure", + 3 => "spectator", + _ => "survival", + } +} + +impl Game<'_> { + /// The guest `conn`, while the hub is in `self.lan`. + pub(in crate::game) fn command_guest(&self, conn: u32) -> Option<&Guest> { + self.lan.as_ref()?.hub.guest(conn) + } + + /// `PlayerList.getPlayers` but the player in place: the guests who + /// joined the world. + fn command_players(&self) -> impl Iterator { + let acting = self.lan_acting; + self.lan + .iter() + .flat_map(|h| h.hub.guests.iter()) + .filter(move |g| g.placed && Some(g.conn) != acting) + } + + /// The entity the command runs as (`CommandSourceStack.getEntity`): a + /// command typed by the player in place runs as them, the server + /// console's as nobody. + pub(in crate::game) fn source_entity(&self) -> Option { + match self.command_source { + Some(s) => s.entity, + None => self.player.is_some().then_some(Target::Player), + } + } + + /// `CommandSourceStack.getPlayerOrException` for the commands whose + /// player argument is optional: the source's player (the player in + /// place when it has none, as before). + pub(in crate::game) fn implied_player(&self) -> Target { + self.source_entity() + .filter(|t| t.is_player()) + .unwrap_or(Target::Player) + } + + /// `PlayerList.getPlayerByName`: names are not case sensitive. + pub(super) fn player_named(&self, name: &str) -> Option { + if self.player.is_some() && name.eq_ignore_ascii_case(self.acting_player_name()) { + return Some(Target::Player); + } + self.command_players() + .find(|g| g.name.eq_ignore_ascii_case(name)) + .map(|g| Target::Guest(g.conn)) + } + + /// `EntitySelector.findEntities` with a UUID: the player with it, else + /// the entity. + pub(super) fn target_by_uuid(&self, uuid: u128) -> Option { + let own = self.lan_acting_uuid.or_else(|| { + self.level.player_uuid.map(|[a, b, c, d]| { + (u128::from(a as u32) << 96) + | (u128::from(b as u32) << 64) + | (u128::from(c as u32) << 32) + | u128::from(d as u32) + }) + }); + if self.player.is_some() && own == Some(uuid) { + return Some(Target::Player); + } + if let Some(g) = self.command_players().find(|g| g.uuid == uuid) { + return Some(Target::Guest(g.conn)); + } + let words = [96, 64, 32, 0].map(|shift| (uuid >> shift) as u32 as i32); + self.target_with_uuid(words) + } + + /// The guests a selector looks at, in join order (`PlayerList.getPlayers`), + /// the one in place as `Target::Player`: all of them, or those in the + /// source's level when it limits the search to a place + /// (`isWorldLimited`); `@e` and `@n` skip the dead (`Entity::isAlive`). + pub(super) fn player_candidates(&self, s: &Selector) -> Vec { + let limited = s.distance.is_some() + || s.pos.iter().any(Option::is_some) + || s.delta.iter().any(Option::is_some); + let alive = matches!(s.kind, 'e' | 'n'); + let here = self.dim.id(); + let in_place = self.lan_acting.filter(|_| self.player.is_some()); + self.lan + .iter() + .flat_map(|h| h.hub.guests.iter()) + .filter(|g| g.placed) + .filter(|g| !limited || g.dimension == here || Some(g.conn) == in_place) + .filter(|g| !alive || (!g.dead && g.health > 0.0)) + .map(|g| { + if Some(g.conn) == in_place { + Target::Player + } else { + Target::Guest(g.conn) + } + }) + .collect() + } + + /// A guest's experience level and game mode, for `level=` and `gamemode=`. + pub(super) fn guest_level_and_mode(&self, conn: u32) -> Option<(i32, &'static str)> { + self.command_guest(conn) + .map(|g| (g.xp_level, mode_name(g.game_mode))) + } + + /// `Player.getDisplayName`: the name as its team shows it, suggesting a + /// `/tell`, showing the player on hover, inserting the name. + pub(in crate::game) fn player_text(&self, name: &str, uuid: u128) -> Text { + let shown = match self.score.board.players_team(name) { + Some(team) => team.formatted_name(Text::literal(name)), + None => Text::literal(name), + }; + shown.with_component_fields(vec![ + ( + "click_event".into(), + serde_json::json!({"action": "suggest_command", "command": format!("/tell {name} ")}), + ), + ( + "hover_event".into(), + serde_json::json!({"action": "show_entity", "id": "minecraft:player", + "uuid": horizon_protocol::crypto::uuid_string(uuid), "name": name}), + ), + ("insertion".into(), name.into()), + ]) + } + + /// Run `f` for the player `t` (None for anything else): in place, or + /// with the guest's state swapped in, in their level, as their own turn. + /// What `f` tells the player (`system_message`) goes to their chat; the + /// command's own feedback is the caller's to send. + pub(in crate::game) fn for_player( + &mut self, + t: Target, + f: impl FnOnce(&mut Self) -> T, + ) -> Option { + let conn = match t { + Target::Player => return Some(f(self)), + Target::Guest(conn) if self.lan_acting == Some(conn) => return Some(f(self)), + Target::Guest(conn) => conn, + _ => return None, + }; + let mut host = self.lan.take()?; + let back = self.dim; + let theirs = host + .hub + .guest(conn) + .map(|g| super::super::Dim::from_id(&g.dimension)); + if let Some(dim) = theirs.filter(|d| *d != back) + && let Err(e) = self.enter_level(Some(&mut host), dim) + { + log::error!("could not open {}: {e}", dim.id()); + } + let Some(swap) = self.enter_guest(&mut host, conn) else { + if self.dim != back + && let Err(e) = self.enter_level(Some(&mut host), back) + { + log::error!("could not reopen {}: {e}", back.id()); + } + self.lan = Some(host); + return None; + }; + self.lan = Some(host); + let source = self.chat_capture.replace(Vec::new()); + let out = f(self); + let told = std::mem::replace(&mut self.chat_capture, source).unwrap_or_default(); + let mut host = self + .lan + .take() + .expect("the hub is back after a player's turn"); + self.leave_guest(&mut host, swap); + for line in told { + host.hub.send_to( + conn, + &C::SystemChat(play::SystemChat { + content: horizon_client::lan::data::component_nbt(&line.component()), + overlay: false, + }), + ); + } + if self.dim != back + && let Err(e) = self.enter_level(Some(&mut host), back) + { + log::error!("could not reopen {}: {e}", back.id()); + } + self.lan = Some(host); + Some(out) + } +} diff --git a/crates/horizon-client/src/game/commands/terrain_cmds.rs b/crates/horizon-client/src/game/commands/terrain_cmds.rs index cee7a1d72..46df0ce7d 100644 --- a/crates/horizon-client/src/game/commands/terrain_cmds.rs +++ b/crates/horizon-client/src/game/commands/terrain_cmds.rs @@ -174,7 +174,7 @@ impl Game<'_> { if volume > i64::from(limit) { return Err(err("commands.fillbiome.toobig", &[&limit, &volume])); } - let Some(target) = self.res.biomes.list.iter().position(|b| b.name == biome) else { + let Some(target) = self.res.biomes().list.iter().position(|b| b.name == biome) else { return Err(err( "argument.resource.not_found", &[&biome, &"minecraft:worldgen/biome"], @@ -201,7 +201,7 @@ impl Game<'_> { continue; }; let current = chunk.biome(x, y, z); - let current_name = &self.res.biomes.list[usize::from(current)].name; + let current_name = &self.res.biomes().list[usize::from(current)].name; if let Some(f) = &filter && !self.biome_matches(f, current_name) { @@ -474,11 +474,11 @@ impl Game<'_> { let json = horizon_client::scoreboard::tag_to_json(&tag); let drops = self .res - .items + .items() .inline_loot_table(&json, &mut self.world.random); (drops, None) } else { - if !self.res.items.has_loot_table(&table) { + if !self.res.items().has_loot_table(&table) { return Err(err("argument.resource_or_id.failed_to_parse", &[&table])); } let held = if id == "loot.fish" { @@ -486,14 +486,14 @@ impl Game<'_> { } else { None }; - let drops = match self.res.items.loot_sequence(&table) { + let drops = match self.res.items().loot_sequence(&table) { Some(seq) => { let random = self.rand_sequences.get(&seq, self.level.seed); self.res - .items + .items() .loot_table(&table, false, held.as_ref(), random) } - None => self.res.items.loot_table( + None => self.res.items().loot_table( &table, false, held.as_ref(), @@ -510,7 +510,7 @@ impl Game<'_> { }; let ty = self.target_type(t); let table = format!("minecraft:entities/{}", ty.trim_start_matches("minecraft:")); - if t == Target::Player || !self.res.items.has_loot_table(&table) { + if t == Target::Player || !self.res.items().has_loot_table(&table) { return Err(err( "commands.drop.no_loot_table.entity", &[&self.target_name(t).plain()], @@ -521,14 +521,14 @@ impl Game<'_> { None | Some(Some(Target::Player)) ); let held = self.slot_get(&super::items::Slot::Inv(self.selected)); - let drops = match self.res.items.loot_sequence(&table) { + let drops = match self.res.items().loot_sequence(&table) { Some(seq) => { let random = self.rand_sequences.get(&seq, self.level.seed); self.res - .items + .items() .entity_drops(&ty, by_player, held.as_ref(), random) } - None => self.res.items.entity_drops( + None => self.res.items().entity_drops( &ty, by_player, held.as_ref(), @@ -543,21 +543,21 @@ impl Game<'_> { let state = self.world.block(p[0], p[1], p[2]); let name = self.data_block_name(p); let table = format!("minecraft:blocks/{}", name.trim_start_matches("minecraft:")); - if !self.res.items.has_loot_table(&table) { + if !self.res.items().has_loot_table(&table) { return Err(err("commands.drop.no_loot_table.block", &[&name])); } let tool = self.tool_stack(ctx)?; - let drops = match self.res.items.loot_sequence(&table) { + let drops = match self.res.items().loot_sequence(&table) { Some(seq) => { let random = self.rand_sequences.get(&seq, self.level.seed); - self.res.items.block_drops( + self.res.items().block_drops( self.pack.assets.registry, state, tool.as_ref(), random, ) } - None => self.res.items.block_drops( + None => self.res.items().block_drops( self.pack.assets.registry, state, tool.as_ref(), @@ -624,7 +624,7 @@ impl Game<'_> { && cur.damage == left.damage && cur.extra == left.extra => { - let max = self.res.items.get(&cur.item).map_or(64, |i| i.max_stack); + let max = self.res.items().get(&cur.item).map_or(64, |i| i.max_stack); let take = left.count.min(max.saturating_sub(cur.count)); if take > 0 { cur.count += take; diff --git a/crates/horizon-client/src/game/commands/text_commands.rs b/crates/horizon-client/src/game/commands/text_commands.rs index da8485849..dead07d71 100644 --- a/crates/horizon-client/src/game/commands/text_commands.rs +++ b/crates/horizon-client/src/game/commands/text_commands.rs @@ -1,6 +1,7 @@ //! `/tellraw` (TellRawCommand) and `/title` (TitleCommand). use super::{Arg, Context, Game, R, Target, err}; -use horizon_client::text::Text; +use horizon_client::{hud_overlays::Titles, lan::data::component_nbt, text::Text}; +use horizon_protocol::packets::play::{self, Clientbound as C}; impl Game<'_> { /// ComponentArgument with selectors resolved for the source @@ -153,30 +154,45 @@ impl Game<'_> { let name = self.target_name(Target::Player); let single = n == 1; let key = if ctx.has("clear") { - self.titles.clear(); + self.titles_or_packet(Titles::clear, C::ClearTitles(play::Bool1 { value: false })); "cleared" } else if ctx.has("reset") { - self.titles.clear(); - self.titles.reset_times(); + self.titles_or_packet( + |t| { + t.clear(); + t.reset_times(); + }, + C::ClearTitles(play::Bool1 { value: true }), + ); "reset" } else if ctx.has("times") { let get = |k: &str| match ctx.get(k) { Some(Arg::Int(v)) => *v, _ => -1, }; - self.titles - .set_times(get("fadeIn"), get("stay"), get("fadeOut")); + let (fade_in, stay, fade_out) = (get("fadeIn"), get("stay"), get("fadeOut")); + self.titles_or_packet( + |t| t.set_times(fade_in, stay, fade_out), + C::SetTitlesAnimation(play::TitlesAnimation { + fade_in, + stay, + fade_out, + }), + ); "times" } else { let text = self.component_arg(ctx, "title")?; + let sent = play::Text { + text: component_nbt(&text.component()), + }; if ctx.has("subtitle") { - self.titles.set_subtitle(text); + self.titles_or_packet(|t| t.set_subtitle(text), C::SetSubtitleText(sent)); "show.subtitle" } else if ctx.has("actionbar") { - self.titles.set_overlay(text, false); + self.titles_or_packet(|t| t.set_overlay(text, false), C::SetActionBarText(sent)); "show.actionbar" } else { - self.titles.set_title(text); + self.titles_or_packet(|t| t.set_title(text), C::SetTitleText(sent)); "show.title" } }; @@ -191,4 +207,13 @@ impl Game<'_> { self.feedback(message); Ok(n as i32) } + /// The player the title is for: the guest acting now is sent the packet + /// (TitleCommand's `connection.send`), the window's own player shows it. + fn titles_or_packet(&mut self, local: impl FnOnce(&mut Titles), packet: C) { + if self.lan_acting.is_some() { + self.guest_packets.push(packet); + } else { + local(&mut self.titles); + } + } } diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 2055798f4..ef2adf80c 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -31,7 +31,7 @@ impl Game<'_> { /// Every recipe id of the recipe manager (what `/recipe` resolves and suggests). pub(super) fn learnable_recipes(&self) -> Vec { - self.res.stations.recipe_index.ids().cloned().collect() + self.res.stations().recipe_index.ids().cloned().collect() } pub(super) fn cmd_recipe(&mut self, id: &str, ctx: &Context) -> R { let targets = self.entities(ctx, "targets", true)?; @@ -52,7 +52,7 @@ impl Game<'_> { // displays (a transmute recipe has one per material count). let mut n = 0; // ServerPlayer.awardRecipes / resetRecipes: the displays changed. - let index = &self.res.stations.recipe_index; + let index = &self.res.stations().recipe_index; n += if give { let (count, unlocked) = self.level.recipe_book.add_recipes(index, &recipes); self.recipe_unlocked(&unlocked); @@ -1267,7 +1267,7 @@ impl Game<'_> { fn spread_spawn_y(&self, p: [f64; 2], max_y: i32) -> i32 { let (x, z) = (p[0].floor() as i32, p[1].floor() as i32); let air = |y: i32| { - let name: &str = &self.res.facts.get(self.world.block(x, y, z)).name; + let name: &str = &self.res.facts().get(self.world.block(x, y, z)).name; matches!( name, "minecraft:air" | "minecraft:cave_air" | "minecraft:void_air" @@ -1292,16 +1292,16 @@ impl Game<'_> { fn spread_safe(&self, p: [f64; 2], max_y: i32) -> bool { let y = self.spread_spawn_y(p, max_y) - 1; let (x, z) = (p[0].floor() as i32, p[1].floor() as i32); - let name = self.res.facts.get(self.world.block(x, y, z)).name.clone(); + let name = self.res.facts().get(self.world.block(x, y, z)).name.clone(); let liquid = matches!(&*name, "minecraft:water" | "minecraft:lava"); let teleportable = self .res - .items + .items() .block_tags .get("entities_can_teleport_to") .or_else(|| { self.res - .items + .items() .block_tags .get("minecraft:entities_can_teleport_to") }) diff --git a/crates/horizon-client/src/game/composter.rs b/crates/horizon-client/src/game/composter.rs index 3e4cb7169..3f57229ad 100644 --- a/crates/horizon-client/src/game/composter.rs +++ b/crates/horizon-client/src/game/composter.rs @@ -21,7 +21,7 @@ impl Game<'_> { } /// The item's `compostable` layers provider. fn compostable(&self, stack: &ItemStack) -> Option { - self.res.items.get(&stack.item)?.compostable.clone() + self.res.items().get(&stack.item)?.compostable.clone() } /// `ComposterBlock.addLayer` and level event 1500: the provider is /// evaluated in the composter's block-interaction loot context (its diff --git a/crates/horizon-client/src/game/consume.rs b/crates/horizon-client/src/game/consume.rs new file mode 100644 index 000000000..50b1fa814 --- /dev/null +++ b/crates/horizon-client/src/game/consume.rs @@ -0,0 +1,330 @@ +//! Finishing a consumable (`Consumable.onConsume` and the use remainder), +//! its particles and sounds, and `TeleportRandomlyConsumeEffect` (chorus +//! fruit) for the local player. The level random stands in for the player's +//! own, as for every other player draw. +use super::{Dim, Game}; +use horizon_client::{ + items::{ConsumeEffect, ItemInfo, ItemStack}, + mobs::Who, + particles::{ParticleOptions, ParticleType}, +}; +use horizon_core::{ + geometry::Vec3, position::BlockPos, random::LegacyRandom, random::RandomSource, +}; +use horizon_world::{ + consumable::{Consumable, EmissionWorld, UseAnimation}, + teleport_consume::{TeleportConsume, TeleportConsumeWorld}, +}; +use std::convert::Infallible; + +type ItemConsumable = Consumable; + +impl Game<'_> { + /// `Consumable.emitParticlesAndSounds(user.getRandom(), user, stack, count)`. + pub(super) fn emit_consume( + &mut self, + consumable: &ItemConsumable, + stack: &ItemStack, + count: i32, + ) { + let Ok(()) = consumable.emit(&mut Emitter(self), (), stack.clone(), count); + } + /// `LivingEntity.completeUsingItem` for a consumable: `Consumable.onConsume`, + /// then `ItemStack.applyAfterUseComponentSideEffects`' use remainder. + pub(super) fn finish_consuming( + &mut self, + info: &ItemInfo, + consumable: &ItemConsumable, + stack: &ItemStack, + ) { + self.emit_consume(consumable, stack, 16); + // ServerPlayer: the used statistic and the consume_item trigger. + self.stats.add("used", &stack.item, 1); + self.trigger_item("minecraft:consume_item", stack); + // FoodProperties.onConsume, the player's one ConsumableListener. + if let Some((nutrition, saturation)) = info.food { + let at = self.feet(); + let pitch = self.world.random.triangle_float(1.0, 0.4); + self.audio.play(&consumable.sound, at, 1.0, pitch); + if let Some(p) = self.player.as_mut() { + // FoodData.eat(nutrition, saturation) + let food = &mut p.health.food; + food.food = (food.food + nutrition as i32).clamp(0, 20); + food.saturation = (food.saturation + saturation).clamp(0.0, food.food as f32); + } + // Mth.randomBetween(random, 0.9, 1.0) + let pitch = self.world.random.next_float() * (1.0f32 - 0.9f32) + 0.9; + self.audio + .play("minecraft:entity.player.burp", self.feet(), 0.5, pitch); + } + for effect in &consumable.effects { + self.apply_consume_effect(effect); + } + let event = if consumable.animation == UseAnimation::Drink { + "minecraft:drink" + } else { + "minecraft:eat" + }; + self.post_entity_event(event, Who::Player); + // ItemStack.consume, then UseRemainder.convertIntoRemainder: nothing + // with infinite materials, the hand when emptied, else the inventory + // (ServerPlayer.handleExtraItemsCreatedOnUse) or a drop. + self.consume_held(); + if let Some(remainder) = &info.use_remainder + && !self.creative + { + let remainder = ItemStack::new(remainder, 1); + if self.held().is_none() { + *self.held_mut() = Some(remainder); + } else if let Some(rest) = self.give(remainder) { + self.player_drop(rest); + } + } + } + fn feet(&self) -> Option<[f64; 3]> { + self.player + .as_ref() + .map(|p| [p.position.x, p.position.y, p.position.z]) + } + /// `TeleportRandomlyConsumeEffect.apply` for the local player. + pub(super) fn teleport_randomly(&mut self, teleport: &TeleportConsume) { + if self.player.is_none() { + return; + } + let dim = self.dim; + let Ok(_) = teleport.apply(&mut Teleporter(self), dim); + } + /// `LivingEntity.randomTeleport(x, y, z, true, avoid)`: down to the first + /// block entities can teleport onto, inside the border, in a loaded chunk. + fn random_teleport(&mut self, target: Vec3, avoid: &str) -> bool { + let [min_x, min_z, max_x, max_z] = self.border.bounds(); + // WorldBorder.clampVec3ToBound (Mth.clamp, 1.0E-5F inside the far edge). + let clamp = |v: f64, low: f64, high: f64| if v < low { low } else { v.min(high) }; + let x = clamp(target.x, min_x, max_x - f64::from(1.0e-5_f32)); + let z = clamp(target.z, min_z, max_z - f64::from(1.0e-5_f32)); + let mut y = target.y; + let mut pos = BlockPos::containing(Vec3::new(x, y, z)); + if !self.world.loaded(pos.x, pos.z) { + return false; + } + while pos.y > self.dim.min_y() { + pos.y -= 1; + let state = self.world.block(pos.x, pos.y, pos.z); + if self.state_in_tag("minecraft:entities_can_teleport_to", state) { + return self.check_position_and_teleport(Vec3::new(x, y, z), state, avoid); + } + y -= 1.0; + } + false + } + /// `LivingEntity.checkPositionAndTeleport`, then `ServerPlayer.teleportTo` + /// (the motion and rotation kept) and entity event 46. + fn check_position_and_teleport( + &mut self, + at: Vec3, + ground: horizon_world::registry::BlockStateId, + avoid: &str, + ) -> bool { + if self.state_in_tag(avoid, ground) { + return false; + } + let entities = self.happy_ghast_player_collisions(); + let Some(player) = self.player.as_mut() else { + return false; + }; + let bounds = player.dimensions.bounds(at); + let free = horizon_client::motion::MotionWorld { + entities: &entities, + player, + scene: &mut self.world, + assets: &self.pack.assets, + collision_binding: self.collision, + resources: self.motion, + } + .no_player_collision(bounds) + .unwrap_or(false); + // LevelReader.containsAnyLiquid and findBlocksIn: the blocks from the + // box's minimum corner to the one holding its maximum corner. + let (lo, hi) = ( + BlockPos::containing(bounds.min_position()), + BlockPos::containing(bounds.max_position()), + ); + let blocks = (lo.x..=hi.x) + .flat_map(|x| (lo.y..=hi.y).flat_map(move |y| (lo.z..=hi.z).map(move |z| (x, y, z)))); + let states: Vec<_> = blocks.map(|(x, y, z)| self.world.block(x, y, z)).collect(); + let liquid = states + .iter() + .any(|&s| self.res.facts().get(s).fluid != horizon_client::blocks::Fluid::None); + if !free || liquid || states.iter().any(|&s| self.state_in_tag(avoid, s)) { + return false; + } + if let Some(p) = self.player.as_mut() { + p.position = at; + } + // The position packet moves the old position along (absolute xyz). + self.previous_position = at; + self.portal_particles(); + true + } + fn state_in_tag(&self, tag: &str, state: horizon_world::registry::BlockStateId) -> bool { + let name = &self.res.facts().get(state).name; + self.res + .items() + .block_tags + .get(tag) + .is_some_and(|s| s.contains(&**name)) + } + /// `LivingEntity.handleEntityEvent(46)`: 128 portal particles from the old + /// to the new position, from the client player's random (the particle + /// engine's here). + fn portal_particles(&mut self) { + let Some(p) = self.player.as_ref() else { + return; + }; + let (from, to) = (self.previous_position, p.position); + let (width, height) = ( + f64::from(p.dimensions.width), + f64::from(p.dimensions.height), + ); + let options = ParticleOptions::simple(ParticleType::Portal); + for i in 0..128 { + let d = f64::from(i) / 127.0; + let r = self.particles.random(); + let v = [0; 3].map(|_| f64::from((r.next_float() - 0.5) * 0.2)); + let x = from.x + d * (to.x - from.x) + (r.next_double() - 0.5) * width * 2.0; + let y = from.y + d * (to.y - from.y) + r.next_double() * height; + let z = from.z + d * (to.z - from.z) + (r.next_double() - 0.5) * width * 2.0; + self.particles.add(&options, [x, y, z], v); + } + } + /// `LivingEntity.stopRiding`. + pub(super) fn stop_riding(&mut self) { + let Some(id) = self.riding else { + return; + }; + if let Some(i) = self.boats.iter().position(|b| b.id == id) { + self.dismount(i); + } else if let Some(i) = self.carts.iter().position(|c| c.id == id) { + self.dismount_cart(i); + } else { + self.dismount_mount(); + } + } +} + +/// `Consumable.emitParticlesAndSounds` against the local player. +struct Emitter<'a, 'g>(&'a mut Game<'g>); +impl EmissionWorld for Emitter<'_, '_> { + type Error = Infallible; + type Stack = ItemStack; + type Sound = String; + type Random = (); + type Source = LegacyRandom; + fn random_source(&mut self, (): ()) -> &mut LegacyRandom { + &mut self.0.world.random + } + /// `LivingEntity.spawnItemParticles`. + fn spawn_item_particles(&mut self, stack: ItemStack, count: i32) -> Result<(), Infallible> { + self.0.eat_particles(&stack, count.max(0) as u32); + Ok(()) + } + fn overrides_consume_sound(&self) -> bool { + false + } + fn consume_sound(&mut self, _: ItemStack) -> Result { + unreachable!("players play the consumable's own sound") + } + /// `Entity.playSound`: at the player's position. + fn play_sound(&mut self, sound: String, volume: f32, pitch: f32) -> Result<(), Infallible> { + let at = self.0.feet(); + self.0.audio.play(&sound, at, volume, pitch); + Ok(()) + } +} + +/// The local player as `TeleportRandomlyConsumeEffect`'s user. +struct Teleporter<'a, 'g>(&'a mut Game<'g>); +impl Teleporter<'_, '_> { + fn at(&self) -> Vec3 { + self.0.player.as_ref().map_or(Vec3::ZERO, |p| p.position) + } +} +impl TeleportConsumeWorld for Teleporter<'_, '_> { + type Error = Infallible; + type Level = Dim; + type Random = (); + type Source = LegacyRandom; + fn position_field(&self) -> Vec3 { + self.at() + } + fn get_random(&mut self) -> Result<(), Infallible> { + Ok(()) + } + fn random_source(&mut self, (): ()) -> &mut LegacyRandom { + &mut self.0.world.random + } + fn min_y(&mut self, level: Dim) -> Result { + Ok(level.min_y()) + } + fn logical_height(&mut self, level: Dim) -> Result { + Ok(level.logical_height()) + } + fn is_passenger(&mut self) -> Result { + Ok(self.0.riding.is_some()) + } + fn stop_riding(&mut self) -> Result<(), Infallible> { + self.0.stop_riding(); + Ok(()) + } + fn position(&mut self) -> Result { + Ok(self.at()) + } + fn random_teleport(&mut self, target: Vec3) -> Result { + Ok(self + .0 + .random_teleport(target, "minecraft:consumable_does_not_teleport_to")) + } + fn teleport_event(&mut self, _: Dim, old: Vec3) -> Result<(), Infallible> { + let ctx = self.0.who_context(Some(Who::Player), None); + self.0 + .post_game_event("minecraft:teleport", [old.x, old.y, old.z], ctx); + Ok(()) + } + fn is_fox(&self) -> bool { + false + } + fn teleport_sound(&mut self, _: Dim, at: Vec3, _: bool) -> Result<(), Infallible> { + self.0.audio.play( + "minecraft:item.chorus_fruit.teleport", + Some([at.x, at.y, at.z]), + 1.0, + 1.0, + ); + Ok(()) + } + fn block_position(&mut self) -> Result { + Ok(BlockPos::containing(self.at())) + } + fn directional_particles( + &mut self, + _: Dim, + origin: BlockPos, + offset: i32, + ) -> Result<(), Infallible> { + self.0 + .level_event_at(2017, [origin.x, origin.y, origin.z], offset); + Ok(()) + } + fn reset_fall_distance(&mut self) -> Result<(), Infallible> { + if let Some(p) = self.0.player.as_mut() { + p.fall_distance = 0.0; + } + Ok(()) + } + fn reset_impulse(&mut self) -> Result<(), Infallible> { + if let Some(p) = self.0.player.as_mut() { + p.impulse.reset(); + } + Ok(()) + } +} diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index fa72c7a40..3e0711aeb 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -54,12 +54,23 @@ pub struct Flight { /// Reply with every frame time too (`fly ... PITCH raw`). raw: bool, reply: Sender, + /// The world's smoothed tick time each frame (the F3 server line): the + /// server thread's when single player runs on one. + tick_ms: Vec, } impl Game<'_> { /// Move the camera along the running flight; reply when it ends. pub(super) fn advance_flight(&mut self) { - let Some(flight) = &self.flight else { return }; + let tick_ms = self + .integrated + .as_ref() + .map_or(self.debug_charts.smoothed_tick_ms, |s| s.smoothed_tick_ms()); + let Some(flight) = self.flight.as_mut() else { + return; + }; + flight.tick_ms.push(tick_ms); + let flight = &*flight; let t = (flight.started.elapsed().as_secs_f64() / flight.seconds).min(1.0); let (a, b) = (flight.from, flight.to); let d = [b.x - a.x, b.y - a.y, b.z - a.z]; @@ -79,6 +90,9 @@ impl Game<'_> { && let Some(flight) = self.flight.take() { let mut summary = self.frame_stats.summary(); + let n = flight.tick_ms.len().max(1) as f32; + summary["tick_ms"] = (flight.tick_ms.iter().sum::() / n).into(); + summary["tick_ms_max"] = flight.tick_ms.iter().copied().fold(0.0, f32::max).into(); if flight.raw { summary["frame_ms"] = self.frame_stats.frame_millis().into(); summary["cpu_ms"] = self.frame_stats.cpu_millis().into(); @@ -183,6 +197,16 @@ impl Game<'_> { } Ok(Some(json!({ "ok": true, "flat": r.flat_draws() }))) } + "section-cull" => { + let r = self.renderer.as_mut().ok_or("no renderer")?; + match words.get(1).copied() { + None => {} + Some("on") => r.set_section_cull(true)?, + Some("off") => r.set_section_cull(false)?, + Some(other) => return Err(format!("unknown section cull mode {other}").into()), + } + Ok(Some(json!({ "ok": true, "cull": r.section_cull() }))) + } "sculk" => Ok(Some(self.sculk_command(&words)?)), "status" => Ok(Some(self.control_status())), "pad" => Ok(Some(self.pad_command(&words)?)), @@ -345,10 +369,18 @@ impl Game<'_> { }; let info = self .res - .items + .items() .get(&item) .ok_or_else(|| format!("unknown item {item}"))?; let count: u32 = words.get(2).map_or(Ok(1), |c| c.parse())?; + // Single player's inventory is its server thread's player's. + if let Some(server) = &self.integrated { + let command = format!("give @s {item} {count}"); + server + .call(move |g| g.owner_console_command(&command)) + .ok_or("the integrated server stopped")?; + return Ok(Some(json!({ "ok": true, "given": count }))); + } let max = info.max_stack; let mut given = 0; // Stop once the inventory is full. @@ -379,7 +411,14 @@ impl Game<'_> { ok() } "time" => { - self.world.day_time = arg(1)?.parse()?; + let time: i64 = arg(1)?.parse()?; + self.world.day_time = time; + // Single player's clock is its server thread's. + if let Some(server) = &self.integrated { + server + .call(move |g| g.world.day_time = time) + .ok_or("the integrated server stopped")?; + } ok() } "summon" => { @@ -437,7 +476,7 @@ impl Game<'_> { match self.screen { Screen::Chat => self.chat_type(text), Screen::CommandBlock => self.command_block_type(text), - Screen::Options => self.ui.options.type_text(&self.atlas, text), + Screen::Options => self.ui.options.type_text(&self.gui.atlas, text), // The port, or the game rules' search and number boxes. Screen::WorldOptions if text == "\\b" => self.world_options_text(None), Screen::WorldOptions => self.world_options_text(Some(text)), @@ -527,6 +566,7 @@ impl Game<'_> { seconds: n(7)?.max(0.1), raw: words.get(9) == Some(&"raw"), reply: reply.clone(), + tick_ms: Vec::new(), }); Ok(None) } @@ -661,7 +701,7 @@ impl Game<'_> { }); let target = self.pick().map(|hit| { let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); - json!({ "pos": hit.pos, "block": &*self.res.facts.get(state).name }) + json!({ "pos": hit.pos, "block": &*self.res.facts().get(state).name }) }); let renderer = self.renderer.as_ref().map(|r| { let [arena_bytes, section_vertex_bytes] = r.section_vertex_bytes(); @@ -684,6 +724,7 @@ impl Game<'_> { "drawn_sections": r.drawn_sections, "section_draws": r.section_draws, "section_draw_calls": r.section_draw_calls, + "culled_sections": r.culled_sections(), "uploaded_bytes": r.uploaded_bytes, "resident_sections": r.resident_sections(), "arena_bytes": arena_bytes, @@ -758,6 +799,10 @@ impl Game<'_> { .map(|e| self.shown_name_tags(glam::DVec3::from_array(e))), }); status["physical_keys"] = json!(physical_keys); + // Boats, minecarts, armor stands, item frames and paintings. + status["objects"] = json!(self.objects_status()); + // Primed TNT, falling blocks, projectiles, tridents and end crystals. + status["projectiles"] = json!(self.projectiles_status()); status } } diff --git a/crates/horizon-client/src/game/copper_golems.rs b/crates/horizon-client/src/game/copper_golems.rs index a12fbd416..2f98e1c7e 100644 --- a/crates/horizon-client/src/game/copper_golems.rs +++ b/crates/horizon-client/src/game/copper_golems.rs @@ -106,7 +106,7 @@ impl Game<'_> { fn golem_chest_sound(&mut self, p: [i32; 3], open: bool) { let name = self .res - .facts + .facts() .get(self.world.block(p[0], p[1], p[2])) .name .clone(); @@ -292,7 +292,7 @@ impl Game<'_> { pub(super) fn golem_shearable(&self, index: usize) -> bool { self.mobs[index].saddle_item().is_some_and(|a| { self.res - .items + .items() .item_tags .get("minecraft:shearable_from_copper_golem") .is_some_and(|t| t.contains(&*a.item)) diff --git a/crates/horizon-client/src/game/creaking.rs b/crates/horizon-client/src/game/creaking.rs index 099f3d7d8..e7a1386f9 100644 --- a/crates/horizon-client/src/game/creaking.rs +++ b/crates/horizon-client/src/game/creaking.rs @@ -110,7 +110,7 @@ impl Game<'_> { let mut next_entity = self.next_entity; let mut random = self.world.random.clone(); let spawning = self.spawning_monsters(); - let creaking = self.res.mob_types.get("minecraft:creaking").cloned(); + let creaking = self.res.mob_types().get("minecraft:creaking").cloned(); let player_uuid = self.level.player_uuid; let snapshot: Vec<_> = mobs.iter().map(|m| seen(m, player_uuid)).collect(); let mut events = Vec::new(); @@ -164,7 +164,7 @@ impl Game<'_> { return; } let key = (home[0], home[1], home[2]); - let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.remove(&key) + let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.take(&key) else { return; }; @@ -173,7 +173,7 @@ impl Game<'_> { }); self.world .block_entities - .insert(key, BlockEntity::CreakingHeart(heart)); + .put(key, BlockEntity::CreakingHeart(heart)); } /// `Creaking.tearDown`: the crumble particles. pub(super) fn creaking_tear_down(&mut self, center: [f64; 3], spread: [f64; 3]) { @@ -220,7 +220,13 @@ impl Game<'_> { /// death and a natural heart drops experience. pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3]) { let key = (pos[0], pos[1], pos[2]); - let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.remove(&key) + if !matches!( + self.world.block_entities.get(&key), + Some(BlockEntity::CreakingHeart(_)) + ) { + return; + } + let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.take(&key) else { return; }; @@ -248,43 +254,35 @@ impl Game<'_> { } self.world .block_entities - .insert(key, BlockEntity::CreakingHeart(heart)); + .put(key, BlockEntity::CreakingHeart(heart)); } - /// `CreakingHeartBlockEntity.serverTick` for every heart. - pub(super) fn tick_creaking_hearts(&mut self) -> Result<()> { - let keys: Vec = self - .world - .block_entities - .iter() - .filter(|(_, e)| matches!(e, BlockEntity::CreakingHeart(_))) - .map(|(k, _)| *k) - .collect(); - for key in keys { - let Some(BlockEntity::CreakingHeart(mut heart)) = - self.world.block_entities.remove(&key) - else { - continue; - }; - let state = self.world.block(key.0, key.1, key.2); - if &*self.res.facts.get(state).name != "minecraft:creaking_heart" { - // The block is gone: preRemoveSideEffects. - self.with_heart(key, &mut heart, |h, _, _, host, out| { - creaking_heart::remove_protector(h, host, false, out); - })?; - continue; - } - // getTicker: none once uprooted. - if self.heart_state_name(state) != "uprooted" { - let pos = [key.0, key.1, key.2]; - self.with_heart(key, &mut heart, |h, w, lr, host, out| { - creaking_heart::server_tick(h, pos, w, lr, host, out); - })?; - } - self.world - .block_entities - .insert(key, BlockEntity::CreakingHeart(heart)); + /// `CreakingHeartBlockEntity.serverTick` of the heart at `key`. Its slot + /// stays while uprooted, so that a heart whose block went away is still + /// found here and lets go of its protector. + pub(super) fn tick_creaking_heart(&mut self, key: Pos) -> Result<()> { + let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.take(&key) + else { + return Ok(()); + }; + let state = self.world.block(key.0, key.1, key.2); + if &*self.res.facts().get(state).name != "minecraft:creaking_heart" { + // The block is gone: preRemoveSideEffects. + self.world.block_entities.forget(&key); + self.with_heart(key, &mut heart, |h, _, _, host, out| { + creaking_heart::remove_protector(h, host, false, out); + })?; + return Ok(()); } - self.scan_for_hearts(); + // getTicker: none once uprooted. + if self.heart_state_name(state) != "uprooted" { + let pos = [key.0, key.1, key.2]; + self.with_heart(key, &mut heart, |h, w, lr, host, out| { + creaking_heart::server_tick(h, pos, w, lr, host, out); + })?; + } + self.world + .block_entities + .put(key, BlockEntity::CreakingHeart(heart)); Ok(()) } /// `ServerLevel.isSpawningMonsters`. @@ -295,7 +293,7 @@ impl Game<'_> { } /// Hearts that came with generated or loaded chunks get their block /// entity (`newBlockEntity`) the first time their chunk is seen. - fn scan_for_hearts(&mut self) { + pub(super) fn scan_for_hearts(&mut self) { let Some(heart) = self .pack .assets @@ -319,7 +317,7 @@ impl Game<'_> { if self.creaking.hearts.is_empty() { self.creaking.hearts = self .res - .facts + .facts() .states .iter() .map(|f| &*f.name == "minecraft:creaking_heart") @@ -327,13 +325,16 @@ impl Game<'_> { } let hearts = &self.creaking.hearts; let _ = heart; + let is_heart = |id: u32| hearts.get(id as usize).copied().unwrap_or(false); for (si, section) in chunk.sections.iter().enumerate() { - if section.is_uniform(0) { + // Only a section whose palette holds a heart state can have + // one: the others are skipped without reading their 4,096 blocks. + if !section.blocks.maybe_has(is_heart) { continue; } for i in 0..4096 { let id = section.get(i); - if !hearts.get(id as usize).copied().unwrap_or(false) { + if !is_heart(id) { continue; } let (lx, lz, ly) = ((i & 15) as i32, ((i >> 4) & 15) as i32, (i >> 8) as i32); @@ -344,8 +345,7 @@ impl Game<'_> { ); self.world .block_entities - .entry(pos) - .or_insert_with(|| BlockEntity::CreakingHeart(Box::default())); + .get_or_insert_with(pos, || BlockEntity::CreakingHeart(Box::default())); } } } diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 6c7fd67fc..422d050b6 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -196,6 +196,7 @@ impl Game<'_> { hero: self.potions.effects.get("hero_of_the_village").is_some(), uuid: self.level.player_uuid.unwrap_or_default(), allies: std::sync::Arc::new(self.player_allies()), + remote: false, }) } /// Biome facts at a position for finalizeSpawn and variant rules. @@ -203,8 +204,8 @@ impl Game<'_> { let Some(chunk) = self.world.chunks.get(&(x >> 4, z >> 4)) else { return BiomeFacts::default(); }; - let b = self.res.biomes.get(chunk.biome(x, y, z)); - let tags = &self.res.mob_data; + let b = self.res.biomes().get(chunk.biome(x, y, z)); + let tags = self.res.mob_data(); let has = |t: &str| tags.biome_has(t, &b.name); let climate = if has("minecraft:spawns_warm_variant_farm_animals") { Climate::Warm @@ -254,7 +255,7 @@ impl Game<'_> { } else { format!("minecraft:{kind}") }; - let t = self.res.mob_types.get(&kind).cloned()?; + let t = self.res.mob_types().get(&kind).cloned()?; self.next_entity += 1; let yaw = self.world.random.next_float() * 360.0; let mut mob = Mob::new(self.next_entity, t, Vec3::new(at[0], at[1], at[2]), yaw); @@ -367,7 +368,7 @@ impl Game<'_> { pub(super) fn motion_top(&self, x: i32, z: i32) -> i32 { let top = if self.dim == Dim::Nether { 127 } else { 319 }; for y in (horizon_client::chunk::MIN_Y..=top).rev() { - let f = self.res.facts.get(self.world.block(x, y, z)); + let f = self.res.facts().get(self.world.block(x, y, z)); if (f.full_collision || f.fluid != Fluid::None) && !f.name.ends_with("leaves") { return y + 1; } @@ -379,10 +380,10 @@ impl Game<'_> { MobWorld { world: &self.world, registry: self.pack.assets.registry, - facts: &self.res.facts, + facts: self.res.facts(), movement: &self.motion.blocks, collision: self.collision, - data: &self.res.mob_data, + data: self.res.mob_data(), player: self.player_view(), others, others_grid: None, @@ -392,14 +393,14 @@ impl Game<'_> { raining: rain > 0.2, thundering: thunder > 0.9, nether: self.dim == Dim::Nether, - block_tags: &self.res.items.block_tags, - biomes: &self.res.biomes, + block_tags: &self.res.items().block_tags, + biomes: self.res.biomes(), mob_griefing: self.ui.rules.bool("mob_griefing"), end: self.dim == Dim::End, world_seed: self.level.seed, sea_level: if self.dim == Dim::Nether { 32 } else { 63 }, teams: self.mob_teams(), - items: Some(&self.res.items), + items: Some(self.res.items()), difficulty: self.local_difficulty( self.player .as_ref() @@ -474,24 +475,11 @@ impl Game<'_> { self.tick_raids(); self.tick_creature_entities() } - /// `DistanceManager.inEntityTickingRange`: chunks within the simulation - /// distance (Chebyshev, in chunks) of the player or of a guest. + /// `DistanceManager.inEntityTickingRange` in an entity-ticking chunk + /// (block coordinates), from every player's tickets (`update_chunk_tickets`). pub(super) fn entity_ticking_area(&self) -> impl Fn(i32, i32) -> bool + use<> { - let d = self.settings.simulation_distance.max(2); - let mut centres: Vec<(i32, i32)> = self.streaming.extra.iter().map(|&(c, _)| c).collect(); - if let Some(p) = &self.player { - centres.push(( - (p.position.x.floor() as i32) >> 4, - (p.position.z.floor() as i32) >> 4, - )); - } - let everywhere = centres.is_empty(); - move |x, z| { - everywhere - || centres - .iter() - .any(|&(cx, cz)| ((x >> 4) - cx).abs().max(((z >> 4) - cz).abs()) <= d) - } + let levels = self.tickets.levels(); + move |x, z| levels.entity_ticking_at(x, z) } /// The entity phase of `tick_creatures`: every mob's tick, deaths, and the /// projectiles and effects that follow from them. @@ -983,7 +971,7 @@ impl Game<'_> { if effect { let old = self.world.block(pos[0], pos[1], pos[2]); self.destroy_particles(pos, old); - let s = self.res.facts.get(old).sounds.break_sound.clone(); + let s = self.res.facts().get(old).sounds.break_sound.clone(); self.audio.play( &s, Some([ @@ -1003,7 +991,7 @@ impl Game<'_> { let old = self.world.block(pos[0], pos[1], pos[2]); self.destroy_particles(pos, old); if drop { - let drops = self.res.items.block_drops_in( + let drops = self.res.items().block_drops_in( self.pack.assets.registry, old, None, @@ -1157,7 +1145,7 @@ impl Game<'_> { MobEvent::GiftLoot { table, at } => { let drops = self.res - .items + .items() .loot_table(table, false, None, &mut self.world.random); for d in drops { self.spawn_item(d, at, [0.0, 0.2, 0.0], 10); @@ -1420,7 +1408,7 @@ impl Game<'_> { } let projectile = self .res - .stations + .stations() .enchantments .damage_tags .get("minecraft:is_projectile") @@ -1780,7 +1768,7 @@ impl Game<'_> { horizon_client::arrows::ArrowScene { world: &self.world, registry: self.pack.assets.registry, - facts: &self.res.facts, + facts: self.res.facts(), collision: self.collision, fluids: &self.motion.fluids, raining: rain, @@ -2032,7 +2020,7 @@ impl Game<'_> { let fire = [pos[0] + face[0], pos[1] + face[1], pos[2] + face[2]]; if self .res - .facts + .facts() .is_air(self.world.block(fire[0], fire[1], fire[2])) && let Some(state) = self.pack.assets.registry.default_state("minecraft:fire") @@ -2358,7 +2346,7 @@ impl Game<'_> { Species::Sheep if item == "minecraft:shears" && !m.extra.sheared && !m.is_baby() => { m.extra.sheared = true; let color = horizon_client::mobs::render::DYE_NAMES[m.extra.color as usize & 15]; - let stacks = self.res.items.loot_table( + let stacks = self.res.items().loot_table( &format!("minecraft:shearing/sheep/{color}"), false, None, @@ -2390,7 +2378,7 @@ impl Game<'_> { Species::Wolf if m.extra.tame && is_food && m.health < m.attrs.max_health => { let heal = self .res - .items + .items() .get(&item) .and_then(|i| i.food.as_ref()) .map_or(2.0, |f| f.0 as f32); @@ -2494,7 +2482,7 @@ impl Game<'_> { Species::Cat if m.extra.tame && is_food && m.health < m.attrs.max_health => { let heal = self .res - .items + .items() .get(&item) .and_then(|i| i.food.as_ref()) .map_or(1.0, |f| f.0 as f32); @@ -2661,7 +2649,7 @@ impl Game<'_> { return; } if let Some(stack) = self.inventory[self.selected].as_mut() - && let Some(info) = self.res.items.get(&stack.item) + && let Some(info) = self.res.items().get(&stack.item) && info.max_damage > 0 { stack.damage += 1; @@ -2734,7 +2722,7 @@ impl Game<'_> { // EntityType.canSpawn: no monsters in peaceful (FAIL ends the click). let id = format!("minecraft:{}", kind.trim_start_matches("minecraft:")); if self.ui.difficulty == 0 - && let Some(t) = self.res.mob_types.get(&id) + && let Some(t) = self.res.mob_types().get(&id) && !horizon_client::mobs::spawn_rules::allowed_in_peaceful(t.species) { return Ok(true); @@ -2798,7 +2786,7 @@ impl Game<'_> { } /// Mob models and projectiles for the entity pass. pub(super) fn mob_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); let scale = f64::from(self.settings.entity_distance); for mob in &self.mobs { @@ -2856,7 +2844,7 @@ impl Game<'_> { camera, &lookup, packed, - &self.res.mob_data, + self.res.mob_data(), &armor, out, ); @@ -3015,7 +3003,7 @@ impl Game<'_> { } /// Mob.getBaseExperienceReward /// The damage type id of a Horizon damage kind. -fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static str { +pub(super) fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static str { use horizon_client::mobs::DamageKind as K; match kind { K::PlayerAttack => "minecraft:player_attack", @@ -3100,13 +3088,17 @@ impl Game<'_> { return; } let mut y = pos[1]; - while &*self.res.facts.get(self.world.block(pos[0], y, pos[2])).name + while &*self + .res + .facts() + .get(self.world.block(pos[0], y, pos[2])) + .name == "minecraft:nether_portal" { y -= 1; } // isValidSpawn: a sturdy top face (portal frames emit no light). - let below = self.res.facts.get(self.world.block(pos[0], y, pos[2])); + let below = self.res.facts().get(self.world.block(pos[0], y, pos[2])); if below.sturdy_full & (1 << 1) == 0 { return; } diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index 1de6669e7..a2e1b0ce6 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -51,6 +51,9 @@ impl DebugHost for Host<'_, '_> { impl Game<'_> { fn open_screen(&self) -> OpenScreen { + if self.title.is_some() { + return OpenScreen::Other; + } match self.screen { Screen::GameModeSwitcher => OpenScreen::GameModeSwitcher, Screen::Playing if self.book.is_none() && self.sign_edit.is_none() => OpenScreen::None, @@ -437,7 +440,7 @@ impl Game<'_> { } } let (left, right) = d.columns(&self.debug_chart_lines()); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let mut draws = debug_overlay::draw(&atlas.font, [&left, &right], scale, width); let charts = self.debug_charts.draw( &atlas.font, diff --git a/crates/horizon-client/src/game/decorated_pot.rs b/crates/horizon-client/src/game/decorated_pot.rs index 3ac43566a..af2eaacb2 100644 --- a/crates/horizon-client/src/game/decorated_pot.rs +++ b/crates/horizon-client/src/game/decorated_pot.rs @@ -63,7 +63,7 @@ impl Game<'_> { /// pot without), or None when no pot is there. fn pot_tag(&mut self, pos: [i32; 3]) -> Option { let state = self.world.block(pos[0], pos[1], pos[2]); - if &*self.res.facts.get(state).name != "minecraft:decorated_pot" { + if &*self.res.facts().get(state).name != "minecraft:decorated_pot" { return None; } let mut tag = spill::saved_entity(&self.world, pos).unwrap_or_else(|| { diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index 49b77eb13..640318529 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -11,9 +11,7 @@ use horizon_client::{ Result, lan::{LoginGate, NetConfig, NetLog, OnlineMode, hub::HubConfig}, server::{ - eula, - java_properties::now_millis, - profiles, + eula, profiles, properties::{GAME_MODES, ServerProperties, SystemEntropy}, user_cache::UserCache, user_lists::{ @@ -84,18 +82,16 @@ fn log_from(thread: &str, level: &str, message: &str) { "ERROR" => ::log::Level::Error, _ => ::log::Level::Info, }; - horizon_client::logging::write_only(file_level, message); + horizon_client::logging::write_as(thread, file_level, message); CAPTURE.with_borrow_mut(|lines| { if let Some(lines) = lines { lines.push(message.to_owned()); } }); - let secs = now_millis().div_euclid(1000).rem_euclid(86_400); + // Log4j's %d{HH:mm:ss}: the local time, as in logs/latest.log. println!( - "[{:02}:{:02}:{:02}] [{thread}/{level}]: {message}", - secs / 3600, - secs / 60 % 60, - secs % 60 + "[{}] [{thread}/{level}]: {message}", + chrono::Local::now().format("%H:%M:%S") ); } @@ -340,7 +336,7 @@ impl Game<'_> { ); } let settings = if flat { - let biomes = &self.res.biomes; + 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(), @@ -402,11 +398,36 @@ struct ServerState { /// When the last passes of the loop ended, for the tick rate horizon-server shows. ticks: std::collections::VecDeque, paused: bool, + /// `broadcast-console-to-ops`. + broadcast_console: bool, } +/// The dedicated-only commands' replies vanilla sends with `broadcast` +/// (`sendSuccess(..., true)`): the operators hear of them. +const BROADCAST: &[&str] = &[ + "commands.ban.success", + "commands.banip.info", + "commands.banip.success", + "commands.deop.success", + "commands.kick.success", + "commands.op.success", + "commands.pardon.success", + "commands.pardonip.success", + "commands.save.disabled", + "commands.save.enabled", + "commands.save.success", + "commands.stop.stopping", + "commands.whitelist.add.success", + "commands.whitelist.disabled", + "commands.whitelist.enabled", + "commands.whitelist.reloaded", + "commands.whitelist.remove.success", +]; + impl Game<'_> { /// DedicatedServer.initServer and MinecraftServer.runServer. pub(super) fn run_dedicated(&mut self) -> Result<()> { + self.join_world_rest()?; let Setup { props, universe, @@ -449,6 +470,18 @@ impl Game<'_> { // DedicatedServer.initServer: names nobody has resolve offline only without authentication. cache.resolve_offline_users = !props.online_mode; *USER_CACHE.lock().unwrap() = Some(cache); + // Services.create: the services' public keys, fetched in the + // background (they check players' chat keys). + let secure_chat = Arc::new(horizon_client::lan::SecureChat::new( + props.enforce_secure_profile && props.online_mode, + || { + let discovery = profiles::discovery_url(); + profiles::fetch_profile_key_keys(&discovery).unwrap_or_else(|e| { + ::log::error!("{e}"); + Vec::new() + }) + }, + )); log("INFO", "Starting minecraft server version 26.3"); log("INFO", "Loading properties"); let game_mode = props.game_mode; @@ -547,8 +580,7 @@ impl Game<'_> { enable_status: props.enable_status, hide_online_players: props.hide_online_players, favicon, - // DedicatedServer.enforceSecureProfile needs online mode. - enforces_secure_chat: false, + secure_chat: Some(secure_chat), accepts_transfers: props.accepts_transfers, announce: false, listen: true, @@ -612,6 +644,7 @@ impl Game<'_> { empty_ticks: 0, ticks: Default::default(), paused: false, + broadcast_console: props.broadcast_console_to_ops, }; let pause_after = props.pause_when_empty_seconds * 20; let idle_timeout = props.player_idle_timeout; @@ -619,7 +652,7 @@ impl Game<'_> { while !state.stop { let tick_start = Instant::now(); while let Ok(line) = state.console.try_recv() { - self.console_command(&mut state, &line); + self.console_line(&mut state, &line); } self.poll_server_control(&mut state); let players = self.lan.as_ref().map_or(0, |h| h.hub.guests.len()); @@ -647,7 +680,7 @@ impl Game<'_> { self.ticks = self.ticks.max(1); } // MinecraftServer.tickServer: while paused only the connections run. - self.tick_server(paused)?; + self.tick_server_timed(paused)?; if idle_timeout > 0 { self.kick_idle(idle_timeout); } @@ -767,14 +800,37 @@ impl Game<'_> { }) }); if found.is_none() { - self.console_reply(Text::translate("argument.player.unknown", &[])); + let unknown = Text::translate("argument.player.unknown", &[]); + log("INFO", &format!("System chat: {}", unknown.plain())); } found } - /// MinecraftServer.sendSystemMessage: what the console is told. - fn console_reply(&self, text: Text) { + /// MinecraftServer.sendSystemMessage: what the console is told; while + /// the console runs a command, the replies vanilla broadcasts go to the + /// operators too. + fn console_reply(&mut self, text: Text) { log("INFO", &format!("System chat: {}", text.plain())); + if self.console_broadcast.is_some() + && text + .translation_key() + .is_some_and(|k| BROADCAST.contains(&k)) + { + self.broadcast_to_admins(text); + } + } + + /// One console line, then the operators' share of its feedback. + fn console_line(&mut self, state: &mut ServerState, line: &str) { + self.console_broadcast = Some(state.broadcast_console); + self.console_command(state, line); + self.console_broadcast = None; + if let Some(mut host) = self.lan.take() { + self.run_level_teleports(&mut host); + self.send_admin_feedback(&mut host, None); + self.lan = Some(host); + } + self.admin_feedback.clear(); } /// DedicatedServer.handleConsoleInputs: one console line, run as the diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index ee8170bc5..ab7a6cf48 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -114,9 +114,9 @@ impl Game<'_> { } fn fixture_reset(&mut self, seed: i64) { - self.world = World::new(self.res.facts.air, seed); + self.world = World::new(self.res.facts().air, seed); // The oracle level is plains everywhere (bone meal's flowers, freezing). - let plains = u32::from(self.res.biomes.id("minecraft:plains")); + let plains = u32::from(self.res.biomes().id("minecraft:plains")); for cx in -2..=2 { for cz in -2..=2 { let mut chunk = Chunk::empty(cx, cz); @@ -198,7 +198,7 @@ impl Game<'_> { let state = BlockStateId(cell[3].as_u64().unwrap_or(0) as u32); self.world.set(p.0, p.1, p.2, state)?; before.insert(p, state.0); - if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) { + if let Some(entity) = BlockEntity::for_block(&self.res.facts().get(state).name) { self.world.block_entities.insert(p, entity); } } @@ -284,7 +284,7 @@ impl Game<'_> { let state = self.world.block(origin.x, origin.y, origin.z); let mut used = Vec::new(); if let Some(op) = case.get("remove") { - self.fixture_remove(origin, op)?; + used = self.fixture_remove(origin, op)?; } else if let Some(op) = case.get("use") { used = self.fixture_use(origin, op)?; } else if let Some(op) = case.get("use_item") { @@ -318,8 +318,18 @@ impl Game<'_> { } else { self.dispense_from(origin, state)?; // CrafterBlockEntity.serverTick, the crafting animation running down. + let mut crafters: Vec<(i32, i32, i32)> = self + .world + .block_entities + .iter() + .filter(|(_, e)| matches!(e, BlockEntity::Crafter(_))) + .map(|(p, _)| *p) + .collect(); + crafters.sort_unstable(); for _ in 0..case["ticks"].as_u64().unwrap_or(0) { - self.tick_crafters(); + for &p in &crafters { + self.tick_crafter(p); + } } } @@ -329,7 +339,7 @@ impl Game<'_> { changed.dedup(); for p in changed { let now = self.world.block(p.0, p.1, p.2).0; - if before.get(&p).copied().unwrap_or(self.res.facts.air.0) != now { + if before.get(&p).copied().unwrap_or(self.res.facts().air.0) != now { out.push(format!("set {},{},{} {now}", p.0, p.1, p.2)); } } @@ -696,7 +706,7 @@ impl Game<'_> { /// lectern's book, or the items of a block entity Horizon keeps as saved. fn fixture_fill(&mut self, p: (i32, i32, i32), slot: usize, stack: Option) { let jukebox = - &*self.res.facts.get(self.world.block(p.0, p.1, p.2)).name == "minecraft:jukebox"; + &*self.res.facts().get(self.world.block(p.0, p.1, p.2)).name == "minecraft:jukebox"; match self.world.block_entities.get_mut(&p) { Some(BlockEntity::Jukebox(j)) => j.record = stack, Some(BlockEntity::Lectern(l)) => l.book = stack, @@ -725,7 +735,7 @@ impl Game<'_> { use horizon_world::nbt::Tag; let name = self .res - .facts + .facts() .get(self.world.block(p.0, p.1, p.2)) .name .clone(); @@ -778,8 +788,9 @@ impl Game<'_> { other => *other = Tag::List(vec![item]), } } - /// `Level.setBlock`, `destroyBlock` or `removeBlock` on the case's block. - fn fixture_remove(&mut self, origin: BlockPos, op: &Value) -> Result<()> { + /// `Level.setBlock`, `destroyBlock` or `removeBlock` on the case's block, or + /// a player mining it (`fixture_mine`). + fn fixture_remove(&mut self, origin: BlockPos, op: &Value) -> Result> { match op["op"].as_str().unwrap_or("") { "set" => { let state = BlockStateId(op["state"].as_u64().unwrap_or(0) as u32); @@ -793,9 +804,61 @@ impl Game<'_> { "remove" => { self.with_level(|b, level, ticks| b.remove_block(level, ticks, origin, false)); } + "mine" => return self.fixture_mine(origin, op), other => return Err(format!("unknown removal {other}").into()), } - self.process_level_events() + self.process_level_events()?; + Ok(Vec::new()) + } + + /// A survival player three blocks south of `pos` mines it holding the + /// case's item (`break_block`, which every player's mining goes through): + /// the statistics and the held stack, as `VanillaDispenserOracle.mine` + /// prints them. + fn fixture_mine(&mut self, pos: BlockPos, op: &Value) -> Result> { + let stack = parse_stack(op["item"].as_str().unwrap_or("-"))?; + self.mode = GameMode::Survival; + self.creative = false; + self.player = Some(PlayerMotion::new( + self.motion, + horizon_core::geometry::Vec3::new( + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 1.0, + f64::from(pos.z) + 3.5, + ), + )?); + self.yaw = 0.0; + self.pitch = 90.0; + self.keys.clear(); + self.inventory[self.selected] = stack.clone(); + self.offhand = None; + let state = self.world.block(pos.x, pos.y, pos.z); + let block = self.res.facts().get(state).name.clone(); + let item = stack.as_ref().map(|s| s.item.clone()); + let before = |game: &Self| { + let used = item.as_ref().map_or(0, |i| game.stats.get("used", i)); + (used, game.stats.get("mined", &block)) + }; + let (used, mined) = before(self); + self.break_block([pos.x, pos.y, pos.z])?; + let (used_after, mined_after) = before(self); + let mut out = Vec::new(); + if let Some(item) = &item + && used_after != used + { + out.push(format!("stat {item} minecraft:used {}", used_after - used)); + } + if mined_after != mined { + out.push(format!( + "stat {block} minecraft:mined {}", + mined_after - mined + )); + } + out.push(format!( + "mine held {}", + canon_stack(self.inventory[self.selected].as_ref()) + )); + Ok(out) } /// `EntityType.create` and `snapTo` for one target: no spawn finalization. @@ -819,7 +882,7 @@ impl Game<'_> { } let t = self .res - .mob_types + .mob_types() .get(kind) .cloned() .ok_or_else(|| format!("no mob type {kind}"))?; diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index cb28aa1cc..0f59e5300 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -328,18 +328,18 @@ impl Game<'_> { self.world.block(p.0, p.1, p.2) } fn dispenser_block_name(&self, p: Pos) -> std::sync::Arc { - self.res.facts.get(self.block_at(p)).name.clone() + self.res.facts().get(self.block_at(p)).name.clone() } fn in_block_tag(&self, tag: &str, block: &str) -> bool { self.res - .items + .items() .block_tags .get(tag) .is_some_and(|s| s.contains(block)) } fn water_at(&self, p: Pos) -> bool { matches!( - self.res.behaviours.fluid_kind(self.block_at(p)), + self.res.behaviours().fluid_kind(self.block_at(p)), FluidKind::Water | FluidKind::FlowingWater ) } @@ -520,7 +520,7 @@ impl Game<'_> { if let Some(entity) = self.world.block_entities.get_mut(&pos) { let max = self .res - .items + .items() .get(&rest.item) .map_or(64, |i| i.max_stack) .max(1); @@ -555,7 +555,11 @@ impl Game<'_> { } /// `ItemStack.hurtAndBreak(amount)` without an entity. fn hurt_and_break(&mut self, mut stack: ItemStack, amount: u32) -> Option { - let max = self.res.items.get(&stack.item).map_or(0, |i| i.max_damage); + let max = self + .res + .items() + .get(&stack.item) + .map_or(0, |i| i.max_damage); if max == 0 { return Some(stack); } @@ -637,7 +641,7 @@ impl Game<'_> { ) -> Result { let equippable = self .res - .items + .items() .get(&stack.item) .is_some_and(|i| i.equip_slot.is_some()); if equippable { @@ -649,7 +653,7 @@ impl Game<'_> { } let swallowable = self .res - .items + .items() .item_tags .get("minecraft:sulfur_cube_swallowable") .is_some_and(|t| t.contains(&*stack.item)); @@ -748,7 +752,7 @@ impl Game<'_> { } else { format!("minecraft:{kind}") }; - let t = self.res.mob_types.get(&name)?.clone(); + let t = self.res.mob_types().get(&name)?.clone(); let y_off = if try_move_down { self.drop_offset(t.width, t.height, p) } else { @@ -768,7 +772,7 @@ impl Game<'_> { /// `EquipmentDispenseItemBehavior.dispenseEquipment`: the first living /// entity in front that `canEquipWithDispenser` gets one of the item. fn dispense_equipment(&mut self, pos: Pos, facing: Direction, stack: &mut ItemStack) -> bool { - let Some(info) = self.res.items.get(&stack.item) else { + let Some(info) = self.res.items().get(&stack.item) else { return false; }; let (Some(slot), true) = ( @@ -1078,7 +1082,7 @@ impl Game<'_> { let below = (front.0, front.1 - 1, front.2); let y_offset = if self.water_at(front) { 1.0 - } else if self.res.facts.is_air(self.block_at(front)) && self.water_at(below) { + } else if self.res.facts().is_air(self.block_at(front)) && self.water_at(below) { 0.0 } else { return (self.dispense_default(pos, facing, stack), CLICK); @@ -1116,7 +1120,7 @@ impl Game<'_> { let y_offset = if let Some(rail) = self.rail(front.0, front.1, front.2) { if rail.shape.is_slope() { 0.6 } else { 0.1 } } else { - if !self.res.facts.is_air(self.block_at(front)) { + if !self.res.facts().is_air(self.block_at(front)) { return (self.dispense_default(pos, facing, stack), CLICK); } let below = (front.0, front.1 - 1, front.2); @@ -1389,7 +1393,7 @@ impl Game<'_> { stack: ItemStack, ) -> Result { let target = offset(pos, facing); - let free = self.res.facts.is_air(self.block_at(target)) + let free = self.res.facts().is_air(self.block_at(target)) && target.1 >= horizon_client::chunk::MIN_Y + 2 && self.ui.difficulty != 0 && self.can_build_wither(target); @@ -1443,7 +1447,7 @@ impl Game<'_> { "minecraft:soul_sand" | "minecraft:soul_soil" ) }; - let air = |p: Pos| self.res.facts.is_air(self.block_at(p)); + let air = |p: Pos| self.res.facts().is_air(self.block_at(p)); for (ax, az) in [(1, 0), (0, 1)] { for col in 0..3 { let left = (head.0 - ax * col, head.1, head.2 - az * col); @@ -1466,7 +1470,7 @@ impl Game<'_> { stack: ItemStack, ) -> Result { let target = offset(pos, facing); - if self.res.facts.is_air(self.block_at(target)) + if self.res.facts().is_air(self.block_at(target)) && self.can_spawn_golem([target.0, target.1, target.2]) { if let Some(pumpkin) = self @@ -1511,7 +1515,7 @@ impl Game<'_> { let front = offset(pos, facing); let below_empty = self .res - .facts + .facts() .is_air(self.block_at((front.0, front.1 - 1, front.2))); let clicked_face = if below_empty { facing } else { Direction::Up }; let ctx = PlaceContext { @@ -1539,7 +1543,7 @@ impl Game<'_> { return Ok((Some(stack), FAIL)); }; let target = (placed.x, placed.y, placed.z); - if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) { + if let Some(entity) = BlockEntity::for_block(&self.res.facts().get(state).name) { self.world.block_entities.insert(target, entity); self.apply_placed_item([target.0, target.1, target.2], &stack, false); } @@ -1689,14 +1693,14 @@ impl Game<'_> { table: &str, held: Option<&ItemStack>, ) -> Vec { - match self.res.items.loot_sequence(parent) { + match self.res.items().loot_sequence(parent) { Some(sequence) => { let random = self.rand_sequences.get(&sequence, self.level.seed); - self.res.items.loot_table_from(table, false, held, random) + self.res.items().loot_table_from(table, false, held, random) } None => self .res - .items + .items() .loot_table(table, false, held, &mut self.world.random), } } @@ -1717,7 +1721,7 @@ impl Game<'_> { /// random draws) keeps the name, flags, persistence and age; the old one /// is discarded. pub(super) fn convert_mob(&mut self, index: usize, kind: &str) -> Option { - let t = self.res.mob_types.get(kind).cloned()?; + let t = self.res.mob_types().get(kind).cloned()?; let old = &self.mobs[index]; self.next_entity += 1; let mut mob = Mob::new(self.next_entity, t, old.position, old.yaw); diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index ff91df583..cbfad527b 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -74,6 +74,8 @@ impl Respawn { } #[derive(Clone, Debug)] pub(super) struct Crystal { + /// The entity id a server tracks it by (0 until it is tracked). + pub id: u32, pub position: Vec3, pub show_bottom: bool, /// EndCrystal.time (the bob and spin), starting random. @@ -445,9 +447,9 @@ impl Game<'_> { } fn end_portal_active(&self) -> bool { (0..256).any(|y| { - &*self.res.facts.get(self.world.block(0, y, 0)).name == "minecraft:bedrock" + &*self.res.facts().get(self.world.block(0, y, 0)).name == "minecraft:bedrock" && (-3..=3).any(|d| { - &*self.res.facts.get(self.world.block(d, y, 0)).name == "minecraft:end_portal" + &*self.res.facts().get(self.world.block(d, y, 0)).name == "minecraft:end_portal" }) }) } @@ -553,6 +555,7 @@ impl Game<'_> { } let time = self.world.random.next_int_bound(100_000).unwrap_or(0); self.crystals.push(Crystal { + id: 0, position: at, show_bottom: true, time, @@ -588,7 +591,7 @@ impl Game<'_> { let p = self.crystals[i].position; let b = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; if let Some(fire) = fire - && self.res.facts.is_air(self.world.block(b[0], b[1], b[2])) + && self.res.facts().is_air(self.world.block(b[0], b[1], b[2])) && self.world.loaded(b[0], b[2]) { let _ = self.level_set(b, fire); @@ -761,7 +764,7 @@ impl Game<'_> { let held = self.held().cloned(); let modifiers = held .as_ref() - .and_then(|h| self.res.items.get(&h.item)) + .and_then(|h| self.res.items().get(&h.item)) .map(|i| (i.attack_damage, i.attack_speed)) .unwrap_or((0.0, 0.0)); let speed = (4.0 + modifiers.1).max(0.1); @@ -810,7 +813,7 @@ impl Game<'_> { (0..256) .rev() .find(|&y| { - let f = self.res.facts.get(self.world.block(x, y, z)); + let f = self.res.facts().get(self.world.block(x, y, z)); (f.full_collision || f.legacy_solid || f.fluid != horizon_client::blocks::Fluid::None) @@ -1254,7 +1257,7 @@ impl Game<'_> { let (x, z) = (head.x + look.x * 2.5, head.z + look.y * 2.5); let mut y = head.y + 0.5; while y > 0.0 - && self.res.facts.is_air(self.world.block( + && self.res.facts().is_air(self.world.block( x.floor() as i32, y.floor() as i32, z.floor() as i32, @@ -1591,7 +1594,7 @@ impl Game<'_> { return; }; let boxes = [d.part_box(0), d.part_box(1), d.part_box(2)]; - let tags = &self.res.items.block_tags; + let tags = &self.res.items().block_tags; let transparent = tags .get("minecraft:dragon_transparent") .cloned() @@ -1607,8 +1610,8 @@ impl Game<'_> { for y in lo.y.floor() as i32..=hi.y.floor() as i32 { for z in lo.z.floor() as i32..=hi.z.floor() as i32 { let state = self.world.block(x, y, z); - let name = &self.res.facts.get(state).name; - if self.res.facts.is_air(state) || transparent.contains(&**name) { + let name = &self.res.facts().get(state).name; + if self.res.facts().is_air(state) || transparent.contains(&**name) { continue; } if griefing && !immune.contains(&**name) { @@ -1710,7 +1713,7 @@ impl Game<'_> { let y = (0..256) .rev() .find(|&y| { - let f = self.res.facts.get(self.world.block(0, y, 0)); + let f = self.res.facts().get(self.world.block(0, y, 0)); f.full_collision || f.legacy_solid }) .map_or(64, |y| y + 1); @@ -1764,7 +1767,7 @@ impl Game<'_> { next.y.floor() as i32, next.z.floor() as i32, ]; - let f = self.res.facts.get(self.world.block(p[0], p[1], p[2])); + let f = self.res.facts().get(self.world.block(p[0], p[1], p[2])); f.full_collision || f.legacy_solid }; let hit_player = player.is_some_and(|pb| { @@ -1866,9 +1869,9 @@ impl Game<'_> { batch.width as i32, batch.height as i32, &bars, - &self.atlas.font, + &self.gui.atlas.font, ); - hud_layout::paint(batch, &self.atlas, &draws); + hud_layout::paint(batch, &self.gui.atlas, &draws); } /// The dragon fight's boss bar shows (`EnderDragonFight.dragonEvent`, /// with `setCreateWorldFog`). @@ -1906,7 +1909,13 @@ impl Game<'_> { return; }; let a = alpha as f32; - let sprite = |n: &str| self.atlas.sprites.get(n).map(|r| [r.u0, r.v0, r.u1, r.v1]); + let sprite = |n: &str| { + self.gui + .atlas + .sprites + .get(n) + .map(|r| [r.u0, r.v0, r.u1, r.v1]) + }; let (Some(skin), Some(eyes)) = ( sprite("entity/enderdragon/dragon"), sprite("entity/enderdragon/dragon_eyes"), @@ -2072,7 +2081,7 @@ impl Game<'_> { } /// `submitRays`: the death rays from a fixed seed, fading in white to magenta. fn dragon_rays(&self, base: glam::Mat4, t: f32, out: &mut Vec) { - let white = self.atlas.font.white(); + let white = self.gui.atlas.font.white(); let uv = [white.u0, white.v0]; let over = if t > 0.8 { ((t - 0.8) / 0.2).min(1.0) @@ -2128,6 +2137,7 @@ impl Game<'_> { out: &mut Vec, ) { let Some(s) = self + .gui .atlas .sprites .get("entity/end_crystal/end_crystal_beam") @@ -2189,6 +2199,7 @@ impl Game<'_> { out: &mut Vec, ) { let Some(s) = self + .gui .atlas .sprites .get("entity/enderdragon/dragon_fireball") @@ -2301,6 +2312,7 @@ impl Crystal { pub(super) fn from_nbt(tag: &Tag, time: i32) -> Option { let (position, _, _) = horizon_client::entity_nbt::boat_from_nbt(tag)?; Some(Self { + id: 0, position, show_bottom: !matches!(tag.get("ShowBottom"), Some(Tag::Byte(0))), time, @@ -2377,7 +2389,7 @@ impl Game<'_> { } let name = self .res - .facts + .facts() .get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2])) .name .clone(); @@ -2387,7 +2399,7 @@ impl Game<'_> { let above = [hit.pos[0], hit.pos[1] + 1, hit.pos[2]]; if !self .res - .facts + .facts() .is_air(self.world.block(above[0], above[1], above[2])) { return false; @@ -2403,6 +2415,7 @@ impl Game<'_> { } let time = self.world.random.next_int_bound(100_000).unwrap_or(0); self.crystals.push(Crystal { + id: 0, position: Vec3::new(x + 0.5, y, z + 0.5), show_bottom: false, time, @@ -2507,7 +2520,7 @@ impl Game<'_> { } fn block_name_at(&self, p: [i32; 3]) -> std::sync::Arc { self.res - .facts + .facts() .get(self.world.block(p[0], p[1], p[2])) .name .clone() @@ -2609,7 +2622,7 @@ impl Game<'_> { for y in h - 10..=h + 10 { for z in cz - 10..=cz + 10 { for x in cx - 10..=cx + 10 { - if !self.res.facts.is_air(self.world.block(x, y, z)) { + if !self.res.facts().is_air(self.world.block(x, y, z)) { let _ = self.level_set([x, y, z], air); } } @@ -2631,7 +2644,7 @@ impl Game<'_> { if &*self.block_name_at([x, y, z]) != "minecraft:obsidian" { let _ = self.set_state_named([x, y, z], "minecraft:obsidian", &[]); } - } else if y > 65 && !self.res.facts.is_air(self.world.block(x, y, z)) { + } else if y > 65 && !self.res.facts().is_air(self.world.block(x, y, z)) { let _ = self.level_set([x, y, z], air); } } @@ -2665,6 +2678,7 @@ impl Game<'_> { .retain(|c| c.position.distance_squared(at) > 0.01); let time = self.world.random.next_int_bound(100_000).unwrap_or(0); self.crystals.push(Crystal { + id: 0, position: at, show_bottom: true, time, diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index 1e36b00f0..0aa3138f6 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -16,7 +16,7 @@ impl Game<'_> { let held = self.inventory[self.selected].as_ref(); speed += self .res - .stations + .stations() .enchantments .attribute_add(held, "minecraft:mining_efficiency") as f32; } @@ -26,7 +26,7 @@ impl Game<'_> { pub(super) fn submerged_mining_speed(&self) -> f32 { let mut total = 0.0; for stack in self.armor.iter().flatten() { - for (attr, _, amount, op) in self.res.stations.enchantments.attributes(stack) { + for (attr, _, amount, op) in self.res.stations().enchantments.attributes(stack) { if attr == "minecraft:submerged_mining_speed" && op == "add_multiplied_total" { total += amount; } @@ -36,13 +36,13 @@ impl Game<'_> { } /// `EnchantmentHelper.processDurabilityChange` (unbreaking) for `amount` points. pub(super) fn durability_loss(&mut self, stack: &ItemStack, amount: u32) -> u32 { - let e = &self.res.stations.enchantments; + let e = &self.res.stations().enchantments; if !e.has_component(stack, "minecraft:item_damage") { return amount; } let ctx = EffectContext { tool: Some(&stack.item), - items: Some(&self.res.items), + items: Some(self.res.items()), ..Default::default() }; e.modify_value( @@ -65,10 +65,10 @@ impl Game<'_> { direct_attacker: Some("minecraft:player"), is_direct: true, damage_type: Some("minecraft:player_attack"), - items: Some(&self.res.items), + items: Some(self.res.items()), ..Default::default() }; - self.res.stations.enchantments.modify_value( + self.res.stations().enchantments.modify_value( Some(&held), "minecraft:damage", &ctx, @@ -96,10 +96,10 @@ impl Game<'_> { attacker: Some("minecraft:player"), direct_attacker: Some("minecraft:player"), is_direct: true, - items: Some(&self.res.items), + items: Some(self.res.items()), ..Default::default() }; - let knockback = self.res.stations.enchantments.modify_value( + let knockback = self.res.stations().enchantments.modify_value( Some(&held), "minecraft:knockback", &ctx, @@ -130,7 +130,7 @@ impl Game<'_> { // minecraft:post_attack ignite effects of the attacker's weapon (fire aspect). let mut ignite = 0.0f32; for (id, level) in held.enchantments() { - let Some(def) = self.res.stations.enchantments.get(id) else { + let Some(def) = self.res.stations().enchantments.get(id) else { continue; }; for effect in def.effects["minecraft:post_attack"] @@ -145,7 +145,7 @@ impl Game<'_> { let mut random = self.world.random.clone(); let ok = effect.get("requirements").is_none_or(|r| { self.res - .stations + .stations() .enchantments .condition(r, *level, &ctx, &mut random) }); @@ -182,13 +182,13 @@ impl Game<'_> { attacker: Some("minecraft:player"), direct_attacker: Some("minecraft:player"), is_direct: true, - items: Some(&self.res.items), + items: Some(self.res.items()), direct_motion: Some(motion), ..Default::default() }; let mut bursts = Vec::new(); for (id, level) in held.enchantments() { - let Some(def) = self.res.stations.enchantments.get(id) else { + let Some(def) = self.res.stations().enchantments.get(id) else { continue; }; for effect in def.effects["minecraft:post_attack"] @@ -205,7 +205,7 @@ impl Game<'_> { continue; } let ok = effect.get("requirements").is_none_or(|r| { - self.res.stations.enchantments.condition( + self.res.stations().enchantments.condition( r, *level, &ctx, @@ -254,16 +254,16 @@ impl Game<'_> { if level == 0 { continue; } - let Some(def) = self.res.stations.enchantments.get("minecraft:thorns") else { + let Some(def) = self.res.stations().enchantments.get("minecraft:thorns") else { continue; }; let effect = def.effects["minecraft:post_attack"][0].clone(); let ctx = EffectContext { - items: Some(&self.res.items), + items: Some(self.res.items()), ..Default::default() }; let mut random = self.world.random.clone(); - let ok = self.res.stations.enchantments.condition( + let ok = self.res.stations().enchantments.condition( &effect["requirements"], level, &ctx, @@ -286,7 +286,7 @@ impl Game<'_> { s.damage += 2; if self .res - .items + .items() .get(&s.item) .is_some_and(|i| s.damage >= i.max_damage) { @@ -330,10 +330,10 @@ impl Game<'_> { }; let Some(stack) = stack else { return amount }; let ctx = EffectContext { - items: Some(&self.res.items), + items: Some(self.res.items()), ..Default::default() }; - let to_repair_xp = self.res.stations.enchantments.modify_value( + let to_repair_xp = self.res.stations().enchantments.modify_value( Some(&stack), "minecraft:repair_with_xp", &ctx, @@ -364,11 +364,11 @@ impl Game<'_> { let Some(bow) = self.inventory[self.selected].clone() else { return (0.0, false); }; - let e = &self.res.stations.enchantments; + let e = &self.res.stations().enchantments; let ctx = EffectContext { direct_attacker: Some("minecraft:arrow"), attacker: Some("minecraft:player"), - items: Some(&self.res.items), + items: Some(self.res.items()), ..Default::default() }; let power = e.modify_value( @@ -380,7 +380,7 @@ impl Game<'_> { ); let ammo_ctx = EffectContext { tool: Some("minecraft:arrow"), - items: Some(&self.res.items), + items: Some(self.res.items()), ..Default::default() }; let infinity = e.has_component(&bow, "minecraft:ammo_use") @@ -399,12 +399,12 @@ impl Game<'_> { let bow = self.inventory[self.selected].clone()?; let ctx = EffectContext { this: Some("minecraft:arrow"), - items: Some(&self.res.items), + items: Some(self.res.items()), ..Default::default() }; let mut ignite: Option = None; for (id, level) in bow.enchantments() { - let Some(def) = self.res.stations.enchantments.get(id) else { + let Some(def) = self.res.stations().enchantments.get(id) else { continue; }; for effect in def.effects["minecraft:projectile_spawned"] @@ -416,7 +416,7 @@ impl Game<'_> { continue; } let ok = effect.get("requirements").is_none_or(|r| { - self.res.stations.enchantments.condition( + self.res.stations().enchantments.condition( r, *level, &ctx, @@ -436,7 +436,7 @@ impl Game<'_> { pub(super) fn apply_enchantment_attributes(&mut self) { let mut wanted: Vec<(String, String, f64, String)> = Vec::new(); for stack in self.armor.iter().flatten() { - wanted.extend(self.res.stations.enchantments.attributes(stack)); + wanted.extend(self.res.stations().enchantments.attributes(stack)); } let Some(p) = self.player.as_mut() else { return; diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index a80c51796..34026bb07 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -132,9 +132,9 @@ impl Game<'_> { /// The environment attributes of the current dimension. pub(super) fn dim_environment(&self) -> &Environment { match self.dim { - Dim::Overworld => &self.res.environment, - Dim::Nether => &self.res.nether_environment, - Dim::End => &self.res.end_environment, + Dim::Overworld => self.res.environment(), + Dim::Nether => self.res.nether_environment(), + Dim::End => self.res.end_environment(), } } @@ -142,7 +142,7 @@ impl Game<'_> { /// tinted 0x282828. The atlas does not wrap, so each face is 16×16 quads. pub(super) fn end_sky_geometry(&self) -> Vec { let mut out = Vec::with_capacity(6 * 256 * 4); - let Some(r) = self.atlas.sprites.get("environment/end_sky").copied() else { + let Some(r) = self.gui.atlas.sprites.get("environment/end_sky").copied() else { return out; }; use std::f32::consts::FRAC_PI_2; @@ -184,6 +184,7 @@ impl Game<'_> { let intensity = self.end.flash.intensity(self.clock.fraction() as f32); if intensity > 1e-5 && let Some(r) = self + .gui .atlas .sprites .get("environment/celestial/end_flash") @@ -224,7 +225,7 @@ impl Game<'_> { pub(super) fn block_name(&self, p: [i32; 3]) -> std::sync::Arc { self.res - .facts + .facts() .get(self.world.block(p[0], p[1], p[2])) .name .clone() @@ -561,7 +562,7 @@ impl Game<'_> { let mut y = (0..256) .rev() .find(|&y| { - let f = self.res.facts.get(self.world.block(0, y, 0)); + let f = self.res.facts().get(self.world.block(0, y, 0)); (f.full_collision || f.fluid != horizon_client::blocks::Fluid::None) && !f.name.ends_with("_leaves") }) @@ -783,7 +784,7 @@ impl Game<'_> { let mut y = 255; while y > floor { let p = [around[0] + xd, y, around[2] + zd]; - let f = self.res.facts.get(self.world.block(p[0], p[1], p[2])); + let f = self.res.facts().get(self.world.block(p[0], p[1], p[2])); if f.full_collision && (allow_bedrock || &*f.name != "minecraft:bedrock") { tallest = Some(p); break; @@ -839,12 +840,12 @@ impl Game<'_> { if &*self.block_name([x, y, z]) != "minecraft:end_stone" || self .res - .facts + .facts() .get(self.world.block(x, y + 1, z)) .full_collision || self .res - .facts + .facts() .get(self.world.block(x, y + 2, z)) .full_collision { @@ -920,7 +921,8 @@ impl Game<'_> { fn end_crystal_geometry(&self, camera: glam::DVec3, out: &mut Vec) { let (Some(model), Some(r)) = ( self.crystal_model.as_ref(), - self.atlas + self.gui + .atlas .sprites .get("entity/end_crystal/end_crystal") .copied(), @@ -1073,7 +1075,7 @@ impl Game<'_> { /// ThrownItemRenderer: the ender eye item facing the camera. fn eye_geometry(&self, camera: glam::DVec3, out: &mut Vec) { - let Some(r) = self.atlas.sprites.get("item/ender_eye").copied() else { + let Some(r) = self.gui.atlas.sprites.get("item/ender_eye").copied() else { return; }; let alpha = self.clock.fraction(); diff --git a/crates/horizon-client/src/game/entity_culling.rs b/crates/horizon-client/src/game/entity_culling.rs index 71ab13378..3abf92835 100644 --- a/crates/horizon-client/src/game/entity_culling.rs +++ b/crates/horizon-client/src/game/entity_culling.rs @@ -21,7 +21,7 @@ impl Game<'_> { && self.settings.resource_packs.iter().all(|id| id == "vanilla") && self.player.is_some() && !self.spectator() - && !opaque(self.res.facts.get(self.world.block(at[0], at[1], at[2])))) + && !opaque(self.res.facts().get(self.world.block(at[0], at[1], at[2])))) .then(|| Culler::new(camera.to_array(), 8_192)); } @@ -31,7 +31,7 @@ impl Game<'_> { if let Some(culler) = &self.entity_culler { culler.cull_vertices(vertices, start, |pos| { let state = self.world.block(pos[0], pos[1], pos[2]); - if !opaque(self.res.facts.get(state)) { + if !opaque(self.res.facts().get(state)) { return false; } let Some(y) = pos[1].checked_sub(MIN_Y) else { @@ -49,3 +49,64 @@ impl Game<'_> { } } } + +/// Entity.shouldRenderAtSqrDistance's default range: 64 times the bounding +/// box's mean edge, scaled by the entity distance option. +pub(super) fn default_range(size: glam::DVec3, view_scale: f32) -> f64 { + let edge = (size.x + size.y + size.z) / 3.0; + let edge = if edge.is_nan() { 1.0 } else { edge }; + edge * 64.0 * f64::from(view_scale) +} + +impl Game<'_> { + /// EntityRenderer.shouldRender: the entity within `range` blocks of the + /// camera, measured from its current `position`, and its culling box + /// (`lo`..`hi`, interpolated, in world space) grown by 0.5 in the view. + pub(super) fn entity_in_view( + &self, + camera: glam::DVec3, + position: glam::DVec3, + range: f64, + lo: glam::DVec3, + hi: glam::DVec3, + ) -> bool { + if (position - camera).length_squared() >= range * range { + return false; + } + self.view_frustum.as_ref().is_none_or(|view| { + view.intersects( + (lo - camera - glam::DVec3::splat(0.5)).as_vec3(), + (hi - camera + glam::DVec3::splat(0.5)).as_vec3(), + ) + }) + } +} + +/// An entity's position as a `DVec3`. +pub(super) fn at(p: horizon_core::geometry::Vec3) -> glam::DVec3 { + glam::DVec3::new(p.x, p.y, p.z) +} + +impl Game<'_> { + /// `entity_in_view` for an entity whose box stands on its position, + /// `width` wide and `height` tall, interpolated by `alpha` and grown by + /// `grow` (a renderer's getBoundingBoxForCulling). + #[allow(clippy::too_many_arguments)] + pub(super) fn standing_entity_in_view( + &self, + camera: glam::DVec3, + previous: glam::DVec3, + position: glam::DVec3, + alpha: f64, + width: f64, + height: f64, + range: f64, + grow: f64, + ) -> bool { + let p = previous.lerp(position, alpha); + let half = glam::DVec3::new(width / 2.0 + grow, grow, width / 2.0 + grow); + let lo = p - half; + let hi = p + glam::DVec3::new(half.x, height + grow, half.z); + self.entity_in_view(camera, position, range, lo, hi) + } +} diff --git a/crates/horizon-client/src/game/events.rs b/crates/horizon-client/src/game/events.rs index 0ffff1b59..8a4207a7f 100644 --- a/crates/horizon-client/src/game/events.rs +++ b/crates/horizon-client/src/game/events.rs @@ -167,7 +167,11 @@ impl Game<'_> { Snapshot { screen: self.screen_label(), dimension: self.dim.id().to_string(), - chat: self.ui.chat.received, + // A remote client counts the server's lines itself. + chat: self + .remote + .as_ref() + .map_or(self.ui.chat.received, |r| r.chat_received), counts: if world.is_some() { self.inventory_counts() } else { @@ -189,8 +193,19 @@ impl Game<'_> { if let Some(before) = &self.events.last && *before != now { - let new_chat = (now.chat - before.chat).min(100) as usize; - let lines = self.ui.chat.recent_lines(new_chat); + // Joining or leaving a server starts another count. + let new_chat = now.chat.saturating_sub(before.chat).min(100) as usize; + // Newest first; the remote client keeps its lines oldest first. + let lines = match &self.remote { + Some(r) => r + .chat + .iter() + .rev() + .take(new_chat) + .map(|(t, _)| t.clone()) + .collect(), + None => self.ui.chat.recent_lines(new_chat), + }; for event in diff(before, &now, &lines) { self.events.push(self.ticks, event); } diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 4ed2772c7..c6df8d9e2 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -196,7 +196,7 @@ impl Game<'_> { break; } let state = self.world.block(pos[0], pos[1], pos[2]); - let f = self.res.facts.get(state); + let f = self.res.facts().get(state); let fluid = if f.fluid != Fluid::None { 100.0f32 } else { @@ -206,7 +206,7 @@ impl Game<'_> { Some((at, resistance)) if at == pos => { power -= (resistance + 0.3) * 0.3; } - _ if !self.res.facts.is_air(state) || f.fluid != Fluid::None => { + _ if !self.res.facts().is_air(state) || f.fluid != Fluid::None => { power -= (f.explosion_resistance.max(fluid) + 0.3) * 0.3; } _ => {} @@ -450,11 +450,11 @@ impl Game<'_> { if self.world.random.next_int_bound(3).unwrap_or(1) == 0 && self .res - .facts + .facts() .is_air(self.world.block(pos[0], pos[1], pos[2])) && self .res - .facts + .facts() .get(self.world.block(pos[0], pos[1] - 1, pos[2])) .solid_render { @@ -475,7 +475,7 @@ impl Game<'_> { } else { targets.len() }; - let (world, facts) = (&self.world, &self.res.facts); + let (world, facts) = (&self.world, self.res.facts()); self.particles.explosion(center, radius, block_count, &|b| { facts.is_air(world.block(b[0], b[1], b[2])) }); @@ -490,10 +490,10 @@ impl Game<'_> { stacks: &mut Vec<([i32; 3], ItemStack)>, ) -> Result<()> { let state = self.world.block(pos[0], pos[1], pos[2]); - if self.res.facts.is_air(state) { + if self.res.facts().is_air(state) { return Ok(()); } - let name = self.res.facts.get(state).name.clone(); + let name = self.res.facts().get(state).name.clone(); let is_tnt = &*name == "minecraft:tnt"; // Block.onExplosionHit: the drops copy from the block entity, which // then spills its contents as the block turns to air. @@ -510,7 +510,7 @@ impl Game<'_> { // tables' survives_explosion and explosion_decay draw from their // random sequence. let decay = (interaction == BlockInteraction::DestroyWithDecay).then_some(radius); - let drops = self.res.items.block_drops_exploded( + let drops = self.res.items().block_drops_exploded( self.pack.assets.registry, state, None, diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index 712796a81..c16c54447 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -188,7 +188,7 @@ impl Game<'_> { let radius = ((reach / 16.0).ceil() as i32 + 1).min(self.settings.render_distance.max(2)); self.extras.minimap.update( &self.world, - &self.res.facts, + self.res.facts(), (bx >> 4, bz >> 4), radius, layer, @@ -197,10 +197,10 @@ impl Game<'_> { if !self.extras.minimap.compose(view) { return; } - let Some(rect) = self.atlas.sprites.get(MINIMAP_SPRITE).copied() else { + let Some(rect) = self.gui.atlas.sprites.get(MINIMAP_SPRITE).copied() else { return; }; - let (w, h) = (self.atlas.width as f32, self.atlas.height as f32); + let (w, h) = (self.gui.atlas.width as f32, self.gui.atlas.height as f32); self.map_patches.push(horizon_client::font::Patch { x: (rect.u0 * w).round() as u32, y: (rect.v0 * h).round() as u32, @@ -246,7 +246,7 @@ impl Game<'_> { let (map_corner, map_size) = (e.minimap_corner, f32::from(e.minimap_size)); let visible = |corner| !(self.debug && corner == Corner::TopLeft); let mut corners = Corners::new(batch.width, batch.height, self.effect_rows_height()); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; if let Some(view) = self.minimap_view() && visible(map_corner) && !self.extras.minimap.image.is_empty() @@ -290,7 +290,7 @@ impl Game<'_> { use_: self.extras.mouse[1], cps, }; - extras_hud::draw_keystrokes(batch, &self.atlas, &mut corners, keys_corner, &k); + extras_hud::draw_keystrokes(batch, &self.gui.atlas, &mut corners, keys_corner, &k); } if mod_panels { self.draw_mod_panels(batch, &mut corners); diff --git a/crates/horizon-client/src/game/falling_damage.rs b/crates/horizon-client/src/game/falling_damage.rs index f10a3b738..8eec28d1d 100644 --- a/crates/horizon-client/src/game/falling_damage.rs +++ b/crates/horizon-client/src/game/falling_damage.rs @@ -6,7 +6,7 @@ use horizon_world::level::LevelEvent; impl Game<'_> { pub(super) fn finish_falling_block(&mut self, mut block: FallingBlock, pos: [i32; 3]) { - let anvil = self.res.facts.get(block.state).name.ends_with("anvil"); + let anvil = self.res.facts().get(block.state).name.ends_with("anvil"); if let Some(impact) = block.damage.impact(block.fall_distance) { if impact.amount > 0.0 { falling_block::hurt_mobs(&mut self.mobs, block.position, impact.amount); @@ -80,7 +80,7 @@ impl Game<'_> { && block.drop_item && self.ui.rules.bool("entity_drops") { - let item = self.res.facts.get(block.state).item.clone(); + let item = self.res.facts().get(block.state).item.clone(); if &*item != "minecraft:air" { self.pop_resource( pos, diff --git a/crates/horizon-client/src/game/fangs.rs b/crates/horizon-client/src/game/fangs.rs index dd2b9bde6..0939f6490 100644 --- a/crates/horizon-client/src/game/fangs.rs +++ b/crates/horizon-client/src/game/fangs.rs @@ -108,6 +108,7 @@ impl Game<'_> { return; }; let Some(r) = self + .gui .atlas .sprites .get("entity/illager/evoker_fangs") diff --git a/crates/horizon-client/src/game/fireworks.rs b/crates/horizon-client/src/game/fireworks.rs index 0e074025f..85fccc2de 100644 --- a/crates/horizon-client/src/game/fireworks.rs +++ b/crates/horizon-client/src/game/fireworks.rs @@ -18,21 +18,46 @@ use horizon_core::{ }; pub(super) struct Rocket { - position: Vec3, + /// The entity id a server tracks it by (0 until it is tracked). + pub id: u32, + pub(super) position: Vec3, previous: Vec3, - velocity: Vec3, + pub(super) velocity: Vec3, life: i32, lifetime: i32, explosions: Vec, /// Boosting the player (attachedToEntity). - attached: bool, + pub(super) attached: bool, /// `DATA_SHOT_AT_ANGLE` (dispensers): constant velocity, exploding on /// the first block it hits. - angled: bool, + pub(super) angled: bool, /// `DATA_ID_FIREWORKS_ITEM`: the stack it was launched from. - item: ItemStack, + pub(super) item: ItemStack, } impl Rocket { + /// A rocket a server sent (`handleAddEntity`): placed and moved by it. + pub(super) fn remote(id: u32, position: Vec3, velocity: Vec3) -> Self { + let item = ItemStack::new("minecraft:firework_rocket", 1); + let (_, explosions) = fireworks_of(&item); + Self { + id, + position, + previous: position, + velocity, + life: 0, + lifetime: i32::MAX, + explosions, + attached: false, + angled: false, + item, + } + } + /// One tick of a server's client: the previous position, then `step`. + pub(super) fn remote_step(&mut self, step: impl FnOnce(Vec3) -> Vec3) { + self.previous = self.position; + self.life += 1; + self.position = step(self.position); + } /// Position and motion (the dispenser parity fixture). pub(super) fn motion(&self) -> (Vec3, Vec3) { (self.position, self.velocity) @@ -56,6 +81,7 @@ impl Game<'_> { + r.next_int_bound(6).unwrap_or(0) + r.next_int_bound(7).unwrap_or(0); Rocket { + id: 0, position: at, previous: at, velocity, @@ -253,6 +279,20 @@ impl Game<'_> { pub(super) fn rocket_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let orientation = glam::Mat4::from_quat(self.camera_orientation()); for r in self.rockets.iter().filter(|r| !r.attached) { + // FireworkRocketEntity.shouldRenderAtSqrDistance: within 64 blocks; + // EntityRenderer.shouldRender: its 0.25 box in the view. + if !self.standing_entity_in_view( + camera, + super::entity_culling::at(r.previous), + super::entity_culling::at(r.position), + alpha, + 0.25, + 0.25, + 64.0, + 0.0, + ) { + continue; + } let p = glam::DVec3::new( r.previous.x + (r.position.x - r.previous.x) * alpha, r.previous.y + (r.position.y - r.previous.y) * alpha, diff --git a/crates/horizon-client/src/game/fishing.rs b/crates/horizon-client/src/game/fishing.rs index 8a63f2cfe..94067e7f9 100644 --- a/crates/horizon-client/src/game/fishing.rs +++ b/crates/horizon-client/src/game/fishing.rs @@ -226,14 +226,18 @@ impl Game<'_> { fn biome_name_at(&self, p: Vec3) -> Option { let (x, y, z) = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); let c = self.world.chunks.get(&(x >> 4, z >> 4))?; - Some(self.res.biomes.list[c.biome(x, y, z) as usize].name.clone()) + Some( + self.res.biomes().list[c.biome(x, y, z) as usize] + .name + .clone(), + ) } fn water_height(&self, x: i32, y: i32, z: i32) -> Option<(f32, bool)> { - let f = self.res.facts.get(self.world.block(x, y, z)); + let f = self.res.facts().get(self.world.block(x, y, z)); if f.fluid != Fluid::Water { return None; } - let above = self.res.facts.get(self.world.block(x, y + 1, z)); + let above = self.res.facts().get(self.world.block(x, y + 1, z)); let h = if above.fluid == Fluid::Water { 1.0 } else { @@ -243,7 +247,7 @@ impl Game<'_> { } /// getOpenWaterTypeForBlock: 0 above water, 1 inside water, 2 invalid. fn open_water_type(&self, x: i32, y: i32, z: i32) -> u8 { - let f = self.res.facts.get(self.world.block(x, y, z)); + let f = self.res.facts().get(self.world.block(x, y, z)); if self.world.is_air(self.world.block(x, y, z)) || &*f.name == "minecraft:lily_pad" { return 0; } @@ -390,7 +394,7 @@ impl Game<'_> { (fish[1] - 1.0).floor() as i32, fish[2].floor() as i32, ); - &*self.res.facts.get(state).name == "minecraft:water" + &*self.res.facts().get(state).name == "minecraft:water" } /// `ServerLevel.sendParticles` of a simple particle. fn send_particles( @@ -565,6 +569,7 @@ impl Game<'_> { return; }; let Some(r) = self + .gui .atlas .sprites .get("entity/fishing/fishing_hook") diff --git a/crates/horizon-client/src/game/fov.rs b/crates/horizon-client/src/game/fov.rs index 64047b4f7..37796c8c3 100644 --- a/crates/horizon-client/src/game/fov.rs +++ b/crates/horizon-client/src/game/fov.rs @@ -75,7 +75,7 @@ impl Game<'_> { } /// The fluid at the camera, as `Camera.getFluidInCamera` reports it. fn camera_fluid(&self, camera: [f64; 3]) -> CameraFluid { - match fog_type(&self.world, &self.res.facts, camera, self.forward()) { + match fog_type(&self.world, self.res.facts(), camera, self.forward()) { FogType::Water => CameraFluid::Water, FogType::Lava => CameraFluid::Lava, FogType::PowderSnow => CameraFluid::PowderSnow, @@ -177,6 +177,6 @@ impl Game<'_> { } let draws = hud_overlays::spyglass(batch.width as i32, batch.height as i32, self.scope_scale); - hud_layout::paint(batch, &self.atlas, &draws); + hud_layout::paint(batch, &self.gui.atlas, &draws); } } diff --git a/crates/horizon-client/src/game/frames.rs b/crates/horizon-client/src/game/frames.rs index 3ffa0e67e..857eb40a4 100644 --- a/crates/horizon-client/src/game/frames.rs +++ b/crates/horizon-client/src/game/frames.rs @@ -110,7 +110,7 @@ impl Game<'_> { return false; } let s = f.step(); - let behind = self.res.facts.get(self.world.block( + let behind = self.res.facts().get(self.world.block( f.pos[0] - s[0], f.pos[1] - s[1], f.pos[2] - s[2], @@ -301,12 +301,30 @@ impl Game<'_> { } /// ItemFrameRenderer: the frame model, then the item half size on its face. pub(super) fn frame_geometry(&mut self, camera: glam::DVec3, out: &mut Vec) { - let sprites = &self.atlas.sprites; + let sprites = &self.gui.atlas.sprites; let mut maps: Vec<(i32, glam::Mat4, u32)> = Vec::new(); let mut items: Vec<(ItemStack, u32, glam::Mat4, u8)> = Vec::new(); + // ItemFrame.shouldRenderAtSqrDistance: 1024 blocks at 100%. + let range = 16.0 * 64.0 * f64::from(self.settings.entity_distance); for f in &self.item_frames { let entity_start = out.len(); let map = f.item.as_ref().and_then(super::maps::map_id); + // EntityRenderer.shouldRender: its box (a block wide with a map), + // measured from the box's centre. + let (lo, hi) = f.bounds(); + let (mut lo, mut hi) = (glam::DVec3::from(lo), glam::DVec3::from(hi)); + if map.is_some() { + let s = f.step(); + for i in 0..3 { + if s[i] == 0 { + let c = (lo[i] + hi[i]) / 2.0; + (lo[i], hi[i]) = (c - 0.5, c + 0.5); + } + } + } + if !self.entity_in_view(camera, (lo + hi) / 2.0, range, lo, hi) { + continue; + } let s = f.step(); // Pose: to the block centre, then X/Y rotation by facing. let (x_rot, y_rot) = if s[1] == 0 { diff --git a/crates/horizon-client/src/game/gamemode_switcher.rs b/crates/horizon-client/src/game/gamemode_switcher.rs index 5f73080f4..db057ad25 100644 --- a/crates/horizon-client/src/game/gamemode_switcher.rs +++ b/crates/horizon-client/src/game/gamemode_switcher.rs @@ -39,7 +39,7 @@ impl Game<'_> { }; switcher.hover(w, h, (self.cursor.0 as i32, self.cursor.1 as i32)); let selected = switcher.selected; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; batch.sprite_region( atlas, "gui/container/gamemode_switcher", @@ -62,14 +62,14 @@ impl Game<'_> { for (index, mode) in MODES.into_iter().enumerate() { let (x, y) = slot_origin(w, h, index); batch.sprite( - &self.atlas, + &self.gui.atlas, "gui/sprites/gamemode_switcher/slot", x as f32, y as f32, ); if mode == selected { batch.sprite( - &self.atlas, + &self.gui.atlas, "gui/sprites/gamemode_switcher/selection", x as f32, y as f32, diff --git a/crates/horizon-client/src/game/golems.rs b/crates/horizon-client/src/game/golems.rs index 2bfeda70d..da204eee6 100644 --- a/crates/horizon-client/src/game/golems.rs +++ b/crates/horizon-client/src/game/golems.rs @@ -8,7 +8,7 @@ use horizon_client::Result; impl Game<'_> { fn golem_block(&self, p: [i32; 3]) -> &str { let state = self.world.block(p[0], p[1], p[2]); - &self.res.facts.get(state).name + &self.res.facts().get(state).name } fn is_golem_head(&self, p: [i32; 3]) -> bool { matches!( @@ -33,7 +33,7 @@ impl Game<'_> { for (ax, az) in [(1, 0), (0, 1)] { let side = |s: i32, row: i32| [head[0] + ax * s, head[1] - row, head[2] + az * s]; let arms = (-1..=1).all(|s| self.golem_block(side(s, 1)) == "minecraft:iron_block"); - let air = |p: [i32; 3]| self.res.facts.is_air(self.world.block(p[0], p[1], p[2])); + let air = |p: [i32; 3]| self.res.facts().is_air(self.world.block(p[0], p[1], p[2])); if arms && self.golem_block(side(0, 2)) == "minecraft:iron_block" && [-1, 1].iter().all(|&s| air(side(s, 0)) && air(side(s, 2))) @@ -58,7 +58,7 @@ impl Game<'_> { let below = [head[0], head[1] - 1, head[2]]; let name = self.golem_block(below); self.res - .items + .items() .block_tags .get("minecraft:copper") .is_some_and(|t| t.contains(name)) @@ -88,7 +88,7 @@ impl Game<'_> { /// `EntityType.create(level, TRIGGERED)` and `snapTo`: a built golem or /// wither has no spawn finalization and draws nothing from the level. pub(super) fn create_triggered(&mut self, kind: &str, at: [f64; 3], yaw: f32) -> Option { - let t = self.res.mob_types.get(kind).cloned()?; + let t = self.res.mob_types().get(kind).cloned()?; self.next_entity += 1; let mut mob = horizon_client::mobs::Mob::new( self.next_entity, @@ -181,9 +181,9 @@ impl Game<'_> { }); if let Some(chest) = chest { self.with_level(|b, level, ticks| b.set_block(level, ticks, pos, chest, 2)); - if let Some(entity) = - horizon_client::containers::BlockEntity::for_block(&self.res.facts.get(chest).name) - { + if let Some(entity) = horizon_client::containers::BlockEntity::for_block( + &self.res.facts().get(chest).name, + ) { self.world .block_entities .insert((below[0], below[1], below[2]), entity); diff --git a/crates/horizon-client/src/game/growth.rs b/crates/horizon-client/src/game/growth.rs index 18591b0fe..a6e062e24 100644 --- a/crates/horizon-client/src/game/growth.rs +++ b/crates/horizon-client/src/game/growth.rs @@ -10,7 +10,7 @@ impl Game<'_> { /// Load the configured/placed feature registry used by saplings, fungi /// and bone meal (once per process; shares the generator's bundle). pub(super) fn install_live_features(&self) { - if self.res.behaviours.live_features().is_some() { + if self.res.behaviours().live_features().is_some() { return; } let dir = self.options.resources.join("worldgen"); @@ -20,7 +20,7 @@ impl Game<'_> { .and_then(|data| LiveFeatures::new(&data).map_err(|e| e.to_string())); match features { Ok(Some(features)) => { - self.res.behaviours.set_live_features(Arc::new(features)); + self.res.behaviours().set_live_features(Arc::new(features)); log::info!("Horizon: live features ready in {:?}", started.elapsed()); } Ok(None) => { diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index 19e66174b..6e11febbd 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -39,7 +39,7 @@ impl Game<'_> { }); self.clicks.destroying = destroying; self.attack_clicks = 0; - self.stop_remote_mining(); + self.request_remote_mining_stop(); self.mining = None; } /// `LivingEntity.swing` with `getModifiedSwingDuration`. @@ -90,7 +90,7 @@ impl Game<'_> { let (pos, first) = (d.pos, (d.ticks as u32 - 1).is_multiple_of(4)); let state = self.world.block(pos[0], pos[1], pos[2]); if first { - let sounds = self.res.facts.get(state).sounds.clone(); + let sounds = self.res.facts().get(state).sounds.clone(); self.audio.play( &sounds.hit, Some(pos.map(|v| f64::from(v) + 0.5)), @@ -117,17 +117,17 @@ impl Game<'_> { /// `BlockBehaviour.getDestroyProgress` with `Player.getDestroySpeed`. pub(super) fn destroy_progress(&self, pos: [i32; 3]) -> f32 { let state = self.world.block(pos[0], pos[1], pos[2]); - let facts = self.res.facts.get(state); + let facts = self.res.facts().get(state); if facts.hardness == -1.0 { return 0.0; } let held = self.held(); - let mut speed = self.res.items.mining_speed(held, &facts.name); + let mut speed = self.res.items().mining_speed(held, &facts.name); speed = self.modify_destroy_speed(speed); if let Some(eye) = self.eye_position() && self .res - .facts + .facts() .get(self.world.block( eye[0].floor() as i32, eye[1].floor() as i32, @@ -141,7 +141,7 @@ impl Game<'_> { if self.player.as_ref().is_some_and(|p| !p.ground.on_ground) { speed /= 5.0; } - let harvest = !facts.requires_tool || self.res.items.correct_for_drops(held, &facts.name); + let harvest = !facts.requires_tool || self.res.items().correct_for_drops(held, &facts.name); speed / facts.hardness / if harvest { 30.0 } else { 100.0 } } /// Whether an attack would hit an entity rather than the block behind @@ -287,7 +287,7 @@ impl Game<'_> { horizon_client::attack_strength::BASE_ATTACK_SPEED + self .held() - .and_then(|h| self.res.items.get(&h.item)) + .and_then(|h| self.res.items().get(&h.item)) .map_or(0.0, |i| f64::from(i.attack_speed)) } /// `evaluateWhichHandsToRender`: which of the main and off hand show. @@ -351,7 +351,7 @@ impl HandWorld for GameHands<'_, '_> { } fn is_air(&mut self, pos: [i32; 3]) -> bool { let state = self.game.world.block(pos[0], pos[1], pos[2]); - self.game.res.facts.get(state).name.ends_with("air") + self.game.res.facts().get(state).name.ends_with("air") } fn creative(&self) -> bool { self.game.creative diff --git a/crates/horizon-client/src/game/initial_spawn.rs b/crates/horizon-client/src/game/initial_spawn.rs index 5fcd90517..3f7a071bb 100644 --- a/crates/horizon-client/src/game/initial_spawn.rs +++ b/crates/horizon-client/src/game/initial_spawn.rs @@ -83,7 +83,7 @@ impl Game<'_> { horizon_client::flatgen::FlatTerrain::from_settings( &s, self.pack.assets.registry, - &self.res.biomes, + self.res.biomes(), ) }) { diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index 412c41693..2b8ffb166 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -10,7 +10,7 @@ //! player joins as a network player, and the server side of a network player //! does not do everything single player does yet. use super::{ - Game, Options, PackResources, Resources, + Game, Options, PackResources, Resources, UiResources, lan::{LanSettings, Owner}, }; use horizon_client::{ @@ -28,7 +28,7 @@ use std::{ path::Path, sync::{ Arc, - atomic::{AtomicBool, AtomicU16, AtomicU32, Ordering}, + atomic::{AtomicBool, AtomicI32, AtomicU16, AtomicU32, Ordering}, mpsc::{Receiver, Sender, channel, sync_channel}, }, thread::JoinHandle, @@ -45,6 +45,10 @@ struct Flags { /// while it is not. published: AtomicU16, smoothed_tick_ms: AtomicU32, + /// `options.renderDistance` and `options.simulationDistance`, which the + /// server follows while it runs (IntegratedServer.tickServer). + render_distance: AtomicI32, + simulation_distance: AtomicI32, } /// Work the window hands its server thread (`MinecraftServer.execute`). @@ -66,6 +70,13 @@ impl Integrated { pub fn set_paused(&self, paused: bool) { self.flags.paused.store(paused, Ordering::Relaxed); } + /// The window's render and simulation distances, for the server to follow. + pub fn set_distances(&self, render: i32, simulation: i32) { + self.flags.render_distance.store(render, Ordering::Relaxed); + self.flags + .simulation_distance + .store(simulation, Ordering::Relaxed); + } /// `IntegratedServer.getPort` while `isPublished`. pub fn published(&self) -> Option { Some(self.flags.published.load(Ordering::Relaxed)).filter(|&p| p != 0) @@ -190,8 +201,15 @@ impl Game<'_> { options.server = None; options.world = None; options.dev_mods.clear(); + self.join_world_rest()?; let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone()); let flags = Arc::new(Flags::default()); + flags + .render_distance + .store(settings.render_distance, Ordering::Relaxed); + flags + .simulation_distance + .store(settings.simulation_distance, Ordering::Relaxed); let (ready_tx, ready) = channel(); let (tasks, server_tasks) = channel(); let server_flags = flags.clone(); @@ -249,7 +267,9 @@ impl Game<'_> { launch.create.as_ref(), )?; let saved = Box::new(self.level.clone()); - let view_distance = self.settings.render_distance.clamp(2, 32); + // Math.max(2, options.renderDistance): past vanilla's 32 when the + // window's render distance is (Horizon's options go to 64). + let view_distance = self.settings.render_distance.max(2); let config = HubConfig { default_game_mode: self.level.mode(), // Only the owner until it is opened to the LAN. @@ -257,7 +277,7 @@ impl Game<'_> { force_game_mode: false, hardcore: self.level.hardcore, view_distance, - simulation_distance: self.settings.simulation_distance.clamp(2, 32), + simulation_distance: self.settings.simulation_distance.max(2), dimension: self.dim.id().to_owned(), seed: self.level.seed, max_players: MAX_PLAYERS, @@ -297,6 +317,7 @@ impl Game<'_> { // The owner is an operator when the world allows commands // (`IntegratedPlayerList`, `MinecraftServer.getProfilePermissions`). host.hub.ops.insert(owner, if commands { 4 } else { 0 }); + host.hub.singleplayer_owner = Some(owner); host.owner = Some(Owner { uuid: owner, saved: Some(saved), @@ -316,10 +337,11 @@ impl Game<'_> { self.run_tasks(); if flags.paused.load(Ordering::Relaxed) { // Only the connections run. - self.tick_server(true)?; + self.tick_server_timed(true)?; } else { + self.follow_distances(&flags); let started = Instant::now(); - self.tick_server(false)?; + self.tick_server_timed(false)?; self.debug_charts.log_tick(started, started.elapsed()); flags.smoothed_tick_ms.store( self.debug_charts.smoothed_tick_ms.to_bits(), @@ -389,6 +411,60 @@ impl Game<'_> { pub(super) fn serving(&self) -> bool { self.serving.is_some() } + /// The window's agent runs a command as single player's console does + /// (`as_console`, as without a server thread): as the world's owner, in + /// the owner's level, at the owner permission level. The feedback goes to + /// the owner's chat and is returned. + pub(super) fn owner_console_command(&mut self, command: &str) -> Vec { + let Some(owner) = self.serving.as_ref().map(|s| s.owner) else { + return Vec::new(); + }; + let Some(mut host) = self.lan.take() else { + return Vec::new(); + }; + let mut out = Vec::new(); + if let Some(g) = host.hub.guests.iter().find(|g| g.uuid == owner && g.placed) { + let conn = g.conn; + // Commands.performCommand runs in the player's level. + let (back, theirs) = (self.dim, super::Dim::from_id(&g.dimension)); + let entered = theirs == back || self.enter_level(Some(&mut host), theirs).is_ok(); + if entered { + let command = command.trim_start_matches('/').to_owned(); + let lines = self.as_guest(&mut host, conn, |g| { + g.as_console(|g| { + g.chat_capture = Some(Vec::new()); + g.run_command(&command); + g.chat_capture.take().unwrap_or_default() + }) + }); + // A teleport into another level happens before its feedback is sent. + self.run_level_teleports(&mut host); + for line in lines.unwrap_or_default() { + out.push(line.plain()); + host.hub.send_to( + conn, + &horizon_protocol::packets::play::Clientbound::SystemChat( + horizon_protocol::packets::play::SystemChat { + content: horizon_client::lan::data::component_nbt( + &line.component(), + ), + overlay: false, + }, + ), + ); + } + self.send_admin_feedback(&mut host, Some(conn)); + } + if theirs != back + && let Err(e) = self.enter_level(Some(&mut host), back) + { + log::error!("could not reopen {}: {e}", back.id()); + } + } + self.lan = Some(host); + out + } + /// The window's requests, between two ticks. fn run_tasks(&mut self) { let tasks: Vec = match &self.serving { @@ -438,6 +514,28 @@ impl Game<'_> { } /// Publish or unpublish for real, once the hub is in its place (a /// player's `/publish` runs while it is out). + /// IntegratedServer.tickServer: the server follows the window's render + /// and simulation distances when they change. + fn follow_distances(&mut self, flags: &Flags) { + let Some(host) = self.lan.as_mut() else { + return; + }; + let view = flags.render_distance.load(Ordering::Relaxed).max(2); + let old = host.hub.config.view_distance; + if view != old { + log::info!("Changing view distance to {view}, from {old}"); + host.hub.set_view_distance(view); + self.settings.render_distance = view; + } + let simulation = flags.simulation_distance.load(Ordering::Relaxed).max(2); + let old = host.hub.config.simulation_distance; + if simulation != old { + log::info!("Changing simulation distance to {simulation}, from {old}"); + host.hub.set_simulation_distance(simulation); + self.settings.simulation_distance = simulation; + } + } + fn apply_publish(&mut self) { if self.lan.is_none() { return; @@ -552,7 +650,14 @@ fn serve( ) -> Result<()> { // It draws nothing: only the font, which books and chat measure with. let atlas = HudAtlas::fonts(&options.resources)?; + let gui = UiResources { + atlas, + panorama: Arc::new(horizon_client::gfx::panorama::Faces { + size: 1, + pixels: [0u8; 4].repeat(6), + }), + }; let audio = Audio::silent(&options.resources); - let mut server = Game::new(res, pack, atlas, options, settings, audio)?; + let mut server = Game::new(res, pack, gui, options, settings, audio)?; server.run_integrated(launch, flags, tasks, ready) } diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index b05f4fbf5..8e7176a70 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -176,7 +176,7 @@ impl Game<'_> { } pub(super) fn item_host(&self) -> Host<'_> { Host { - banners: &self.res.stations.banners, + banners: &self.res.stations().banners, } } /// The client level as item models read it. @@ -255,7 +255,7 @@ impl Game<'_> { item_render::gui::draw( &state, &self.pack.item_renderer, - &self.atlas.sprites, + &self.gui.atlas.sprites, &self.item_host(), batch, x, @@ -279,7 +279,7 @@ impl Game<'_> { }; state.submit( &self.pack.item_renderer, - &self.atlas.sprites, + &self.gui.atlas.sprites, &self.item_host(), pose, &mut sink, @@ -300,7 +300,7 @@ impl Game<'_> { }; state.submit( &self.pack.item_renderer, - &self.atlas.sprites, + &self.gui.atlas.sprites, &self.item_host(), pose, &mut sink, diff --git a/crates/horizon-client/src/game/jukebox.rs b/crates/horizon-client/src/game/jukebox.rs index 235ad7c24..c3ed75ebb 100644 --- a/crates/horizon-client/src/game/jukebox.rs +++ b/crates/horizon-client/src/game/jukebox.rs @@ -51,7 +51,7 @@ impl Game<'_> { pub(super) fn use_jukebox(&mut self, pos: [i32; 3], held: Option<&ItemStack>) -> bool { if &*self .res - .facts + .facts() .get(self.world.block(pos[0], pos[1], pos[2])) .name != "minecraft:jukebox" @@ -65,7 +65,7 @@ impl Game<'_> { let Some(stack) = held else { return false }; let Some(song) = self .res - .items + .items() .get(&stack.item) .and_then(|i| i.jukebox_song.clone()) else { @@ -95,7 +95,7 @@ impl Game<'_> { /// Level event 1010: the song from the jukebox, and the "Now Playing" overlay. fn start_song(&mut self, pos: [i32; 3], song: &str) { self.stop_song(pos); - let Some(s) = self.res.items.songs.get(song).cloned() else { + let Some(s) = self.res.items().songs.get(song).cloned() else { return; }; // LevelRenderer.playJukeboxSong: SimpleSoundInstance.forJukeboxSong. @@ -140,63 +140,53 @@ impl Game<'_> { pub(super) fn jukebox_removed(&mut self, pos: [i32; 3]) { self.stop_song(pos); } - /// `JukeboxSongPlayer.tick` for every playing jukebox. - pub(super) fn tick_jukeboxes(&mut self) { - let playing: Vec<((i32, i32, i32), String, i64)> = self - .world - .block_entities - .iter() - .filter_map(|(k, e)| match e { - BlockEntity::Jukebox(j) if j.playing => { - let song = self - .res - .items - .get(&j.record.as_ref()?.item)? - .jukebox_song - .clone()?; - Some((*k, song, j.ticks)) - } - _ => None, - }) - .collect(); - for (key, song, ticks) in playing { - let pos = [key.0, key.1, key.2]; - let Some(s) = self.res.items.songs.get(&song).cloned() else { - continue; - }; - if s.finished(ticks) { - if let Some(BlockEntity::Jukebox(j)) = self.world.block_entities.get_mut(&key) { - j.playing = false; - j.ticks = 0; - } - self.stop_song(pos); - self.jukebox_changed(pos); - continue; - } - if !self.jukebox_sounds.contains_key(&key) && ticks == 0 { - self.start_song(pos, &song); - } - if ticks % 20 == 0 { - let color = f64::from(self.world.random.next_int_bound(4).unwrap_or(0)) / 24.0; - let at = [ - f64::from(pos[0]) + 0.5, - f64::from(pos[1]) + 1.2, - f64::from(pos[2]) + 0.5, - ]; - self.particles.add( - &ParticleOptions::simple(ParticleType::Note), - at, - [color, 0.0, 0.0], - ); - } + /// `JukeboxSongPlayer.tick` of the jukebox at `key`, while it plays. + pub(super) fn tick_jukebox(&mut self, key: (i32, i32, i32)) { + let playing = match self.world.block_entities.get(&key) { + Some(BlockEntity::Jukebox(j)) if j.playing => j.record.as_ref().and_then(|r| { + let song = self.res.items().get(&r.item)?.jukebox_song.clone()?; + Some((song, j.ticks)) + }), + _ => None, + }; + let Some((song, ticks)) = playing else { + return; + }; + let pos = [key.0, key.1, key.2]; + let Some(s) = self.res.items().songs.get(&song).cloned() else { + return; + }; + if s.finished(ticks) { if let Some(BlockEntity::Jukebox(j)) = self.world.block_entities.get_mut(&key) { - j.ticks += 1; + j.playing = false; + j.ticks = 0; } + self.stop_song(pos); + self.jukebox_changed(pos); + return; + } + if !self.jukebox_sounds.contains_key(&key) && ticks == 0 { + self.start_song(pos, &song); + } + if ticks % 20 == 0 { + let color = f64::from(self.world.random.next_int_bound(4).unwrap_or(0)) / 24.0; + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 1.2, + f64::from(pos[2]) + 0.5, + ]; + self.particles.add( + &ParticleOptions::simple(ParticleType::Note), + at, + [color, 0.0, 0.0], + ); + } + if let Some(BlockEntity::Jukebox(j)) = self.world.block_entities.get_mut(&key) { + j.ticks += 1; } - self.update_song_volumes(); } /// Let go of songs that ended or whose jukebox stopped. - fn update_song_volumes(&mut self) { + pub(super) fn update_song_volumes(&mut self) { let sounds: Vec<_> = self .jukebox_sounds .iter() diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 78588cf4f..57c44cb07 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -2,7 +2,7 @@ //! server threads and the play-state hub, feeds it the world's entities each //! tick and turns what the guests do into gameplay. A world that is not open //! costs one `Option` check per tick. -use super::Game; +use super::{Game, shield::OFFHAND_SLOT}; use horizon_client::{ Result, items::ItemStack, @@ -42,6 +42,8 @@ pub(super) struct LanHost { pub hub: Hub, pub settings: LanSettings, pub host_entity: i32, + /// The host's swings the guests were told of (`Game::swings_started`). + pub host_swings: u32, pub host_uuid: u128, /// The host's profile name (the account's, or the offline name). pub host_name: String, @@ -61,6 +63,9 @@ pub(super) struct LanHost { /// are dead, whose respawn replaces their waypoint. pub waypoints: lan::waypoints::Waypoints, pub waypoint_dead: std::collections::HashSet, + /// Guests' commands waiting for the hub to be back in `self.lan`, where + /// a command can reach every player (game/lan_actions.rs). + pub commands: Vec, } /// The player who owns an integrated server's world: a guest whose state is @@ -73,7 +78,7 @@ pub(super) struct Owner { } /// A stable UUID for an entity that has none. -fn entity_uuid(id: u32) -> u128 { +pub(super) fn entity_uuid(id: u32) -> u128 { 0x4856_5a4e_0000_0000_0000_0000_0000_0000u128 | u128::from(id) } @@ -144,11 +149,15 @@ fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> { meta.push((3, serializer::BOOLEAN, Value::Bool(true))); } } - if m.health < m.kind.max_health { - meta.push((9, serializer::FLOAT, Value::Float(m.health.max(0.0)))); + // LivingEntity.DATA_HEALTH_ID: defined as 1, then set to the max health. + let health = m.health.max(0.0); + if health != 1.0 { + meta.push((9, serializer::FLOAT, Value::Float(health))); } - if kind == "minecraft:rabbit" && m.no_ai { - meta.push((15, serializer::BYTE, Value::Byte(1))); + // Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2. + let flags = i8::from(m.no_ai) | i8::from(m.extra.left_handed) << 1; + if flags != 0 { + meta.push((15, serializer::BYTE, Value::Byte(flags))); } if m.is_baby() && let Some(index) = baby_index(kind) @@ -363,6 +372,12 @@ impl Game<'_> { "open": true, "host": h.host_name, "port": h.settings.port, + // The server's own world: its finished chunks and how many it + // has generated or loaded so far. + "world": { + "chunks": self.world.chunks.len(), + "generated": self.streaming.generated_total, + }, "guests": h.hub.guests.iter().map(|g| json!({ "name": g.name, "position": g.position, @@ -370,6 +385,7 @@ impl Game<'_> { "loaded": g.loaded, "game_mode": g.game_mode, "sneaking": g.sneaking, + "sleeping": g.bed, "health": g.health, // FoodData: food level, saturation and exhaustion. "food": [ @@ -384,6 +400,10 @@ impl Game<'_> { [&m.extra.head, &m.extra.chest, &m.extra.legs, &m.extra.feet] .map(|s| s.as_deref()) }), + // The host draws this guest's arm swinging. + "model_swinging": h.models.get(&g.conn).map(|m| m.ai.swinging), + // For how many ticks the host draws this guest using an item. + "model_using": h.models.get(&g.conn).map(|m| m.extra.using_item), })).collect::>(), }), _ => json!({ "open": false }), @@ -456,7 +476,7 @@ impl Game<'_> { .clone()?; let biome_names: Vec = self .res - .biomes + .biomes() .list .iter() .map(|b| b.name.clone()) @@ -469,7 +489,7 @@ impl Game<'_> { .unwrap_or_default(); let mut encoder = ChunkEncoder::new( self.res - .facts + .facts() .states .iter() .map(|s| (s.name.clone(), s.fluid_level > 0 || s.waterlogged)), @@ -493,10 +513,12 @@ impl Game<'_> { let hub = Hub::new(lan, sync, encoder, config); let port = hub.lan.port; self.world.block_log = Some(Vec::new()); + self.world.light_log = Some(Default::default()); self.lan = Some(LanHost { hub, settings: LanSettings { port, ..settings }, host_entity, + host_swings: self.swings_started, host_uuid, host_name: self.options.player_name(), models: HashMap::new(), @@ -508,6 +530,7 @@ impl Game<'_> { owner: None, waypoints: Default::default(), waypoint_dead: Default::default(), + commands: Vec::new(), }); self.audio.capture = Some(Vec::new()); Ok(()) @@ -542,6 +565,7 @@ impl Game<'_> { // Give the writer threads a moment to flush the disconnect packets. std::thread::sleep(std::time::Duration::from_millis(100)); self.world.block_log = None; + self.world.light_log = None; self.audio.capture = None; self.lan_events.clear(); self.streaming.extra.clear(); @@ -709,16 +733,19 @@ impl Game<'_> { sprinting: p.sprinting, equipment, health: p.health.health(), + attributes: horizon_client::lan::attributes::syncable(&p.attributes), + living_flags: living_flags(self.using), }) } - /// Mobs and items as the entities guests track. - fn lan_entities(&self, hub: &mut Hub) -> Vec { - let mut out = Vec::with_capacity(self.mobs.len() + self.dropped.len()); + /// The entities guests track: mobs, items and the rest (game/lan_entities.rs). + fn lan_entities(&self, host_entity: Option, hub: &mut Hub) -> Vec { + let mut out = Vec::with_capacity(self.mobs.len() + self.dropped.len() + self.orbs.len()); for m in self.mobs.iter().filter(|m| !m.removed) { let kind = m.kind.id.as_str(); let meta = mob_meta(m, hub); let equipment = mob_equipment(m, hub); + let attributes = self.mob_attributes(m); let (yaw, pitch) = (m.yaw, m.head_pitch); out.push(EntityState { id: m.id as i32, @@ -733,6 +760,8 @@ impl Game<'_> { data: 0, meta, equipment, + attributes, + precise: false, }); } for d in &self.dropped { @@ -750,8 +779,30 @@ impl Game<'_> { data: 0, meta: vec![(8, serializer::ITEM_STACK, Value::Item(stack))], equipment: Vec::new(), + attributes: Vec::new(), + precise: false, }); } + for o in &self.orbs { + out.push(EntityState { + id: o.id as i32, + uuid: entity_uuid(o.id), + kind: "minecraft:experience_orb".to_owned(), + position: [o.position.x, o.position.y, o.position.z], + yaw: 0.0, + pitch: 0.0, + head_yaw: 0.0, + on_ground: o.on_ground, + velocity: [o.velocity.x, o.velocity.y, o.velocity.z], + data: 0, + // ExperienceOrb.DATA_VALUE. + meta: vec![(8, serializer::INT, Value::Int(o.value as i32))], + equipment: Vec::new(), + attributes: Vec::new(), + precise: false, + }); + } + self.lan_object_states(host_entity, hub, &mut out); out } @@ -762,17 +813,29 @@ impl Game<'_> { }; // What the tick sends a guest goes to its connection at the end. let holding = lan::Holding::start(); + // The host's own commands' (and command blocks') players moving + // to another level, and their broadcastToAdmins lines. + if !self.level_teleports.is_empty() { + self.run_level_teleports(&mut host); + } + if !self.admin_feedback.is_empty() { + self.send_admin_feedback(&mut host, None); + } let state = self.lan_host_state(&host); // A dedicated server runs the hub without a host player. if state.is_some() || host.hub.config.dedicated { let has_guests = !host.hub.guests.is_empty(); let entities = if has_guests { - self.lan_entities(&mut host.hub) + let host_entity = state.as_ref().map(|s| s.entity_id); + self.lan_assign_ids(); + self.lan_riding(host_entity, &mut host.hub.riding); + self.lan_entities(host_entity, &mut host.hub) } else { Vec::new() }; let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); let events = { + let clock_rate = self.network_clock_rate(); let mut ctx = TickCtx { world: &mut self.world, host: state.as_ref(), @@ -781,11 +844,7 @@ impl Game<'_> { spawn, difficulty: i32::from(self.ui.difficulty), difficulty_locked: self.level.difficulty_locked, - clock_rate: if self.ui.rules.bool("advance_time") { - self.ui.clock.rate - } else { - 0.0 - }, + clock_rate, tick_rate: self.clock.rate(), tick_frozen: self.clock.frozen(), collision: Some(self.collision), @@ -816,6 +875,9 @@ impl Game<'_> { } for event in events { match event { + event @ (HostEvent::Chat { .. } | HostEvent::Warn(_) | HostEvent::Error(_)) => { + self.lan_log_event(event); + } HostEvent::Joined(conn) => { self.lan_guest_joined(&mut host, conn, state.as_ref(), &entities, spawn); if self.options.dedicated.is_some() @@ -872,23 +934,20 @@ impl Game<'_> { ); } } - // MinecraftServer.logChatMessage of an unsigned message. - HostEvent::Chat(line) if self.options.dedicated.is_some() => { - 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); + if !host.commands.is_empty() { + self.lan = Some(host); + self.run_guest_commands(); + host = self.lan.take().expect("the hub is back after the commands"); + } } } } } self.lan_flush_effects(&mut host); self.tick_guests(&mut host); + self.lan_living_flags(&mut host); self.tick_server_travel(&mut host); self.lan_swings(&mut host); self.lan_update_streaming(&host); @@ -950,11 +1009,13 @@ impl Game<'_> { log::error!("could not open {}: {e}", level.id()); return; } - theirs = self.lan_entities(&mut host.hub); + // A dedicated server has no host player. + theirs = self.lan_entities(None, &mut host.hub); &theirs[..] } else { entities }; + let clock_rate = self.network_clock_rate(); let mut ctx = TickCtx { world: &mut self.world, host: state, @@ -963,7 +1024,7 @@ impl Game<'_> { spawn, difficulty: i32::from(self.ui.difficulty), difficulty_locked: self.level.difficulty_locked, - clock_rate: self.ui.clock.rate, + clock_rate, tick_rate: self.clock.rate(), tick_frozen: self.clock.frozen(), collision: Some(self.collision), @@ -1032,8 +1093,30 @@ impl Game<'_> { .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); + // LivingEntity.hurtServer: a hurt that restarted the hurt time. + if m.hurt_time > old.map_or(0, |o| o.0) + && !dead + && let Some((source, _)) = m.last_damage + { + use horizon_client::mobs::{DamageKind as K, Who}; + let player = source.attacker == Some(Who::Player); + let kind = super::creatures::damage_type(source.kind, player); + // The player a mob sees is the guest acting, else the host. + let cause = source.attacker.map(|who| match who { + Who::Player => host + .mob_players + .get(&m.id) + .and_then(|conn| host.hub.guest(*conn)) + .map_or(host.host_entity, |g| g.entity_id), + Who::Mob(id) => id as i32, + }); + // A projectile is the direct entity of its hit: not tracked here. + let melee = matches!( + source.kind, + K::PlayerAttack | K::MaceSmash | K::MobAttack | K::Sting | K::SonicBoom + ); + let direct = cause.filter(|_| melee); + host.hub.damage_event(m.id as i32, kind, cause, direct, at); } if dead && !old.is_some_and(|o| o.1) { host.hub.entity_event(m.id as i32, 3, at); @@ -1045,20 +1128,26 @@ impl Game<'_> { /// Keep the chunks around every guest loaded. fn lan_update_streaming(&mut self, host: &LanHost) { + // DistanceManager.PlayerTicketTracker: every chunk within the server's + // view distance (Chebyshev) of a player holds a PLAYER_LOADING ticket + // at the entity-ticking level (31), whatever the player asked for; + // levels rise by one a chunk, so FULL (33) reaches two chunks past + // it. An extra area finishes its chunks out to its radius + 1. That + // covers what the player tracks (`ChunkTrackingView`, within its view + // distance + 1) and those chunks' lit neighbours. + let radius = host.hub.config.view_distance + 1; self.streaming.extra = host .hub .guests .iter() .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)) + .map(|g| (g.chunk(), radius)) .collect(); } /// The guests' models, for the host to see them. fn lan_update_models(&mut self, host: &mut LanHost) { - let Some(kind) = self.res.player_type.clone() else { + let Some(kind) = self.res.player_type().clone() else { return; }; host.models @@ -1116,6 +1205,14 @@ impl Game<'_> { .each_ref() .map(|s| s.as_ref().map(|s| s.item.clone())); m.extra.crouching = g.sneaking; + // LivingEntity.updateSwingTime: the arm swing lan_swings started. + m.anim.attack_anim_o = m.anim.attack_anim; + horizon_client::mobs::ai::tick_swing(m); + // LivingEntity.onSyncedDataUpdated(DATA_LIVING_ENTITY_FLAGS): the + // item in use and its hand (the arm poses of a bow, a shield...). + let using = host.play.get(&g.conn).and_then(|p| p.using()); + m.extra.using_item = using.map_or(0, |(_, ticks)| ticks as i32 + 1); + m.extra.using_off_hand = using.is_some_and(|(slot, _)| slot == OFFHAND_SLOT); } } @@ -1129,7 +1226,7 @@ impl Game<'_> { let Some(host) = &self.lan else { return; }; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); for m in host.models.values() { let entity_start = out.len(); @@ -1145,7 +1242,7 @@ impl Game<'_> { camera, &lookup, packed, - &self.res.mob_data, + self.res.mob_data(), &self.worn_armor_layers(m), out, ); @@ -1163,3 +1260,30 @@ impl Game<'_> { } } } + +impl Game<'_> { + /// A hub's chat and log lines: a dedicated server logs them + /// (MinecraftServer.logChatMessage, `[Not Secure]` for unsigned or + /// expired messages); a LAN host shows the chat. + pub(super) fn lan_log_event(&mut self, event: HostEvent) { + let dedicated = self.options.dedicated.is_some(); + match event { + HostEvent::Chat { line, secure } if dedicated => { + let tag = if secure { "" } else { "[Not Secure] " }; + super::dedicated::log("INFO", &format!("{tag}{line}")); + } + HostEvent::Chat { line, .. } => self.system_message(Text::literal(line)), + HostEvent::Warn(line) if dedicated => super::dedicated::log("WARN", &line), + HostEvent::Warn(line) => log::warn!("{line}"), + HostEvent::Error(line) if dedicated => super::dedicated::log("ERROR", &line), + HostEvent::Error(line) => log::error!("{line}"), + _ => {} + } + } +} + +/// `LivingEntity.DATA_LIVING_ENTITY_FLAGS` for an item in use: 1, and 2 when +/// it is the off hand's. +pub(super) fn living_flags(using: Option<(usize, u32)>) -> i8 { + using.map_or(0, |(slot, _)| if slot == OFFHAND_SLOT { 3 } else { 1 }) +} diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 9281cc3a1..64ee29776 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -10,6 +10,7 @@ use horizon_client::{ command::vanilla, containers::BlockEntity, entities::Experience, + first_person::{Hand, SwingAnimation}, items::ItemStack, lan::{ guest::SPECTATOR, @@ -18,7 +19,7 @@ use horizon_client::{ }, motion::{MotionEvent, MotionWorld, PlayerMotion}, }; -use horizon_core::geometry::Vec3; +use horizon_core::{geometry::Vec3, random::RandomSource}; use horizon_protocol::{ packets::play::{self, Clientbound as C, Serverbound as S}, text::literal, @@ -43,8 +44,9 @@ pub(super) struct GuestPlay { /// its progress since `dig_start` is complete (ServerPlayerGameMode.hasDelayedDestroy). delayed: Option<([i32; 3], u64)>, last_progress: i32, - /// Hand movements the client announced and the host animated. - swung: bool, + /// Swings the guest's actions started this tick, for the players around + /// (`LivingEntity.swing` sends ClientboundSwingAnimationPacket). + swings: u32, /// The trading screen the guest has open. pub(super) merchant: Option, /// The inventory menu and the crafting table the guest crafts in. @@ -56,6 +58,80 @@ pub(super) struct GuestPlay { last_inventory: u64, /// `Entity.portalProcess` and `portalCooldown` (game/server_travel.rs). pub(super) portal: horizon_client::nether_portal::PortalState, + /// `Player.takeXpDelay`: ticks until the next orb can be taken. + xp_delay: u32, + /// What last killed the guest outright (`/kill`): the death message's key. + death_cause: Option, +} + +/// A guest's command waiting for the hub (`LanHost::commands`). +pub(super) struct GuestCommand { + conn: u32, + command: String, + permission: u8, + /// An integrated server's: no admin feedback or level teleports (yet). + integrated: bool, +} + +/// The game's own state while a guest's is swapped in (`enter_guest`), and +/// the guest's records that live outside `Guest`. +pub(super) struct GuestSwap { + conn: u32, + i: usize, + play: GuestPlay, + player: Option, + /// The guest's eye height and the game's. + eye: (f32, f32), + yaw: f32, + pitch: f32, + selected: usize, + mode: horizon_client::command::args::GameMode, + creative: bool, + xp: Experience, + host_keys: std::collections::HashSet, + screen: Screen, + host_sign: Option, + host_book: Option, + host_command_block: Option, + host_mount_menu: super::mount_menu::MountMenu, + craft_size: usize, + craft_grid: Vec>, + container: Option<(i32, i32, i32)>, + mining: Option, + destroy_delay: u32, + using: Option<(usize, u32)>, + use_delay: u32, + attack_ticks: u32, + swing: horizon_client::first_person::SwingState, + left: bool, + right: bool, + riding: Option, + host_station: Option, + sleeping: Option<[i32; 3]>, + sleep_timer: u32, + spawn: Option, + respawn: ( + Option, + Option<[f64; 3]>, + ), + message: Option<(String, std::time::Instant)>, + host_ender: Option<(i32, i32, i32)>, + adv_loaded: bool, + last_inventory: u64, + death_cause: Option, + /// The guest whose turn this one nests in, if any. + acting: (Option, Option, Option), + /// The packets queued for that guest. + packets: Vec, + /// The host's count of swings started, kept while the guest acts. + swings: u32, +} + +impl GuestPlay { + /// The item in use: its slot and for how many ticks. + pub(super) fn using(&self) -> Option<(usize, u32)> { + self.using + } } struct ItemRules<'a>(&'a horizon_client::items::Items); @@ -93,6 +169,24 @@ impl Game<'_> { conn: u32, f: impl FnOnce(&mut Self) -> R, ) -> Option { + let swap = self.enter_guest(host, conn)?; + let result = f(self); + self.leave_guest(host, swap); + Some(result) + } + + /// The first half of `as_guest`: the guest's state in place of the + /// game's, which the returned swap keeps until `leave_guest`. Between the + /// two the host may go back into `self.lan`, so that what the guest does + /// can reach the other players (their commands, `for_player`), and a + /// guest's turn can nest in another's: the acting guest and the packets + /// queued for them are kept and restored too. + pub(super) fn enter_guest(&mut self, host: &mut LanHost, conn: u32) -> Option { + // The guest whose turn it is is in place already (their record holds + // the game's state until their turn ends). + if self.lan_acting == Some(conn) { + return None; + } let i = host.hub.guests.iter().position(|g| g.conn == conn)?; if host.hub.guests[i].motion.is_none() { let p = Vec3::new( @@ -172,6 +266,16 @@ impl Game<'_> { self.right = play.using.is_some() || self.using.is_some(); let riding = self.riding.take(); let host_station = self.station.take(); + // The guest's bed, sleep counter and respawn point; the host's + // respawn point, anchor and action bar stay theirs. + let sleeping = std::mem::replace(&mut self.sleeping, g.bed); + let sleep_timer = std::mem::replace(&mut self.sleep_timer, g.sleep_timer); + let spawn = std::mem::replace( + &mut self.spawn, + g.spawn.map(|s| Vec3::new(s[0], s[1], s[2])), + ); + let respawn = (self.respawn_config.take(), self.level.spawn); + let message = self.message.take(); // The guest's own ender inventory; one the host has open goes back // into the host's while the guest acts. let host_ender = self.ender_open; @@ -186,14 +290,115 @@ impl Game<'_> { std::mem::swap(&mut self.stats, &mut play.stats); let adv_loaded = std::mem::replace(&mut self.adv.loaded, true); let last_inventory = std::mem::replace(&mut self.adv.last_inventory, play.last_inventory); - self.lan_acting = Some(conn); - self.lan_acting_name = Some(g.name.clone()); - self.lan_acting_uuid = Some(g.uuid); + let death_cause = std::mem::replace(&mut self.ui.death_cause, play.death_cause.take()); + let acting = ( + self.lan_acting.replace(conn), + self.lan_acting_name.replace(g.name.clone()), + self.lan_acting_uuid.replace(g.uuid), + ); + let packets = std::mem::take(&mut self.guest_packets); + let swings = self.swings_started; + Some(GuestSwap { + conn, + i, + play, + player, + eye, + yaw, + pitch, + selected, + mode, + creative, + xp, + host_keys, + screen, + host_sign, + host_book, + host_command_block, + host_mount_menu, + craft_size, + craft_grid, + container, + mining, + destroy_delay, + using, + use_delay, + attack_ticks, + swing, + left, + right, + riding, + host_station, + sleeping, + sleep_timer, + spawn, + respawn, + message, + host_ender, + adv_loaded, + last_inventory, + death_cause, + acting, + packets, + swings, + }) + } - let result = f(self); - self.lan_acting = None; - self.lan_acting_name = None; - self.lan_acting_uuid = None; + /// The second half of `as_guest`: the guest's state back into their + /// record, the game's back in place, and what the turn changed sent. + pub(super) fn leave_guest(&mut self, host: &mut LanHost, swap: GuestSwap) { + let GuestSwap { + conn, + i, + mut play, + mut player, + eye, + yaw, + pitch, + selected, + mode, + creative, + xp, + host_keys, + screen, + host_sign, + host_book, + host_command_block, + host_mount_menu, + craft_size, + craft_grid, + container, + mining, + destroy_delay, + using, + use_delay, + attack_ticks, + swing, + left, + right, + riding, + host_station, + sleeping, + sleep_timer, + spawn, + respawn, + message, + host_ender, + adv_loaded, + last_inventory, + death_cause, + acting, + packets, + swings, + } = swap; + // The guest's swings are theirs: the host's own count stays the host's. + play.swings += self.swings_started.wrapping_sub(swings); + self.swings_started = swings; + for packet in std::mem::replace(&mut self.guest_packets, packets) { + host.hub.send_to(conn, &packet); + } + (self.lan_acting, self.lan_acting_name, self.lan_acting_uuid) = acting; + play.death_cause = std::mem::replace(&mut self.ui.death_cause, death_cause); // An ender chest the guest opened: the menu shows their inventory // itself (lan_open_container), not a stand-in block entity. self.close_ender_chest(); @@ -203,6 +408,12 @@ impl Game<'_> { let opened_table = std::mem::replace(&mut self.craft_size, craft_size) == 3; self.craft_grid = craft_grid; let opened_station = std::mem::replace(&mut self.station, host_station); + let bed = std::mem::replace(&mut self.sleeping, sleeping); + let guest_sleep_timer = std::mem::replace(&mut self.sleep_timer, sleep_timer); + let guest_spawn = std::mem::replace(&mut self.spawn, spawn).map(|s| [s.x, s.y, s.z]); + (self.respawn_config, self.level.spawn) = respawn; + // ServerPlayer.displayClientMessage(_, true): the guest's action bar. + let guest_message = std::mem::replace(&mut self.message, message); self.riding = riding; self.left = left; self.right = right; @@ -220,6 +431,15 @@ impl Game<'_> { self.mount_menu = host_mount_menu; self.keys = host_keys; let g = &mut host.hub.guests[i]; + let fell_asleep = bed.is_some() && g.bed.is_none(); + (g.bed, g.sleep_timer, g.spawn) = (bed, guest_sleep_timer, guest_spawn); + g.sleeping = g.bed.is_some(); + if let Some((text, _)) = guest_message { + g.send(&C::SystemChat(play::SystemChat { + content: literal(&text), + overlay: true, + })); + } std::mem::swap(&mut self.ender_items, &mut g.ender_items); std::mem::swap(&mut self.adv.progress, &mut g.advancements); std::mem::swap(&mut self.adv.changed, &mut g.advancements_changed); @@ -251,6 +471,9 @@ impl Game<'_> { std::mem::swap(&mut self.armor, &mut g.armor); std::mem::swap(&mut self.offhand, &mut g.offhand); std::mem::swap(&mut self.carried, &mut g.carried); + // A teleport with a rotation (commands) turns the guest. + let turned = [self.yaw, self.pitch] != [g.yaw, g.pitch]; + [g.yaw, g.pitch] = [self.yaw, self.pitch]; self.yaw = yaw; self.pitch = pitch; self.eye = eye.1; @@ -264,11 +487,24 @@ impl Game<'_> { m.sprinting = false; let moved: f64 = (0..3).map(|k| (at[k] - g.position[k]).powi(2)).sum(); g.motion = Some(Box::new(m)); - if moved > 0.0001 { + if moved > 0.0001 || turned { host.hub.teleport(i, Some(at)); } } let g = &mut host.hub.guests[i]; + if let Some(head) = g.bed.filter(|_| fell_asleep) { + // LivingEntity.startSleeping: in the bed, still. + let at = [ + f64::from(head[0]) + 0.5, + f64::from(head[1]) + 0.5625, + f64::from(head[2]) + 0.5, + ]; + g.position = at; + if let Some(m) = g.motion.as_mut() { + m.position = Vec3::new(at[0], at[1], at[2]); + m.velocity = Vec3::ZERO; + } + } if new_mode != g.game_mode { let conn = g.conn; host.hub.set_game_mode(conn, new_mode); @@ -288,7 +524,6 @@ impl Game<'_> { if opened_table { self.lan_open_crafting(host, conn); } - Some(result) } /// `ServerLevel.players()` in turn: the host's own player, then each @@ -334,7 +569,7 @@ impl Game<'_> { fn lan_open_container(&mut self, host: &mut LanHost, conn: u32, pos: (i32, i32, i32)) -> bool { let name = &self .res - .facts + .facts() .get(self.world.block(pos.0, pos.1, pos.2)) .name; let (menu, title, slots) = if &**name == "minecraft:ender_chest" { @@ -352,6 +587,13 @@ impl Game<'_> { _ => ("minecraft:furnace", "container.furnace"), }; (menu, title, Slots::Block(pos)) + } else if let Some(BlockEntity::Brewing(_)) = self.world.block_entities.get(&pos) { + // BrewingStandBlock.useWithoutItem: BrewingStandMenu. + ( + "minecraft:brewing_stand", + "container.brewing", + Slots::Block(pos), + ) } else if let Some((other, right)) = self.chest_partner(pos) { // ChestBlock.combine: the right half's slots come first. let halves = if right { @@ -499,6 +741,16 @@ impl Game<'_> { } } } + // ServerGamePacketListenerImpl.handlePunch: the main hand swings + // with the held item's attack animation (mining, attacking, a + // click on nothing), seen by the players around, and the attack + // strength starts again. + S::Punch(_) => { + self.as_guest(host, conn, |g| { + g.swing_hand(Hand::Main, SwingAnimation::DEFAULT); + g.reset_attack_strength(); + }); + } S::UseItemOn(p) => { host.hub.ack(conn, p.sequence); if spectator { @@ -514,11 +766,14 @@ impl Game<'_> { f64::from(p.pos[2]) + f64::from(p.cursor[2]), ], }; - self.as_guest(host, conn, |g| { + let swung = self.as_guest(host, conn, |g| { g.forced_hit = Some(hit); + let swings = g.swings_started; let _ = g.use_item(); g.forced_hit = None; + g.swings_started != swings }); + self.lan_swing_back(host, conn, swung); // The client predicted a result: correct it with what really is. for pos in [ p.pos, @@ -536,20 +791,26 @@ impl Game<'_> { } // handleUseItem: the client's rotation, then the item alone. What it // looked at a moment ago (a block, a mob) is UseItemOn's or Interact's. - self.as_guest(host, conn, |g| { + let swung = self.as_guest(host, conn, |g| { (g.yaw, g.pitch) = (p.yaw, p.pitch); g.lan_item_only = true; + let swings = g.swings_started; let _ = g.use_item(); g.lan_item_only = false; + g.swings_started != swings }); + self.lan_swing_back(host, conn, swung); } S::Attack(p) => self.guest_attack(host, conn, p.id), S::Interact(p) => { if let Some((position, eye)) = self.look_at_entity(host, gi, p.id) { let _ = (position, eye); - self.as_guest(host, conn, |g| { + let swung = self.as_guest(host, conn, |g| { + let swings = g.swings_started; let _ = g.use_item(); + g.swings_started != swings }); + self.lan_swing_back(host, conn, swung); } } S::SetCreativeModeSlot(p) => { @@ -563,7 +824,7 @@ impl Game<'_> { S::ContainerClick(p) if self.lan_merchant_click(host, conn, &p) => {} S::ContainerClick(p) if self.lan_inventory_click(host, conn, &p) => {} S::ContainerClick(p) if self.lan_crafting_click(host, conn, &p) => {} - S::ContainerClick(p) if self.lan_furnace_click(host, conn, &p) => {} + S::ContainerClick(p) if self.lan_machine_click(host, conn, &p) => {} S::SelectTrade(p) => self.lan_select_trade(host, conn, p.item), S::ContainerClose(p) if self.lan_merchant_closed(host, conn, Some(p.container)) => { let g = &mut host.hub.guests[gi]; @@ -578,7 +839,7 @@ impl Game<'_> { } } S::ContainerClick(p) => { - let rules = ItemRules(&self.res.items); + let rules = ItemRules(self.res.items()); let drops = host.hub.container_click(conn, &p, &mut self.world, &rules); self.drop_guest_items(host, gi, drops); } @@ -596,7 +857,8 @@ impl Game<'_> { self.drop_guest_items(host, gi, vec![c]); } } - S::ChatCommand(c) => self.guest_command(host, conn, &c.command), + S::ChatCommand(c) => self.guest_chat_command(host, conn, &c.command), + S::ChatCommandSigned(p) => self.guest_signed_command(host, conn, p), S::ChangeDifficulty(p) if host.hub.guests[gi].permission >= 2 => { if !self.level.difficulty_locked && (0..=3).contains(&p.difficulty) { self.ui.difficulty = if self.level.hardcore { @@ -685,13 +947,7 @@ impl Game<'_> { }), ); } - self.send_admin_feedback(host, conn); - } - } - S::Unknown(8, payload) => { - // A signed command: the text comes first. - if let Ok(text) = horizon_protocol::buf::Reader::new(&payload).string(32767) { - self.guest_command(host, conn, &text); + self.send_admin_feedback(host, Some(conn)); } } S::Unknown(id, payload) @@ -712,7 +968,7 @@ impl Game<'_> { } S::PickItemFromBlock(p) => { let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]); - let item = self.res.facts.get(state).item.clone(); + let item = self.res.facts().get(state).item.clone(); let g = &mut host.hub.guests[gi]; if g.creative() && &*item != "minecraft:air" { let slot = g.selected; @@ -818,7 +1074,18 @@ impl Game<'_> { } /// Commands.performCommand for a guest with command access. - fn guest_command(&mut self, host: &mut LanHost, conn: u32, command: &str) { + /// Commands.performCommand for a guest, with the message arguments it + /// signed (none after an unsigned command packet). + pub(super) fn guest_command( + &mut self, + host: &mut LanHost, + conn: u32, + command: &str, + signed: Option>, + ) { + if self.guest_message_command(host, conn, command, signed.as_ref()) { + return; + } // ListPlayersCommand needs no permission and lists every player. let words: Vec<&str> = command.trim_start_matches('/').split(' ').collect(); if words[0] == "list" && (words.len() == 1 || words[1..] == ["uuids"]) { @@ -835,34 +1102,12 @@ impl Game<'_> { return; } // An integrated server runs every player's commands at their own - // permission level (`CommandSourceStack.permissions`). - if host.hub.config.integrated { - let Some(level) = host.hub.guest(conn).map(|g| g.permission) else { - return; - }; - let command = command.trim_start_matches('/').to_owned(); - let lines = self.as_guest(host, conn, |g| { - let console = std::mem::replace(&mut g.ui.registries.permission, level); - g.chat_capture = Some(Vec::new()); - g.run_command(&command); - g.ui.registries.permission = console; - g.chat_capture.take().unwrap_or_default() - }); - for line in lines.unwrap_or_default() { - host.hub.send_to( - conn, - &C::SystemChat(play::SystemChat { - content: horizon_client::lan::data::component_nbt(&line.component()), - overlay: false, - }), - ); - } - return; - } - // A LAN world follows its Allow Commands; a dedicated server leaves - // it to the ops list (the guest's permission level). + // permission level (`CommandSourceStack.permissions`); a LAN world + // follows its Allow Commands, and a dedicated server leaves it to + // the ops list (the guest's permission level). + let integrated = host.hub.config.integrated; let allowed = self.options.dedicated.is_some() || self.allow_commands(); - if !host.settings.guest_commands || !allowed { + if !integrated && (!host.settings.guest_commands || !allowed) { host.hub.send_to( conn, &C::SystemChat(play::SystemChat { @@ -872,38 +1117,74 @@ impl Game<'_> { ); return; } - let command = command.trim_start_matches('/').to_owned(); - // The guest's own level (Commands.performCommand with the player's source): an - // operator's on a dedicated server, never the host's. - let permission = host.hub.guest(conn).map_or(0, |g| g.permission); - let lines = self.as_guest(host, conn, |g| { - g.chat_capture = Some(Vec::new()); - let level = std::mem::replace(&mut g.ui.registries.permission, permission); - g.run_command(&command); - g.ui.registries.permission = level; - g.chat_capture - .take() - .unwrap_or_default() - .iter() - .map(|t| horizon_client::lan::data::component_nbt(&t.component())) - .collect::>() + // The guest's own level (Commands.performCommand with the player's + // source): an operator's on a dedicated server, never the host's. + let Some(permission) = host.hub.guest(conn).map(|g| g.permission) else { + return; + }; + host.commands.push(GuestCommand { + conn, + command: command.trim_start_matches('/').to_owned(), + permission, + integrated, }); - for content in lines.unwrap_or_default() { - host.hub.send_to( - conn, - &C::SystemChat(play::SystemChat { - content, - overlay: false, - }), - ); - } - self.send_admin_feedback(host, conn); } - /// The `broadcastToAdmins` lines a guest's command queued: every other + /// The guests' queued commands, run with the hub in `self.lan` so that + /// they reach the other players too (`/give Bob`, `/tp Bob`, `/kick`). + pub(super) fn run_guest_commands(&mut self) { + loop { + let Some(host) = self.lan.as_mut() else { + return; + }; + if host.commands.is_empty() { + return; + } + let c = host.commands.remove(0); + let mut host = self.lan.take().expect("checked above"); + let Some(swap) = self.enter_guest(&mut host, c.conn) else { + self.lan = Some(host); + continue; + }; + self.lan = Some(host); + self.chat_capture = Some(Vec::new()); + let level = std::mem::replace(&mut self.ui.registries.permission, c.permission); + self.run_command(&c.command); + self.ui.registries.permission = level; + let lines = self.chat_capture.take().unwrap_or_default(); + let mut host = self.lan.take().expect("a command puts the hub back"); + self.leave_guest(&mut host, swap); + host.hub.sync_all_effects(); + if !c.integrated { + // A teleport into another level happens before its feedback is sent. + self.run_level_teleports(&mut host); + } + for line in lines { + host.hub.send_to( + c.conn, + &C::SystemChat(play::SystemChat { + content: horizon_client::lan::data::component_nbt(&line.component()), + overlay: false, + }), + ); + } + if !c.integrated { + self.send_admin_feedback(&mut host, Some(c.conn)); + } + self.lan = Some(host); + } + } + + /// The `broadcastToAdmins` lines a command queued (`source`: the guest + /// whose it was; none for the host's or the console's): 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) { + pub(super) fn send_admin_feedback(&mut self, host: &mut LanHost, source: Option) { + // PlayerList.isOp for the host of a world open to LAN: the owner when + // the world allows commands, everyone when the LAN does. + let host_op = source.is_some() + && !host.hub.config.dedicated + && (self.allow_commands() || host.hub.config.guest_commands); for (line, ops, console) in std::mem::take(&mut self.admin_feedback) { if ops { let content = horizon_client::lan::data::component_nbt(&line.component()); @@ -911,13 +1192,16 @@ impl Game<'_> { .hub .guests .iter() - .filter(|g| g.conn != source && g.permission > 0) + .filter(|g| Some(g.conn) != source && g.permission > 0) { g.send(&C::SystemChat(play::SystemChat { content: content.clone(), overlay: false, })); } + if host_op { + self.system_message(line.clone()); + } } if console { super::dedicated::log("INFO", &format!("System chat: {}", line.plain())); @@ -966,10 +1250,19 @@ impl Game<'_> { } fn guest_respawn(&mut self, host: &mut LanHost, conn: u32) { - let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else { return; }; + // The guest's own bed, else the world spawn: never the host's bed. + let world = self + .level + .world_spawn + .map(|[x, y, z]| [f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5]); + let spawn = host.hub.guests[i] + .spawn + .or(world) + .or(self.spawn.map(|s| [s.x, s.y, s.z])) + .unwrap_or([0.5, 80.0, 0.5]); if !host.hub.guests[i].dead { return; } @@ -1003,6 +1296,7 @@ impl Game<'_> { if let Some(play) = host.play.get_mut(&conn) { play.potions = Default::default(); } + let clock_rate = self.network_clock_rate(); let ctx = TickCtx { world: &mut self.world, host: None, @@ -1011,11 +1305,7 @@ impl Game<'_> { spawn, difficulty: i32::from(self.ui.difficulty), difficulty_locked: self.level.difficulty_locked, - clock_rate: if self.ui.rules.bool("advance_time") { - self.ui.clock.rate - } else { - 0.0 - }, + clock_rate, tick_rate: self.clock.rate(), tick_frozen: self.clock.frozen(), collision: Some(self.collision), @@ -1041,6 +1331,7 @@ impl Game<'_> { let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { continue; }; + self.guest_sleep_tick(host, gi); if host.hub.guests[gi].dead || self.on_server_trip(conn) { continue; } @@ -1079,10 +1370,12 @@ impl Game<'_> { self.as_guest(host, conn, |g| { g.count_tick_stats(sleeping); g.tick_advancements(); + g.update_player_attributes(); }); host.hub.flush_progress(conn); self.guest_dig_feedback(host, conn); self.guest_pickups(host, gi); + self.guest_orbs(host, gi); let g = &mut host.hub.guests[gi]; if g.health <= 0.0 && !g.dead { g.dead = true; @@ -1094,7 +1387,34 @@ impl Game<'_> { total: g.xp_total, } .death_reward(self.ui.rules.bool("keep_inventory") || g.game_mode == SPECTATOR); - let message = literal(&format!("{} died", g.name)); + let (name, uuid) = (g.name.clone(), g.uuid); + let cause = host.play.get_mut(&conn).and_then(|p| p.death_cause.take()); + let message = match cause { + // ServerPlayer.die: the death message, to everyone unless + // the player's team hides it. + Some(key) if self.ui.rules.bool("show_death_messages") => { + let text = horizon_client::text::Text::translate( + &key, + &[self.player_text(&name, uuid)], + ); + let message = horizon_client::lan::data::component_nbt(&text.component()); + let team = self.score.board.players_team(&name); + if horizon_client::scoreboard::own_death_message_shown(team) { + host.hub.system_message(message.clone()); + if self.options.dedicated.is_some() { + super::dedicated::log( + "INFO", + &format!("System chat: {}", text.plain()), + ); + } else if self.player.is_some() { + self.system_message(text); + } + } + message + } + Some(_) => literal(""), + None => literal(&format!("{name} died")), + }; host.hub.send_to( conn, &C::PlayerCombatKill(play::PlayerCombatKill { id, message }), @@ -1106,6 +1426,62 @@ impl Game<'_> { } } + /// `Player.tick`'s sleep counter, and `LivingEntity.tick`'s wake-up of a + /// sleeper who died or whose bed is gone. + fn guest_sleep_tick(&mut self, host: &mut LanHost, gi: usize) { + let g = &mut host.hub.guests[gi]; + g.sleep_timer = super::tick_sleep_timer(g.sleep_timer, g.bed.is_some()); + if let Some(head) = g.bed { + let block = self.world.block(head[0], head[1], head[2]); + let bed = self.res.facts().get(block).name.ends_with("_bed"); + if g.dead || g.health <= 0.0 || !bed { + host.hub.wake(gi); + } + } + } + + /// `SleepStatus.areEnoughSleeping` and `areEnoughDeepSleeping` over the + /// host's player and the guests: of the players not in spectator mode, + /// players_sleeping_percentage of them (at least one) are in bed, and as + /// many have slept 100 ticks. + pub(super) fn enough_slept(&self) -> bool { + let (mut active, mut sleeping, mut deep) = (0i64, 0i64, 0i64); + let mut count = |in_bed: bool, timer: u32| { + active += 1; + if in_bed { + sleeping += 1; + if timer >= 100 { + deep += 1; + } + } + }; + if self.player.is_some() && !self.spectator() { + count(self.sleeping.is_some(), self.sleep_timer); + } + if let Some(host) = self.lan.as_ref() { + for g in host + .hub + .guests + .iter() + .filter(|g| g.placed && !g.spectator()) + { + count(g.bed.is_some(), g.sleep_timer); + } + } + let percent = i64::from(self.ui.rules.int("players_sleeping_percentage").max(0)); + let needed = ((active * percent + 99) / 100).max(1); + sleeping >= needed && deep >= needed + } + + /// `ServerLevel.wakeUpAllPlayers` for the guests. + pub(super) fn wake_guests(&mut self) { + if let Some(host) = self.lan.as_mut() { + for i in 0..host.hub.guests.len() { + host.hub.wake(i); + } + } + } + /// `PlayerList.broadcastSystemMessage` of the advancements guests made /// (their own actions, commands and ticks). fn announce_guest_advancements(&mut self, host: &mut LanHost) { @@ -1225,7 +1601,7 @@ impl Game<'_> { let range = |v: f64| (v - half).floor() as i32..=(v + half).floor() as i32; range(at[0]).any(|x| { range(at[2]).any(|z| { - let f = self.res.facts.get(self.world.block(x, y, z)); + let f = self.res.facts().get(self.world.block(x, y, z)); f.full_collision && f.solid_render }) }) @@ -1243,7 +1619,7 @@ impl Game<'_> { play.mining = None; let start = play.dig_start; let state = self.world.block(pos[0], pos[1], pos[2]); - if !dug || self.res.facts.is_air(state) { + if !dug || self.res.facts().is_air(state) { return; } let progress = self @@ -1267,7 +1643,7 @@ impl Game<'_> { }; let ticks = host.hub.ticks; let state = self.world.block(pos[0], pos[1], pos[2]); - let progress = if self.res.facts.is_air(state) { + let progress = if self.res.facts().is_air(state) { None } else { self.as_guest(host, conn, |g| g.destroy_progress(pos)) @@ -1384,6 +1760,79 @@ impl Game<'_> { } } + /// `Player.tick`'s takeXpDelay and `Player.aiStep`'s touch of the + /// experience orbs in the guest's box grown by 1, 0.5, 1: one of them at + /// random, at most every 2 ticks (`ExperienceOrb.playerTouch`), repairs + /// with Mending and gives the rest as points. Everyone near hears it. + fn guest_orbs(&mut self, host: &mut LanHost, gi: usize) { + let g = &host.hub.guests[gi]; + // Player's standing and crouching boxes: 1.8 and 1.5 high. + let height = if g.sneaking { 1.5 } else { 1.8 }; + let (conn, id, at) = (g.conn, g.entity_id, g.position); + let unable = g.spectator() || g.dead || g.health <= 0.0; + let play = host.play.entry(conn).or_default(); + if play.xp_delay > 0 { + play.xp_delay -= 1; + } + if unable || play.xp_delay > 0 { + return; + } + let (min, max) = ( + [at[0] - 1.3, at[1] - 0.5, at[2] - 1.3], + [at[0] + 1.3, at[1] + height + 0.5, at[2] + 1.3], + ); + let touching: Vec = self + .orbs + .iter() + .enumerate() + .filter(|(_, o)| { + o.position.x + 0.25 > min[0] + && o.position.x - 0.25 < max[0] + && o.position.y + 0.5 > min[1] + && o.position.y < max[1] + && o.position.z + 0.25 > min[2] + && o.position.z - 0.25 < max[2] + }) + .map(|(i, _)| i) + .collect(); + if touching.is_empty() { + return; + } + // Util.getRandom(orbs, random). + let pick = self + .world + .random + .next_int_bound(touching.len() as i32) + .unwrap_or(0) as usize; + let orb = self.orbs.remove(touching[pick]); + play.xp_delay = 2; + host.hub.take_item(orb.id as i32, id, 1, at); + // ClientPacketListener.handleTakeItemEntity's sound, at the orb. + let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.35 + 0.9; + let p = orb.position; + self.audio.play( + "minecraft:entity.experience_orb.pickup", + Some([p.x, p.y, p.z]), + 0.1, + pitch, + ); + let value = orb.value; + if let Some(target) = super::pickups::guest_target(host, id as u32) { + use super::pickups::{Collector, Taken}; + self.add_pickup_toward( + Taken::Orb(Box::new(orb)), + Collector::Guest(id as u32), + target, + ); + } + self.as_guest(host, conn, |game| { + let rest = game.mending(value); + if rest > 0 { + game.give_orb_points(rest); + } + }); + } + /// The host's own `ItemPickupParticle` toward the guest's model. fn guest_pickup( &mut self, @@ -1419,23 +1868,72 @@ impl Game<'_> { } } - /// Guests' arm swings for everyone else. + /// The guests' items in use, for the players around (`LivingEntity.startUsingItem` + /// and `stopUsingItem` set DATA_LIVING_ENTITY_FLAGS). + pub(super) fn lan_living_flags(&mut self, host: &mut LanHost) { + for g in &mut host.hub.guests { + let using = host.play.get(&g.conn).and_then(GuestPlay::using); + g.living_flags = super::lan::living_flags(using); + } + } + + /// A use the server ran swung the guest's hand: their own client is told + /// too (`swing(hand, true)` for a SwingSource.SERVER result). Horizon's + /// client does not run uses itself, so it does not predict the swing; a + /// client that did (a block placed) is still in the first half of its + /// swing and ignores it (`SwingState.startIfAble`). + fn lan_swing_back(&mut self, host: &mut LanHost, conn: u32, swung: Option) { + if swung != Some(true) { + return; + } + let (Some(g), Some(play)) = (host.hub.guest(conn), host.play.get(&conn)) else { + return; + }; + if let Some(c) = play.swing.current { + host.hub + .send_to(conn, &swing_packet(g.entity_id, c.hand, c.animation)); + } + } + + /// The tick's arm swings for the players around (the guests' to everyone + /// else, the host's to the guests), and `LivingEntity.updateSwingTime` + /// for the guests' bodies here. pub(super) fn lan_swings(&mut self, host: &mut LanHost) { let conns: Vec = host.play.keys().copied().collect(); for conn in conns { 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 (id, at, here) = (g.entity_id, g.position, host.hub.here(g)); let play = host.play.get_mut(&conn).expect("play"); - let swinging = play.swing.swinging() && play.swing.ticks == 0; - if swinging && !play.swung { - host.hub.swing(id, 0, at, Some(conn)); + let swung = std::mem::take(&mut play.swings) > 0; + if let (true, true, Some(c)) = (swung, here, play.swing.current) { + let packet = swing_packet(id, c.hand, c.animation); + host.hub.broadcast_near(at, 128.0, &packet, Some(conn)); + if let Some(m) = host.models.get_mut(&conn) { + m.swing(); + } + } + play.swing.tick(); + } + if self.swings_started != host.host_swings { + host.host_swings = self.swings_started; + if let (Some(p), Some(c)) = (self.player.as_ref(), self.swing.current) { + let at = [p.position.x, p.position.y, p.position.z]; + let packet = swing_packet(host.host_entity, c.hand, c.animation); + host.hub.broadcast_near(at, 128.0, &packet, None); } - play.swung = swinging; } } } + +/// ClientboundSwingAnimationPacket: the hand and the animation (its type and +/// base duration; each client applies the swinger's haste and fatigue). +fn swing_packet(id: i32, hand: Hand, animation: SwingAnimation) -> C { + C::SwingAnimation(play::SwingAnimation { + id, + hand: i32::from(hand == Hand::Off), + kind: i32::from(animation.kind), + duration: animation.duration, + }) +} diff --git a/crates/horizon-client/src/game/lan_attributes.rs b/crates/horizon-client/src/game/lan_attributes.rs new file mode 100644 index 000000000..72d06c2ef --- /dev/null +++ b/crates/horizon-client/src/game/lan_attributes.rs @@ -0,0 +1,274 @@ +//! The attribute instances a server syncs for the living entities it tracks +//! (`ClientboundUpdateAttributesPacket`, lan/attributes.rs): the ones +//! vanilla's `AttributeMap` would have created by then, since only those are +//! sent, never the type's other defaults. +use super::Game; +use super::commands::Target; +use horizon_client::{ + effects, + lan::attributes::{add_modifier, generic_syncable, instance, operation_named}, + mobs::{ + Mob, + finalize::{self, Attr, Op}, + }, +}; +use horizon_protocol::packets::play::{AttributeModifier, AttributeSnapshot}; +use std::sync::Arc; + +/// `EquipmentSlotGroup.test`: whether a modifier's slot group covers a slot. +fn slot_in_group(group: &str, slot: &str) -> bool { + group == slot + || group == "any" + || (group == "hand" && matches!(slot, "mainhand" | "offhand")) + || (group == "armor" && matches!(slot, "feet" | "legs" | "chest" | "head" | "body")) +} + +impl Game<'_> { + /// The registry id of a client-syncable attribute the entity type has + /// (`AttributeMap.getInstance` is null for the others), by name. + fn synced_attribute(&self, entity: &str, name: &str) -> Option { + let catalog = &self.motion.attributes; + let id = catalog.id(name)?; + (catalog.attribute(id).syncable && catalog.default_base(entity, id).is_some()) + .then(|| id.registry_id()) + } + + /// The type's base value of an attribute, as the instance starts. + fn attribute_default(&self, entity: &str, name: &str) -> f64 { + let catalog = &self.motion.attributes; + catalog + .id(name) + .and_then(|id| catalog.default_base(entity, id)) + .unwrap_or(0.0) + } + + /// `LivingEntity.collectEquipmentChanges`: each worn or held item's + /// attribute modifiers, slot by slot in `EquipmentSlot` order, create + /// their instances (an instance without a modifier keeps its base). + fn equipment_attributes<'a>( + &self, + entity: &str, + base: impl Fn(&str) -> Option, + slots: impl IntoIterator>)>, + out: &mut Vec, + ) { + for (slot, item) in slots { + let Some(info) = item.and_then(|i| self.res.items().get(i)) else { + continue; + }; + for (attribute, id, amount, op, group) in &info.modifiers { + if !slot_in_group(group, slot) { + continue; + } + let Some(a) = self.synced_attribute(entity, attribute) else { + continue; + }; + let start = + base(attribute).unwrap_or_else(|| self.attribute_default(entity, attribute)); + add_modifier( + out, + a, + start, + AttributeModifier { + id: id.clone(), + amount: *amount, + operation: operation_named(op), + }, + ); + } + } + } + + /// A mob's synced instances: movement speed (its first `aiStep` reads it, + /// `LivingEntity.removeFrost`), what finalizeSpawn set, the baby speed + /// modifier, its effects' modifiers, its equipment's, and what + /// `/attribute` changed. + pub(super) fn mob_attributes(&self, m: &Mob) -> Vec { + let kind = m.kind.id.as_str(); + let mut out = Vec::new(); + if let Some(a) = self.synced_attribute(kind, "minecraft:movement_speed") { + instance(&mut out, a, finalize::base_value(m, Attr::MovementSpeed)); + } + if let Some(s) = m.extra.attributes.as_deref() { + for (attr, v) in &s.bases { + if let Some(a) = self.synced_attribute(kind, &format!("minecraft:{}", attr.name())) + { + instance(&mut out, a, *v).base = *v; + } + } + for x in &s.modifiers { + if let Some(a) = + self.synced_attribute(kind, &format!("minecraft:{}", x.attr.name())) + { + add_modifier( + &mut out, + a, + finalize::base_value(m, x.attr), + AttributeModifier { + id: x.id.to_owned(), + amount: x.amount, + operation: match x.op { + Op::AddValue => 0, + Op::AddMultipliedBase => 1, + Op::AddMultipliedTotal => 2, + }, + }, + ); + } + } + } + if let (Some(a), Some((amount, Op::AddMultipliedBase))) = ( + self.synced_attribute(kind, "minecraft:movement_speed"), + finalize::transient(m, Attr::MovementSpeed), + ) { + add_modifier( + &mut out, + a, + finalize::base_value(m, Attr::MovementSpeed), + AttributeModifier { + id: "minecraft:baby".into(), + amount, + operation: 1, + }, + ); + } + let base = |name: &str| { + Attr::ALL + .into_iter() + .find(|a| name.strip_prefix("minecraft:") == Some(a.name())) + .map(|a| finalize::base_value(m, a)) + }; + // LivingEntity.onEffectAdded: MobEffect.addAttributeModifiers. + for &(effect, _, amplifier) in &m.extra.effects { + let Some((attribute, id, amount, op)) = + effects::effect_modifier(effect.trim_start_matches("minecraft:")) + else { + continue; + }; + let Some(a) = self.synced_attribute(kind, attribute) else { + continue; + }; + let start = base(attribute).unwrap_or_else(|| self.attribute_default(kind, attribute)); + add_modifier( + &mut out, + a, + start, + AttributeModifier { + id: id.to_owned(), + amount: amount * f64::from(amplifier + 1), + operation: operation_named(op), + }, + ); + } + let e = &m.extra; + self.equipment_attributes( + kind, + base, + [ + ("mainhand", e.main_hand.as_ref()), + ("offhand", e.off_hand.as_ref()), + ("feet", e.feet.as_ref()), + ("legs", e.legs.as_ref()), + ("chest", e.chest.as_ref()), + ("head", e.head.as_ref()), + ], + &mut out, + ); + self.generic_attributes_of(Target::Mob(m.id), &mut out); + out + } + + /// An armor stand's synced instances: movement speed (its first + /// `aiStep`), its equipment's modifiers and what `/attribute` changed. + pub(super) fn stand_attributes( + &self, + id: u32, + equipment: &[Option; 6], + ) -> Vec { + const KIND: &str = "minecraft:armor_stand"; + let mut out = Vec::new(); + if let Some(a) = self.synced_attribute(KIND, "minecraft:movement_speed") { + instance( + &mut out, + a, + self.attribute_default(KIND, "minecraft:movement_speed"), + ); + } + let slots = horizon_client::entities::ArmorStand::SLOTS + .into_iter() + .zip(equipment.iter().map(|s| s.as_ref().map(|s| &s.item))); + self.equipment_attributes(KIND, |_| None, slots, &mut out); + self.generic_attributes_of(Target::Stand(id), &mut out); + out + } + + /// The instances a server player's tick creates, and + /// `ServerPlayer.updatePlayerAttributes`: a creative player reaches 0.5 + /// further to blocks and 2 to entities. Its client reads the reach from + /// these synced modifiers. (The crouching player's waypoint range is + /// server-side only: lan_waypoints.rs hides it.) + pub(super) fn update_player_attributes(&mut self) { + let creative = self.mode_id() == 1; + let Some(p) = self.player.as_mut() else { + return; + }; + // LivingEntity.aiStep's removeFrost reads the movement speed instance + // every tick, which creates it (and its first sync). + if let Some(key) = p.attributes.key("minecraft:movement_speed") { + let _ = p.attributes.get_instance(Some(key)); + } + for (attribute, id, amount) in [ + ( + "minecraft:block_interaction_range", + "minecraft:creative_mode_block_range", + 0.5, + ), + ( + "minecraft:entity_interaction_range", + "minecraft:creative_mode_entity_range", + 2.0, + ), + ] { + let Some(key) = p.attributes.key(attribute) else { + continue; + }; + // getAttribute creates the instance, a creative player's or not. + if !matches!(p.attributes.get_instance(Some(key.clone())), Ok(Some(_))) { + continue; + } + // addOrUpdateTransientModifier with the same modifier and + // removeModifier of a missing one leave the instance clean. + let has = p.attributes.has_modifier(Some(key), id).unwrap_or(false); + if has != creative { + let _ = p.set_modifier(attribute, id, amount, "add_value", creative); + } + } + } + + /// The instances `/attribute` created in an entity's generic map + /// replace the ones derived from its state. + fn generic_attributes_of(&self, t: Target, out: &mut Vec) { + let Some(map) = self.cmds.attributes.get(&t) else { + return; + }; + for s in generic_syncable(map) { + let (attribute, base) = (s.attribute, s.base); + *instance(out, attribute, base) = s; + } + } +} + +#[cfg(test)] +mod tests { + use super::slot_in_group; + + #[test] + fn slot_groups_cover_their_slots() { + assert!(slot_in_group("head", "head")); + assert!(slot_in_group("armor", "chest")); + assert!(!slot_in_group("armor", "mainhand")); + assert!(slot_in_group("hand", "offhand")); + assert!(slot_in_group("any", "feet")); + assert!(!slot_in_group("mainhand", "offhand")); + } +} diff --git a/crates/horizon-client/src/game/lan_chat.rs b/crates/horizon-client/src/game/lan_chat.rs new file mode 100644 index 000000000..f678480ab --- /dev/null +++ b/crates/horizon-client/src/game/lan_chat.rs @@ -0,0 +1,194 @@ +//! A guest's commands that carry chat: the unsigned and signed command +//! packets (ServerGamePacketListenerImpl.handleChatCommand and +//! handleSignedChatCommand), and the message commands whose text they sign +//! (SayCommand, EmoteCommands, MsgCommand), relayed by the hub as chat. +use super::{Game, lan::LanHost}; +use horizon_client::{ + command::{Arg, ArgType, NodeKind, ParseResults, vanilla}, + lan::{ + data::component_nbt, + hub::{HostEvent, chat::ChatMessage}, + }, + text::{self, Text}, +}; +use horizon_protocol::packets::play::{self, Clientbound as C}; + +/// The signing context of a command: each message argument as the chain +/// let it through, by argument name (CommandSigningContext.SignedArguments). +type Signed = Vec<(String, ChatMessage)>; + +impl Game<'_> { + /// CommandDispatcher.parse with the guest's permission level. + fn parse_as(&mut self, permission: u8, command: &str) -> ParseResults { + let level = std::mem::replace(&mut self.ui.registries.permission, permission); + let parse = vanilla::game_dispatcher().parse(command, &self.ui.registries); + self.ui.registries.permission = level; + parse + } + + /// SignableCommand.of: the command's message arguments, by name, with + /// their text, not past a redirect to the root (`execute ... run`). + fn signable_arguments(&mut self, permission: u8, command: &str) -> Vec<(String, String)> { + let parse = self.parse_as(permission, command); + let nodes = &vanilla::game_dispatcher().nodes; + let root = parse.context.root; + let mut out = Vec::new(); + let mut context = Some(&parse.context); + while let Some(c) = context { + for &(node, (start, end)) in &c.nodes { + if let NodeKind::Argument { + ty: ArgType::Message, + name, + } = &nodes[node].kind + && let Some(text) = command.get(start..end) + { + out.push((name.clone(), text.to_owned())); + } + } + context = c.child.as_deref().filter(|child| child.root != root); + } + out + } + + /// handleChatCommand (performUnsignedChatCommand): refused when the + /// server enforces secure chat and the command has a message to sign. + pub(super) fn guest_chat_command(&mut self, host: &mut LanHost, conn: u32, command: &str) { + let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return; + }; + if !host.hub.try_handle_chat(i, command, true) { + return; + } + let permission = host.hub.guests[i].permission; + if host.hub.enforces_secure_chat() + && !self.signable_arguments(permission, command).is_empty() + { + let name = host.hub.guests[i].name.clone(); + self.lan_log_event(HostEvent::Error(format!( + "Received unsigned command packet from {name}, but the command requires signable arguments: {command}" + ))); + let failure = Text::translate("chat.disabled.invalid_command_signature", &[]) + .with_color(text::RED); + host.hub.guests[i].send(&C::SystemChat(play::SystemChat { + content: component_nbt(&failure.component()), + overlay: false, + })); + return; + } + self.guest_command(host, conn, command, None); + } + + /// handleSignedChatCommand: the acknowledgements, then each message + /// argument through the sender's chain, then the command with them. + pub(super) fn guest_signed_command( + &mut self, + host: &mut LanHost, + conn: u32, + p: play::ChatCommandSigned, + ) { + let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return; + }; + let mut events = Vec::new(); + let mut signed = None; + if let Some(last_seen) = host.hub.apply_last_seen(i, &p.last_seen, &mut events) + && host.hub.try_handle_chat(i, &p.command, true) + { + let permission = host.hub.guests[i].permission; + let parsed = self.signable_arguments(permission, &p.command); + match host + .hub + .signed_arguments(i, &p, &parsed, &last_seen, &mut events) + { + Ok(arguments) => signed = Some(arguments), + Err(e) => host.hub.decode_failure(i, e, &mut events), + } + } + for event in events { + self.lan_log_event(event); + } + if let Some(signed) = signed { + self.guest_command(host, conn, &p.command, Some(signed)); + } + } + + /// SayCommand, EmoteCommands and MsgCommand for a guest: chat to the + /// players, signed when the guest signed it (a disguised chat after an + /// unsigned command packet). False when the command is another one, or + /// one this can't run (selectors other than `@s` and `@a`), for the + /// game's dispatcher to handle. + pub(super) fn guest_message_command( + &mut self, + host: &mut LanHost, + conn: u32, + command: &str, + signed: Option<&Signed>, + ) -> bool { + let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return false; + }; + let parse = self.parse_as(host.hub.guests[i].permission, command); + let Ok((context, id)) = parse.executable() else { + return false; + }; + let argument = if id == "me" { "action" } else { "message" }; + let (Some(Arg::Str(text)), true) = + (context.get(argument), matches!(id, "say" | "me" | "msg")) + else { + return false; + }; + let message = signed.and_then(|s| { + s.iter() + .find(|(n, _)| n == argument) + .map(|(_, m)| m.clone()) + }); + let mut events = Vec::new(); + if id == "msg" { + let Some(Arg::Entity(selector)) = context.get("targets") else { + return false; + }; + let raw = context + .args + .iter() + .rev() + .find(|a| a.name == "targets") + .and_then(|a| command.get(a.range.0..a.range.1)); + let guests = &host.hub.guests; + let placed = |k: &usize| guests[*k].placed; + let targets: Vec = match (raw, &selector.player_name, selector.uuid) { + (Some("@s"), ..) => vec![i], + (Some("@a"), ..) => (0..guests.len()).filter(placed).collect(), + (_, Some(name), _) => (0..guests.len()) + .filter(|&k| placed(&k) && guests[k].name.eq_ignore_ascii_case(name)) + .collect(), + (_, None, Some(uuid)) => (0..guests.len()) + .filter(|&k| placed(&k) && guests[k].uuid == uuid) + .collect(), + _ => return false, + }; + if targets.is_empty() { + let failure = Text::empty() + .append(Text::translate("argument.entity.notfound.player", &[])) + .with_color(text::RED); + host.hub.guests[i].send(&C::SystemChat(play::SystemChat { + content: component_nbt(&failure.component()), + overlay: false, + })); + return true; + } + host.hub.whisper(i, &targets, message, text); + } else { + let chat_type = if id == "say" { + "say_command" + } else { + "emote_command" + }; + host.hub + .broadcast_command_chat(i, chat_type, message, text, &mut events); + } + for event in events { + self.lan_log_event(event); + } + true + } +} diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index 1f16a9c74..de26e84aa 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -21,9 +21,10 @@ pub(super) struct GuestCrafting { inventory: Option>, /// The open crafting table: its window, state id and menu. table: Option<(i32, i32, Box)>, - /// The open furnace's window and menu (`AbstractFurnaceMenu`); its slots live in - /// the furnace block entity and the hub's container menu keeps the client in sync. - furnace: Option<(i32, Box)>, + /// The open furnace's or brewing stand's window and menu (`AbstractFurnaceMenu`, + /// `BrewingStandMenu`); its slots live in the block entity and the hub's + /// container menu keeps the client in sync. + machine: Option<(i32, Box)>, } /// ServerboundContainerClickPacket's input. @@ -84,10 +85,10 @@ fn place_back(menu: &mut Menu, env: &Env, stacks: Vec) { impl Game<'_> { fn menu_env(&self) -> Env<'_> { Env { - items: &self.res.items, - recipes: &self.res.recipes, - brewing: &self.res.stations.brewing, - banners: &self.res.stations.banners, + items: self.res.items(), + recipes: self.res.recipes(), + brewing: &self.res.stations().brewing, + banners: &self.res.stations().banners, trade: None, } } @@ -157,10 +158,11 @@ impl Game<'_> { true } - /// A click on the guest's open furnace, blast furnace or smoker: the host's - /// `AbstractFurnaceMenu` (fuel slot, take-only result, quick moves by recipe and - /// fuel) over the block entity's slots. False for other windows. - pub(super) fn lan_furnace_click( + /// A click on the guest's open furnace, blast furnace, smoker or brewing stand: + /// the host's `AbstractFurnaceMenu` (fuel slot, take-only result, quick moves by + /// recipe and fuel) or `BrewingStandMenu` (one bottle per slot, ingredient and + /// blaze powder slots) over the block entity's slots. False for other windows. + pub(super) fn lan_machine_click( &mut self, host: &mut LanHost, conn: u32, @@ -180,15 +182,18 @@ impl Game<'_> { else { return false; }; - let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get(&pos) else { - return false; + let (kind, items) = match self.world.block_entities.get(&pos) { + Some(BlockEntity::Furnace(f)) => { + let recipe = match f.kind.recipe_type() { + "minecraft:blasting" => "blasting", + "minecraft:smoking" => "smoking", + _ => "smelting", + }; + (Kind::Furnace(recipe), f.items.to_vec()) + } + Some(BlockEntity::Brewing(b)) => (Kind::Brewing, b.items.to_vec()), + _ => return false, }; - let recipe = match f.kind.recipe_type() { - "minecraft:blasting" => "blasting", - "minecraft:smoking" => "smoking", - _ => "smelting", - }; - let items = f.items.clone(); if host.hub.guests[gi].spectator() { return true; } @@ -197,10 +202,10 @@ impl Game<'_> { .entry(conn) .or_default() .crafting - .furnace + .machine .take() .filter(|(window, _)| *window == p.container) - .map_or_else(|| Box::new(Menu::new(Kind::Furnace(recipe))), |(_, m)| m); + .map_or_else(|| Box::new(Menu::new(kind)), |(_, m)| m); let changed = self.guest_menu_op(host, gi, &mut menu, |menu, env| { for (k, s) in items.iter().enumerate() { menu.set_slot(env, k, s.clone()); @@ -213,14 +218,23 @@ impl Game<'_> { .filter(|&s| menu.slot(s) != before[s].as_ref()) .collect::>() }); - if let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get_mut(&pos) { - for k in 0..3 { - f.items[k] = menu.slot(k).cloned(); + match self.world.block_entities.get_mut(&pos) { + Some(BlockEntity::Furnace(f)) => { + for k in 0..3 { + f.items[k] = menu.slot(k).cloned(); + } + // AbstractFurnaceBlockEntity.setItem: only a new input restarts cooking. + f.input_clicked(self.res.recipes(), items[0].clone()); } - // AbstractFurnaceBlockEntity.setItem: only a new input restarts cooking. - f.input_clicked(&self.res.recipes, items[0].clone()); + // BrewingStandBlockEntity.serverTick notices a new ingredient itself. + Some(BlockEntity::Brewing(b)) => { + for k in 0..5 { + b.items[k] = menu.slot(k).cloned(); + } + } + _ => {} } - host.play.entry(conn).or_default().crafting.furnace = Some((p.container, menu)); + host.play.entry(conn).or_default().crafting.machine = Some((p.container, menu)); host.hub.inventory_clicked(conn, p, &self.world, &changed); true } @@ -245,7 +259,7 @@ impl Game<'_> { } let Some(id) = self .res - .stations + .stations() .recipe_index .recipe_of_display(p.recipe) .map(str::to_owned) @@ -256,7 +270,7 @@ impl Game<'_> { if !g.recipe_book.knows(&id) || self .res - .recipes + .recipes() .placement(&id) .is_none_or(|placement| placement.impossible()) { diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs new file mode 100644 index 000000000..7a1236e52 --- /dev/null +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -0,0 +1,451 @@ +//! The entities beyond mobs and items that a server tracks to its clients +//! (`ChunkMap.TrackedEntity`, `ServerEntity`): boats, minecarts, armor +//! stands, item frames, paintings and the entities Horizon keeps without +//! simulating them, each as vanilla pairs it (`getAddEntityPacket` and the +//! synched data that differs from the defaults), and who rides what. +use super::Game; +use horizon_client::lan::{ + entity::{EntityState, Riding}, + hub::Hub, +}; +use horizon_protocol::entity_data::{Value, serializer}; +use horizon_world::nbt::Tag; + +/// `ArmorStand`'s default poses (head, body, left arm, right arm, left leg, +/// right leg), DATA_HEAD_POSE to DATA_RIGHT_LEG_POSE (entries 16 to 21), +/// under their `Pose` keys. +const STAND_POSES: [(&str, [f32; 3]); 6] = [ + ("Head", [0.0, 0.0, 0.0]), + ("Body", [0.0, 0.0, 0.0]), + ("LeftArm", [-10.0, 0.0, -10.0]), + ("RightArm", [-15.0, 0.0, 10.0]), + ("LeftLeg", [-1.0, 0.0, -1.0]), + ("RightLeg", [1.0, 0.0, 1.0]), +]; + +fn state(id: u32, kind: &str, position: [f64; 3], yaw: f32, on_ground: bool) -> EntityState { + EntityState { + id: id as i32, + uuid: super::lan::entity_uuid(id), + kind: kind.to_owned(), + position, + yaw, + pitch: 0.0, + head_yaw: 0.0, + on_ground, + velocity: [0.0; 3], + data: 0, + meta: Vec::new(), + equipment: Vec::new(), + attributes: Vec::new(), + precise: false, + } +} + +/// `VehicleEntity`'s DATA_ID_HURT, DATA_ID_HURTDIR and DATA_ID_DAMAGE +/// (entries 8 to 10) when they differ from their defaults (0, 1, 0). +fn vehicle_meta(hurt_time: i32, hurt_dir: i32, damage: f32) -> Vec<(u8, i32, Value)> { + let mut meta = Vec::new(); + if hurt_time != 0 { + meta.push((8, serializer::INT, Value::Int(hurt_time))); + } + if hurt_dir != 1 { + meta.push((9, serializer::INT, Value::Int(hurt_dir))); + } + if damage != 0.0 { + meta.push((10, serializer::FLOAT, Value::Float(damage))); + } + meta +} + +/// An armor stand's pose from its compound (`ArmorStandPose`), each part +/// that differs from the default. +fn stand_poses(raw: Option<&Tag>) -> Vec<(u8, i32, Value)> { + let Some(pose) = raw.and_then(|t| t.get("Pose")) else { + return Vec::new(); + }; + let mut meta = Vec::new(); + for (i, (key, default)) in STAND_POSES.iter().enumerate() { + let Some(Tag::List(values)) = pose.get(key) else { + continue; + }; + let mut r = *default; + for (k, v) in values.iter().take(3).enumerate() { + if let Tag::Float(bits) = v { + r[k] = f32::from_bits(*bits); + } + } + if r != *default { + meta.push(( + 16 + i as u8, + serializer::ROTATIONS, + Value::Floats(r.to_vec()), + )); + } + } + meta +} + +impl Game<'_> { + /// Who rides what (`Entity.getPassengers`): mobs on mobs, and the + /// host in its boat or minecart. + pub(super) fn lan_riding(&self, host_entity: Option, riding: &mut Riding) { + riding.clear(); + for m in self.mobs.iter().filter(|m| !m.removed) { + if let Some(vehicle) = m.extra.mount { + riding.add(vehicle as i32, m.id as i32); + } + } + if let (Some(host), Some(vehicle)) = (host_entity, self.riding) { + riding.add(vehicle as i32, host); + } + } + + /// Boats, minecarts, armor stands, item frames, paintings and the + /// entities kept unsimulated, as guests track them. + pub(super) fn lan_object_states( + &self, + host_entity: Option, + hub: &mut Hub, + out: &mut Vec, + ) { + for b in &self.boats { + let p = b.position; + let mut e = state(b.id, &b.entity_type(), [p.x, p.y, p.z], b.yaw, b.on_ground); + e.velocity = [b.velocity.x, b.velocity.y, b.velocity.z]; + e.meta = vehicle_meta(b.hurt_time, b.hurt_dir, b.damage); + // AbstractBoat.DATA_ID_PADDLE_LEFT and DATA_ID_PADDLE_RIGHT. + for (k, paddling) in b.paddling.iter().enumerate() { + if *paddling { + e.meta + .push((11 + k as u8, serializer::BOOLEAN, Value::Bool(true))); + } + } + out.push(e); + } + for c in &self.carts { + let p = c.position; + let mut e = state(c.id, c.kind.id(), [p.x, p.y, p.z], c.yaw, c.on_ground()); + e.velocity = [c.velocity.x, c.velocity.y, c.velocity.z]; + e.meta = vehicle_meta(c.hurt_time, c.hurt_dir, c.damage); + match c.kind { + // MinecartFurnace.DATA_ID_FUEL. + super::minecarts::CartKind::Furnace if c.fuel > 0 => { + e.meta.push((13, serializer::BOOLEAN, Value::Bool(true))); + } + // MinecartCommandBlock.DATA_ID_COMMAND_NAME. + super::minecarts::CartKind::CommandBlock => { + if let Some(Tag::String(command)) = + self.persist.raw.get(&c.id).and_then(|t| t.get("Command")) + { + let command = command.to_string_lossy(); + if !command.is_empty() { + e.meta + .push((13, serializer::STRING, Value::String(command))); + } + } + } + _ => {} + } + out.push(e); + } + for a in &self.armor_stands { + let p = a.position; + let mut e = state( + a.id, + "minecraft:armor_stand", + [p.x, p.y, p.z], + a.yaw, + a.on_ground, + ); + e.head_yaw = a.yaw; + e.velocity = [a.velocity.x, a.velocity.y, a.velocity.z]; + if a.fire_ticks > 0 { + e.meta.push((0, serializer::BYTE, Value::Byte(1))); + } + // LivingEntity.DATA_HEALTH_ID: 1 until the stand's max health is set. + e.meta.push((9, serializer::FLOAT, Value::Float(a.health))); + // ArmorStand.DATA_CLIENT_FLAGS: small 1, arms 4, no base plate 8, marker 16. + let flags = i8::from(a.small) + | i8::from(a.show_arms) << 2 + | i8::from(a.no_base_plate) << 3 + | i8::from(a.marker) << 4; + if flags != 0 { + e.meta.push((15, serializer::BYTE, Value::Byte(flags))); + } + e.meta.extend(stand_poses(self.persist.raw.get(&a.id))); + // Stored main hand, off hand, feet, legs, chest, head: the wire's slots 0 to 5. + for (slot, item) in a.equipment.iter().enumerate() { + if item.is_some() { + e.equipment.push((slot as u8, hub.stack(item))); + } + } + e.attributes = self.stand_attributes(a.id, &a.equipment); + out.push(e); + } + for f in &self.item_frames { + // ItemFrame.getAddEntityPacket: the block it hangs in and its direction. + let mut e = state(f.id, f.kind(), f.pos.map(f64::from), 0.0, false); + e.pitch = match f.facing { + 0 => 90.0, + 1 => -90.0, + _ => 0.0, + }; + e.yaw = match f.facing { + 2 => 180.0, + 4 => 90.0, + 5 => 270.0, + _ => 0.0, + }; + e.data = i32::from(f.facing); + // HangingEntity.DATA_DIRECTION, south by default. + if f.facing != 3 { + e.meta + .push((8, serializer::DIRECTION, Value::Id(i32::from(f.facing)))); + } + if f.item.is_some() { + e.meta + .push((9, serializer::ITEM_STACK, Value::Item(hub.stack(&f.item)))); + } + if f.rotation != 0 { + e.meta + .push((10, serializer::INT, Value::Int(i32::from(f.rotation)))); + } + out.push(e); + } + for p in &self.paintings { + let mut e = state(p.id, "minecraft:painting", p.pos.map(f64::from), 0.0, false); + // Direction.get2DDataValue (south 0, west 1, north 2, east 3) to its + // 3D data value and yaw. + let facing = [3, 4, 2, 5][usize::from(p.facing & 3)]; + e.yaw = f32::from(p.facing & 3) * 90.0; + e.data = facing; + if facing != 3 { + e.meta.push((8, serializer::DIRECTION, Value::Id(facing))); + } + // Painting.DATA_PAINTING_VARIANT_ID, a registry holder (id + 1), + // set unless it is the registry's first variant (VariantUtils.getAny). + if let Some(id) = hub.registry_id("minecraft:painting_variant", &p.variant) + && id != 0 + { + e.meta + .push((9, serializer::PAINTING_VARIANT, Value::Id(id + 1))); + } + out.push(e); + } + self.lan_projectile_states(host_entity, hub, out); + for o in &self.others { + let p = o.position; + let mut e = state(o.id, &o.kind, [p.x, p.y, p.z], o.yaw, false); + e.pitch = o.pitch; + e.head_yaw = o.yaw; + out.push(e); + } + } +} + +impl Game<'_> { + /// Gives the entities Horizon keeps without an id one (`Entity.id`, from + /// the same counter as the rest) before they are first tracked. + pub(super) fn lan_assign_ids(&mut self) { + let next = &mut self.next_entity; + let mut give = |id: &mut u32| { + if *id == 0 { + *next += 1; + *id = *next; + } + }; + self.tnts.iter_mut().for_each(|t| give(&mut t.id)); + self.falling.iter_mut().for_each(|f| give(&mut f.id)); + self.creatures + .projectiles + .iter_mut() + .for_each(|p| give(&mut p.id)); + self.tridents.iter_mut().for_each(|t| give(&mut t.id)); + self.rockets.iter_mut().for_each(|r| give(&mut r.id)); + self.crystals.iter_mut().for_each(|c| give(&mut c.id)); + } + + /// Primed TNT, falling blocks, projectiles, tridents, firework rockets and + /// end crystals, as guests track them. + fn lan_projectile_states( + &self, + host_entity: Option, + hub: &mut Hub, + out: &mut Vec, + ) { + let owner = |who: Option| match who { + Some(horizon_client::mobs::Who::Mob(id)) => id as i32, + Some(horizon_client::mobs::Who::Player) => host_entity.unwrap_or(0), + None => 0, + }; + let at = |p: horizon_core::geometry::Vec3| [p.x, p.y, p.z]; + for t in self.tnts.iter().filter(|t| t.id != 0) { + let mut e = state(t.id, "minecraft:tnt", at(t.position), 0.0, t.on_ground); + e.velocity = at(t.velocity); + // PrimedTnt.DATA_FUSE_ID, 80 by default; requiresPrecisePosition + // while it touches a block. + if t.fuse != 80 { + e.meta.push((8, serializer::INT, Value::Int(t.fuse))); + } + e.precise = t.on_ground; + out.push(e); + } + for f in self.falling.iter().filter(|f| f.id != 0) { + let mut e = state(f.id, "minecraft:falling_block", at(f.position), 0.0, false); + e.velocity = at(f.velocity); + // getAddEntityPacket: the block state; DATA_START_POS. + e.data = f.state.0 as i32; + if f.no_gravity { + e.meta.push((5, serializer::BOOLEAN, Value::Bool(true))); + } + let start = [f.start_pos.x, f.start_pos.y, f.start_pos.z]; + if start != [0; 3] { + e.meta.push((8, serializer::BLOCK_POS, Value::Pos(start))); + } + out.push(e); + } + for p in self.creatures.projectiles.iter().filter(|p| p.id != 0) { + use horizon_client::projectiles::ProjectileKind as K; + let kind = match &p.kind { + K::Arrow { .. } => "minecraft:arrow", + K::Snowball => "minecraft:snowball", + K::Egg => "minecraft:egg", + K::EnderPearl => "minecraft:ender_pearl", + K::SmallFireball => "minecraft:small_fireball", + K::LargeFireball { .. } => "minecraft:fireball", + K::LlamaSpit => "minecraft:llama_spit", + K::WindCharge => "minecraft:wind_charge", + K::BreezeWindCharge => "minecraft:breeze_wind_charge", + K::ShulkerBullet { .. } => "minecraft:shulker_bullet", + K::WitherSkull { .. } => "minecraft:wither_skull", + K::Potion { .. } => "minecraft:splash_potion", + }; + let mut e = state(p.id, kind, at(p.position), p.yaw, false); + e.pitch = p.pitch; + e.velocity = at(p.velocity); + e.data = owner(p.owner); + match &p.kind { + K::Arrow { critical, .. } => { + let a = p.arrow.as_deref(); + e.meta.extend(arrow_meta( + *critical, + a.is_some_and(|a| a.no_physics), + a.map_or(0, |a| a.pierce), + a.is_some_and(|a| a.in_ground) || p.stuck, + )); + } + // WitherSkull.DATA_DANGEROUS. + K::WitherSkull { dangerous: true } => { + e.meta.push((8, serializer::BOOLEAN, Value::Bool(true))); + } + _ => {} + } + out.push(e); + } + for t in self.tridents.iter().filter(|t| t.id != 0) { + let mut e = state(t.id, "minecraft:trident", at(t.position), t.yaw, false); + e.pitch = t.pitch; + e.velocity = at(t.velocity); + e.meta = arrow_meta(false, t.no_physics, 0, t.in_ground); + // ThrownTrident.ID_LOYALTY and ID_FOIL. + if t.loyalty != 0 { + e.meta + .push((11, serializer::BYTE, Value::Byte(t.loyalty as i8))); + } + if t.stack.has_any_enchantments() { + e.meta.push((12, serializer::BOOLEAN, Value::Bool(true))); + } + out.push(e); + } + for r in self.rockets.iter().filter(|r| r.id != 0) { + let mut e = state( + r.id, + "minecraft:firework_rocket", + at(r.position), + 0.0, + false, + ); + e.velocity = at(r.velocity); + // DATA_ID_FIREWORKS_ITEM once set from a stack, DATA_ATTACHED_TO_TARGET, + // DATA_SHOT_AT_ANGLE. + let plain = &*r.item.item == "minecraft:firework_rocket" + && r.item.count == 1 + && r.item.extra.is_none(); + if !plain { + e.meta.push(( + 8, + serializer::ITEM_STACK, + Value::Item(hub.stack(&Some(r.item.clone()))), + )); + } + if r.attached + && let Some(host) = host_entity + { + e.meta + .push((9, serializer::OPTIONAL_UNSIGNED_INT, Value::Id(host + 1))); + } + if r.angled { + e.meta.push((10, serializer::BOOLEAN, Value::Bool(true))); + } + out.push(e); + } + for c in self.crystals.iter().filter(|c| c.id != 0) { + let mut e = state(c.id, "minecraft:end_crystal", at(c.position), 0.0, false); + // EndCrystal.DATA_BEAM_TARGET and DATA_SHOW_BOTTOM (true by default). + if c.beam.is_some() { + e.meta + .push((8, serializer::OPTIONAL_BLOCK_POS, Value::OptPos(c.beam))); + } + if !c.show_bottom { + e.meta.push((9, serializer::BOOLEAN, Value::Bool(false))); + } + out.push(e); + } + } +} + +/// `AbstractArrow`'s ID_FLAGS (critical 1, no physics 2), PIERCE_LEVEL and +/// IN_GROUND, when they differ from the defaults. +fn arrow_meta( + critical: bool, + no_physics: bool, + pierce: u8, + in_ground: bool, +) -> Vec<(u8, i32, Value)> { + let mut meta = Vec::new(); + let flags = i8::from(critical) | i8::from(no_physics) << 1; + if flags != 0 { + meta.push((8, serializer::BYTE, Value::Byte(flags))); + } + if pierce != 0 { + meta.push((9, serializer::BYTE, Value::Byte(pierce as i8))); + } + if in_ground { + meta.push((10, serializer::BOOLEAN, Value::Bool(true))); + } + meta +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn armor_stand_poses_send_only_what_differs() { + let tag = + horizon_world::nbt::parse_snbt("{Pose:{Head:[10f,20f,0f],LeftArm:[-10f,0f,-10f]}}") + .unwrap() + .0; + let meta = stand_poses(Some(&tag)); + assert_eq!( + meta, + vec![( + 16, + serializer::ROTATIONS, + Value::Floats(vec![10.0, 20.0, 0.0]) + )] + ); + assert!(stand_poses(None).is_empty()); + } +} diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 53b79407c..0ee991737 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -107,6 +107,7 @@ impl Game<'_> { v.velocity = Vec3::new(moved[0], moved[1], moved[2]); v.uuid = horizon_client::lan::playerdata::uuid_ints(uuid); v.allies = Default::default(); + v.remote = true; views.push((conn, v)); } } @@ -130,6 +131,26 @@ impl Game<'_> { self.lan = Some(host); } + /// The guests' boxes for the blocks entities trigger (pressure plates, + /// tripwires, detector rails): `Entity.checkInsideBlocks` and + /// `Level.getEntities` see every player in the level, but not spectators + /// (`Entity.isIgnoringBlockTriggers`). + pub(super) fn lan_block_trigger_boxes(&self) -> Vec<([f64; 3], [f64; 3])> { + let Some(host) = self.lan.as_ref() else { + return Vec::new(); + }; + host.hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator()) + .map(|g| { + let [x, y, z] = g.position; + let height = if g.sneaking { 1.5 } else { 1.8 }; + ([x - 0.3, y, z - 0.3], [x + 0.3, y + height, z + 0.3]) + }) + .collect() + } + /// The guests a projectile can hit, under their entity ids. pub(super) fn lan_projectile_targets(&self) -> Vec<(Who, Aabb)> { let Some(host) = self.lan.as_ref() else { @@ -274,6 +295,7 @@ mod tests { hero: false, uuid: [0; 4], allies: Default::default(), + remote: false, } } diff --git a/crates/horizon-client/src/game/lan_screen.rs b/crates/horizon-client/src/game/lan_screen.rs index 6be6fc7fa..335b5fbae 100644 --- a/crates/horizon-client/src/game/lan_screen.rs +++ b/crates/horizon-client/src/game/lan_screen.rs @@ -596,11 +596,11 @@ impl Game<'_> { View::Restrictions => self.draw_restrictions(batch), View::GameRules => { if let Some(rules) = o.rules.as_mut() { - rules.draw(batch, &self.atlas, self.cursor); + rules.draw(batch, &self.gui.atlas, self.cursor); } else { ui::menu_background( batch, - &self.atlas, + &self.gui.atlas, 0.0, 0.0, batch.width, @@ -614,7 +614,7 @@ impl Game<'_> { } fn draw_lock_question(&self, o: &WorldOptions, batch: &mut HudBatch) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); // Screen.extractTransparentBackground. batch.fill_gradient( @@ -656,7 +656,7 @@ impl Game<'_> { } fn draw_restrictions(&self, batch: &mut HudBatch) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); let title = Text::translate("restrictions_screen.title", &[]); @@ -687,7 +687,7 @@ impl Game<'_> { } fn draw_options_view(&self, o: &mut WorldOptions, batch: &mut HudBatch, cursor: (f32, f32)) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); o.scroll = o.scroll.clamp(0.0, o.scroll_limit(h)); // extractMenuBackground: the in-world background, the list @@ -810,7 +810,7 @@ impl Game<'_> { match o.view { View::Options => {} View::GameRules => { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let exit = o.rules.as_mut().and_then(|rules| { if rules.clicks_button(atlas, self.cursor, (w, h)) { self.audio.play_button_click(); @@ -824,7 +824,7 @@ impl Game<'_> { return; } View::LockQuestion => { - let p = Popup::lock_question(&self.atlas.font, o.difficulty, (w, h)); + let p = Popup::lock_question(&self.gui.atlas.font, o.difficulty, (w, h)); let hit = p .buttons .iter() @@ -842,7 +842,8 @@ impl Game<'_> { return; } View::Restrictions => { - let r = Restrictions::new(&self.atlas.font, self.settings.chat_visibility, (w, h)); + let r = + Restrictions::new(&self.gui.atlas.font, self.settings.chat_visibility, (w, h)); let in_body = self.cursor.1 >= r.area.0 && self.cursor.1 < r.area.1; let action = r.action.is_some_and(|(ax, ay)| { in_body && ui::hovered(self.cursor, ax, ay, 200.0, 20.0) diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index ee6b55d16..c7f8a94a6 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -133,7 +133,7 @@ impl Game<'_> { if let Some(name) = &state.name { return name.clone(); } - let e = &self.res.stations.enchantments; + let e = &self.res.stations().enchantments; let profession = state.session.profession.trim_start_matches("minecraft:"); if state.session.villager { e.translate(&format!("entity.minecraft.villager.{profession}")) @@ -245,15 +245,15 @@ impl Game<'_> { next_id: std::cell::Cell::new(next_map), }; let trade_env = merchant::TradeEnv { - trades: &self.res.stations.trades, - enchantments: &self.res.stations.enchantments, + trades: &self.res.stations().trades, + enchantments: &self.res.stations().enchantments, maps: Some(&maps), }; let env = Env { - items: &self.res.items, - recipes: &self.res.recipes, - brewing: &self.res.stations.brewing, - banners: &self.res.stations.banners, + items: self.res.items(), + recipes: self.res.recipes(), + brewing: &self.res.stations().brewing, + banners: &self.res.stations().banners, trade: Some(&trade_env), }; let mut menu = Menu::new(Kind::Merchant); diff --git a/crates/horizon-client/src/game/leads.rs b/crates/horizon-client/src/game/leads.rs index 3b8fc29c4..ae5d87fff 100644 --- a/crates/horizon-client/src/game/leads.rs +++ b/crates/horizon-client/src/game/leads.rs @@ -220,11 +220,11 @@ impl Game<'_> { }; let name = self .res - .facts + .facts() .get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2])); if !self .res - .items + .items() .block_tags .get("minecraft:fences") .is_some_and(|s| s.contains(&*name.name)) @@ -283,7 +283,7 @@ impl Game<'_> { } /// `LeashFeatureRenderer` for every lead and `LeashKnotRenderer` for the knots. pub(super) fn leash_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let white = atlas.font.white(); let uv = [ [white.u0, white.v1], diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index 4516ce7dd..47d06254d 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -1,6 +1,7 @@ //! Level events whose client handler (`LevelEventHandler`) spawns particles -//! on a block: dragon egg teleportation (2015), electric sparks (3002), -//! waxing (3003), wax off (3004) and scraping (3005). +//! on a block: dragon egg teleportation (2015), a consumable's teleport +//! (2017), electric sparks (3002), waxing (3003), wax off (3004) and +//! scraping (3005). use super::Game; use horizon_client::particles::{self, ParticleOptions, ParticleType}; use horizon_core::position::BlockPos; @@ -9,7 +10,12 @@ use horizon_world::level::LevelEvent; impl Game<'_> { pub(super) fn dragon_egg_particles(&mut self, pos: [i32; 3], data: i32) { self.particles - .block_teleportation(pos, data, self.settings.particles); + .block_teleportation(pos, data, [16, 8, 16], self.settings.particles); + } + /// Event 2017: `TeleportRandomlyConsumeEffect`'s directional particles. + pub(super) fn consume_teleport_particles(&mut self, pos: [i32; 3], data: i32) { + self.particles + .block_teleportation(pos, data, [127, 127, 127], self.settings.particles); } /// `LevelEventHandler.levelEvent` 3002 to 3005, drawing from the client /// level's random. diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index 3a84e2f78..3225408f5 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -20,10 +20,11 @@ use super::{ }; use horizon_client::{ Result, block_entity_anim::BlockEntityAnims, random_tick_sections::RandomTickSections, - save::SaveDir, streaming::Streaming, tick_chunk_membership::TickChunkMembership, world::World, + save::SaveDir, streaming::Streaming, tick_chunk_membership::TickChunkMembership, + ticket_levels::ChunkTickets, world::World, }; use horizon_world::level::{LevelEvent, Ticks}; -use std::{collections::HashMap, sync::Arc}; +use std::{collections::HashMap, sync::Arc, time::Instant}; /// 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 @@ -37,6 +38,7 @@ pub(super) struct Parked { save: Arc, block_ticks: Ticks, tick_chunks: TickChunkMembership, + tickets: ChunkTickets, random_tick_sections: RandomTickSections, level_events: Vec, falling: Vec, @@ -105,7 +107,7 @@ impl Game<'_> { 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); + let mut world = World::new(self.res.facts().air, self.level.seed); world.fast_lava = dim == Dim::Nether; Ok(Parked { world, @@ -113,6 +115,7 @@ impl Game<'_> { save, block_ticks: Ticks::new(self.level.seed as i32), tick_chunks: Default::default(), + tickets: Default::default(), random_tick_sections: Default::default(), level_events: Vec::new(), falling: Vec::new(), @@ -159,6 +162,7 @@ impl Game<'_> { 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.tickets, &mut p.tickets); 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); @@ -287,6 +291,37 @@ impl Game<'_> { self.close_idle_levels() } + /// `tick_server` as a server thread runs it. With `HORIZON_SPIKES=MS`, a + /// tick longer than MS is logged with its thread CPU time and spans. + pub(super) fn tick_server_timed(&mut self, paused: bool) -> Result<()> { + let Some(threshold) = self.options.spikes else { + return self.tick_server(paused); + }; + let (started, cpu) = (Instant::now(), horizon_client::spans::thread_cpu()); + let result = self.tick_server(paused); + let wall = started.elapsed().as_secs_f32() * 1000.0; + // Taken every tick: nothing else takes this thread's spans. + let spans = horizon_client::spans::take(); + if wall > threshold { + let cpu = horizon_client::spans::thread_cpu() + .zip(cpu) + .map_or_else(String::new, |(end, start)| { + format!(", cpu {:.1} ms", (end - start).as_secs_f32() * 1000.0) + }); + let list: Vec = spans + .iter() + .filter(|(_, ms)| *ms >= 0.5) + .map(|(n, ms)| format!("{n} {ms:.1}")) + .collect(); + log::info!( + "Horizon: slow tick {wall:.1} ms{cpu} ({} mobs): {}", + self.mobs.len(), + list.join(", ") + ); + } + result + } + /// 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. diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 834925c57..7b480a8e6 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -50,7 +50,7 @@ impl Game<'_> { let difficulty = f64::from(self.ui.difficulty) * 0.75; let below = &self .res - .facts + .facts() .get(self.world.block(pos[0], pos[1] - 1, pos[2])) .name; let trap = self.ui.rules.bool("spawn_mobs") @@ -160,11 +160,11 @@ impl Game<'_> { } for p in spots { let state = self.world.block(p[0], p[1], p[2]); - if !self.res.facts.is_air(state) { + if !self.res.facts().is_air(state) { continue; } // BaseFireBlock.getState: soul fire on soul soil and sand. - let below = self.res.facts.get(self.world.block(p[0], p[1] - 1, p[2])); + let below = self.res.facts().get(self.world.block(p[0], p[1] - 1, p[2])); let name = if matches!(&*below.name, "minecraft:soul_soil" | "minecraft:soul_sand") { "minecraft:soul_fire" } else { @@ -236,7 +236,7 @@ impl Game<'_> { at[2].floor() as i32, ]; let state = self.world.block(p[0], p[1], p[2]); - if !self.res.facts.get(state).name.ends_with("lightning_rod") { + if !self.res.facts().get(state).name.ends_with("lightning_rod") { return; } let registry = self.pack.assets.registry; @@ -348,7 +348,7 @@ impl Game<'_> { /// `LightningBoltRenderer`: 4 layers of a trunk and two branches, 8 /// segments of 16 blocks, from the bolt's seed. pub(super) fn bolt_geometry(&self, camera: glam::DVec3, out: &mut Vec) { - let white = self.atlas.font.white(); + let white = self.gui.atlas.font.white(); let uv = [white.u0, white.v0]; // ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA. let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114; diff --git a/crates/horizon-client/src/game/loom.rs b/crates/horizon-client/src/game/loom.rs index 541e4e6a9..f1ff1a300 100644 --- a/crates/horizon-client/src/game/loom.rs +++ b/crates/horizon-client/src/game/loom.rs @@ -192,14 +192,14 @@ impl Game<'_> { base: &str, layers: &[BannerLayer], ) { - let banners = &self.res.stations.banners; + let banners = &self.res.stations().banners; let layers: Vec<(String, String)> = layers .iter() .map(|l| (banners.banner_texture(&l.pattern), l.color.to_string())) .collect(); horizon_client::item_render::gui::draw_banner_result( &self.pack.item_renderer, - &self.atlas.sprites, + &self.gui.atlas.sprites, batch, x, y, @@ -217,7 +217,7 @@ impl Game<'_> { draws: &[ScreenDraw], background: bool, ) -> Option> { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let mut tooltip = None; let mut sheet: Option = None; for d in draws { @@ -317,7 +317,7 @@ impl Game<'_> { let l = &s.loom; let dye = s.inputs[1] .as_ref() - .and_then(|d| self.res.items.get(&d.item)) + .and_then(|d| self.res.items().get(&d.item)) .and_then(|i| i.dye.clone()) .unwrap_or_else(|| "white".to_owned()); let result = s @@ -342,7 +342,7 @@ impl Game<'_> { dye: &dye, mouse: local, }; - let draws = screen_layout::loom(&view, &self.res.stations.banners); + let draws = screen_layout::loom(&view, &self.res.stations().banners); self.paint_screen(batch, ox, oy, &draws, false) } } diff --git a/crates/horizon-client/src/game/mace.rs b/crates/horizon-client/src/game/mace.rs index 062d04525..46091a773 100644 --- a/crates/horizon-client/src/game/mace.rs +++ b/crates/horizon-client/src/game/mace.rs @@ -84,11 +84,11 @@ impl Game<'_> { direct_attacker: Some("minecraft:player"), is_direct: true, damage_type: Some("minecraft:mace_smash"), - items: Some(&self.res.items), + items: Some(self.res.items()), ..Default::default() }; // EnchantmentHelper.modifyFallBasedDamage(..., 0) - let per_block = self.res.stations.enchantments.modify_value( + let per_block = self.res.stations().enchantments.modify_value( held.as_ref(), "minecraft:smash_damage_per_fallen_block", &ctx, @@ -111,10 +111,10 @@ impl Game<'_> { horizon_client::mobs::DamageKind::MaceSmash => "minecraft:mace_smash", _ => "minecraft:player_attack", }), - items: Some(&self.res.items), + items: Some(self.res.items()), ..Default::default() }; - let enchantments = &self.res.stations.enchantments; + let enchantments = &self.res.stations().enchantments; let random = &mut self.world.random; // CombatRules.getDamageAfterAbsorb: EnchantmentHelper.modifyArmorEffectiveness. let mut breach = |fraction: f32| { @@ -143,7 +143,7 @@ impl Game<'_> { }; let weapon = self .res - .items + .items() .get(&stack.item) .and_then(|i| i.weapon_damage.map(|d| (d, i.max_damage))); let smash = self.smash_attack(); diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index a736be2db..c05c7295f 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -361,10 +361,10 @@ impl Game<'_> { fn containers(&self) -> Containers<'_> { Containers { world: &self.world, - behaviours: &self.res.behaviours, - items: &self.res.items, + behaviours: self.res.behaviours(), + items: self.res.items(), registry: self.pack.assets.registry, - brewing: Some(&self.res.stations.brewing), + brewing: Some(&self.res.stations().brewing), bone_meal: bone_meal(), } } @@ -497,42 +497,35 @@ impl Game<'_> { } } } - /// Every hopper's `pushItemsTick`, in a stable position order. - pub(super) fn tick_hoppers(&mut self) -> Result<()> { + /// `HopperBlockEntity.pushItemsTick` of the hopper at `pos`, if its block + /// is still a hopper (`BlockEntityType.isValid`). + pub(super) fn tick_hopper(&mut self, pos: Pos) { let hopper = self - .pack - .assets - .registry - .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 the plain container with five slots - // (`BlockEntity::for_block`; `BlockEntity::id` names it the hopper): - // 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 - .iter() - .filter(|(_, e)| matches!(e, BlockEntity::Chest(items) if items.len() == HOPPER_SLOTS)) - .map(|(p, _)| *p) - .filter(|p| self.res.facts.get(self.world.block(p.0, p.1, p.2)).name == hopper) - .collect(); - positions.sort_unstable(); - self.hoppers - .retain(|p, _| positions.binary_search(p).is_ok()); - let time = self.world.game_time; - for pos in positions { - let state = self.hoppers.entry(pos).or_default(); - state.cooldown -= 1; - state.ticked = time; - if state.cooldown <= 0 { - state.cooldown = 0; - self.hopper_try_move_items(pos); - } + .res + .facts() + .get(self.world.block(pos.0, pos.1, pos.2)) + .name + .as_ref() + == "minecraft:hopper"; + if !hopper { + self.hoppers.remove(&pos); + return; } - Ok(()) + let time = self.world.game_time; + let state = self.hoppers.entry(pos).or_default(); + state.cooldown -= 1; + state.ticked = time; + if state.cooldown <= 0 { + state.cooldown = 0; + self.hopper_try_move_items(pos); + } + } + /// Drops the cooldowns of hoppers whose block entity is gone. + pub(super) fn forget_gone_hoppers(&mut self) { + let entities = &self.world.block_entities; + self.hoppers.retain(|p, _| { + matches!(entities.get(p), Some(BlockEntity::Chest(items)) if items.len() == HOPPER_SLOTS) + }); } /// `HopperBlockEntity.tryMoveItems` with `suckInItems`. pub(super) fn hopper_try_move_items(&mut self, pos: Pos) { @@ -633,12 +626,12 @@ impl Game<'_> { return false; } let above_state = self.world.block(above.0, above.1, above.2); - let blocked = self.res.facts.get(above_state).full_collision + let blocked = self.res.facts().get(above_state).full_collision && !self .res - .behaviours + .behaviours() .tag("minecraft:does_not_block_hoppers") - .is_some_and(|t| t.contains(self.res.behaviours.block(above_state))); + .is_some_and(|t| t.contains(self.res.behaviours().block(above_state))); if blocked { return false; } @@ -685,7 +678,7 @@ impl Game<'_> { /// `DispenserBlock.dispenseFrom` / `DropperBlock.dispenseFrom`. pub(super) fn dispense_from(&mut self, pos: BlockPos, state: BlockStateId) -> Result<()> { let key = (pos.x, pos.y, pos.z); - let name = self.res.facts.get(state).name.clone(); + let name = self.res.facts().get(state).name.clone(); if &*name == "minecraft:crafter" { return self.crafter_dispense(pos, state); } @@ -777,12 +770,20 @@ enum Screen { impl Game<'_> { fn machine_screen(&self) -> Option { let key = self.container?; + // A server's menu shows by its type, whatever block (or minecart) holds it. + if let Some(menu) = self.remote_menu_type() { + return match menu { + "minecraft:hopper" => Some(Screen::Hopper), + "minecraft:generic_3x3" => Some(Screen::Dispenser), + _ => None, + }; + } if key.1 == super::minecarts::CART_KEY_Y { return (self.open_cart_kind() == Some(super::minecarts::CartKind::Hopper)) .then_some(Screen::Hopper); } let state = self.world.block(key.0, key.1, key.2); - match &*self.res.facts.get(state).name { + match &*self.res.facts().get(state).name { "minecraft:hopper" => Some(Screen::Hopper), "minecraft:dispenser" => Some(Screen::Dispenser), "minecraft:dropper" => Some(Screen::Dropper), @@ -839,7 +840,7 @@ impl Game<'_> { let Some(screen) = self.machine_screen() else { return false; }; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let key_is_cart = self .container .is_some_and(|k| k.1 == super::minecarts::CART_KEY_Y); @@ -859,7 +860,9 @@ impl Game<'_> { batch.rect_uv(ox, oy, 176.0, height, r, u32::MAX); } let grey = horizon_client::hud::rgba(64, 64, 64, 255); - let title = &self.container_title(title.to_owned()); + let title = &self + .remote_menu_title() + .unwrap_or_else(|| self.container_title(title.to_owned())); let title_x = if screen == Screen::Hopper { 8.0 } else { diff --git a/crates/horizon-client/src/game/machines/crafter.rs b/crates/horizon-client/src/game/machines/crafter.rs index 11ca70d5d..d87646fe0 100644 --- a/crates/horizon-client/src/game/machines/crafter.rs +++ b/crates/horizon-client/src/game/machines/crafter.rs @@ -56,44 +56,33 @@ impl Game<'_> { _ => None, } } - /// `CrafterBlockEntity.serverTick` for every crafter, and the powered - /// flag following the block state. - pub(in crate::game) fn tick_crafters(&mut self) { - let positions: Vec = self - .world - .block_entities - .iter() - .filter(|(_, e)| matches!(e, BlockEntity::Crafter(_))) - .map(|(p, _)| *p) - .collect(); - let mut positions = positions; - positions.sort_unstable(); - for pos in positions { - let state = self.world.block(pos.0, pos.1, pos.2); - let triggered = self.containers().prop(state, "triggered") == Some("true"); - let mut finished = false; - if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&pos) { - // CrafterBlock.neighborChanged sets the flag with the state; a - // loaded crafter keeps its saved flag until then. - if c.state_triggered.is_some_and(|t| t != triggered) { - c.triggered = triggered; - } - c.state_triggered = Some(triggered); - let remaining = c.crafting_ticks - 1; - if remaining >= 0 { - c.crafting_ticks = remaining; - finished = remaining == 0; - } + /// `CrafterBlockEntity.serverTick` of the crafter at `pos`, and the + /// powered flag following the block state. + pub(in crate::game) fn tick_crafter(&mut self, pos: Pos) { + let state = self.world.block(pos.0, pos.1, pos.2); + let triggered = self.containers().prop(state, "triggered") == Some("true"); + let mut finished = false; + if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&pos) { + // CrafterBlock.neighborChanged sets the flag with the state; a + // loaded crafter keeps its saved flag until then. + if c.state_triggered.is_some_and(|t| t != triggered) { + c.triggered = triggered; } - if finished { - self.set_bool_prop( - pos, - "crafting", - false, - horizon_world::level::flags::UPDATE_ALL, - ); + c.state_triggered = Some(triggered); + let remaining = c.crafting_ticks - 1; + if remaining >= 0 { + c.crafting_ticks = remaining; + finished = remaining == 0; } } + if finished { + self.set_bool_prop( + pos, + "crafting", + false, + horizon_world::level::flags::UPDATE_ALL, + ); + } } /// `CrafterBlock.dispenseFrom` (the scheduled tick after a redstone pulse). pub(super) fn crafter_dispense(&mut self, pos: BlockPos, state: BlockStateId) -> Result<()> { @@ -105,7 +94,7 @@ impl Game<'_> { // RecipeCache.get: the first crafting recipe that matches, assembled. let found = self .res - .recipes + .recipes() .find(&grid, 3) .map(|(name, result)| (name.to_owned(), result)) .filter(|(_, result)| result.count > 0); @@ -131,7 +120,7 @@ impl Game<'_> { horizon_world::level::flags::UPDATE_CLIENTS, ); // The remainders come from the grid as it was before anything moved. - let remainders = self.res.recipes.remainders(&recipe, &grid, 3); + let remainders = self.res.recipes().remainders(&recipe, &grid, 3); self.crafter_eject(key, facing, result, &recipe); for rest in remainders.into_iter().flatten() { self.crafter_eject(key, facing, rest, &recipe); @@ -213,7 +202,7 @@ impl Game<'_> { pub(in crate::game) fn crafter_result(&self) -> Option { let key = self.container?; let c = self.crafter_at(key)?; - self.res.recipes.craft(&c.items, 3) + self.res.recipes().craft(&c.items, 3) } fn crafter_open(&self) -> bool { matches!(self.container_kind(), Some(BlockEntity::Crafter(_))) @@ -254,7 +243,7 @@ impl Game<'_> { // The background goes first, then the labels, then the slot decorations. let (background, rest) = draws.split_at(2.min(draws.len())); self.paint_screen(batch, ox, oy, background, true); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let grey = rgba(64, 64, 64, 255); let title = self.container_title(self.translate("container.crafter", "Crafter")); let tw = HudBatch::text_width(atlas, &title); diff --git a/crates/horizon-client/src/game/maps.rs b/crates/horizon-client/src/game/maps.rs index 2d7639260..855ef941a 100644 --- a/crates/horizon-client/src/game/maps.rs +++ b/crates/horizon-client/src/game/maps.rs @@ -673,17 +673,18 @@ impl Game<'_> { } else { loop { y -= 1; - color = self.res.facts.get(self.world.block(x, y, z)).map_color; + color = + self.res.facts().get(self.world.block(x, y, z)).map_color; if color != 0 || y <= min_y { break; } } - let f = self.res.facts.get(self.world.block(x, y, z)); + let f = self.res.facts().get(self.world.block(x, y, z)); if y > min_y && f.fluid != Fluid::None { let mut solid = y - 1; loop { let below = - self.res.facts.get(self.world.block(x, solid, z)); + self.res.facts().get(self.world.block(x, solid, z)); solid -= 1; water_depth += 1; if solid <= min_y || below.fluid == Fluid::None { @@ -789,6 +790,7 @@ impl Game<'_> { } let slot = self.maps.slots.last()?.1; let rect = self + .gui .atlas .sprites .get(&format!("horizon/map{slot}")) @@ -797,7 +799,7 @@ impl Game<'_> { if m.texture_dirty { m.texture_dirty = false; let rgba: Vec = m.colors.iter().flat_map(|&c| packed_rgba(c)).collect(); - let (w, h) = (self.atlas.width as f32, self.atlas.height as f32); + let (w, h) = (self.gui.atlas.width as f32, self.gui.atlas.height as f32); self.map_patches.push(horizon_client::font::Patch { x: (rect.u0 * w).round() as u32, y: (rect.v0 * h).round() as u32, @@ -855,7 +857,7 @@ impl Game<'_> { .map(|m| m.decorations.clone()) .unwrap_or_default(); for (i, d) in decorations.iter().enumerate() { - let Some(s) = self.atlas.sprites.get(d.sprite).copied() else { + let Some(s) = self.gui.atlas.sprites.get(d.sprite).copied() else { continue; }; let dm = glam::Mat4::from_translation(glam::Vec3::new( @@ -931,7 +933,7 @@ impl Game<'_> { } else { "map/map_background" }; - if let Some(r) = self.atlas.sprites.get(background).copied() { + if let Some(r) = self.gui.atlas.sprites.get(background).copied() { for (c, uv) in [ ([-7.0, 135.0, 0.0], [r.u0, r.v1]), ([135.0, 135.0, 0.0], [r.u1, r.v1]), diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index de440433d..367dc6aaf 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -157,6 +157,10 @@ pub(super) struct Rail { powered: bool, } impl Minecart { + /// `Entity.onGround`. + pub(super) fn on_ground(&self) -> bool { + self.on_ground + } pub fn new(id: u32, kind: CartKind, position: Vec3) -> Self { Self { id, @@ -214,7 +218,7 @@ impl CartModels { impl Game<'_> { pub(super) fn rail(&self, x: i32, y: i32, z: i32) -> Option { let state = self.world.block(x, y, z); - let name = self.res.facts.get(state).name.clone(); + let name = self.res.facts().get(state).name.clone(); if !matches!( &*name, "minecraft:rail" @@ -243,11 +247,14 @@ impl Game<'_> { } } fn conductor(&self, x: i32, y: i32, z: i32) -> bool { - self.res.facts.get(self.world.block(x, y, z)).full_collision + self.res + .facts() + .get(self.world.block(x, y, z)) + .full_collision } fn cart_in_water(&self, c: &Minecart) -> bool { let p = c.position; - let f = self.res.facts.get(self.world.block( + let f = self.res.facts().get(self.world.block( p.x.floor() as i32, (p.y + 0.1).floor() as i32, p.z.floor() as i32, @@ -657,7 +664,7 @@ impl Game<'_> { stack.count = 0; } Some(s) if s.same_item_same_components(&stack) => { - let max = self.res.items.get(&s.item).map_or(64, |i| i.max_stack); + let max = self.res.items().get(&s.item).map_or(64, |i| i.max_stack); let moved = stack.count.min(max.saturating_sub(s.count)); s.count += moved; stack.count -= moved; @@ -885,9 +892,9 @@ impl Game<'_> { (-1, 1), ] { let (x, y, z) = (bx + dx, by + dy, bz + dz); - let below = self.res.facts.get(self.world.block(x, y - 1, z)); - let here = self.res.facts.get(self.world.block(x, y, z)); - let head = self.res.facts.get(self.world.block(x, y + 1, z)); + let below = self.res.facts().get(self.world.block(x, y - 1, z)); + let here = self.res.facts().get(self.world.block(x, y, z)); + let head = self.res.facts().get(self.world.block(x, y + 1, z)); if (below.full_collision || below.legacy_solid) && !here.full_collision && !head.full_collision @@ -1152,7 +1159,7 @@ impl Game<'_> { diffuse: bool, out: &mut Vec, ) { - let Ok(models) = self.pack.assets.model_catalog.collect_seeded(state, seed) else { + let Ok(models) = self.pack.render.model_catalog.collect_seeded(state, seed) else { return; }; for (_, model) in &models { @@ -1161,7 +1168,7 @@ impl Game<'_> { .pack .layer_names .get(&face.layer) - .and_then(|n| self.atlas.sprites.get(n)) + .and_then(|n| self.gui.atlas.sprites.get(n)) else { continue; }; @@ -1235,6 +1242,7 @@ impl Game<'_> { pub(super) fn cart_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let a = alpha as f32; let Some(uv) = self + .gui .atlas .sprites .get("entity/minecart/minecart") @@ -1378,15 +1386,15 @@ impl Game<'_> { game_time: self.world.game_time, max_y: self.dim.max_y(), world: &self.world, - sprites: &self.atlas.sprites, + sprites: &self.gui.atlas.sprites, nether: self.dim == super::Dim::Nether, lid: &lid, sign: &|_| None, banner: &|_| Vec::new(), - glyph: &|c| self.atlas.glyph_cell(c), + glyph: &|c| self.gui.atlas.glyph_cell(c), }; self.res - .block_entity_render + .block_entity_render() .render_state(&scene, state.0, m, light, out); } } diff --git a/crates/horizon-client/src/game/mob_blocks.rs b/crates/horizon-client/src/game/mob_blocks.rs index 8b2b2da40..27a60ca19 100644 --- a/crates/horizon-client/src/game/mob_blocks.rs +++ b/crates/horizon-client/src/game/mob_blocks.rs @@ -75,10 +75,10 @@ impl Game<'_> { if left <= 0 { return; } - let Some(kind) = self.res.mob_types.get("minecraft:elder_guardian") else { + let Some(kind) = self.res.mob_types().get("minecraft:elder_guardian") else { return; }; - let Some(r) = self.atlas.sprites.get("entity/guardian_elder").copied() else { + let Some(r) = self.gui.atlas.sprites.get("entity/guardian_elder").copied() else { return; }; let age = (APPARITION_TICKS - left) as f32 + alpha as f32; @@ -142,12 +142,12 @@ impl Game<'_> { return; }; let Some(head) = - render::part_transform(mob, alpha as f32, camera, &self.res.mob_data, "head") + render::part_transform(mob, alpha as f32, camera, self.res.mob_data(), "head") else { return; }; let m = banner_matrix(head); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let uv = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); // BannerRenderer: the flag sways with a per-banner phase. let phase = @@ -187,7 +187,7 @@ impl Game<'_> { ) { for (corners, shade, side) in FACES { let name = cube.sprites[usize::from(side)]; - let Some(r) = self.atlas.sprites.get(name).copied() else { + let Some(r) = self.gui.atlas.sprites.get(name).copied() else { continue; }; let tint = if side == 0 { cube.tint } else { 0xFF_FFFF }; @@ -261,7 +261,7 @@ impl Game<'_> { 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) + render::held_item_transform(mob, alpha as f32, camera, self.res.mob_data(), left) else { continue; }; diff --git a/crates/horizon-client/src/game/mob_gear.rs b/crates/horizon-client/src/game/mob_gear.rs index c4a77e38c..809b250dc 100644 --- a/crates/horizon-client/src/game/mob_gear.rs +++ b/crates/horizon-client/src/game/mob_gear.rs @@ -91,9 +91,9 @@ impl Game<'_> { let cost = random .next_int_between_inclusive(MIN_COST, top) .unwrap_or(MIN_COST); - let e = &self.res.stations.enchantments; + let e = &self.res.stations().enchantments; let pool = e.tag("minecraft:on_mob_spawn_equipment"); - let picked = e.select(&self.res.items, random, item, cost, pool); + let picked = e.select(self.res.items(), random, item, cost, pool); if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { for (enchantment, level) in picked { gear::upgrade(m, slot, &enchantment, level); diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 5a1131c3b..b6abf38ef 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -284,7 +284,7 @@ impl Game<'_> { let focused = self.screen == Screen::Chat; self.ui .chat - .add(&self.atlas, line, None, self.ticks, focused); + .add(&self.gui.atlas, line, None, self.ticks, focused); } } /// The mods' HUD panels, stacked with the extras in their corners. @@ -305,7 +305,7 @@ impl Game<'_> { .iter() .map(|l| (l.text.as_str(), l.color)) .collect(); - extras_hud::draw_lines(batch, &self.atlas, corners, corner, &lines); + extras_hud::draw_lines(batch, &self.gui.atlas, corners, corner, &lines); } } } diff --git a/crates/horizon-client/src/game/mount_menu.rs b/crates/horizon-client/src/game/mount_menu.rs index 55e9dde11..1db2210d3 100644 --- a/crates/horizon-client/src/game/mount_menu.rs +++ b/crates/horizon-client/src/game/mount_menu.rs @@ -283,7 +283,7 @@ impl Game<'_> { let Some(open) = self.mount_menu.open.as_ref() else { return; }; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; batch.sprite_region( atlas, "gui/container/horse", @@ -376,7 +376,7 @@ impl Game<'_> { m.hurt_time = 0; m.death_time = 0; let camera = glam::DVec3::new(m.position.x, m.position.y, m.position.z); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); let mut verts = Vec::new(); horizon_client::mobs::render::render_with( @@ -385,7 +385,7 @@ impl Game<'_> { camera, &lookup, 240 | 240 << 8, - &self.res.mob_data, + self.res.mob_data(), &[], &mut verts, ); diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index 869364176..42eac1e9b 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -90,7 +90,11 @@ impl Game<'_> { && let Some(stack) = self.inventory[self.selected].as_mut() { stack.damage += wear; - let max = self.res.items.get(&stack.item).map_or(25, |i| i.max_damage); + let max = self + .res + .items() + .get(&stack.item) + .map_or(25, |i| i.max_damage); if stack.damage >= max { self.inventory[self.selected] = Some(ItemStack::new("minecraft:fishing_rod", 1)); } @@ -406,7 +410,7 @@ impl Game<'_> { .find(|c| { let f = |dy: i32| { self.res - .facts + .facts() .get(self.world.block( c.x.floor() as i32, c.y.floor() as i32 + dy, @@ -457,7 +461,7 @@ impl Game<'_> { return (0, false); }; let m = &self.mobs[i]; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let hearts = horizon_client::hud_layout::vehicle_max_hearts(m.attrs.max_health); let draws = horizon_client::hud_layout::vehicle_health(w, h, hearts, m.health); horizon_client::hud_layout::paint(batch, atlas, &draws); diff --git a/crates/horizon-client/src/game/music.rs b/crates/horizon-client/src/game/music.rs index 381af21cf..9198a78a1 100644 --- a/crates/horizon-client/src/game/music.rs +++ b/crates/horizon-client/src/game/music.rs @@ -50,7 +50,7 @@ impl Game<'_> { let (background, probe_volume) = match eye { Some(eye) => { let (dimension, biome) = (self.dim.id(), self.biome_at(eye)); - let tables = &self.res.music; + let tables = self.res.music(); ( tables.background(dimension, biome), tables.volume(dimension, biome), @@ -81,7 +81,7 @@ impl Game<'_> { .chunks .get(&(x >> 4, z >> 4)) .map_or("minecraft:plains", |c| { - self.res.biomes.list[c.biome(x, y, z) as usize] + self.res.biomes().list[c.biome(x, y, z) as usize] .name .as_str() }) @@ -89,11 +89,11 @@ impl Game<'_> { /// `isEyeInFluid(WATER)`: the eye inside the water of its block column. fn eye_in_water(&self, x: f64, eye_y: f64, z: f64) -> bool { let (bx, by, bz) = (x.floor() as i32, eye_y.floor() as i32, z.floor() as i32); - let f = self.res.facts.get(self.world.block(bx, by, bz)); + let f = self.res.facts().get(self.world.block(bx, by, bz)); if f.fluid != Fluid::Water { return false; } - let above = self.res.facts.get(self.world.block(bx, by + 1, bz)); + let above = self.res.facts().get(self.world.block(bx, by + 1, bz)); let height = if above.fluid == Fluid::Water { 1.0 } else { @@ -111,7 +111,7 @@ impl Game<'_> { }; let feet = [p.position.x, p.position.y, p.position.z]; let eye_y = feet[1] + f64::from(p.dimensions.eye_height); - let sounds = self.res.ambient.get(self.dim.id(), self.biome_at(feet)); + let sounds = self.res.ambient().get(self.dim.id(), self.biome_at(feet)); let underwater = self.eye_in_water(feet[0], eye_y, feet[2]); let world = &self.world; let light = |b: [i32; 3]| { @@ -123,7 +123,7 @@ impl Game<'_> { f64::from(p.dimensions.height), ); let registry = &self.pack.assets.registry; - let facts = &self.res.facts; + let facts = self.res.facts(); let bubble_column = horizon_client::ambience::bubble_column_in( [ feet[0] - half, diff --git a/crates/horizon-client/src/game/names.rs b/crates/horizon-client/src/game/names.rs index 368c5c0f2..707b9df96 100644 --- a/crates/horizon-client/src/game/names.rs +++ b/crates/horizon-client/src/game/names.rs @@ -218,7 +218,7 @@ impl Game<'_> { let forward = glam::DVec3::from_array(view_vector(self.yaw, self.pitch)); let right = forward.cross(glam::DVec3::Y).normalize_or_zero(); let up = right.cross(forward).normalize_or_zero(); - let white = self.atlas.font.white(); + let white = self.gui.atlas.font.white(); let away = forward.as_vec3() * 0.002; for (text, lift) in lines { let o = (o + glam::DVec3::new(0.0, *lift, 0.0)).as_vec3(); @@ -240,7 +240,7 @@ impl Game<'_> { .collect(); let width: f32 = chars .iter() - .map(|(c, _)| self.atlas.glyph(*c).map_or(6.0, |g| g.1)) + .map(|(c, _)| self.gui.atlas.glyph(*c).map_or(6.0, |g| g.1)) .sum(); let x0 = -(width / 2.0).trunc(); let y0 = if text.plain() == "deadmau5" { @@ -278,7 +278,7 @@ impl Game<'_> { } let mut x = x0; for (ch, color) in chars { - let Some((g, advance)) = self.atlas.glyph(ch) else { + let Some((g, advance)) = self.gui.atlas.glyph(ch) else { x += 6.0; continue; }; diff --git a/crates/horizon-client/src/game/natural_spawning.rs b/crates/horizon-client/src/game/natural_spawning.rs index 80d26a823..059437d7b 100644 --- a/crates/horizon-client/src/game/natural_spawning.rs +++ b/crates/horizon-client/src/game/natural_spawning.rs @@ -35,7 +35,7 @@ pub(super) struct GameLevel<'g, 'a> { impl GameLevel<'_, '_> { fn biome(&self, x: i32, y: i32, z: i32) -> Option<&BiomeInfo> { let chunk = self.game.world.chunks.get(&(x >> 4, z >> 4))?; - Some(self.game.res.biomes.get(chunk.biome(x, y, z))) + Some(self.game.res.biomes().get(chunk.biome(x, y, z))) } } impl SpawnLevel for GameLevel<'_, '_> { @@ -106,7 +106,7 @@ impl NaturalLevel for GameLevel<'_, '_> { self.game.dim == Dim::Nether } fn mob_type(&self, entity: &str) -> Option<(Species, f32, f32, Category)> { - let t = self.game.res.mob_types.get(entity)?; + let t = self.game.res.mob_types().get(entity)?; Some(( t.species, t.width as f32, @@ -198,10 +198,14 @@ impl NaturalLevel for GameLevel<'_, '_> { fn spawn_mobs(&self) -> bool { self.game.ui.rules.bool("spawn_mobs") } - /// Scanned down the column: sections of air alone are skipped (air counts - /// for no heightmap), and an unloaded column reads as air. + /// WORLD_SURFACE (every spawn attempt's) is the chunk's kept heightmap. + /// The others are scanned down the column: sections of air alone are + /// skipped (air counts for no heightmap). An unloaded column reads as air. fn heightmap(&self, kind: Heightmap, x: i32, z: i32) -> i32 { let world = self.w.world; + if kind == Heightmap::WorldSurface { + return self.w.world_surface(x, z); + } world .chunks .get(&(x >> 4, z >> 4)) @@ -234,7 +238,7 @@ impl horizon_client::mobs::spawner::SpawnerLevel for GameLevel<'_, '_> { self.game.ui.rules.bool("spawner_blocks_work") } fn entity_exists(&self, id: &str) -> bool { - self.game.res.mob_types.contains_key(id) || self.game.entity_type_exists(id) + self.game.res.mob_types().contains_key(id) || self.game.entity_type_exists(id) } fn count_entities(&self, id: &str, bounds: Aabb) -> usize { let mobs = self @@ -264,7 +268,7 @@ impl<'a> Game<'a> { /// Creates a mob the spawner accepted, finalized the game's way; the /// caller adds it with [`Game::add_spawned`]. fn finalize_spawned(&self, r: &SpawnRequest, pending: &mut Vec) -> Option { - let kind = self.res.mob_types.get(r.entity)?.clone(); + let kind = self.res.mob_types().get(r.entity)?.clone(); let [x, y, z] = r.position; let mut mob = Mob::new(0, kind, Vec3::new(x, y, z), r.yaw); let facts = self.biome_facts(x.floor() as i32, y.floor() as i32, z.floor() as i32); diff --git a/crates/horizon-client/src/game/nautili.rs b/crates/horizon-client/src/game/nautili.rs index c039b7d9a..e7f16ca18 100644 --- a/crates/horizon-client/src/game/nautili.rs +++ b/crates/horizon-client/src/game/nautili.rs @@ -11,7 +11,7 @@ use horizon_core::random::RandomSource; impl Game<'_> { fn item_tagged(&self, tag: &str, item: &str) -> bool { self.res - .items + .items() .item_tags .get(tag) .is_some_and(|t| t.contains(item)) @@ -43,7 +43,7 @@ impl Game<'_> { } let taming: Vec = self .res - .items + .items() .item_tags .get("minecraft:nautilus_taming_items") .map(|t| t.iter().cloned().collect()) diff --git a/crates/horizon-client/src/game/nether_portal.rs b/crates/horizon-client/src/game/nether_portal.rs index 582092f57..039b3145a 100644 --- a/crates/horizon-client/src/game/nether_portal.rs +++ b/crates/horizon-client/src/game/nether_portal.rs @@ -65,6 +65,8 @@ pub(super) struct Portals { arrivals: Vec, loaded: bool, dirty: bool, + /// Per-chunk portal palette masks, kept across ticks (portal_sections). + pub(super) sections: horizon_client::portal_sections::PortalSections, } fn rotate_y(v: Vec3, degrees: f32) -> Vec3 { @@ -112,7 +114,7 @@ impl Game<'_> { Dim::Nether }; let state = self.world.block(entry.x, entry.y, entry.z); - let b = &self.res.behaviours; + let b = self.res.behaviours(); let (entry_x_axis, offset) = match b.portal_axis(state) { Some(x_axis) => { let area = largest_rectangle_around( @@ -150,7 +152,7 @@ impl Game<'_> { /// (the points of interest `PortalForcer` searches): loaded chunks as /// they are, the others as saved; chunks never generated have none. fn portal_blocks(&self, center: BlockPos, radius: i32) -> Vec { - let b = &self.res.behaviours; + let b = self.res.behaviours(); let chunk_radius = radius.div_euclid(16) + 1; let (cx, cz) = (center.x >> 4, center.z >> 4); let mut out = Vec::new(); @@ -161,7 +163,7 @@ impl Game<'_> { Some(c) => &**c, None => match self .save - .load(x, z, self.pack.assets.registry, &self.res.biomes) + .load(x, z, self.pack.assets.registry, self.res.biomes()) { Some(c) => { saved = c; @@ -211,7 +213,7 @@ impl Game<'_> { ); if let Some(found) = found { let state = self.world.block(found.x, found.y, found.z); - let x_axis = self.res.behaviours.portal_axis(state).unwrap_or(true); + let x_axis = self.res.behaviours().portal_axis(state).unwrap_or(true); return Some(largest_rectangle_around( found, if x_axis { Axis::X } else { Axis::Z }, @@ -232,7 +234,7 @@ impl Game<'_> { /// `NetherPortalBlock.createDimensionTransition`: the arrival position /// and the yaw turned by. pub(super) fn arrival(&self, plan: &Plan, exit: FoundRectangle) -> (Vec3, f32) { - let b = &self.res.behaviours; + let b = self.res.behaviours(); let corner = exit.min_corner; let exit_x_axis = b .portal_axis(self.world.block(corner.x, corner.y, corner.z)) @@ -499,13 +501,14 @@ impl Game<'_> { .filter(|m| self.mob_can_use_portal(m)) .map(|m| (m.id, m.position, m.width(), m.height())) .collect(); - let mut portal_sections = horizon_client::fast_hash::FxHashMap::default(); + let mut portal_sections = std::mem::take(&mut self.portals.sections); for (id, to, width, height) in items.into_iter().chain(mobs) { let from = self.portals.before.get(&id).copied().unwrap_or(to); if let Some(pos) = self.swept_portal(from, to, width, height, &mut portal_sections) { inside.push((id, pos)); } } + self.portals.sections = portal_sections; for (id, pos) in inside { self.portals .entities @@ -522,7 +525,7 @@ impl Game<'_> { to: Vec3, width: f32, height: f32, - portal_sections: &mut horizon_client::fast_hash::FxHashMap<(i32, i32, i32), bool>, + portal_sections: &mut horizon_client::portal_sections::PortalSections, ) -> Option { let half = f64::from(width) / 2.0; let bounds = horizon_core::geometry::Aabb::new( @@ -550,7 +553,7 @@ impl Game<'_> { |p, _| { if self .res - .behaviours + .behaviours() .portal_axis(self.world.block(p.x, p.y, p.z)) .is_some() { @@ -563,12 +566,13 @@ impl Game<'_> { found } /// Whether a section `reach` touches has a nether portal state in its - /// palette: without one, no block there is a portal. Answers are kept - /// per section for the tick; a box over many sections is not checked. + /// palette: without one, no block there is a portal. Palette answers are + /// kept per chunk across ticks (`portal_sections`); a box over many + /// sections is not checked. fn may_hold_portal( &self, reach: horizon_core::geometry::Aabb, - seen: &mut horizon_client::fast_hash::FxHashMap<(i32, i32, i32), bool>, + sections: &mut horizon_client::portal_sections::PortalSections, ) -> bool { use horizon_client::chunk::{MIN_Y, SECTIONS}; let (min, max) = (reach.min_position(), reach.max_position()); @@ -589,23 +593,21 @@ impl Game<'_> { if count > 64 { return true; } - let behaviours = &self.res.behaviours; + let mut y_mask = 0u32; + for sy in y0..=y1 { + y_mask |= 1 << sy; + } + let behaviours = self.res.behaviours(); let chunks = &self.world.chunks; (x0..=x1).any(|cx| { (z0..=z1).any(|cz| { - (y0..=y1).any(|sy| { - *seen.entry((cx, sy, cz)).or_insert_with(|| { - chunks - .get(&(cx, cz)) - .and_then(|c| c.sections.get(sy as usize)) - .is_some_and(|s| { - s.blocks.maybe_has(|v| { - behaviours - .portal_axis(horizon_world::registry::BlockStateId(v)) - .is_some() - }) - }) - }) + chunks.get(&(cx, cz)).is_some_and(|chunk| { + sections.get((cx, cz), chunk, |v| { + behaviours + .portal_axis(horizon_world::registry::BlockStateId(v)) + .is_some() + }) & y_mask + != 0 }) }) }) diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index ed0dccb06..12efde5be 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -111,7 +111,7 @@ impl Game<'_> { } pub(super) fn draw_options(&mut self, batch: &mut HudBatch) { let mut ui = std::mem::take(&mut self.ui.options); - ui.draw(&self.settings, batch, &self.atlas, self.cursor); + ui.draw(&self.settings, batch, &self.gui.atlas, self.cursor); self.ui.options = ui; } pub(super) fn options_mouse(&mut self, pressed: bool, right: bool) -> Result<()> { @@ -133,7 +133,7 @@ impl Game<'_> { let mut ui = std::mem::take(&mut self.ui.options); let events = ui.click( &mut self.settings, - &self.atlas, + &self.gui.atlas, self.cursor.0, self.cursor.1, size, @@ -152,7 +152,7 @@ impl Game<'_> { let mut ui = std::mem::take(&mut self.ui.options); let events = ui.click( &mut self.settings, - &self.atlas, + &self.gui.atlas, self.cursor.0, self.cursor.1, size, @@ -165,7 +165,7 @@ impl Game<'_> { } pub(super) fn options_key(&mut self, key: KeyCode, text: Option<&str>) -> Result<()> { let mut ui = std::mem::take(&mut self.ui.options); - let events = ui.key(&mut self.settings, &self.atlas, key, text); + let events = ui.key(&mut self.settings, &self.gui.atlas, key, text); self.ui.options = ui; self.handle_option_events(events) } @@ -176,7 +176,7 @@ impl Game<'_> { ) -> bool { self.ui .options - .shortcut(&self.atlas, shortcut, &mut self.clipboard) + .shortcut(&self.gui.atlas, shortcut, &mut self.clipboard) } pub(super) fn options_scroll(&mut self, amount: f32) { let size = self.gui_size(); @@ -225,6 +225,11 @@ impl Game<'_> { let _ = std::fs::create_dir_all(&dir); super::packs::open_folder(&dir); } + Event::OpenModFolder => { + let dir = Self::options_path().with_file_name(horizon_client::mod_list::DIR); + let _ = std::fs::create_dir_all(&dir); + super::packs::open_folder(&dir); + } } } Ok(()) @@ -233,7 +238,7 @@ impl Game<'_> { pub(super) fn load_language(&mut self, code: &str) { let root = self.options.resources.clone(); lang::set(lang::Language::load(&[&root], code)); - self.ui.chat.rescale(&self.atlas); + self.ui.chat.rescale(&self.gui.atlas); } /// Settings that Horizon applies beyond render distance, volume and GUI scale. pub(super) fn apply_ui_settings(&mut self) { @@ -264,14 +269,14 @@ impl Game<'_> { }; self.ui.chat.options = chat; if rescale { - self.ui.chat.rescale(&self.atlas); + self.ui.chat.rescale(&self.gui.atlas); } - let font = &mut self.atlas.font; + let font = &mut self.gui.atlas.font; if font.uniform != s.force_unicode || font.japanese != s.japanese_glyphs { font.uniform = s.force_unicode; font.japanese = s.japanese_glyphs; font.reset_cache(); - self.ui.chat.rescale(&self.atlas); + self.ui.chat.rescale(&self.gui.atlas); } // A new renderer (resource reload, first window) takes the loaded pack. let stale = self diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index 0b95dd2ad..0f5a48312 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -74,6 +74,15 @@ fn vanilla_info() -> PackInfo { fixed: false, } } +/// Shared by the startup menu, which has no world resources yet. +pub(super) fn pack_infos(vanilla: &Path) -> Vec { + let mut infos: Vec = packs::discover(vanilla, &packs_dir()) + .iter() + .map(info) + .collect(); + infos.push(vanilla_info()); + infos +} impl Game<'_> { fn vanilla_root(&self) -> PathBuf { if self.ui.vanilla_root.as_os_str().is_empty() { @@ -85,9 +94,7 @@ impl Game<'_> { /// The packs the pack screen offers and the current selection /// (`PackSelectionScreen` makes its `PackSelectionModel` from them). pub(super) fn refresh_pack_lists(&mut self) { - let all = packs::discover(&self.vanilla_root(), &packs_dir()); - let mut infos: Vec = all.iter().map(info).collect(); - infos.push(vanilla_info()); + let infos = pack_infos(&self.vanilla_root()); let o = &mut self.ui.options; o.pack_infos = infos; o.pack_selection = self.settings.resource_packs.clone(); @@ -100,6 +107,12 @@ impl Game<'_> { /// particle and font textures), item models, sounds, languages, GUI /// metadata and the cloud and world border textures. pub(super) fn reload_packs(&mut self) { + // Pack reload updates tail-owned mob metadata. Keep menus responsive + // until those resources exist, then apply the latest selection once. + if self.rest_loader.is_some() { + self.pending_pack_reload = true; + return; + } let vanilla = self.vanilla_root(); if self.ui.vanilla_root.as_os_str().is_empty() { self.ui.vanilla_root = vanilla.clone(); @@ -119,14 +132,19 @@ impl Game<'_> { } } fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> { - let assets = std::sync::Arc::new(self.pack.assets.reload(root)?); + let render = std::sync::Arc::new(self.pack.assets.reload(root)?); let mut atlas = HudAtlas::build(root)?; atlas.font.uniform = self.settings.force_unicode; atlas.font.japanese = self.settings.japanese_glyphs; + let gui = super::UiResources { + atlas, + panorama: std::sync::Arc::new(horizon_client::gfx::panorama::Faces::load(root)), + }; let pack = super::PackResources::load( root, - assets, - &self.res.facts, + self.pack.assets.clone(), + render, + self.res.facts(), self.pack.context.biomes.clone(), self.pack.context.light.clone(), )?; @@ -137,7 +155,7 @@ impl Game<'_> { let renderer = match self .window .clone() - .map(|window| self.renderer_for(window, &pack, &atlas)) + .map(|window| self.renderer_for(window, &pack, &gui)) .transpose() { Ok(renderer) => renderer, @@ -154,15 +172,16 @@ impl Game<'_> { }; // Everything loaded: switch over. self.random_tick_sections.clear(); + self.portals.sections.clear(); self.options.resources = root.to_path_buf(); let context = pack.context.clone(); self.pack = pack; - self.atlas = atlas; + self.gui = gui; horizon_client::ui_theme::reset_atlas(); // Villager hats come from the pack's texture metadata (shared data, swapped in place). *self .res - .mob_data + .mob_data() .villager_hats .write() .unwrap_or_else(std::sync::PoisonError::into_inner) = @@ -178,7 +197,7 @@ impl Game<'_> { self.renderer = Some(renderer); self.apply_ui_settings(); } - self.ui.chat.rescale(&self.atlas); + self.ui.chat.rescale(&self.gui.atlas); Ok(()) } } diff --git a/crates/horizon-client/src/game/pad.rs b/crates/horizon-client/src/game/pad.rs index 0c988c3b7..9a71bdc75 100644 --- a/crates/horizon-client/src/game/pad.rs +++ b/crates/horizon-client/src/game/pad.rs @@ -6,12 +6,12 @@ use super::{Game, Screen}; use horizon_client::{ Result, - gamepad::{self, Button, Edges, GlyphStyle, HealthWatch, PadState, Rumble, TriggerFeel}, + gamepad::{self, Button, Edges, GlyphStyle, HealthWatch, PadState, Rumble}, keybinds::{KeyBinds, key_code, mouse_button}, mouse::Rotation, }; use serde_json::{Value, json}; -use std::time::{Duration, Instant}; +use std::time::Instant; use winit::{event_loop::ActiveEventLoop, keyboard::KeyCode}; pub(super) const HELP: &[&str] = &[ @@ -25,10 +25,9 @@ pub(super) const HELP: &[&str] = &[ /// The controllers and the state the game last acted on. #[derive(Default)] pub(super) struct Pads { - gilrs: Option, - started: bool, - /// The pad last touched; only its input counts. - active: Option, + /// The real controllers and the DualSense's output. + #[cfg(feature = "controllers")] + devices: hardware::Devices, /// The virtual pad of `horizon-ctl pad`. injected: PadState, /// The virtual pad was in use at the last poll. @@ -48,49 +47,38 @@ pub(super) struct Pads { pub(super) style: GlyphStyle, /// The cursor the pad drives in menus. pub(super) menu: super::pad_menu::MenuCursor, - /// Vibrations playing (an effect stops when dropped) and when they end. - rumbles: Vec<(gilrs::ff::Effect, Instant)>, /// The last vibration asked for, for `pad status`. last_rumble: Option<(&'static str, gamepad::Pulse)>, /// The player's health between polls (a drop is damage taken). health: HealthWatch, - /// The active pad is a DualSense. - dualsense: bool, - /// Its own output over HID (rumble here; gilrs only reads it), started once this window - /// has the pad in hand; dropped, it releases the pad. - output: Option, - /// Its HD haptics, on USB: looked for once each time the output opens. - haptics: Option, - haptics_tried: bool, - /// What it was last told to show. - shown: Option, } -fn gilrs_button(button: Button) -> gilrs::Button { - use gilrs::Button as G; - match button { - Button::South => G::South, - Button::East => G::East, - Button::West => G::West, - Button::North => G::North, - Button::LeftBumper => G::LeftTrigger, - Button::RightBumper => G::RightTrigger, - Button::LeftTrigger => G::LeftTrigger2, - Button::RightTrigger => G::RightTrigger2, - Button::Select => G::Select, - Button::Start => G::Start, - Button::LeftStick => G::LeftThumb, - Button::RightStick => G::RightThumb, - Button::DPadUp => G::DPadUp, - Button::DPadDown => G::DPadDown, - Button::DPadLeft => G::DPadLeft, - Button::DPadRight => G::DPadRight, +#[cfg(feature = "controllers")] +mod hardware; + +/// A build without the `controllers` feature (the server build, which must not need libudev): no +/// hardware pads, only `horizon-ctl pad`'s virtual one. +#[cfg(not(feature = "controllers"))] +mod hardware { + use super::{super::Game, Pads}; + use horizon_client::gamepad::{PadState, Pulse, Rumble}; + use serde_json::{Value, json}; + + impl Pads { + pub(super) fn read(&mut self) -> PadState { + PadState::default() + } } -} -fn is_dualsense(pad: &gilrs::Gamepad) -> bool { - matches!((pad.vendor_id(), pad.product_id()), - (Some(vendor), Some(product)) if horizon_dualsense::is_dualsense(vendor, product)) + impl Game<'_> { + pub(super) fn pad_output_off(&mut self) {} + pub(super) fn pad_output_frame(&mut self) {} + pub(in crate::game) fn pad_close_output(&mut self) {} + pub(super) fn pad_vibrate(&mut self, _: Rumble, _: Pulse) {} + pub(super) fn pad_devices_status(&self) -> Value { + json!({ "backend": false, "controllers": [] }) + } + } } impl Pads { @@ -99,93 +87,6 @@ impl Pads { pub(super) fn player_replaced(&mut self) { self.health.forget(); } - /// Open gilrs on first use. A platform without it (or a Linux without - /// udev) leaves controllers off; the game runs as before. - fn start(&mut self) { - if self.started { - return; - } - self.started = true; - self.gilrs = match gilrs::Gilrs::new() { - Ok(g) => { - for (_, pad) in g.gamepads() { - log::info!("Controller connected: {}", pad.name()); - } - Some(g) - } - Err(gilrs::Error::NotImplemented(_)) => None, - Err(e) => { - log::warn!("Horizon: controllers are unavailable: {e}"); - None - } - }; - } - - /// Drain gilrs' events and read the active pad. - fn read(&mut self) -> PadState { - let Some(gilrs) = self.gilrs.as_mut() else { - return PadState::default(); - }; - while let Some(gilrs::Event { id, event, .. }) = gilrs.next_event() { - use gilrs::EventType as E; - match event { - E::Connected => { - log::info!("Controller connected: {}", gilrs.gamepad(id).name()); - if let Some(output) = &self.output { - output.scan(); - } - } - E::Disconnected => { - log::info!("Controller disconnected: {}", gilrs.gamepad(id).name()); - if self.active == Some(id) { - self.active = None; - } - if let Some(output) = &self.output { - output.scan(); - } - } - E::ButtonPressed(..) => self.active = Some(id), - E::AxisChanged(_, value, _) | E::ButtonChanged(_, value, _) - if value.abs() > 0.5 => - { - self.active = Some(id) - } - _ => {} - } - } - let Some(pad) = self.active.and_then(|id| gilrs.connected_gamepad(id)) else { - // Before any pad is touched (the virtual pad playing), a DualSense still shows it. - self.dualsense = gilrs.gamepads().any(|(_, pad)| is_dualsense(&pad)); - return PadState::default(); - }; - self.style = GlyphStyle::of_vendor(pad.vendor_id()); - self.dualsense = is_dualsense(&pad); - let mut state = PadState::default(); - for button in Button::ALL { - if !matches!(button, Button::LeftTrigger | Button::RightTrigger) { - state.set(button, pad.is_pressed(gilrs_button(button))); - } - } - let axis = |a| pad.value(a); - use gilrs::Axis as A; - state.left = [axis(A::LeftStickX), axis(A::LeftStickY)]; - state.right = [axis(A::RightStickX), axis(A::RightStickY)]; - // Triggers arrive as analog buttons on most mappings, as plain - // buttons on some. - let trigger = |b: gilrs::Button| { - let value = pad.button_data(b).map_or(0.0, |d| d.value()); - if pad.is_pressed(b) { - value.max(1.0) - } else { - value - } - }; - state.triggers = [ - trigger(gilrs::Button::LeftTrigger2), - trigger(gilrs::Button::RightTrigger2), - ]; - state - } } impl Game<'_> { @@ -193,9 +94,7 @@ impl Game<'_> { pub(super) fn poll_pads(&mut self, event_loop: &ActiveEventLoop) { let settings = &self.settings.controller; if !settings.enabled { - // Dropping the output frees the triggers. - self.pad.output = None; - self.pad.shown = None; + self.pad_output_off(); if self.pad.state != PadState::default() { self.pad.state = PadState::default(); for (button, down) in self.pad.edges.release_all() { @@ -204,7 +103,6 @@ impl Game<'_> { } return; } - self.pad.start(); let hardware = self.pad.read(); self.ui.options.pad_style = self.settings.controller.glyphs.resolve(self.pad.style); let state = hardware.merge(&self.pad.injected); @@ -219,11 +117,7 @@ impl Game<'_> { self.pad.in_use = true; } self.pad.state = state; - if self.pad.dualsense && self.pad.in_use && self.focused && self.pad.output.is_none() { - self.pad.output = Some(horizon_dualsense::Link::start()); - } - self.pad_haptics(); - self.pad_show(); + self.pad_output_frame(); // Damage from any source, here or on a server; nothing counts on // the title screen. let health = self @@ -234,8 +128,6 @@ impl Game<'_> { if let Some(damage) = self.pad.health.observe(health) { self.pad_rumble(Rumble::Hurt(damage)); } - let now = Instant::now(); - self.pad.rumbles.retain(|(_, end)| *end > now); let ticking = self.title.is_none() && self.screen == Screen::Playing && !self.pause; for button in std::mem::take(&mut self.pad.late_releases) { if !ticking || self.pad.pressed_at[button as usize] != Some(self.ticks) { @@ -404,150 +296,8 @@ impl Game<'_> { self.pitch = rotation.x_rot; } - /// The DualSense's HID output, while it is the active pad, open, and this window has focus - /// (another game on the same pad keeps it otherwise). - fn pad_output(&self) -> Option<&horizon_dualsense::Link> { - let output = self.pad.output.as_ref()?; - (self.pad.dualsense && self.focused && output.open().is_some()).then_some(output) - } - - /// What the DualSense shows: while playing, its triggers feel what their actions do; in - /// menus, paused, unfocused or with another pad active, they are free. - fn pad_show(&mut self) { - if self.pad.output.is_none() { - return; - } - let playing = self.pad.dualsense - && self.focused - && self.title.is_none() - && self.screen == Screen::Playing - && !self.pause; - let (using, attacking) = if playing { - self.trigger_feels() - } else { - (TriggerFeel::Free, TriggerFeel::Free) - }; - // The lightbar follows the player; menus keep the last colour. - let in_world = self.title.is_none(); - let lightbar = match self.player.as_mut().filter(|_| in_world) { - Some(p) => { - let max = p.attribute("minecraft:max_health").unwrap_or(20.0) as f32; - let health = p.health.health() / max.max(1.0); - self.settings - .controller - .lightbar - .colour(health, self.dim.id()) - } - None => self.pad.shown.and_then(|s| s.lightbar), - }; - let lights = self.settings.controller.lightbar != gamepad::Lightbar::Off; - let state = horizon_dualsense::device::State { - triggers: self.settings.controller.trigger_effects(using, attacking), - lightbar: lightbar.filter(|_| lights), - player_leds: lights.then_some(horizon_dualsense::PLAYER_1), - }; - if self.pad.shown != Some(state) - && let Some(output) = &self.pad.output - { - output.set(state); - self.pad.shown = Some(state); - } - } - - /// What `key.use` and `key.attack` are doing, for the triggers bound to them. - fn trigger_feels(&self) -> (TriggerFeel, TriggerFeel) { - let using = match self.using { - Some((slot, ticks)) => match self.stack_in(slot) { - Some(s) if &*s.item == "minecraft:bow" => { - TriggerFeel::Draw(gamepad::bow_power(ticks)) - } - // TridentItem.THROW_THRESHOLD_TIME. - Some(s) if &*s.item == "minecraft:trident" => { - TriggerFeel::Draw(ticks as f32 / 10.0) - } - Some(s) if &*s.item == "minecraft:crossbow" => { - TriggerFeel::Draw(ticks as f32 / Self::charge_ticks(s).max(1) as f32) - } - Some(s) if self.blocks_attacks(s).is_some() => TriggerFeel::Brace, - _ => TriggerFeel::Free, - }, - None => self.idle_use_feel(), - }; - // Creative breaks at once; blocks that can't be broken have a negative hardness. - let attacking = match &self.mining { - Some(m) if !self.creative => { - let state = self.world.block(m.pos[0], m.pos[1], m.pos[2]); - TriggerFeel::Texture(self.res.facts.get(state).hardness) - } - _ => TriggerFeel::Free, - }; - (using, attacking) - } - - /// The use trigger while nothing is in use: a loaded crossbow clicks, an item that boosts (a - /// rocket while gliding, the stick of the mount being ridden) catches, a shield weighs, and - /// locks while an axe has disabled it. - fn idle_use_feel(&self) -> TriggerFeel { - let gliding = self.player.as_ref().is_some_and(|p| p.fall_flying); - let mount = self - .riding - .and_then(|id| self.mobs.iter().find(|m| m.id == id)); - let mount = mount.map_or("", |m| m.kind.id.as_str()); - let feel = |stack: Option<&horizon_client::items::ItemStack>| match stack - .map(|s| (s, &*s.item)) - { - Some((s, "minecraft:crossbow")) if s.data().is_some_and(|d| !d.charged.is_empty()) => { - TriggerFeel::Click - } - Some((_, "minecraft:firework_rocket")) if gliding => TriggerFeel::Boost, - Some((_, "minecraft:carrot_on_a_stick")) if mount == "minecraft:pig" => { - TriggerFeel::Boost - } - Some((_, "minecraft:warped_fungus_on_a_stick")) if mount == "minecraft:strider" => { - TriggerFeel::Boost - } - Some((s, _)) if self.blocks_attacks(s).is_some() => match self.shield_cooldown { - 0 => TriggerFeel::Brace, - _ => TriggerFeel::Locked, - }, - _ => TriggerFeel::Free, - }; - // Use tries the main hand first. - match feel(self.stack_in(self.selected)) { - TriggerFeel::Free => feel(self.offhand.as_ref()), - main => main, - } - } - - /// Open the pad's haptics once its output is open over USB (its audio device is there - /// only then); close them when it goes. Opt-in with `HORIZON_DUALSENSE_HAPTICS=1` until - /// they are proven on a pad (docs/controllers.md); never for games without sound (tests). - fn pad_haptics(&mut self) { - let usb = self.pad.output.as_ref().and_then(|o| o.open()) - == Some(horizon_dualsense::Transport::Usb); - if !usb { - self.pad.haptics = None; - self.pad.haptics_tried = false; - } else if !self.pad.haptics_tried { - self.pad.haptics_tried = true; - if std::env::var_os("HORIZON_DUALSENSE_HAPTICS").is_some_and(|v| v == "1") - && std::env::var_os("HORIZON_NO_AUDIO").is_none() - { - self.pad.haptics = horizon_dualsense::haptics::Haptics::open(); - } - } - } - - /// Release the DualSense's output (the game is quitting). - pub(super) fn pad_close_output(&mut self) { - self.pad.haptics = None; - self.pad.output = None; - } - /// Vibrate the active pad, when vibration is on and the pad is the one - /// playing (a pad lying idle while the mouse plays stays still): a - /// DualSense through its own report, else gilrs' force feedback, which - /// platforms without it (gilrs on macOS) skip. + /// playing (a pad lying idle while the mouse plays stays still). pub(super) fn pad_rumble(&mut self, rumble: Rumble) { let settings = &self.settings.controller; if !settings.enabled || !settings.vibration || !self.pad.in_use { @@ -557,68 +307,7 @@ impl Game<'_> { return; }; self.pad.last_rumble = Some((rumble.name(), pulse)); - let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - if let Some(haptics) = self - .pad - .haptics - .as_ref() - .filter(|_| self.pad_output().is_some()) - { - let steps = rumble.shape().into_iter().map(|step| { - ( - step.strong, - step.weak, - Duration::from_millis(u64::from(step.millis)), - ) - }); - haptics.play(&steps.collect::>()); - return; - } - if let Some(output) = self.pad_output() { - let steps = rumble.shape().into_iter().map(|step| { - let length = Duration::from_millis(u64::from(step.millis)); - ([level(step.strong), level(step.weak)], length) - }); - output.rumble(steps.collect()); - return; - } - let (Some(gilrs), Some(id)) = (self.pad.gilrs.as_mut(), self.pad.active) else { - return; - }; - if !gilrs - .connected_gamepad(id) - .is_some_and(|g| g.is_ff_supported()) - { - return; - } - use gilrs::ff::{BaseEffect, BaseEffectType, EffectBuilder, Repeat, Replay, Ticks}; - let length = Ticks::from_ms(pulse.millis); - let motor = |kind| BaseEffect { - kind, - scheduling: Replay { - play_for: length, - ..Default::default() - }, - envelope: Default::default(), - }; - let magnitude = |v: f32| (v.clamp(0.0, 1.0) * f32::from(u16::MAX)) as u16; - let effect = EffectBuilder::new() - .add_effect(motor(BaseEffectType::Strong { - magnitude: magnitude(pulse.strong), - })) - .add_effect(motor(BaseEffectType::Weak { - magnitude: magnitude(pulse.weak), - })) - .repeat(Repeat::For(length)) - .gamepads(&[id]) - .finish(gilrs); - match effect.and_then(|e| e.play().map(|()| e)) { - Ok(effect) => { - let end = Instant::now() + Duration::from_millis(u64::from(pulse.millis) + 50); - self.pad.rumbles.push((effect, end)); - } - Err(e) => log::debug!("Horizon: controller vibration: {e}"), - } + self.pad_vibrate(rumble, pulse); } /// `horizon-ctl pad ...`. @@ -639,32 +328,15 @@ impl Game<'_> { }; match arg(1)? { "status" => { - let pads: Vec = self.pad.gilrs.as_ref().map_or(Vec::new(), |g| { - g.gamepads() - .map(|(id, p)| { - json!({ - "name": p.name(), - "vendor": p.vendor_id(), - "product": p.product_id(), - "active": self.pad.active == Some(id), - }) - }) - .collect() - }); let s = &self.pad.state; let held: Vec<&str> = Button::ALL .into_iter() .filter(|b| self.pad.edges.is_held(*b)) .map(Button::name) .collect(); - Ok(json!({ + let mut status = json!({ "enabled": self.settings.controller.enabled, - "backend": self.pad.gilrs.is_some(), - "controllers": pads, "glyphs": self.pad.style.name(), - "dualsense_output": self.pad.output.as_ref().and_then(|o| o.open()) - .map(|t| format!("{t:?}")), - "trigger_effects": self.pad.shown.map(|s| s.triggers), "last_rumble": self.pad.last_rumble.map(|(why, p)| json!({ "reason": why, "strong": p.strong, "weak": p.weak, "ms": p.millis, })), @@ -674,7 +346,13 @@ impl Game<'_> { "left": s.left, "right": s.right, "triggers": s.triggers, - })) + }); + if let (Some(status), Value::Object(devices)) = + (status.as_object_mut(), self.pad_devices_status()) + { + status.extend(devices); + } + Ok(status) } "release" => { self.pad.injected = PadState::default(); diff --git a/crates/horizon-client/src/game/pad/hardware.rs b/crates/horizon-client/src/game/pad/hardware.rs new file mode 100644 index 000000000..b464ef3ee --- /dev/null +++ b/crates/horizon-client/src/game/pad/hardware.rs @@ -0,0 +1,409 @@ +//! The real controllers (the `controllers` feature): gilrs' pads, and the DualSense's own output +//! over HID: its rumble, adaptive triggers, lights and HD haptics. A build without the feature (the +//! server build) has the stub in pad.rs instead, and only `horizon-ctl pad`'s virtual pad. +use super::{ + super::{Game, Screen}, + Pads, +}; +use horizon_client::gamepad::{self, Button, GlyphStyle, PadState, Rumble, TriggerFeel}; +use serde_json::{Value, json}; +use std::time::{Duration, Instant}; + +/// The controllers gilrs sees and the DualSense's output. +#[derive(Default)] +pub(super) struct Devices { + gilrs: Option, + started: bool, + /// The pad last touched; only its input counts. + active: Option, + /// Vibrations playing (an effect stops when dropped) and when they end. + rumbles: Vec<(gilrs::ff::Effect, Instant)>, + /// The active pad is a DualSense. + dualsense: bool, + /// Its own output over HID (rumble here; gilrs only reads it), started once this window + /// has the pad in hand; dropped, it releases the pad. + output: Option, + /// Its HD haptics, on USB: looked for once each time the output opens. + haptics: Option, + haptics_tried: bool, + /// What it was last told to show. + shown: Option, +} + +fn gilrs_button(button: Button) -> gilrs::Button { + use gilrs::Button as G; + match button { + Button::South => G::South, + Button::East => G::East, + Button::West => G::West, + Button::North => G::North, + Button::LeftBumper => G::LeftTrigger, + Button::RightBumper => G::RightTrigger, + Button::LeftTrigger => G::LeftTrigger2, + Button::RightTrigger => G::RightTrigger2, + Button::Select => G::Select, + Button::Start => G::Start, + Button::LeftStick => G::LeftThumb, + Button::RightStick => G::RightThumb, + Button::DPadUp => G::DPadUp, + Button::DPadDown => G::DPadDown, + Button::DPadLeft => G::DPadLeft, + Button::DPadRight => G::DPadRight, + } +} + +fn is_dualsense(pad: &gilrs::Gamepad) -> bool { + matches!((pad.vendor_id(), pad.product_id()), + (Some(vendor), Some(product)) if horizon_dualsense::is_dualsense(vendor, product)) +} + +impl Pads { + /// Open gilrs on first use. A platform without it (or a Linux without + /// udev) leaves controllers off; the game runs as before. + fn start(&mut self) { + if self.devices.started { + return; + } + self.devices.started = true; + self.devices.gilrs = match gilrs::Gilrs::new() { + Ok(g) => { + for (_, pad) in g.gamepads() { + log::info!("Controller connected: {}", pad.name()); + } + Some(g) + } + Err(gilrs::Error::NotImplemented(_)) => None, + Err(e) => { + log::warn!("Horizon: controllers are unavailable: {e}"); + None + } + }; + } + + /// Drain gilrs' events and read the active pad (opening gilrs the first time). + pub(super) fn read(&mut self) -> PadState { + self.start(); + let Some(gilrs) = self.devices.gilrs.as_mut() else { + return PadState::default(); + }; + while let Some(gilrs::Event { id, event, .. }) = gilrs.next_event() { + use gilrs::EventType as E; + match event { + E::Connected => { + log::info!("Controller connected: {}", gilrs.gamepad(id).name()); + if let Some(output) = &self.devices.output { + output.scan(); + } + } + E::Disconnected => { + log::info!("Controller disconnected: {}", gilrs.gamepad(id).name()); + if self.devices.active == Some(id) { + self.devices.active = None; + } + if let Some(output) = &self.devices.output { + output.scan(); + } + } + E::ButtonPressed(..) => self.devices.active = Some(id), + E::AxisChanged(_, value, _) | E::ButtonChanged(_, value, _) + if value.abs() > 0.5 => + { + self.devices.active = Some(id) + } + _ => {} + } + } + let Some(pad) = self + .devices + .active + .and_then(|id| gilrs.connected_gamepad(id)) + else { + // Before any pad is touched (the virtual pad playing), a DualSense still shows it. + self.devices.dualsense = gilrs.gamepads().any(|(_, pad)| is_dualsense(&pad)); + return PadState::default(); + }; + self.style = GlyphStyle::of_vendor(pad.vendor_id()); + self.devices.dualsense = is_dualsense(&pad); + let mut state = PadState::default(); + for button in Button::ALL { + if !matches!(button, Button::LeftTrigger | Button::RightTrigger) { + state.set(button, pad.is_pressed(gilrs_button(button))); + } + } + let axis = |a| pad.value(a); + use gilrs::Axis as A; + state.left = [axis(A::LeftStickX), axis(A::LeftStickY)]; + state.right = [axis(A::RightStickX), axis(A::RightStickY)]; + // Triggers arrive as analog buttons on most mappings, as plain + // buttons on some. + let trigger = |b: gilrs::Button| { + let value = pad.button_data(b).map_or(0.0, |d| d.value()); + if pad.is_pressed(b) { + value.max(1.0) + } else { + value + } + }; + state.triggers = [ + trigger(gilrs::Button::LeftTrigger2), + trigger(gilrs::Button::RightTrigger2), + ]; + state + } +} + +impl Game<'_> { + /// Controllers are turned off: dropping the DualSense's output frees its triggers. + pub(super) fn pad_output_off(&mut self) { + self.pad.devices.output = None; + self.pad.devices.shown = None; + } + + /// After each poll: the DualSense's output opens once this window has the pad in hand, then + /// shows what the game is doing; vibrations that are over stop. + pub(super) fn pad_output_frame(&mut self) { + if self.pad.devices.dualsense + && self.pad.in_use + && self.focused + && self.pad.devices.output.is_none() + { + self.pad.devices.output = Some(horizon_dualsense::Link::start()); + } + self.pad_haptics(); + self.pad_show(); + let now = Instant::now(); + self.pad.devices.rumbles.retain(|(_, end)| *end > now); + } + + /// The DualSense's HID output, while it is the active pad, open, and this window has focus + /// (another game on the same pad keeps it otherwise). + fn pad_output(&self) -> Option<&horizon_dualsense::Link> { + let output = self.pad.devices.output.as_ref()?; + (self.pad.devices.dualsense && self.focused && output.open().is_some()).then_some(output) + } + + /// What the DualSense shows: while playing, its triggers feel what their actions do; in + /// menus, paused, unfocused or with another pad active, they are free. + fn pad_show(&mut self) { + if self.pad.devices.output.is_none() { + return; + } + let playing = self.pad.devices.dualsense + && self.focused + && self.title.is_none() + && self.screen == Screen::Playing + && !self.pause; + let (using, attacking) = if playing { + self.trigger_feels() + } else { + (TriggerFeel::Free, TriggerFeel::Free) + }; + // The lightbar follows the player; menus keep the last colour. + let in_world = self.title.is_none(); + let lightbar = match self.player.as_mut().filter(|_| in_world) { + Some(p) => { + let max = p.attribute("minecraft:max_health").unwrap_or(20.0) as f32; + let health = p.health.health() / max.max(1.0); + self.settings + .controller + .lightbar + .colour(health, self.dim.id()) + } + None => self.pad.devices.shown.and_then(|s| s.lightbar), + }; + let lights = self.settings.controller.lightbar != gamepad::Lightbar::Off; + let state = horizon_dualsense::device::State { + triggers: self.settings.controller.trigger_effects(using, attacking), + lightbar: lightbar.filter(|_| lights), + player_leds: lights.then_some(horizon_dualsense::PLAYER_1), + }; + if self.pad.devices.shown != Some(state) + && let Some(output) = &self.pad.devices.output + { + output.set(state); + self.pad.devices.shown = Some(state); + } + } + + /// What `key.use` and `key.attack` are doing, for the triggers bound to them. + fn trigger_feels(&self) -> (TriggerFeel, TriggerFeel) { + let using = match self.using { + Some((slot, ticks)) => match self.stack_in(slot) { + Some(s) if &*s.item == "minecraft:bow" => { + TriggerFeel::Draw(gamepad::bow_power(ticks)) + } + // TridentItem.THROW_THRESHOLD_TIME. + Some(s) if &*s.item == "minecraft:trident" => { + TriggerFeel::Draw(ticks as f32 / 10.0) + } + Some(s) if &*s.item == "minecraft:crossbow" => { + TriggerFeel::Draw(ticks as f32 / Self::charge_ticks(s).max(1) as f32) + } + Some(s) if self.blocks_attacks(s).is_some() => TriggerFeel::Brace, + _ => TriggerFeel::Free, + }, + None => self.idle_use_feel(), + }; + // Creative breaks at once; blocks that can't be broken have a negative hardness. + let attacking = match &self.mining { + Some(m) if !self.creative => { + let state = self.world.block(m.pos[0], m.pos[1], m.pos[2]); + TriggerFeel::Texture(self.res.facts().get(state).hardness) + } + _ => TriggerFeel::Free, + }; + (using, attacking) + } + + /// The use trigger while nothing is in use: a loaded crossbow clicks, an item that boosts (a + /// rocket while gliding, the stick of the mount being ridden) catches, a shield weighs, and + /// locks while an axe has disabled it. + fn idle_use_feel(&self) -> TriggerFeel { + let gliding = self.player.as_ref().is_some_and(|p| p.fall_flying); + let mount = self + .riding + .and_then(|id| self.mobs.iter().find(|m| m.id == id)); + let mount = mount.map_or("", |m| m.kind.id.as_str()); + let feel = |stack: Option<&horizon_client::items::ItemStack>| match stack + .map(|s| (s, &*s.item)) + { + Some((s, "minecraft:crossbow")) if s.data().is_some_and(|d| !d.charged.is_empty()) => { + TriggerFeel::Click + } + Some((_, "minecraft:firework_rocket")) if gliding => TriggerFeel::Boost, + Some((_, "minecraft:carrot_on_a_stick")) if mount == "minecraft:pig" => { + TriggerFeel::Boost + } + Some((_, "minecraft:warped_fungus_on_a_stick")) if mount == "minecraft:strider" => { + TriggerFeel::Boost + } + Some((s, _)) if self.blocks_attacks(s).is_some() => match self.shield_cooldown { + 0 => TriggerFeel::Brace, + _ => TriggerFeel::Locked, + }, + _ => TriggerFeel::Free, + }; + // Use tries the main hand first. + match feel(self.stack_in(self.selected)) { + TriggerFeel::Free => feel(self.offhand.as_ref()), + main => main, + } + } + + /// Open the pad's haptics once its output is open over USB (its audio device is there + /// only then); close them when it goes. Opt-in with `HORIZON_DUALSENSE_HAPTICS=1` until + /// they are proven on a pad (docs/controllers.md); never for games without sound (tests). + fn pad_haptics(&mut self) { + let usb = self.pad.devices.output.as_ref().and_then(|o| o.open()) + == Some(horizon_dualsense::Transport::Usb); + if !usb { + self.pad.devices.haptics = None; + self.pad.devices.haptics_tried = false; + } else if !self.pad.devices.haptics_tried { + self.pad.devices.haptics_tried = true; + if std::env::var_os("HORIZON_DUALSENSE_HAPTICS").is_some_and(|v| v == "1") + && std::env::var_os("HORIZON_NO_AUDIO").is_none() + { + self.pad.devices.haptics = horizon_dualsense::haptics::Haptics::open(); + } + } + } + + /// Release the DualSense's output (the game is quitting). + pub(in crate::game) fn pad_close_output(&mut self) { + self.pad.devices.haptics = None; + self.pad.devices.output = None; + } + + /// Play a vibration on the active pad: a DualSense through its own report, else gilrs' force + /// feedback, which platforms without it (gilrs on macOS) skip. + pub(super) fn pad_vibrate(&mut self, rumble: Rumble, pulse: gamepad::Pulse) { + let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + if let Some(haptics) = self + .pad + .devices + .haptics + .as_ref() + .filter(|_| self.pad_output().is_some()) + { + let steps = rumble.shape().into_iter().map(|step| { + ( + step.strong, + step.weak, + Duration::from_millis(u64::from(step.millis)), + ) + }); + haptics.play(&steps.collect::>()); + return; + } + if let Some(output) = self.pad_output() { + let steps = rumble.shape().into_iter().map(|step| { + let length = Duration::from_millis(u64::from(step.millis)); + ([level(step.strong), level(step.weak)], length) + }); + output.rumble(steps.collect()); + return; + } + let (Some(gilrs), Some(id)) = (self.pad.devices.gilrs.as_mut(), self.pad.devices.active) + else { + return; + }; + if !gilrs + .connected_gamepad(id) + .is_some_and(|g| g.is_ff_supported()) + { + return; + } + use gilrs::ff::{BaseEffect, BaseEffectType, EffectBuilder, Repeat, Replay, Ticks}; + let length = Ticks::from_ms(pulse.millis); + let motor = |kind| BaseEffect { + kind, + scheduling: Replay { + play_for: length, + ..Default::default() + }, + envelope: Default::default(), + }; + let magnitude = |v: f32| (v.clamp(0.0, 1.0) * f32::from(u16::MAX)) as u16; + let effect = EffectBuilder::new() + .add_effect(motor(BaseEffectType::Strong { + magnitude: magnitude(pulse.strong), + })) + .add_effect(motor(BaseEffectType::Weak { + magnitude: magnitude(pulse.weak), + })) + .repeat(Repeat::For(length)) + .gamepads(&[id]) + .finish(gilrs); + match effect.and_then(|e| e.play().map(|()| e)) { + Ok(effect) => { + let end = Instant::now() + Duration::from_millis(u64::from(pulse.millis) + 50); + self.pad.devices.rumbles.push((effect, end)); + } + Err(e) => log::debug!("Horizon: controller vibration: {e}"), + } + } + + /// The hardware part of `pad status`. + pub(super) fn pad_devices_status(&self) -> Value { + let devices = &self.pad.devices; + let pads: Vec = devices.gilrs.as_ref().map_or(Vec::new(), |g| { + g.gamepads() + .map(|(id, p)| { + json!({ + "name": p.name(), + "vendor": p.vendor_id(), + "product": p.product_id(), + "active": devices.active == Some(id), + }) + }) + .collect() + }); + json!({ + "backend": devices.gilrs.is_some(), + "controllers": pads, + "dualsense_output": devices.output.as_ref().and_then(|o| o.open()).map(|t| format!("{t:?}")), + "trigger_effects": devices.shown.map(|s| s.triggers), + }) + } +} diff --git a/crates/horizon-client/src/game/pad_menu.rs b/crates/horizon-client/src/game/pad_menu.rs index 5c623202b..257586572 100644 --- a/crates/horizon-client/src/game/pad_menu.rs +++ b/crates/horizon-client/src/game/pad_menu.rs @@ -939,7 +939,7 @@ impl Game<'_> { } else if self.screen == Screen::Options { let result = match text { Some(t) => { - self.ui.options.type_text(&self.atlas, t); + self.ui.options.type_text(&self.gui.atlas, t); Ok(()) } None => self.options_key(key.expect("a key"), None), @@ -983,7 +983,7 @@ impl Game<'_> { .focus .is_some_and(|f| f.center().1 > batch.height / 2.0) || self.screen == Screen::Chat; - let mut ui = horizon_client::ui_theme::Ui::new(&self.atlas, batch, self.cursor); + let mut ui = horizon_client::ui_theme::Ui::new(&self.gui.atlas, batch, self.cursor); keyboard.draw(&mut ui, at_top, self.ui.options.pad_style); ui.finish(); return; @@ -998,7 +998,7 @@ impl Game<'_> { return; } // An arrow, outlined, pointing up-left at (x, y). - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (x, y) = (x.floor(), y.floor()); const ROWS: [u8; 10] = [1, 2, 3, 4, 5, 6, 7, 4, 2, 1]; for (i, &w) in ROWS.iter().enumerate() { @@ -1043,7 +1043,7 @@ impl Game<'_> { }; if horizon { use horizon_client::ui_theme::{self as theme, Ui, color}; - let mut ui = Ui::new(&self.atlas, batch, self.cursor); + let mut ui = Ui::new(&self.gui.atlas, batch, self.cursor); let k = ui.batch.scale / ui.density; let (x, y, w, h) = (x * k, y * k, w * k, h * k); let radius = match focus.kind { @@ -1066,7 +1066,7 @@ impl Game<'_> { return; } if matches!(focus.kind, Kind::Row | Kind::Field) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let white = rgba(255, 255, 255, 255); batch.fill(atlas, x, y, w, 1.0, white); batch.fill(atlas, x, y + h - 1.0, w, 1.0, white); diff --git a/crates/horizon-client/src/game/paintings.rs b/crates/horizon-client/src/game/paintings.rs index 2e5542ccc..bd2884575 100644 --- a/crates/horizon-client/src/game/paintings.rs +++ b/crates/horizon-client/src/game/paintings.rs @@ -94,7 +94,7 @@ impl Game<'_> { for x in slo[0].floor() as i32..=shi[0].floor() as i32 { for y in slo[1].floor() as i32..=shi[1].floor() as i32 { for z in slo[2].floor() as i32..=shi[2].floor() as i32 { - let f = self.res.facts.get(self.world.block(x, y, z)); + let f = self.res.facts().get(self.world.block(x, y, z)); if !(f.legacy_solid || f.has_class("DiodeBlock")) { return false; } @@ -249,12 +249,21 @@ impl Game<'_> { /// PaintingRenderer: the variant on the front, the back texture behind and /// on the edges. pub(super) fn painting_geometry(&self, camera: glam::DVec3, out: &mut Vec) { - let sprites = &self.atlas.sprites; + let sprites = &self.gui.atlas.sprites; let Some(back) = sprites.get("painting/back").copied() else { return; }; for p in &self.paintings { let entity_start = out.len(); + // EntityRenderer.shouldRender: the default range and its box, + // measured from the box's centre (HangingEntity's position). + let (lo, hi) = p.bounds(); + let (lo, hi) = (glam::DVec3::from(lo), glam::DVec3::from(hi)); + let range = + super::entity_culling::default_range(hi - lo, self.settings.entity_distance); + if !self.entity_in_view(camera, (lo + hi) / 2.0, range, lo, hi) { + continue; + } let Some(v) = self.painting_variants.get(&p.variant) else { continue; }; diff --git a/crates/horizon-client/src/game/passengers.rs b/crates/horizon-client/src/game/passengers.rs index 27d8a4af6..4e6ba339d 100644 --- a/crates/horizon-client/src/game/passengers.rs +++ b/crates/horizon-client/src/game/passengers.rs @@ -186,9 +186,9 @@ impl Game<'_> { at[2].floor() as i32, ); let frequent = self.world.chunks.get(&(x >> 4, z >> 4)).is_some_and(|c| { - let b = self.res.biomes.get(c.biome(x, y, z)); + let b = self.res.biomes().get(c.biome(x, y, z)); self.res - .mob_data + .mob_data() .biome_has("minecraft:more_frequent_drowned_spawns", &b.name) }); if frequent { diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 96d879f13..7a967a024 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -105,7 +105,9 @@ impl Game<'_> { chunk.saved = Some(Arc::new(extras)); } /// Register a newly resident chunk with the tick scheduler, with the - /// block and fluid ticks it was saved with. + /// block and fluid ticks it was saved with (`LevelChunk.registerTickContainerInLevel` + /// at FULL). They are unpacked when the chunk starts ticking + /// (`start_ticking_chunks`). pub(super) fn register_chunk_ticks(&mut self, key: (i32, i32)) { let pos = ChunkPos::new(key.0, key.1); let saved = self.world.chunks.get(&key).and_then(|c| c.saved.clone()); @@ -130,9 +132,7 @@ impl Game<'_> { .is_ok() && loaded { - let time = self.world.game_time; - self.block_ticks.blocks.unpack_chunk(pos, time); - self.block_ticks.fluids.unpack_chunk(pos, time); + self.tick_chunks.wait(key); } // The saved list is consumed: later saves take the scheduler's ticks. if loaded && let Some(c) = self.world.chunks.get_mut(&key) { @@ -176,7 +176,13 @@ impl Game<'_> { self.dropped.push(e); } } - "minecraft:experience_orb" => self.orbs.extend(entity_nbt::orbs_from_nbt(&tag)), + "minecraft:experience_orb" => { + for mut orb in entity_nbt::orbs_from_nbt(&tag) { + self.next_entity += 1; + orb.id = self.next_entity; + self.orbs.push(orb); + } + } "minecraft:arrow" => { if let Some((mut p, in_block)) = entity_nbt::arrow_from_nbt( &tag, @@ -196,6 +202,7 @@ impl Game<'_> { { let (no_gravity, drop_item) = entity_nbt::falling_block_flags(&tag); self.falling.push(FallingBlock { + id: 0, state, // DATA_START_POS is not persisted by vanilla. start_pos: horizon_core::position::BlockPos::default(), @@ -208,12 +215,29 @@ impl Game<'_> { fall_distance, damage: horizon_client::falling_block::Damage::from_nbt( &tag, - self.res.facts.get(state).name.ends_with("anvil"), + self.res.facts().get(state).name.ends_with("anvil"), ), saved: uuid.map(|u| Box::new((u, tag.clone()))), }); } } + // PrimedTnt.readAdditionalSaveData: its fuse (80 when absent) and motion. + "minecraft:tnt" => { + if let Some(position) = entity_nbt::position(&tag) { + let fuse = match tag.get("fuse") { + Some(Tag::Short(f)) => i32::from(*f), + _ => 80, + }; + self.tnts.push(super::tnt::PrimedTnt { + id: 0, + position, + previous: position, + velocity: entity_nbt::motion(&tag), + fuse, + on_ground: matches!(tag.get("OnGround"), Some(Tag::Byte(1))), + }); + } + } k if super::boats::any_boat_wood(k) .is_some_and(|(wood, chest)| self.boat_models.has(wood, chest)) => { @@ -297,7 +321,7 @@ impl Game<'_> { self.persist.unknown.entry(key).or_default().push(tag); } } - _ if self.res.mob_types.contains_key(&kind) => { + _ if self.res.mob_types().contains_key(&kind) => { self.load_mob(tag, None); } _ if !kind.is_empty() && entity_nbt::position(&tag).is_some() => { @@ -322,7 +346,7 @@ impl Game<'_> { if let Some(Tag::List(list)) = c.remove(&"Passengers".into()) { for p in list { let known = - entity_nbt::kind(&p).is_some_and(|k| self.res.mob_types.contains_key(&k)); + entity_nbt::kind(&p).is_some_and(|k| self.res.mob_types().contains_key(&k)); if known { riders.push(p); } else { @@ -334,7 +358,7 @@ impl Game<'_> { c.insert("Passengers".into(), Tag::List(unknown)); } } - let mut m = entity_nbt::mob_from_nbt(&tag, &self.res.mob_types, self.next_entity)?; + let mut m = entity_nbt::mob_from_nbt(&tag, self.res.mob_types(), self.next_entity)?; m.extra.mount = mount; m.extra.passenger = mount.is_some(); if finalize { diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index 4214bdd70..cdc7fa2d8 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -266,7 +266,7 @@ impl Game<'_> { binding: self.collision, subject: None, }, - facts: &self.res.facts, + facts: self.res.facts(), context, }; view.align_with_entity(&entity, partial, kind, |from, to| { @@ -296,7 +296,7 @@ impl Game<'_> { return; }; if self.player_model.is_none() { - let Some(kind) = self.res.player_type.clone() else { + let Some(kind) = self.res.player_type().clone() else { return; }; self.player_model = Some(Mob::new(0, kind, p.position, self.yaw)); @@ -430,7 +430,7 @@ impl Game<'_> { m.position.z.floor() as i32, ); let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); horizon_client::mobs::render::render_with( m, @@ -438,7 +438,7 @@ impl Game<'_> { camera, &lookup, packed, - &self.res.mob_data, + self.res.mob_data(), &self.player_armor_layers(), out, ); @@ -484,7 +484,7 @@ impl Game<'_> { m.position.y += 0.125 * f64::from(u8::from(m.extra.crouching)); m.previous = m.position; let camera = glam::DVec3::new(m.position.x, m.position.y, m.position.z); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); let mut verts = Vec::new(); horizon_client::mobs::render::render_with( @@ -493,7 +493,7 @@ impl Game<'_> { camera, &lookup, 240 | 240 << 8, - &self.res.mob_data, + self.res.mob_data(), &self.player_armor_layers(), &mut verts, ); @@ -546,7 +546,7 @@ impl Game<'_> { ) { let Some(asset) = self.armor[1] .as_ref() - .and_then(|s| self.res.items.get(&s.item)) + .and_then(|s| self.res.items().get(&s.item)) .and_then(|i| i.equip_asset.as_ref()) else { return; @@ -555,9 +555,10 @@ impl Game<'_> { let Some((texture, _)) = assets.equipment.get(asset).and_then(|k| k.get("wings")) else { return; }; - let (Some(model), Some(rect)) = - (assets.player.get("elytra"), self.atlas.sprites.get(texture)) - else { + let (Some(model), Some(rect)) = ( + assets.player.get("elytra"), + self.gui.atlas.sprites.get(texture), + ) else { return; }; let base = horizon_client::mobs::render::base_transform(m, partial, camera) diff --git a/crates/horizon-client/src/game/pickups.rs b/crates/horizon-client/src/game/pickups.rs index 2729dc98f..1e19bcfc3 100644 --- a/crates/horizon-client/src/game/pickups.rs +++ b/crates/horizon-client/src/game/pickups.rs @@ -148,6 +148,7 @@ mod tests { fn orb_at(x: f64, y: f64, z: f64) -> Taken { let at = horizon_core::geometry::Vec3::new(x, y, z); Taken::Orb(Box::new(ExperienceOrb { + id: 0, position: at, previous: at, velocity: horizon_core::geometry::Vec3::new(0.0, 0.0, 0.0), diff --git a/crates/horizon-client/src/game/piglins.rs b/crates/horizon-client/src/game/piglins.rs index 3515b380b..9df5311aa 100644 --- a/crates/horizon-client/src/game/piglins.rs +++ b/crates/horizon-client/src/game/piglins.rs @@ -11,14 +11,18 @@ use horizon_core::random::RandomSource; impl Game<'_> { fn piglin_loved(&self, item: &str) -> bool { self.res - .items + .items() .item_tags .get("minecraft:piglin_loved") .is_some_and(|t| t.contains(item)) } /// `PiglinAi.isWearingSafeArmor`. pub(super) fn wearing_gold(&self) -> bool { - let tag = self.res.items.item_tags.get("minecraft:piglin_safe_armor"); + let tag = self + .res + .items() + .item_tags + .get("minecraft:piglin_safe_armor"); self.armor .iter() .flatten() @@ -119,7 +123,7 @@ impl Game<'_> { let m = &self.mobs[i]; let from = [m.position.x, m.position.y + 1.3, m.position.z]; let items = if &*item == "minecraft:gold_ingot" && !m.is_baby() { - self.res.items.loot_table( + self.res.items().loot_table( "minecraft:gameplay/piglin_bartering", false, None, @@ -191,7 +195,7 @@ impl Game<'_> { ]; !self .res - .facts + .facts() .get(self.world.block( p[0].floor() as i32, p[1].floor() as i32, @@ -203,7 +207,7 @@ impl Game<'_> { /// Whether breaking or opening this block angers piglins. pub(super) fn guarded_by_piglins(&self, name: &str) -> bool { self.res - .items + .items() .block_tags .get("minecraft:guarded_by_piglins") .is_some_and(|t| t.contains(name)) diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index bc4f3b6bc..51cb1fc0a 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -169,7 +169,7 @@ impl Game<'_> { return Ok(false); }; let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); - if self.res.facts.get(state).fluid != horizon_client::blocks::Fluid::Water { + if self.res.facts().get(state).fluid != horizon_client::blocks::Fluid::Water { return Ok(false); } let at = [ @@ -369,11 +369,11 @@ impl Game<'_> { let armor: Vec> = self.armor.to_vec(); if self.potions.protection_for.as_ref() != Some(&armor) { let mut table = Vec::new(); - let e = &self.res.stations.enchantments; + let e = &self.res.stations().enchantments; let mut random = horizon_core::random::LegacyRandom::new(0); for (_, def) in self.motion.health.damage.entries() { let ctx = horizon_client::enchant::EffectContext { - items: Some(&self.res.items), + items: Some(self.res.items()), damage_type: Some(&def.name), this: Some("minecraft:player"), ..Default::default() @@ -429,7 +429,7 @@ impl Game<'_> { let state = self.world .block(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); - if self.res.facts.get(state).full_collision + if self.res.facts().get(state).full_collision || self.mobs.iter().any(|m| { m.alive() && (m.position.x - p.x).abs() < m.kind.width / 2.0 + 0.125 @@ -587,7 +587,7 @@ impl Game<'_> { // `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 undead = &self.res.stations().enchantments.entity_tags; let mut hits = Vec::new(); for (i, m) in self.mobs.iter().enumerate() { let d2 = (m.position.x - at.x).powi(2) @@ -644,7 +644,7 @@ impl Game<'_> { .map(hud_overlays::EffectIcon::from) .collect(); let draws = hud_overlays::effects(batch.width as i32, false, &icons); - hud_layout::paint(batch, &self.atlas, &draws); + hud_layout::paint(batch, &self.gui.atlas, &draws); } /// `EffectsInInventory`: panels to the right of survival/creative inventory. pub(super) fn draw_inventory_effects( @@ -660,11 +660,11 @@ impl Game<'_> { &self.potions.effects.list, self.clock.rate(), &|key| self.pack.names.get(key).map(str::to_owned), - &|text| self.atlas.font.width(text).ceil() as i32, + &|text| self.gui.atlas.font.width(text).ceil() as i32, ); if let Some(lines) = inventory_effects::paint( batch, - &self.atlas, + &self.gui.atlas, &panels, [self.cursor.0 as i32, self.cursor.1 as i32], ) { diff --git a/crates/horizon-client/src/game/powder_snow.rs b/crates/horizon-client/src/game/powder_snow.rs index 7d0a7770d..6a904706f 100644 --- a/crates/horizon-client/src/game/powder_snow.rs +++ b/crates/horizon-client/src/game/powder_snow.rs @@ -68,7 +68,7 @@ impl Game<'_> { pub(super) fn is_powder_snow(&self, pos: [i32; 3]) -> bool { &*self .res - .facts + .facts() .get(self.world.block(pos[0], pos[1], pos[2])) .name == "minecraft:powder_snow" diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index 25a440af3..8c31ca25b 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -100,7 +100,7 @@ impl RaidLevel for Lvl<'_, '_> { let w = g.mob_world_base(&[]); spawn_rules::is_spawn_position_ok(Species::Ravager, &w, x, y, z) || w.block_name(x, y - 1, z) == "minecraft:snow" - && g.res.facts.is_air(g.world.block(x, y, z)) + && g.res.facts().is_air(g.world.block(x, y, z)) } fn player(&self) -> Option { let p = self.game.player.as_ref()?; @@ -221,7 +221,7 @@ impl Game<'_> { let top = if self.dim == Dim::Nether { 127 } else { 319 }; (horizon_client::chunk::MIN_Y..=top) .rev() - .find(|&y| !self.res.facts.is_air(self.world.block(x, y, z))) + .find(|&y| !self.res.facts().is_air(self.world.block(x, y, z))) .map_or(horizon_client::chunk::MIN_Y, |y| y + 1) } /// Every claimed village point of interest (job sites, beds, bells). @@ -356,7 +356,7 @@ impl Game<'_> { .get(&(at[0] >> 4, at[2] >> 4)) .map(|c| { self.res - .biomes + .biomes() .get(c.biome(at[0], at[1], at[2])) .name .clone() @@ -716,7 +716,7 @@ impl Game<'_> { leader: bool, reason: raider::Reason, ) -> Option { - let t = self.res.mob_types.get(kind).cloned()?; + let t = self.res.mob_types().get(kind).cloned()?; self.next_entity += 1; let mut mob = Mob::new(self.next_entity, t, Vec3::new(at[0], at[1], at[2]), 0.0); if leader { @@ -982,11 +982,11 @@ impl Game<'_> { for z in c[2] - 64..=c[2] + 64 { for x in c[0] - 64..=c[0] + 64 { let state = self.world.block(x, y, z); - if self.res.facts.is_air(state) { + if self.res.facts().is_air(state) { continue; } let bed = *known.entry(state.0).or_insert_with(|| { - self.res.facts.get(state).name.ends_with("_bed") + self.res.facts().get(state).name.ends_with("_bed") && self.pack.assets.registry.state(state).is_some_and(|s| { s.properties.get("part").map(String::as_str) == Some("head") }) @@ -1121,7 +1121,7 @@ impl Game<'_> { pub(super) fn throw_gift(&mut self, table: &str, from: [f64; 3], to: [f64; 3]) { let drops = self .res - .items + .items() .loot_table(table, false, None, &mut self.world.random); let d = Vec3::new(to[0] - from[0], to[1] - from[1], to[2] - from[2]).normalize(); for stack in drops { @@ -1163,7 +1163,7 @@ impl Game<'_> { .get(&(at[0] >> 4, at[2] >> 4)) .map(|c| { game.res - .biomes + .biomes() .get(c.biome(at[0], at[1], at[2])) .name .clone() diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 706c8d73e..843c01476 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -205,7 +205,7 @@ impl Game<'_> { return; } self.ensure_book(); - let index = &self.res.stations.recipe_index; + let index = &self.res.stations().recipe_index; let book = self.recipe_ui.book.as_ref(); // SmithingTrimDemoSlotDisplay draws from a random of its own. let mut random = super::dispenser::entity_random(); @@ -224,8 +224,8 @@ impl Game<'_> { }) .or_else(|| index.result(id).map(|r| ItemStack::new(r, 1))) .or_else(|| { - self.res.stations.recipes.trim_demo( - &self.res.stations.enchantments, + self.res.stations().recipes.trim_demo( + &self.res.stations().enchantments, id, &mut |n| { horizon_core::random::RandomSource::next_int_bound( @@ -275,10 +275,10 @@ impl Game<'_> { Kind::Inventory }); let env = Env { - items: &self.res.items, - recipes: &self.res.recipes, - brewing: &self.res.stations.brewing, - banners: &self.res.stations.banners, + items: self.res.items(), + recipes: self.res.recipes(), + brewing: &self.res.stations().brewing, + banners: &self.res.stations().banners, trade: None, }; for i in 0..36 { @@ -306,7 +306,7 @@ impl Game<'_> { return; } let known = &self.level.recipe_book.recipes; - let index = &self.res.stations.recipe_index; + let index = &self.res.stations().recipe_index; let ui = &mut self.recipe_ui; match ui.client_known.as_ref() { Some(previous) if previous == known => return, @@ -336,8 +336,8 @@ impl Game<'_> { } fn ensure_book(&mut self) { if self.recipe_ui.book.is_none() { - let mut book = Book::build(&self.res.recipes, &self.res.items); - book.set_display_ids(&self.res.stations.recipe_index); + let mut book = Book::build(self.res.recipes(), self.res.items()); + book.set_display_ids(&self.res.stations().recipe_index); self.recipe_ui.book = Some(book); } if self.recipe_ui.search.is_none() { @@ -497,7 +497,7 @@ impl Game<'_> { && !book.collection_matches(&c.entries, &query, &|stack| { horizon_client::item_tooltip::lines( stack, - self.res.items.get(&stack.item), + self.res.items().get(&stack.item), &|k| self.pack.names.get(k).map(str::to_owned), ) }) @@ -660,7 +660,7 @@ impl Game<'_> { search.focused = true; search.reset_blink(); if !magnifier { - let idx = search.index_at(&self.atlas, cursor.0); + let idx = search.index_at(&self.gui.atlas, cursor.0); search.set_cursor(idx, false); } return true; @@ -895,7 +895,7 @@ impl Game<'_> { ui.client.highlight.insert(e.id); } if e.flags & 1 != 0 - && let Some(id) = self.res.stations.recipe_index.recipe_of_display(e.id) + && let Some(id) = self.res.stations().recipe_index.recipe_of_display(e.id) && !toast.iter().any(|t| t == id) { toast.push(id.to_owned()); @@ -959,7 +959,7 @@ impl Game<'_> { return; }; let ghost = book - .ghost(entry, book_type, grid, fuel_empty, &self.res.items) + .ghost(entry, book_type, grid, fuel_empty, self.res.items()) .into_iter() .map(|g| Ghost { slot: match (g.target, book_type) { @@ -992,7 +992,7 @@ impl Game<'_> { let (bx, by) = self.book_button_pos(book_type, ox, batch); let hover = inside(cursor, bx, by, 20.0, 18.0); batch.sprite( - &self.atlas, + &self.gui.atlas, &sprite(if hover { "button_highlighted" } else { @@ -1040,7 +1040,7 @@ impl Game<'_> { fn draw_book_panel(&mut self, batch: &mut HudBatch, book_type: BookType) { let (xo, yo) = self.book_origin(batch); let cursor = self.cursor; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let search = match self.recipe_ui.search.as_mut() { Some(edit) => { // The box's place, for clicks and typing. @@ -1163,7 +1163,7 @@ impl Game<'_> { let mut tooltip: Option> = None; for d in calls { let start = batch.vertices.len(); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; match &d.call { Call::Blit { x, y, w, h, u, v, .. diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 089748295..36c9fe4f3 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -11,15 +11,17 @@ use horizon_client::{ Result, chunk::{BIOME_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, Section, block_strategy}, containers::{BlockEntity, Furnace, FurnaceKind}, - entities::{Experience, ItemEntity}, + entities::{Experience, ExperienceOrb, ItemEntity}, hud::{HudBatch, rgba}, items::ItemStack, - mobs::{Mob, MobType}, + menu::Input, + mobs::{Mob, MobType, Who}, motion::{MotionWorld, PlayerMotion}, net::{Event, Session}, save::SaveDir, sprint::Keys, streaming::{ChunkGenerator, Proto, Streaming}, + tab_list::SPECTATOR, world::World, }; use horizon_core::{ @@ -38,13 +40,18 @@ use horizon_protocol::{ text::{Language, format_java, plain}, }; use horizon_world::{nbt::Tag, registry::BlockStateId}; -use std::{ - collections::HashMap, - sync::Arc, - time::{Duration, Instant}, -}; +use std::{collections::HashMap, sync::Arc, time::Instant}; use winit::{event::MouseButton, keyboard::KeyCode}; +/// A text component the server sent, for the HUD. +fn remote_text(tag: &Tag) -> horizon_client::text::Text { + use horizon_client::scoreboard::{comp_text, tag_to_json}; + comp_text(&tag_to_json(tag)) +} + +/// A section's sky and block light layers from the wire. +type LightLayers = (Option>, Option>); + /// Streaming needs a generator; a server world never generates. struct NoTerrain; impl ChunkGenerator for NoTerrain { @@ -65,8 +72,11 @@ struct Tracked { } /// Smooth an entity toward a new position over three ticks (InterpolationHandler). #[derive(Clone, Copy)] +/// `LinearInterpolationHandler`'s target: a position and rotation (yRot, +/// xRot) reached in `steps` ticks. struct Lerp { target: [f64; 3], + rotation: Option<(f32, f32)>, steps: u32, } @@ -75,7 +85,7 @@ pub(super) struct Remote { pub brand: String, builtin: Arc, lang: Arc, - registries: Arc, + pub(super) registries: Arc, joined: bool, status: String, entity_id: i32, @@ -84,15 +94,13 @@ pub(super) struct Remote { biome_bits: u8, view_distance: i32, sequence: i32, - last_pos: [f64; 3], - last_rot: (f32, f32), - last_on_ground: bool, - last_collision: bool, - reminder: u32, + position_sender: horizon_client::player_sync::PositionSender, last_input: u8, was_sprinting: bool, carried: Option, loaded_sent: bool, + /// The view distance last sent in ClientInformation. + sent_view: i8, /// BlockStatePredictionHandler: blocks changed ahead of the server (a predicted break), /// with the sequence of the last action that changed them and the state the server /// last said they have. Until the server acknowledges that sequence its block updates @@ -106,14 +114,17 @@ pub(super) struct Remote { use_target: Option<[i32; 3]>, entities: HashMap, lerps: HashMap, + /// `LivingEntity.lerpHeadTo`: the head yaw and the ticks left to reach it. + head_lerps: HashMap, /// Item entities waiting for their item data. pending_items: HashMap, health: (f32, i32, f32), game_mode: i32, pub chat: Vec<(String, Instant)>, + /// Lines received since joining, for the control socket's events. + pub chat_received: u64, /// The server's command tree (ClientboundCommandsPacket). pub commands: Option, - action_bar: Option<(String, Instant)>, players: HashMap, /// `ClientPacketListener.playerInfoMap` as player-list entries, and /// which of them are listed. @@ -129,6 +140,8 @@ pub(super) struct Remote { profile: u128, destroying: Option<([i32; 3], u8, f32)>, destroy_delay: u32, + input: horizon_client::interaction_input::InteractionInput, + stop_mining: bool, placing: Option<([i32; 3], u64)>, death_message: Option, player_type: Option>, @@ -136,7 +149,12 @@ pub(super) struct Remote { synced: Vec>, decode_errors: u32, clock: Option, + /// `ClientClockManager.ClientClockInstance`'s rate and partial tick for + /// the level's clock (its total is `world.day_time`), and + /// `lastTickGameTime`. clock_rate: f32, + clock_partial: f32, + clock_game_time: i64, /// `ClientChunkCache.Storage`'s view centre (ClientboundSetChunkCacheCenterPacket). chunk_center: (i32, i32), } @@ -166,6 +184,13 @@ fn number_format(f: &play::NumberFormat) -> horizon_client::scoreboard::NumberFo impl Game<'_> { /// Leave the title for a server (ConnectScreen): an empty world fed by the connection. pub(super) fn connect_server(&mut self, address: &str, name: &str) -> Result<()> { + if self.defer_world_entry(super::PendingWorldEntry::Server { + address: address.to_owned(), + name: name.to_owned(), + })? { + return Ok(()); + } + self.join_world_rest()?; if let Err(error) = self.join_server(address, name, None) { log::warn!("Horizon: could not join server: {error}"); if self.title.is_none() { @@ -201,7 +226,7 @@ impl Game<'_> { .and_then(|p| Builtin::load(&p).ok()) .ok_or("Resources are incomplete: registries.json is missing or invalid. Click \"Prepare again\" in the launcher (or run horizon-prepare), then try again.")?; let lang = Arc::new(horizon_client::net::load_language(&root)); - let view = self.settings.render_distance.clamp(2, 32) as i8; + let view = client_view_distance(self.settings.render_distance); if local.is_none() { horizon_client::crash::set_detail( "Server", @@ -222,12 +247,12 @@ impl Game<'_> { let mut streaming = Streaming::new( Arc::new(NoTerrain), self.pack.context.clone(), - self.res.threads, + self.res.threads(), ); streaming.remote = true; streaming.radius = self.settings.render_distance; self.streaming = streaming; - self.world = World::new(self.res.facts.air, 0); + self.world = World::new(self.res.facts().air, 0); self.save = Arc::new(SaveDir::new( std::env::temp_dir().join("horizon-remote-unused"), )); @@ -238,6 +263,8 @@ impl Game<'_> { self.player = None; self.spawn = None; self.mobs.clear(); + self.clear_remote_objects(); + self.clear_remote_projectiles(); self.creatures.projectiles.clear(); self.dropped.clear(); self.particles.clear(); @@ -249,6 +276,7 @@ impl Game<'_> { self.container = None; self.carried = None; self.using = None; + self.clicks.miss_time = 0; self.set_mode_id(0); self.experience = Experience { level: 0, @@ -277,15 +305,12 @@ impl Game<'_> { biome_bits: 7, view_distance: self.settings.render_distance, sequence: 0, - last_pos: [0.0; 3], - last_rot: (0.0, 0.0), - last_on_ground: false, - last_collision: false, - reminder: 0, + position_sender: Default::default(), last_input: 0, was_sprinting: false, carried: None, loaded_sent: false, + sent_view: view, predictions: HashMap::new(), menu: None, menu_title: None, @@ -293,12 +318,13 @@ impl Game<'_> { use_target: None, entities: HashMap::new(), lerps: HashMap::new(), + head_lerps: HashMap::new(), pending_items: HashMap::new(), health: (20.0, 20, 5.0), game_mode: 0, chat: Vec::new(), + chat_received: 0, commands: None, - action_bar: None, players: HashMap::new(), tab_players: HashMap::new(), skin_textures: HashMap::new(), @@ -308,6 +334,8 @@ impl Game<'_> { profile: 0, destroying: None, destroy_delay: 0, + input: Default::default(), + stop_mining: false, placing: None, death_message: None, player_type, @@ -315,6 +343,8 @@ impl Game<'_> { decode_errors: 0, clock: None, clock_rate: 1.0, + clock_partial: 0.0, + clock_game_time: 0, chunk_center: (0, 0), }); // The level's TickRateManager follows the server's ticking packets. @@ -352,9 +382,11 @@ impl Game<'_> { self.score.board = Default::default(); self.streaming = Streaming::new(Arc::new(NoTerrain), self.pack.context.clone(), 1); self.streaming.paused = true; - self.world = World::new(self.res.facts.air, 0); + self.world = World::new(self.res.facts().air, 0); self.player = None; self.mobs.clear(); + self.clear_remote_objects(); + self.clear_remote_projectiles(); self.dropped.clear(); self.particles.clear(); self.pickups.clear(); @@ -437,7 +469,7 @@ impl Game<'_> { .and_then(|i| i.id(name)) .unwrap_or(0) } - fn to_stack(&self, s: &Option) -> Option { + pub(super) fn to_stack(&self, s: &Option) -> Option { let s = s.as_ref()?; let mut out = ItemStack { item: self.item_name(s.item), @@ -469,6 +501,7 @@ impl Game<'_> { log::info!("[chat] {text}"); if let Some(r) = self.remote.as_mut() { r.chat.push((text, Instant::now())); + r.chat_received += 1; if r.chat.len() > 100 { r.chat.remove(0); } @@ -550,15 +583,65 @@ impl Game<'_> { break; } } + self.send_suggestion_request(); Ok(()) } + /// ClientSuggestionProvider.customSuggestion: the chat's completion + /// request for an `ask_server` node goes to the server. + fn send_suggestion_request(&mut self) { + if self.remote.is_none() { + return; + } + let Some((id, command)) = self.ui.chat_screen.as_mut().and_then(|s| s.take_request()) + else { + return; + }; + let mut w = horizon_protocol::buf::Writer::new(); + w.varint(id); + w.string(&command); + self.send(S::Unknown( + horizon_protocol::ids::play::serverbound::COMMAND_SUGGESTION, + w.data, + )); + } + /// ClientboundCommandSuggestionsPacket: id, range start and length, then + /// each suggestion's text and optional tooltip. + fn handle_command_suggestions(&mut self, data: &[u8]) { + let lang = self + .remote + .as_ref() + .map(|r| r.lang.clone()) + .unwrap_or_default(); + let mut r = horizon_protocol::buf::Reader::new(data); + let decoded = (|| { + let id = r.varint()?; + let start = r.varint()?; + let length = r.varint()?; + let n = r.count(usize::MAX)?; + let mut list = Vec::with_capacity(n.min(1000)); + for _ in 0..n { + let text = r.string(32767)?; + let tooltip = if r.bool()? { + Some(plain(&r.nbt()?, &lang)) + } else { + None + }; + list.push((text, tooltip)); + } + horizon_protocol::Result::Ok((id, start, length, list)) + })(); + if let Ok((id, start, length, list)) = decoded { + let range = (start.max(0) as usize, length.max(0) as usize); + self.chat_server_suggestions(id, range, list); + } + } fn set_registries(&mut self, registries: Arc) { let biomes: Vec = registries .registries .get("minecraft:worldgen/biome") .map(|list| { list.iter() - .map(|(name, _)| self.res.biomes.id(name)) + .map(|(name, _)| self.res.biomes().id(name)) .collect() }) .unwrap_or_default(); @@ -578,6 +661,8 @@ impl Game<'_> { r.dimension = dimension; r.game_mode = spawn.game_type; r.loaded_sent = false; + // A replacement LocalPlayer has a fresh sendPosition baseline. + r.position_sender = Default::default(); r.predictions.clear(); self.set_mode_id(spawn.game_type); self.dim = Dim::from_id(&spawn.dimension); @@ -585,7 +670,7 @@ impl Game<'_> { let mut streaming = Streaming::new( Arc::new(NoTerrain), self.pack.context.clone(), - self.res.threads, + self.res.threads(), ); streaming.remote = true; streaming.radius = self.streaming.radius; @@ -595,17 +680,20 @@ impl Game<'_> { self.world.day_time, self.world.weather, ); - self.world = World::new(self.res.facts.air, spawn.seed); + self.world = World::new(self.res.facts().air, spawn.seed); self.world.game_time = time; self.world.day_time = day; self.world.weather = weather; self.mobs.clear(); + self.clear_remote_objects(); + self.clear_remote_projectiles(); self.dropped.clear(); self.particles.clear(); self.pickups.clear(); if let Some(r) = self.remote.as_mut() { r.entities.clear(); r.lerps.clear(); + r.head_lerps.clear(); r.pending_items.clear(); // A new ClientLevel: a new chunk storage, centred on 0, 0. r.chunk_center = (0, 0); @@ -703,8 +791,64 @@ impl Game<'_> { PalettedContainer::from_values(BIOME_STRATEGY, &cells); } } + // ClientPacketListener.applyLightData: the column keeps the light + // the server sent; nothing is relit. + let (layers, above) = self.wire_light(&p.light); + let sky = r.dimension.has_skylight; + horizon_client::light::light_from_layers(&mut chunk, &layers, above, sky); Ok(chunk) } + /// `ClientPacketListener.readSectionList`: the sky and block layers of a + /// light packet, by section of the client's column, and the sky light + /// above the column's top section (from the light section just above + /// it, else open sky). + fn wire_light( + &self, + light: &horizon_protocol::chunk::LightData, + ) -> (Vec, [u8; 256]) { + let mut layers: Vec = vec![(None, None); SECTIONS]; + let Some(r) = self.remote.as_ref() else { + return (layers, [0; 256]); + }; + let sky = r.dimension.has_skylight; + let mut above = [if sky { 15 } else { 0 }; 256]; + // Light section b is the dimension's section b - 1. + let first = (r.dimension.min_y - MIN_Y).div_euclid(16) - 1; + for (b, layer) in light + .layers(r.dimension.sections() + 2) + .into_iter() + .enumerate() + { + let si = first + b as i32; + if (0..SECTIONS as i32).contains(&si) { + layers[si as usize] = layer; + } else if si == SECTIONS as i32 + && sky + && let Some(l) = &layer.0 + { + for (i, a) in above.iter_mut().enumerate() { + *a = (l[i >> 1] >> ((i & 1) * 4)) & 15; + } + } + } + (layers, above) + } + /// `handleLightUpdatePacket`: the sections it names take its light. + fn remote_light_update(&mut self, p: &play::LightUpdate) { + let Some(sky) = self.remote.as_ref().map(|r| r.dimension.has_skylight) else { + return; + }; + if !self.world.chunks.contains_key(&(p.x, p.z)) { + return; + } + let (layers, _) = self.wire_light(&p.light); + let Some(chunk) = self.world.chunks.get_mut(&(p.x, p.z)) else { + return; + }; + let changed = + horizon_client::light::update_light_layers(Arc::make_mut(chunk), &layers, sky); + Streaming::light_updated(&mut self.world, p.x, p.z, &changed); + } /// `ClientChunkCache.Storage.inRange`: within the storage around the /// view centre, `calculateStorageRange` (the server's radius, at least /// two, plus three) chunks each way. @@ -799,6 +943,7 @@ impl Game<'_> { 0 => { if me { self.sleeping = None; + self.sleep_timer = 100; } return; } @@ -829,7 +974,7 @@ impl Game<'_> { } /// Keep the renderable block entities (chests, furnaces) in step with blocks. fn sync_block_entity(&mut self, pos: (i32, i32, i32), state: BlockStateId) { - let name = self.res.facts.get(state).name.clone(); + let name = self.res.facts().get(state).name.clone(); match BlockEntity::for_block(&name) { Some(entity) => { let same = self @@ -892,9 +1037,9 @@ impl Game<'_> { // A block we just placed: play its place sound (the server skips the placer). if let Some((target, _)) = self.remote.as_ref().and_then(|r| r.placing) && target == pos - && !self.res.facts.is_air(state) + && !self.res.facts().is_air(state) { - let s = self.res.facts.get(state).sounds.clone(); + let s = self.res.facts().get(state).sounds.clone(); let at = [ f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, @@ -907,17 +1052,33 @@ impl Game<'_> { } } } - fn spawn_entity(&mut self, id: i32, kind: &str, position: [f64; 3], yaw: f32, head: f32) { + /// `recreateFromPacket`: yRot and xRot from the packet, the body and head + /// both at its head yaw (LivingEntity). + fn spawn_entity(&mut self, id: i32, kind: &str, position: [f64; 3], rotation: [f32; 3]) { + let [yaw, pitch, head] = rotation; let at = Vec3::new(position[0], position[1], position[2]); let mob_type = if kind == "minecraft:player" { self.remote.as_ref().and_then(|r| r.player_type.clone()) } else { - self.res.mob_types.get(kind).cloned() + self.res.mob_types().get(kind).cloned() }; + if kind == "minecraft:experience_orb" { + // Its value (ExperienceOrb.DATA_VALUE) follows in SetEntityData. + self.orbs.retain(|o| o.id != id as u32); + self.orbs.push(ExperienceOrb { + id: id as u32, + position: at, + previous: at, + velocity: Vec3::ZERO, + value: 1, + age: 0, + on_ground: false, + }); + } if let Some(t) = mob_type { let mut mob = Mob::new(id as u32, t, at, head); - mob.body_yaw = yaw; - mob.previous_body_yaw = yaw; + (mob.yaw, mob.previous_yaw) = (yaw, yaw); + (mob.head_pitch, mob.previous_head_pitch) = (pitch, pitch); mob.persistent = true; self.mobs.retain(|m| m.id != id as u32); self.mobs.push(mob); @@ -942,14 +1103,21 @@ impl Game<'_> { rotation: Option<(f32, f32)>, on_ground: bool, ) { + let mob = self.mobs.iter_mut().find(|m| m.id == id as u32); if let Some(r) = self.remote.as_mut() { if let Some(t) = r.entities.get_mut(&id) { t.position = position; } + // AbstractInterpolationHandler.interpolateTo: without a rotation, + // the one it was heading for (or has). + let rotation = rotation + .or_else(|| r.lerps.get(&id).and_then(|l| l.rotation)) + .or_else(|| mob.as_ref().map(|m| (m.yaw, m.head_pitch))); r.lerps.insert( id, Lerp { target: position, + rotation, steps: 3, }, ); @@ -957,34 +1125,38 @@ impl Game<'_> { *p = position; } } - if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) { + if let Some(m) = mob { m.on_ground = on_ground; - if let Some((yaw, pitch)) = rotation { - m.body_yaw = yaw; - m.head_pitch = pitch; - } } + self.turn_remote_object(id, rotation.map(|(yaw, _)| yaw), on_ground); + self.turn_remote_projectile(id, rotation); } fn remove_entity(&mut self, id: i32) { self.mobs.retain(|m| m.id != id as u32); + self.orbs.retain(|o| o.id != id as u32); self.dropped.retain(|d| d.id != id as u32); + self.remove_remote_object(id as u32); + self.remove_remote_projectile(id as u32); if let Some(r) = self.remote.as_mut() { r.entities.remove(&id); r.lerps.remove(&id); + r.head_lerps.remove(&id); r.pending_items.remove(&id); } } /// Map a menu slot to Horizon's inventory screen slot ids. fn menu_slot(menu: &str, slot: i32) -> Option { let s = usize::try_from(slot).ok()?; - let rows = |n: usize| -> Option { + // A container of `n` slots, then the inventory and the hotbar. + let slots = |n: usize| -> Option { match s { - _ if s < n * 9 => Some(300 + s), - _ if s < n * 9 + 27 => Some(9 + s - n * 9), - _ if s < n * 9 + 36 => Some(s - n * 9 - 27), + _ if s < n => Some(300 + s), + _ if s < n + 27 => Some(9 + s - n), + _ if s < n + 36 => Some(s - n - 27), _ => None, } }; + let rows = |n: usize| slots(n * 9); match menu { "inventory" => match s { 0 => Some(200), @@ -1022,6 +1194,10 @@ impl Game<'_> { "minecraft:generic_9x4" => rows(4), "minecraft:generic_9x5" => rows(5), "minecraft:generic_9x6" => rows(6), + // HopperMenu; DispenserMenu (dispensers and droppers). + "minecraft:hopper" => slots(5), + "minecraft:generic_3x3" => slots(9), + "minecraft:brewing_stand" => slots(5), _ => None, } } @@ -1047,6 +1223,9 @@ impl Game<'_> { fn handle_packet(&mut self, packet: C) -> Result<()> { match packet { + // ClientCommonPacketListenerImpl.handlePing runs on the game + // thread, after all preceding packets (especially teleports). + C::Ping(p) => self.send(S::Pong(p)), // PingDebugMonitor.onPongReceived. C::PongResponse(p) => { let delay = self.debug_millis() - p.time; @@ -1062,10 +1241,12 @@ impl Game<'_> { self.streaming.radius = self.settings.render_distance.min(p.chunk_radius + 1).max(2); self.enter_remote_dimension(&p.spawn, false); + let view = client_view_distance(self.settings.render_distance); + if let Some(r) = self.remote.as_mut() { + r.sent_view = view; + } self.send(S::ClientInformation( - horizon_protocol::packets::configuration::ClientInformation::new( - self.settings.render_distance.clamp(2, 32) as i8, - ), + horizon_protocol::packets::configuration::ClientInformation::new(view), )); } C::Respawn(p) => { @@ -1123,6 +1304,7 @@ impl Game<'_> { } Err(e) => log::warn!("Horizon: chunk {} {}: {e}", p.x, p.z), }, + C::LightUpdate(p) => self.remote_light_update(&p), C::ForgetLevelChunk(p) => { let [x, z] = p.pos; self.streaming.forget(&mut self.world, x, z); @@ -1159,7 +1341,7 @@ impl Game<'_> { // shulker boxes, bells) when the block is still the one it names. C::BlockEvent(p) => { let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]); - let block = &self.res.facts.get(state).name; + let block = &self.res.facts().get(state).name; let named = self.remote.as_ref().and_then(|r| { r.builtin .get("minecraft:block")? @@ -1173,10 +1355,13 @@ impl Game<'_> { C::LevelEvent(p) if p.kind == 2015 => { self.dragon_egg_particles(p.pos, p.data); } + C::LevelEvent(p) if p.kind == 2017 => { + self.consume_teleport_particles(p.pos, p.data); + } C::LevelEvent(p) if p.kind == 2001 => { // LevelEvent.PARTICLES_DESTROY_BLOCK: someone else broke a block. let state = BlockStateId(p.data.max(0) as u32); - let s = self.res.facts.get(state).sounds.clone(); + let s = self.res.facts().get(state).sounds.clone(); let at = [ f64::from(p.pos[0]) + 0.5, f64::from(p.pos[1]) + 0.5, @@ -1220,8 +1405,8 @@ impl Game<'_> { .map(str::to_owned) }) .unwrap_or_default(); - let yaw = horizon_protocol::buf::unpack_degrees(p.yaw); - let head = horizon_protocol::buf::unpack_degrees(p.head_yaw); + let rotation = + [p.yaw, p.pitch, p.head_yaw].map(horizon_protocol::buf::unpack_degrees); if let Some(r) = self.remote.as_mut() { if kind == "minecraft:player" { r.level_players.insert(p.id, p.uuid); @@ -1229,7 +1414,17 @@ impl Game<'_> { r.level_players.remove(&p.id); } } - self.spawn_entity(p.id, &kind, p.position, yaw, head); + self.spawn_entity(p.id, &kind, p.position, rotation); + if !self.spawn_remote_object(p.id, &kind, p.position, rotation[0], p.data) { + self.spawn_remote_projectile( + p.id, + &kind, + p.position, + (rotation[0], rotation[1]), + p.velocity, + p.data, + ); + } } C::RemoveEntities(p) => { for id in p.ids { @@ -1280,9 +1475,11 @@ impl Game<'_> { ]; self.move_entity(p.id, position, Some((p.yaw, p.pitch)), p.on_ground); } + // ClientPacketListener.handleRotateMob: lerpHeadTo(yHeadRot, 3). C::RotateHead(p) => { - if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { - m.yaw = horizon_protocol::buf::unpack_degrees(p.head_yaw); + if let Some(r) = self.remote.as_mut() { + let yaw = horizon_protocol::buf::unpack_degrees(p.head_yaw); + r.head_lerps.insert(p.id, (yaw, 3)); } } C::SetEntityData(p) => { @@ -1310,17 +1507,72 @@ impl Game<'_> { } } } + // LivingEntity.onSyncedDataUpdated(DATA_LIVING_ENTITY_FLAGS): + // another player starts using the item in a hand (eating, a + // bow drawn, a shield up), or stops. + let other = self + .remote + .as_ref() + .is_some_and(|r| r.level_players.contains_key(&p.id) && r.entity_id != p.id); + if other && let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { + for (index, _, value) in &p.values { + if let (8, Value::Byte(flags)) = (index, value) { + m.extra.using_off_hand = flags & 2 != 0; + if flags & 1 == 0 { + m.extra.using_item = 0; + } else if m.extra.using_item == 0 { + m.extra.using_item = 1; + } + } + } + } + // LivingEntity.onSyncedDataUpdated(SLEEPING_POS_ID): this + // player lies down in the bed, or gets up. + if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) { + for (index, _, value) in &p.values { + if let (14, Value::OptPos(bed)) = (index, value) { + if bed.is_some() && self.sleeping.is_none() { + self.sleep_timer = 0; + } + self.sleeping = *bed; + } + } + } + // Entity.DATA_SHARED_FLAGS_ID's crouching bit: another + // player's crouch (their model and Entity.isDiscrete's name tag). + if self + .remote + .as_ref() + .is_some_and(|r| r.level_players.contains_key(&p.id)) + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) + { + for (index, _, value) in &p.values { + if let (0, Value::Byte(flags)) = (index, value) { + m.extra.crouching = flags & 2 != 0; + } + } + } for (index, _, value) in &p.values { if *index == ITEM_ENTITY_ITEM && let Value::Item(stack) = value { self.remote_item_data(p.id, stack); } + // ExperienceOrb.DATA_VALUE (the icon's size). + if *index == 8 + && let Value::Int(v) = value + && let Some(o) = self.orbs.iter_mut().find(|o| o.id == p.id as u32) + { + o.value = (*v).max(0) as u32; + } } + self.remote_object_data(p.id, &p.values); + self.remote_projectile_data(p.id, &p.values); } // ClientPacketListener.handleSetEquipment: what a mob or another // player holds and wears (EquipmentSlot ordinals). C::SetEquipment(p) => { + self.remote_object_equipment(p.id, &p.slots); let items: Vec<(u8, Option>)> = p .slots .iter() @@ -1342,10 +1594,13 @@ impl Game<'_> { } } C::TakeItemEntity(p) => { - if self - .remote - .as_ref() - .is_some_and(|r| r.entity_id == p.player) + // An orb's sound comes from the server, at the orb. + let orb = self.orbs.iter().any(|o| o.id == p.item as u32); + if !orb + && self + .remote + .as_ref() + .is_some_and(|r| r.entity_id == p.player) && let Some(eye) = self.eye_position() { let pitch = ((self.world.random.next_float() - self.world.random.next_float()) @@ -1356,17 +1611,20 @@ impl Game<'_> { .play("minecraft:entity.item.pickup", Some(eye), 0.2, pitch); } // ItemPickupParticle toward the collector (this player, another one or a mob). + let collector = if self + .remote + .as_ref() + .is_some_and(|r| r.entity_id == p.player) + { + super::pickups::Collector::Player + } else { + super::pickups::Collector::Mob(p.player as u32) + }; if let Some(item) = self.dropped.iter().find(|d| d.id == p.item as u32).cloned() { - let collector = if self - .remote - .as_ref() - .is_some_and(|r| r.entity_id == p.player) - { - super::pickups::Collector::Player - } else { - super::pickups::Collector::Mob(p.player as u32) - }; self.add_pickup(super::pickups::Taken::Item(Box::new(item)), collector); + } else if let Some(orb) = self.orbs.iter().find(|o| o.id == p.item as u32).cloned() + { + self.add_pickup(super::pickups::Taken::Orb(Box::new(orb)), collector); } self.remove_entity(p.item); } @@ -1376,6 +1634,15 @@ impl Game<'_> { pl.velocity = Vec3::new(p.velocity[0], p.velocity[1], p.velocity[2]); } } + // ClientPacketListener.handleDamageEvent: LivingEntity.handleDamageEvent + // jolts the walk animation and restarts the hurt flash. Its hurt + // sound comes as a sound from Horizon's host, which plays it itself. + C::DamageEvent(p) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { + m.limb_speed = 1.5; + m.hurt_time = 10; + } + } C::HurtAnimation(p) => { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { m.hurt_time = 10; @@ -1403,6 +1670,21 @@ impl Game<'_> { } } C::Animate(p) => self.remote_animate(p.id, p.action), + // ClientPacketListener.handleSwingAnimation: the entity swings + // (LivingEntity.swing, which a swing in its first half ignores). + C::SwingAnimation(p) => { + use horizon_client::first_person::Hand; + let hand = if p.hand == 1 { Hand::Off } else { Hand::Main }; + let animation = horizon_client::first_person::SwingAnimation { + kind: p.kind.clamp(0, 255) as u8, + duration: p.duration, + }; + if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) { + self.swing_hand(hand, animation); + } else if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { + m.swing(); + } + } C::UpdateMobEffect(p) => self.remote_effect(&p), C::RemoveMobEffect(p) => { if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) @@ -1452,8 +1734,12 @@ impl Game<'_> { total: p.total, } } + // ClientPacketListener.handleSetTime: the game time, then + // ClientClockManager.handleUpdates: the clock catches up with the + // game time and takes the server's state. C::SetTime(p) => { self.world.game_time = p.game_time; + self.remote_clock_tick(); let clock = { let r = self.remote.as_ref(); let names = @@ -1474,6 +1760,7 @@ impl Game<'_> { if let Some(r) = self.remote.as_mut() { r.clock = Some(c.clock); r.clock_rate = c.rate; + r.clock_partial = c.partial_tick; } } } @@ -1557,17 +1844,27 @@ impl Game<'_> { self.remote_synced(); } C::ContainerSetData(p) => { - if let Some(key) = self.container - && let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get_mut(&key) + let v = i32::from(p.value); + match self + .container + .and_then(|key| self.world.block_entities.get_mut(&key)) { - let v = i32::from(p.value); - match p.id { + Some(BlockEntity::Furnace(f)) => match p.id { 0 => f.lit_remaining = v, 1 => f.lit_total = v, 2 => f.cooking_timer = v, 3 => f.cooking_total = v, _ => {} - } + }, + // BrewingStandBlockEntity.dataAccess. + Some(BlockEntity::Brewing(b)) => match p.id { + 0 => b.brew_time = v, + 1 => b.fuel = v, + 2 => b.total_brew_time = v, + 3 => b.total_fuel = v, + _ => {} + }, + _ => {} } } C::OpenScreen(p) => self.remote_open_screen(p), @@ -1583,6 +1880,11 @@ impl Game<'_> { self.capture(true); } } + C::Unknown(id, data) + if id == horizon_protocol::ids::play::clientbound::COMMAND_SUGGESTIONS => + { + self.handle_command_suggestions(&data); + } C::Commands(p) => { let tree = horizon_client::command::network::from_packet( &p, @@ -1601,10 +1903,9 @@ impl Game<'_> { .map(|r| r.lang.clone()) .unwrap_or_default(), ); + // ChatListener.handleOverlay. if p.overlay { - if let Some(r) = self.remote.as_mut() { - r.action_bar = Some((text, Instant::now())); - } + self.titles.set_overlay(remote_text(&p.content), false); } else { self.chat_line(text); } @@ -1835,15 +2136,16 @@ impl Game<'_> { self.stats.values.entry(ty).or_default().insert(key, count); } } - C::SetActionBarText(p) | C::SetTitleText(p) => { - let lang = self - .remote - .as_ref() - .map(|r| r.lang.clone()) - .unwrap_or_default(); - let text = plain(&p.text, &lang); - if let Some(r) = self.remote.as_mut() { - r.action_bar = Some((text, Instant::now())); + // ClientPacketListener.setActionBarText, setTitleText, + // setSubtitleText, setTitlesAnimation and handleTitlesClear. + C::SetActionBarText(p) => self.titles.set_overlay(remote_text(&p.text), false), + C::SetTitleText(p) => self.titles.set_title(remote_text(&p.text)), + C::SetSubtitleText(p) => self.titles.set_subtitle(remote_text(&p.text)), + C::SetTitlesAnimation(p) => self.titles.set_times(p.fade_in, p.stay, p.fade_out), + C::ClearTitles(p) => { + self.titles.clear(); + if p.value { + self.titles.reset_times(); } } _ => {} @@ -1980,10 +2282,11 @@ impl Game<'_> { self.skin_slots.len() } else { let (old, slot) = self.skin_slots.remove(0); - self.atlas.sprites.remove(&old); + self.gui.atlas.sprites.remove(&old); slot }; let Some(rect) = self + .gui .atlas .sprites .get(&format!("horizon/skin{slot}")) @@ -1991,7 +2294,7 @@ impl Game<'_> { else { return; }; - let (w, h) = (self.atlas.width as f32, self.atlas.height as f32); + let (w, h) = (self.gui.atlas.width as f32, self.gui.atlas.height as f32); self.map_patches.push(horizon_client::font::Patch { x: (rect.u0 * w).round() as u32, y: (rect.v0 * h).round() as u32, @@ -1999,7 +2302,7 @@ impl Game<'_> { height: 64, rgba, }); - self.atlas.sprites.insert(location.clone(), rect); + self.gui.atlas.sprites.insert(location.clone(), rect); self.skin_slots.push((location, slot)); } /// Whether a downloaded skin is in the atlas, marking it recently shown. @@ -2122,10 +2425,11 @@ impl Game<'_> { p.pitch }) .clamp(-90.0, 90.0); - let delta = Vec3::new( - pick(rel::DELTA_X, velocity.x, p.delta[0]), - pick(rel::DELTA_Y, velocity.y, p.delta[1]), - pick(rel::DELTA_Z, velocity.z, p.delta[2]), + let delta = horizon_client::player_sync::teleport_velocity( + velocity, + (self.yaw, self.pitch), + (yaw, pitch), + p, ); match self.player.as_mut() { Some(player) => { @@ -2148,8 +2452,8 @@ impl Game<'_> { self.yaw = yaw; self.pitch = pitch; if let Some(r) = self.remote.as_mut() { - r.last_pos = [position.x, position.y, position.z]; - r.last_rot = (yaw, pitch); + // handleMovePlayer does not change LocalPlayer.sendPosition's + // baseline: the next tick must still report the corrected state. r.destroying = None; } self.mining = None; @@ -2166,16 +2470,34 @@ impl Game<'_> { /// One client tick while connected (Minecraft.tick with a ClientLevel). pub(super) fn tick_remote(&mut self) -> Result<()> { + self.tick_remote_level()?; + // Minecraft.tick sends this even when the player cannot tick yet, + // including while waiting for chunks. Keep it outside early returns. + if self.remote.as_ref().is_some_and(|r| r.joined) { + self.send(S::ClientTickEnd(Empty)); + } + Ok(()) + } + + fn tick_remote_level(&mut self) -> Result<()> { self.ticks += 1; - // Minecraft.tick: TickRateManager.tick; ClientLevel.tick advances + // Options.broadcastOptions: a changed render distance is sent again. + let view = client_view_distance(self.settings.render_distance); + if let Some(r) = self.remote.as_mut() + && r.joined + && r.sent_view != view + { + r.sent_view = view; + self.send(S::ClientInformation( + horizon_protocol::packets::configuration::ClientInformation::new(view), + )); + } + // Minecraft.tick: TickRateManager.tick; ClientLevel.tickTime advances // the time only while the level runs normally. let running = self.clock.world_runs(); if running { self.world.game_time += 1; - let rate = self.remote.as_ref().map_or(1.0, |r| r.clock_rate); - if rate > 0.0 { - self.world.day_time += rate.round() as i64; - } + self.remote_clock_tick(); } // Weather levels drift toward their targets between server updates. let w = &mut self.world.weather; @@ -2184,6 +2506,10 @@ impl Game<'_> { if self.use_delay > 0 { self.use_delay -= 1; } + // Minecraft.handleKeybinds precedes entity ticking and sendChanges. + // Window callbacks only queue clicks, so an interaction cannot leak + // between CLIENT_TICK_END and a later pong. + self.remote_handle_input(); // ClientLevel.tick: the border's size change. self.border.tick(); self.tick_remote_entities(running); @@ -2192,7 +2518,12 @@ impl Game<'_> { self.tick_hand(); self.tick_particles(); self.tick_client_effects(); + // Player.tick's sleep counter (the darkening and the wake-up fade). + self.sleep_timer = super::tick_sleep_timer(self.sleep_timer, self.sleeping.is_some()); + // Gui.tick: the titles, the action bar and the held item's name. + self.tick_hud(); let ghast_collisions = self.happy_ghast_player_collisions(); + let pushed = self.remote_pushes(); let Some(player) = self.player.as_mut() else { return Ok(()); }; @@ -2201,6 +2532,15 @@ impl Game<'_> { (player.position.z.floor() as i32) >> 4, ); if !self.streaming.is_lit(cx, cz) { + // LocalPlayer.tick can wait for chunks, but Minecraft.tick still + // calls sendChanges: rotations and the 20-tick position reminder + // must continue, as well as moves into the unloaded area. + if let Some(r) = self.remote.as_ref() + && r.loaded_sent + { + let input = r.last_input; + self.remote_send_state(input); + } return Ok(()); } if self.remote.as_ref().is_some_and(|r| !r.loaded_sent) { @@ -2243,7 +2583,16 @@ impl Game<'_> { ); player.yaw = self.yaw; let dead = self.screen == Screen::Dead; - if !dead { + // LivingEntity.isImmobile: a sleeper lies still in the bed. + if let Some(head) = self.sleeping { + player.position = Vec3::new( + f64::from(head[0]) + 0.5, + f64::from(head[1]) + 0.5625, + f64::from(head[2]) + 0.5, + ); + player.velocity = Vec3::ZERO; + } else if !dead { + player.velocity = player.velocity.add_vector(pushed); MotionWorld { entities: &ghast_collisions, player, @@ -2264,7 +2613,7 @@ impl Game<'_> { horizon_client::motion::MotionEvent::Emission { state, in_water, .. } if !crouching => { - let sounds = self.res.facts.get(state).sounds.clone(); + let sounds = self.res.facts().get(state).sounds.clone(); // Player.playStepSound: muffled under the swim sound in water. let (volume, pitch) = if in_water { (sounds.volume * 0.05, sounds.pitch * 0.8) @@ -2286,16 +2635,75 @@ impl Game<'_> { // The player's own model (third person, the inventory's preview). self.tick_player_model(); if !dead { - self.remote_mining(); - if self.right && self.use_delay == 0 && playing { - self.remote_use(); - self.use_delay = 4; - } + self.remote_tick_using(); } self.remote_send_state(input); - self.send(S::ClientTickEnd(Empty)); Ok(()) } + /// The local player's share of every touching entity's + /// `LivingEntity.pushEntities`: on a client `EntitySelector.pushableBy` + /// lets entities push only the local player, so the server never sends + /// these pushes. `doPush(player)` is `player.push(entity)`. + fn remote_pushes(&self) -> Vec3 { + let (Some(p), Some(r)) = (self.player.as_ref(), self.remote.as_ref()) else { + return Vec3::ZERO; + }; + // LivingEntity.isPushable: alive, no spectator, off ladders. + let feet = [ + p.position.x.floor() as i32, + p.position.y.floor() as i32, + p.position.z.floor() as i32, + ]; + if self.screen == Screen::Dead + || p.spectator + || self.block_in_tag("minecraft:climbable", &self.block_name(feet)) + { + return Vec3::ZERO; + } + let bounds = p.bounds(); + let teams = self.mob_teams(); + let mut push = Vec3::ZERO; + for m in &self.mobs { + let spectator = r + .level_players + .get(&(m.id as i32)) + .and_then(|uuid| r.tab_players.get(uuid)) + .is_some_and(|t| t.game_mode == SPECTATOR); + // Bats never push; a spectator has no physics; passengers of the + // same vehicle never push each other. + if !m.alive() + || spectator + || m.species() == horizon_client::mobs::Species::Bat + || self + .riding + .is_some_and(|v| v == m.id || m.extra.mount == Some(v)) + || !m.bounds().intersects(bounds) + || !horizon_client::scoreboard::pushable_by( + teams.of(Who::Mob(m.id)), + teams.of(Who::Player), + true, + ) + { + continue; + } + // Entity.push(Entity), `this` the player. + let (mut xa, mut za) = (m.position.x - p.position.x, m.position.z - p.position.z); + let mut dd = xa.abs().max(za.abs()); + if dd < f64::from(0.01_f32) { + continue; + } + dd = dd.sqrt(); + xa /= dd; + za /= dd; + let pow = (1.0 / dd).min(1.0); + xa *= pow; + za *= pow; + xa *= f64::from(0.05_f32); + za *= f64::from(0.05_f32); + push = Vec3::new(push.x - xa, push.y, push.z - za); + } + push + } /// ClientLevel.tickEntities; a frozen level only ticks the players /// (`TickRateManager.isEntityFrozen`). fn tick_remote_entities(&mut self, running: bool) { @@ -2303,14 +2711,19 @@ impl Game<'_> { return; }; let mut lerps = std::mem::take(&mut r.lerps); + let head_lerps = &mut r.head_lerps; let players = &r.level_players; + let mut using = Vec::new(); for m in &mut self.mobs { - if !running && !players.contains_key(&(m.id as i32)) { + let player = players.contains_key(&(m.id as i32)); + if !running && !player { continue; } m.previous = m.position; m.previous_yaw = m.yaw; m.previous_body_yaw = m.body_yaw; + m.previous_head_yaw = m.head_yaw; + m.previous_head_pitch = m.head_pitch; m.previous_limb_speed = m.limb_speed; m.age += 1; if m.species() == horizon_client::mobs::Species::Rabbit { @@ -2325,6 +2738,10 @@ impl Game<'_> { if !m.alive() { m.death_time += 1; } + // LivingEntity.updateSwingTime. + m.anim.attack_anim_o = m.anim.attack_anim; + horizon_client::mobs::ai::tick_swing(m); + // Entity.commonTick: LinearInterpolationHandler.interpolate. if let Some(l) = lerps.get_mut(&(m.id as i32)) && l.steps > 0 { @@ -2334,8 +2751,49 @@ impl Game<'_> { m.position.y + (l.target[1] - m.position.y) / n, m.position.z + (l.target[2] - m.position.z) / n, ); + if let Some((yaw, pitch)) = l.rotation { + let alpha = 1.0 / l.steps as f32; + m.yaw += wrap_degrees(yaw - m.yaw) * alpha; + m.head_pitch += (pitch - m.head_pitch) * alpha; + } l.steps -= 1; } + // LivingEntity.aiStep: the head's own interpolation. + if let Some((yaw, steps)) = head_lerps.get_mut(&(m.id as i32)) + && *steps > 0 + { + m.head_yaw += wrap_degrees(*yaw - m.head_yaw) / *steps as f32; + *steps -= 1; + } + // LivingEntity.updatingUsingItem for another player: the ticks the + // item has been used before this one. + if player && m.extra.using_item > 0 { + let item = if m.extra.using_off_hand { + m.extra.off_hand.clone() + } else { + m.extra.main_hand.clone() + }; + if let Some(item) = item { + let eye = if m.extra.crouching { 1.27 } else { 1.62 }; + let at = [m.position.x, m.position.y, m.position.z]; + using.push(( + item, + m.extra.using_item as u32 - 1, + at, + eye, + m.head_pitch, + m.yaw, + )); + } + m.extra.using_item += 1; + } + // LivingEntity.tick's tickHeadTurn: a mob's BodyRotationControl, + // a player's body following its walk and look. + if player { + remote_player_head_turn(m); + } else if m.alive() { + m.body_rotation_tick(); + } // WalkAnimationState.update from the horizontal distance moved. let (dx, dz) = (m.position.x - m.previous.x, m.position.z - m.previous.z); let target = (((dx * dx + dz * dz).sqrt() * 4.0) as f32).min(1.0); @@ -2345,6 +2803,21 @@ impl Game<'_> { horizon_client::mobs::rabbit::post_tick(m); } } + for o in self.orbs.iter_mut().filter(|_| running) { + o.previous = o.position; + o.age += 1; + if let Some(l) = lerps.get_mut(&(o.id as i32)) + && l.steps > 0 + { + let n = f64::from(l.steps); + o.position = Vec3::new( + o.position.x + (l.target[0] - o.position.x) / n, + o.position.y + (l.target[1] - o.position.y) / n, + o.position.z + (l.target[2] - o.position.z) / n, + ); + l.steps -= 1; + } + } for d in self.dropped.iter_mut().filter(|_| running) { d.previous = d.position; d.age += 1; @@ -2360,6 +2833,28 @@ impl Game<'_> { l.steps -= 1; } } + head_lerps.retain(|_, (_, steps)| *steps > 0); + for (item, ticks, at, eye, pitch, yaw) in using { + self.remote_player_eating(&item, ticks, at, eye, pitch, yaw); + } + if running { + // Boats, minecarts, armor stands, projectiles and the rest + // interpolate like mobs. + let mut step = |id: u32, at: Vec3| match lerps.get_mut(&(id as i32)) { + Some(l) if l.steps > 0 => { + let n = f64::from(l.steps); + l.steps -= 1; + Vec3::new( + at.x + (l.target[0] - at.x) / n, + at.y + (l.target[1] - at.y) / n, + at.z + (l.target[2] - at.z) / n, + ) + } + _ => at, + }; + self.tick_remote_objects(&mut step); + self.tick_remote_projectiles(&mut step); + } lerps.retain(|_, l| l.steps > 0); if let Some(r) = self.remote.as_mut() { for (id, l) in lerps { @@ -2367,6 +2862,47 @@ impl Game<'_> { } } } + /// `Consumable.onConsumeTick` for another player using a consumable: the + /// crumbs at their mouth every 4 ticks once 21.875% of its use has passed + /// (`shouldEmitParticlesAndSounds`; the sounds come from the server). + fn remote_player_eating( + &mut self, + item: &str, + ticks: u32, + at: [f64; 3], + eye: f64, + pitch: f32, + yaw: f32, + ) { + let Some(consumable) = self + .res + .items() + .get(item) + .and_then(|i| i.consumable.as_ref()) + .filter(|c| c.particles) + else { + return; + }; + let duration = consumable.ticks().max(0) as u32; + let remaining = duration - ticks.min(duration); + if !consumable.should_emit(remaining as i32) { + return; + } + let options = self.item_particle(&ItemStack::new(item, 1)); + let mut spawned = Vec::new(); + horizon_client::particles::item_use_particles( + &mut self.world.random, + pitch, + yaw, + at, + at[1] + eye, + 5, + |p, v| spawned.push((p, v)), + ); + for (p, v) in spawned { + self.particles.add(&options, p, v); + } + } /// LocalPlayer.sendPosition plus input, sprint and held-slot updates. fn remote_send_state(&mut self, input: u8) { let Some(p) = self.player.as_ref() else { @@ -2401,41 +2937,12 @@ impl Game<'_> { data: 0, })); } - r.reminder += 1; - let d = [ - pos[0] - r.last_pos[0], - pos[1] - r.last_pos[1], - pos[2] - r.last_pos[2], - ]; - let moved = d[0] * d[0] + d[1] * d[1] + d[2] * d[2] > 2.0e-4 * 2.0e-4 || r.reminder >= 20; - let rotated = yaw != r.last_rot.0 || pitch != r.last_rot.1; - let flags = u8::from(on_ground) | u8::from(collision) << 1; - let [x, y, z] = pos; - if moved && rotated { - out.push(S::MovePlayerPosRot(play::MovePlayerPosRot { - x, - y, - z, - yaw, - pitch, - flags, - })); - } else if moved { - out.push(S::MovePlayerPos(play::MovePlayerPos { x, y, z, flags })); - } else if rotated { - out.push(S::MovePlayerRot(play::MovePlayerRot { yaw, pitch, flags })); - } else if r.last_on_ground != on_ground || r.last_collision != collision { - out.push(S::MovePlayerStatus(play::MovePlayerStatus { flags })); + if let Some(packet) = r + .position_sender + .update(pos, (yaw, pitch), on_ground, collision) + { + out.push(packet); } - if moved { - r.last_pos = pos; - r.reminder = 0; - } - if rotated { - r.last_rot = (yaw, pitch); - } - r.last_on_ground = on_ground; - r.last_collision = collision; // Creative inventory edits are sent slot by slot (SetCreativeModeSlot). let mut creative_slots = Vec::new(); if self.creative { @@ -2478,16 +2985,12 @@ impl Game<'_> { } /// MultiPlayerGameMode.startDestroyBlock / continueDestroyBlock. - fn remote_mining(&mut self) { + fn remote_mining(&mut self, start: bool) { let Some(r) = self.remote.as_mut() else { return; }; - if r.destroy_delay > 0 { + if !start && r.destroy_delay > 0 { r.destroy_delay -= 1; - } - if !self.left || self.screen != Screen::Playing { - self.stop_remote_mining(); - self.mining = None; return; } let Some(hit) = self.pick() else { @@ -2496,14 +2999,9 @@ impl Game<'_> { }; let face = face_direction(hit.face); let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); - if self.res.facts.is_air(state) { + if self.res.facts().is_air(state) { return; } - if self.remote.as_ref().is_some_and(|r| r.destroy_delay > 0) { - return; - } - self.swing_arm(); - self.send(S::Punch(Empty)); if self.creative { let seq = self.next_sequence(); self.predict_break(hit.pos, state, seq); @@ -2518,14 +3016,17 @@ impl Game<'_> { } return; } - let facts = self.res.facts.get(state).clone(); + let facts = self.res.facts().get(state).clone(); let held = self.held().cloned(); - let mut speed = self.res.items.mining_speed(held.as_ref(), &facts.name); + let mut speed = self.res.items().mining_speed(held.as_ref(), &facts.name); if self.player.as_ref().is_some_and(|p| !p.ground.on_ground) { speed /= 5.0; } - let harvest = - !facts.requires_tool || self.res.items.correct_for_drops(held.as_ref(), &facts.name); + let harvest = !facts.requires_tool + || self + .res + .items() + .correct_for_drops(held.as_ref(), &facts.name); let progress = if facts.hardness < 0.0 { 0.0 } else if facts.hardness == 0.0 { @@ -2538,6 +3039,9 @@ impl Game<'_> { .as_ref() .and_then(|r| r.destroying) .is_some_and(|(p, _, _)| p == hit.pos); + if start && same { + return; + } if !same { if let Some((old, _, _)) = self.remote.as_mut().and_then(|r| r.destroying.take()) { self.send(S::PlayerAction(play::PlayerAction { @@ -2632,7 +3136,7 @@ impl Game<'_> { .and_modify(|p| p.0 = sequence) .or_insert((sequence, state.0 as i32)); } - let s = self.res.facts.get(state).sounds.clone(); + let s = self.res.facts().get(state).sounds.clone(); let at = [ f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, @@ -2652,15 +3156,25 @@ impl Game<'_> { } self.mining = None; } - /// Minecraft.startUseItem: use on the targeted block, then the item itself. + /// Minecraft.startUseItem: use one crosshair target, then the item itself. fn remote_use(&mut self) { - let held_block = self - .held() - .and_then(|h| self.res.items.get(&h.item)) - .is_some_and(|i| i.block.is_some()); + // Minecraft.startUseItem returns before resetting rightClickDelay + // while a survival block break is active. + if self.remote.as_ref().is_some_and(|r| r.destroying.is_some()) { + return; + } + self.use_delay = 4; + // Resolve the crosshair once. A passing entity interaction keeps + // that target and may only fall back to using the item itself. + let entity = self.entity_targeted(); + horizon_client::interaction_input::use_on_target(&mut RemoteUseWorld(self), entity); + } + + fn remote_use_entity(&mut self) -> bool { let sneaking = self.keys.contains(&KeyCode::ShiftLeft); - // Entities first (interact), like the hit result order. - if let Some((i, _)) = self.mob_hit() { + if let Some((i, distance)) = self.mob_hit() + && self.before_block(distance) + { let id = self.mobs[i].id as i32; self.send(S::Interact(play::Interact { id, @@ -2668,9 +3182,25 @@ impl Game<'_> { location: [0.0, 1.0, 0.0], secondary: sneaking, })); - self.swing_arm(); - return; + // Player.interactOn: another player passes, and the held item is + // used instead (Minecraft.startUseItem). + let player = self + .remote + .as_ref() + .is_some_and(|r| r.level_players.contains_key(&id)); + if !player { + self.swing_arm(); + return true; + } } + false + } + + fn remote_use_block(&mut self) -> bool { + let held_block = self + .held() + .and_then(|h| self.res.items().get(&h.item)) + .is_some_and(|i| i.block.is_some()); if let Some(hit) = self.pick() { let seq = self.next_sequence(); let cursor = [ @@ -2699,10 +3229,14 @@ impl Game<'_> { } if held_block { self.swing_arm(); - return; + return true; } } - if self.held().is_some() { + false + } + + fn remote_use_item(&mut self) { + if let Some(held) = self.held().cloned() { let seq = self.next_sequence(); self.send(S::UseItem(play::UseItem { hand: 0, @@ -2710,54 +3244,184 @@ impl Game<'_> { yaw: self.yaw, pitch: self.pitch, })); + // MultiPlayerGameMode.useItem runs the use here too: food starts + // being eaten (Consumable.startConsuming). + if let Some(info) = self.res.items().get(&held.item).cloned() { + self.start_eating(&info); + } } } - /// Left click: attack the targeted entity (MultiPlayerGameMode.attack). - pub(super) fn remote_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> { - if self.screen == Screen::Chat { - return Ok(()); + /// `LivingEntity.updatingUsingItem` for a consumable on a server client: the + /// eating animation and its crumbs. The server eats it and sends the + /// stack, the hunger and the sounds. + fn remote_tick_using(&mut self) { + let Some((slot, ticks)) = self.using else { + return; + }; + let stack = self.stack_in(slot).cloned(); + let consumable = stack + .as_ref() + .and_then(|s| self.res.items().get(&s.item)) + .and_then(|i| i.consumable.clone()); + let (Some(stack), Some(consumable)) = (stack, consumable) else { + self.using = None; + return; + }; + // Button release belongs to the next handleKeybinds phase, which + // sends RELEASE_USE_ITEM. Do not silently clear a use begun by a + // quick press/release between ticks. + if slot != self.selected { + self.using = None; + return; } - match button { + // Consumable.shouldEmitParticlesAndSounds, as in tick_used_item. + let duration = consumable.ticks().max(0) as u32; + let remaining = duration - ticks.min(duration); + if consumable.particles && consumable.should_emit(remaining as i32) { + self.eat_particles(&stack, 5); + } + if ticks + 1 >= duration { + self.using = None; + if consumable.particles { + self.eat_particles(&stack, 16); + } + } else { + self.using = Some((slot, ticks + 1)); + } + } + /// MouseHandler updates KeyMapping; handleKeybinds sends packets on a tick. + pub(super) fn remote_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> { + use horizon_client::interaction_input::Button; + let input = match button { MouseButton::Left => { - if pressed && let Some((i, _)) = self.mob_hit() { - let id = self.mobs[i].id as i32; - self.send(S::Attack(play::Attack { id })); - self.send(S::Punch(Empty)); - self.swing_arm(); - return Ok(()); - } - if pressed && self.pick().is_none() { - self.send(S::Punch(Empty)); - self.swing_arm(); - } - self.left = pressed; + self.toggles + .button(2, pressed, false, self.settings.toggle_attack); + self.left = self.toggles.is_down(2); + Some(Button::Attack) } MouseButton::Right => { - self.right = pressed; - if pressed { - self.remote_use(); - self.use_delay = 4; - } else { - self.send(S::PlayerAction(play::PlayerAction { - action: 6, - pos: [0; 3], - direction: 0, - sequence: 0, - })); - } + self.toggles + .button(3, pressed, false, self.settings.toggle_use); + self.right = self.toggles.is_down(3); + Some(Button::Use) } - MouseButton::Middle if pressed => { - if let Some(hit) = self.pick() { - self.send(S::PickItemFromBlock(play::PickItemFromBlock { - pos: hit.pos, - include_data: self.has_control_down(), - })); - } - } - _ => {} + MouseButton::Middle => Some(Button::Pick), + _ => None, + }; + if pressed + && let Some(button) = input + && let Some(remote) = self.remote.as_mut() + { + remote.input.press(button); } Ok(()) } + + pub(super) fn request_remote_mining_stop(&mut self) { + if let Some(r) = self.remote.as_mut() { + r.stop_mining = true; + } + } + + fn remote_handle_input(&mut self) { + let Some(r) = self.remote.as_mut() else { + return; + }; + let mut input = std::mem::take(&mut r.input); + let stop = std::mem::take(&mut r.stop_mining); + let ready = r.loaded_sent && self.screen == Screen::Playing && self.sleeping.is_none(); + if stop || !ready { + self.stop_remote_mining(); + } + if !ready { + return; + } + // MultiPlayerGameMode.tick syncs the carried slot before keybinds. + let carried_changed = self.remote.as_mut().is_some_and(|r| { + if r.carried == Some(self.selected) { + false + } else { + r.carried = Some(self.selected); + true + } + }); + if carried_changed { + self.send(S::SetCarriedItem(play::SetCarriedItem { + slot: self.selected as i16, + })); + } + let (attack, use_item) = (self.left, self.right); + input.tick(&mut RemoteInputWorld(self), attack, use_item); + if self.clicks.miss_time > 0 { + self.clicks.miss_time -= 1; + } + if let Some(r) = self.remote.as_mut() { + r.input = input; + } + } + + fn remote_start_attack(&mut self) -> bool { + if self.clicks.miss_time > 0 { + return false; + } + if self.spectator() { + return true; + } + let mut instant = false; + if let Some((i, distance)) = self.mob_hit() + && self.before_block(distance) + { + self.send(S::Attack(play::Attack { + id: self.mobs[i].id as i32, + })); + self.reset_attack_strength(); + } else if !self.entity_targeted() + && let Some(hit) = self.pick() + { + self.remote_mining(true); + instant = self + .res + .facts() + .is_air(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2])); + } else { + if !self.creative { + self.clicks.miss_time = 10; + } + self.reset_attack_strength(); + } + self.swing_arm(); + self.send(S::Punch(Empty)); + instant + } + + fn remote_continue_attack(&mut self, down: bool) { + if !down { + self.clicks.miss_time = 0; + } + if self.clicks.miss_time > 0 || self.using.is_some() { + return; + } + let entity = self.entity_targeted(); + if down + && !entity + && let Some(hit) = self.pick() + { + let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); + if !self.res.facts().is_air(state) { + self.remote_mining(false); + self.swing_arm(); + self.send(S::Punch(Empty)); + } else { + if let Some(r) = self.remote.as_mut() { + r.destroying = None; + } + self.mining = None; + } + } else { + self.stop_remote_mining(); + self.mining = None; + } + } /// Keys with a multiplayer meaning; returns true when consumed. pub(super) fn remote_key(&mut self, key: KeyCode) -> Result { if self.screen != Screen::Playing { @@ -2862,17 +3526,108 @@ impl Game<'_> { let Some(internal) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return; }; - let input = if self.has_shift_down() { 1 } else { 0 }; - self.remote_slot_click(internal, i8::from(right), input); + let input = if self.has_shift_down() { + Input::QuickMove + } else { + Input::Pickup + }; + self.remote_menu_ops(&[(Some(internal), i32::from(right), input)]); + } + /// The server's open menu: its window id and menu type (0, "inventory" + /// when none is open). + fn remote_menu(&self) -> (i32, String) { + match self.remote.as_ref().and_then(|r| r.menu.clone()) { + Some((id, name)) => (id, name), + None => (0, "inventory".to_owned()), + } + } + /// `MultiPlayerGameMode.handleContainerInput` for each click of `ops` on + /// the server's open menu (a quick craft drag is several): the verified + /// menu engine predicts them on this client's copy, then each goes out as + /// a `ContainerClick` with the slots it changed and the carried stack + /// after it; the server corrects anything it sees differently. A menu the + /// engine doesn't model sends the clicks unpredicted. False when a click's + /// slot isn't one of the menu's. + pub(super) fn remote_menu_ops(&mut self, ops: &[(Option, i32, Input)]) -> bool { + let (container, menu) = self.remote_menu(); + let mut clicks = Vec::with_capacity(ops.len()); + for &(slot, button, input) in ops { + let slot = match slot { + None => -999, + Some(internal) => { + match (0..64).find(|&s| Self::menu_slot(&menu, s) == Some(internal)) { + Some(s) => s as i16, + None => return false, + } + } + }; + clicks.push((slot, button, input)); + } + // Unpredicted: nothing changed, the carried stack as it is. + let mut sent: Vec = clicks + .iter() + .map(|&(slot, button, input)| (slot, button, input, Vec::new(), self.carried.clone())) + .collect(); + // The engine's slot indices are the menu's own, as on the network. + self.menu_session(|m, env, _| { + let mut predicted = Vec::with_capacity(clicks.len()); + for &(slot, button, input) in &clicks { + let before = menu_items(m); + if m.click(env, i32::from(slot), button, input).is_err() { + // The server throws on it too: nothing is predicted. + return Some(false); + } + let changed = changed_slots(&before, m); + predicted.push((slot, button, input, changed, m.carried.clone())); + } + sent = predicted; + Some(true) + }); + self.send_clicks(container, sent); + true + } + /// A Shift double click on a server (`AbstractContainerScreen.mouseReleased`): + /// a predicted QUICK_MOVE for every slot the engine moves, each sent. + pub(super) fn remote_quick_move_all(&mut self, slot: usize, moved: &ItemStack) { + let (container, _) = self.remote_menu(); + let mut sent: Vec = Vec::new(); + self.menu_session(|m, env, to_menu| { + let clicked = to_menu(slot)?; + let mut before = menu_items(m); + let mut each = |m: &horizon_client::menu::Menu, t: usize| { + let changed = changed_slots(&before, m); + sent.push((t as i16, 0, Input::QuickMove, changed, m.carried.clone())); + before = menu_items(m); + }; + Some( + m.quick_move_all_each(env, clicked, moved, &mut each) + .is_ok(), + ) + }); + self.send_clicks(container, sent); + } + fn send_clicks(&mut self, container: i32, clicks: Vec) { + let state = self.remote.as_ref().map_or(0, |r| r.state_id); + let hashed = |g: &Self, s: &Option| g.to_network(s).map(|s| Hashed::of(&s)); + for (slot, button, input, changed, carried) in clicks { + let changed = changed.iter().map(|(i, s)| (*i, hashed(self, s))).collect(); + let carried = hashed(self, &carried); + self.send(S::ContainerClick(play::ContainerClick { + container, + state, + slot, + button: button as i8, + input: input_ordinal(input), + changed, + carried, + })); + } } /// A `ContainerClick` on game slot `internal` of the server's open menu /// (`input` is the ContainerInput ordinal). False when the menu has no /// such slot. pub(super) fn remote_slot_click(&mut self, internal: usize, button: i8, input: i32) -> bool { - let (container, menu) = match self.remote.as_ref().and_then(|r| r.menu.clone()) { - Some((id, name)) => (id, name), - None => (0, "inventory".to_owned()), - }; + let (container, menu) = self.remote_menu(); let slot = (0..64).find(|&s| Self::menu_slot(&menu, s) == Some(internal)); let Some(slot) = slot else { return false }; let carried = self.to_network(&self.carried).map(|s| Hashed::of(&s)); @@ -3057,6 +3812,14 @@ impl Game<'_> { speed: 1.0, })) } + // HopperMenu, and DispenserMenu (MenuType.GENERIC_3x3: dispensers + // and droppers). + "minecraft:hopper" => Some(BlockEntity::Chest(vec![None; 5])), + // BrewingStandMenu: its times come in ContainerSetData. + "minecraft:brewing_stand" => Some(BlockEntity::Brewing(Box::new( + horizon_client::brewing::BrewingStand::new(), + ))), + "minecraft:generic_3x3" => Some(BlockEntity::Chest(vec![None; 9])), m if m.starts_with("minecraft:generic_9x") || m == "minecraft:shulker_box" => { let rows = m .strip_prefix("minecraft:generic_9x") @@ -3092,7 +3855,7 @@ impl Game<'_> { // an ender chest's or a double chest's slots are no one block's, // so they go under a key no block has. let holds = |k: &(i32, i32, i32)| { - let name = &self.res.facts.get(self.world.block(k.0, k.1, k.2)).name; + let name = &self.res.facts().get(self.world.block(k.0, k.1, k.2)).name; BlockEntity::for_block(name).is_some_and(|e| { e.id() == entity.id() && e.slots().len() == entity.slots().len() }) @@ -3104,6 +3867,14 @@ impl Game<'_> { self.screen = Screen::Inventory; self.capture(false); } + /// The type of the menu a server opened (`MenuType`'s id). + pub(super) fn remote_menu_type(&self) -> Option<&str> { + Some(self.remote.as_ref()?.menu.as_ref()?.1.as_str()) + } + /// The title the server gave the menu it opened. + pub(super) fn remote_menu_title(&self) -> Option { + self.remote.as_ref()?.menu_title.clone() + } /// A server's chest-like menu (`MenuType.GENERIC_9xN`): its rows and title. pub(super) fn remote_chest_menu(&self) -> Option<(usize, String)> { let r = self.remote.as_ref()?; @@ -3116,6 +3887,15 @@ impl Game<'_> { .ok()?; Some((rows, r.menu_title.clone().unwrap_or_default())) } + /// ServerboundPlayerCommandPacket STOP_SLEEPING. + pub(super) fn remote_stop_sleeping(&mut self) { + let id = self.remote.as_ref().map_or(0, |r| r.entity_id); + self.send(S::PlayerCommand(play::PlayerCommand { + id, + action: 0, + data: 0, + })); + } pub(super) fn remote_respawn(&mut self) { self.send(S::ClientCommand(play::ClientCommand { action: 0 })); } @@ -3126,7 +3906,7 @@ impl Game<'_> { if self.player.is_some() { return false; } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); batch.fill(atlas, 0.0, 0.0, w, h, rgba(20, 20, 20, 255)); let shown = horizon_client::net::shown_address(&r.session.address); @@ -3151,7 +3931,7 @@ impl Game<'_> { /// Chat (ChatComponent), the chat input line and the action bar. pub(super) fn remote_hud(&self, batch: &mut HudBatch) { let Some(r) = &self.remote else { return }; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); let open = self.screen == Screen::Chat; let now = Instant::now(); @@ -3185,12 +3965,6 @@ impl Game<'_> { batch.text(atlas, text, 4.0, y, rgba(255, 255, 255, a), true); y -= 9.0; } - if let Some((text, at)) = &r.action_bar - && now.duration_since(*at) < Duration::from_secs(3) - { - let tw = HudBatch::text_width(atlas, text); - batch.text(atlas, text, (w - tw) / 2.0, h - 68.0, u32::MAX, true); - } if self.screen == Screen::Dead && let Some(message) = &r.death_message { @@ -3211,12 +3985,29 @@ impl Game<'_> { .filter_map(|(id, uuid)| Some((*id as u32, r.players.get(uuid)?.clone()))) .collect() } + /// `ClientClockManager.tick`: the clock moves on by the game time that + /// passed since its last tick, at its rate. A game time the server sets + /// forward (its sync every second) moves the clock with it. + fn remote_clock_tick(&mut self) { + let Some(r) = self.remote.as_mut() else { + return; + }; + let delta = self.world.game_time - r.clock_game_time; + r.clock_game_time = self.world.game_time; + let partial = f64::from(r.clock_partial) + delta as f64 * f64::from(r.clock_rate); + let full = partial.floor(); + r.clock_partial = (partial - full) as f32; + self.world.day_time += full as i64; + } pub(super) fn remote_status(&self) -> Option { let r = self.remote.as_ref()?; Some(serde_json::json!({ "address": horizon_client::net::shown_address(&r.session.address), "name": r.session.name, "joined": r.joined, + // ServerboundPlayerLoadedPacket sent: the level around the + // player is ready, and the client ticks and sends its moves. + "loaded": r.loaded_sent, "status": r.status, "entity_id": r.entity_id, "dimension": r.dimension.name, @@ -3238,6 +4029,8 @@ impl Game<'_> { let armor = [&e.head, &e.chest, &e.legs, &e.feet].map(|s| s.as_deref()); serde_json::json!({ "id": m.id, + "swinging": m.ai.swinging, + "using": m.extra.using_item, "armor": armor, "main_hand": e.main_hand.as_deref(), "off_hand": e.off_hand.as_deref(), @@ -3250,6 +4043,13 @@ impl Game<'_> { .filter(|t| t.kind == "minecraft:player") .map(|t| t.position) .collect::>(), + // The other players this client draws dead (lying down, after EntityEvent DEATH). + "dead_players": self + .mobs + .iter() + .filter(|m| r.level_players.contains_key(&(m.id as i32)) && !m.alive()) + .map(|m| m.id) + .collect::>(), // The player's own model exists (third person and the inventory draw it). "player_model": self.player_model.is_some(), "health": r.health.0, @@ -3260,6 +4060,138 @@ impl Game<'_> { } } +/// `Mth.wrapDegrees`. +fn wrap_degrees(a: f32) -> f32 { + let a = a % 360.0; + if a >= 180.0 { + a - 360.0 + } else if a < -180.0 { + a + 360.0 + } else { + a + } +} + +/// `LivingEntity.tick`'s body target and `tickHeadTurn` for another player: +/// the body turns toward where it walks (backwards when walking back), or to +/// the look while the arm swings, and stays within 50 degrees of the look. +fn remote_player_head_turn(m: &mut Mob) { + let (dx, dz) = (m.position.x - m.previous.x, m.position.z - m.previous.z); + let mut target = m.body_yaw; + if (dx * dx + dz * dz) as f32 > 0.002_500_000_2 { + let walk = (dz.atan2(dx) as f32).to_degrees() - 90.0; + let facing = (wrap_degrees(m.yaw) - walk).abs(); + target = if 95.0 < facing && facing < 265.0 { + walk - 180.0 + } else { + walk + }; + } + if m.anim.attack_anim > 0.0 { + target = m.yaw; + } + m.body_yaw += wrap_degrees(target - m.body_yaw) * 0.3; + let head = wrap_degrees(m.yaw - m.body_yaw); + if head.abs() > 50.0 { + m.body_yaw += head - head.signum() * 50.0; + } +} + +/// A click sent to a server: its slot, button and input, the slots it +/// changed and the carried stack after it. +type Predicted = ( + i16, + i32, + Input, + Vec<(i16, Option)>, + Option, +); + +fn menu_items(m: &horizon_client::menu::Menu) -> Vec> { + (0..m.slot_count()).map(|i| m.slot(i).cloned()).collect() +} + +/// The slots whose stack is no longer `before`'s (`ItemStack.matches`). +fn changed_slots( + before: &[Option], + m: &horizon_client::menu::Menu, +) -> Vec<(i16, Option)> { + (0..m.slot_count()) + .filter(|&i| m.slot(i) != before.get(i).and_then(Option::as_ref)) + .map(|i| (i as i16, m.slot(i).cloned())) + .collect() +} + +/// ServerboundContainerClickPacket's `ContainerInput` ordinal. +pub(super) fn input_ordinal(input: Input) -> i32 { + match input { + Input::Pickup => 0, + Input::QuickMove => 1, + Input::Swap => 2, + Input::Clone => 3, + Input::Throw => 4, + Input::QuickCraft => 5, + Input::PickupAll => 6, + } +} + +/// The view distance a client asks for: its render distance, which Horizon +/// lets go past vanilla's 32 (a vanilla server still caps it at its own). +fn client_view_distance(render_distance: i32) -> i8 { + render_distance.clamp(2, i32::from(i8::MAX)) as i8 +} + +struct RemoteInputWorld<'g, 'a>(&'g mut Game<'a>); + +struct RemoteUseWorld<'g, 'a>(&'g mut Game<'a>); + +impl horizon_client::interaction_input::TargetUseWorld for RemoteUseWorld<'_, '_> { + fn use_entity(&mut self) -> bool { + self.0.remote_use_entity() + } + fn use_block(&mut self) -> bool { + self.0.remote_use_block() + } + fn use_item(&mut self) { + self.0.remote_use_item(); + } +} + +impl horizon_client::interaction_input::InteractionWorld for RemoteInputWorld<'_, '_> { + fn using_item(&self) -> bool { + self.0.using.is_some() + } + fn release_using(&mut self) { + self.0.send(S::PlayerAction(play::PlayerAction { + action: 6, + pos: [0; 3], + direction: 0, + sequence: 0, + })); + self.0.using = None; + } + fn start_attack(&mut self) -> bool { + self.0.remote_start_attack() + } + fn start_use(&mut self) { + self.0.remote_use(); + } + fn pick(&mut self) { + if let Some(hit) = self.0.pick() { + self.0.send(S::PickItemFromBlock(play::PickItemFromBlock { + pos: hit.pos, + include_data: self.0.has_control_down(), + })); + } + } + fn use_delay(&self) -> u32 { + self.0.use_delay + } + fn continue_attack(&mut self, down: bool) { + self.0.remote_continue_attack(down); + } +} + #[cfg(test)] mod tests { use super::Game; diff --git a/crates/horizon-client/src/game/remote_objects.rs b/crates/horizon-client/src/game/remote_objects.rs new file mode 100644 index 000000000..12a15bc34 --- /dev/null +++ b/crates/horizon-client/src/game/remote_objects.rs @@ -0,0 +1,270 @@ +//! Boats, minecarts, armor stands, item frames and paintings on a server's +//! client (`ClientPacketListener.handleAddEntity`, `handleSetEntityData`, +//! `handleSetEquipment`): the server simulates them, the client places them +//! where it says and interpolates their moves like a mob's. +use super::Game; +use horizon_client::entities::{ArmorStand, ItemFrame, Painting}; +use horizon_core::geometry::Vec3; +use horizon_protocol::entity_data::Value; +use std::sync::Arc; + +impl Game<'_> { + /// `handleAddEntity` for an object type; false when `kind` isn't one. + /// Hanging entities come at their block, with their direction as the + /// spawn data (`Direction.from3DDataValue`). + pub(super) fn spawn_remote_object( + &mut self, + id: i32, + kind: &str, + position: [f64; 3], + yaw: f32, + data: i32, + ) -> bool { + let id = id as u32; + let at = Vec3::new(position[0], position[1], position[2]); + let block = position.map(|v| v.floor() as i32); + self.remove_remote_object(id); + if let Some(cart) = super::minecarts::CartKind::from_id(kind) { + let mut c = super::minecarts::Minecart::new(id, cart, at); + c.yaw = yaw; + c.previous_yaw = yaw; + self.carts.push(c); + } else if let Some((wood, chest)) = super::boats::any_boat_wood(kind) + && self.boat_models.has(wood, chest) + { + let mut b = super::boats::Boat::new(id, Arc::from(wood), at, yaw); + if chest { + b = b.with_chest(); + } + self.boats.push(b); + } else if kind == "minecraft:armor_stand" { + self.armor_stands.push(ArmorStand::new(id, at, yaw)); + } else if kind == "minecraft:item_frame" || kind == "minecraft:glow_item_frame" { + self.item_frames.push(ItemFrame { + id, + pos: block, + facing: data.clamp(0, 5) as u8, + glow: kind == "minecraft:glow_item_frame", + item: None, + rotation: 0, + drop_chance: 1.0, + fixed: false, + invisible: false, + check_interval: 0, + }); + } else if kind == "minecraft:painting" { + // The variant comes with the entity data; until then the + // registry's first one (VariantUtils.getAny). + let (variant, width, height) = self + .remote_painting_variant(0) + .map_or((Arc::from("minecraft:kebab"), 1, 1), |v| { + (v.id, v.width, v.height) + }); + // Direction 3D data value (north 2, south 3, west 4, east 5) to 2D. + let facing = match data { + 2 => 2, + 4 => 1, + 5 => 3, + _ => 0, + }; + self.paintings.push(Painting { + id, + pos: block, + facing, + variant, + width, + height, + check_interval: 0, + }); + } else { + return false; + } + true + } + + /// A `painting_variant` by its network id, from the server's registry. + fn remote_painting_variant(&self, id: i32) -> Option { + let r = self.remote.as_ref()?; + let name = r.registries.name("minecraft:painting_variant", id)?; + self.painting_variants.get(name).cloned() + } + + /// `handleSetEntityData` for an object: what changes how it looks. + pub(super) fn remote_object_data(&mut self, id: i32, values: &[(u8, i32, Value)]) { + let id = id as u32; + for (index, _, value) in values { + if self.item_frames.iter().any(|f| f.id == id) { + // HangingEntity.DATA_DIRECTION, ItemFrame.DATA_ITEM and DATA_ROTATION. + let item = match (index, value) { + (9, Value::Item(stack)) => Some(self.to_stack(stack)), + _ => None, + }; + let Some(f) = self.item_frames.iter_mut().find(|f| f.id == id) else { + continue; + }; + match (index, value) { + (8, Value::Id(d)) => f.facing = (*d).clamp(0, 5) as u8, + (10, Value::Int(r)) => f.rotation = r.rem_euclid(8) as u8, + _ => {} + } + if let Some(item) = item { + f.item = item; + } + } else if self.paintings.iter().any(|p| p.id == id) { + // Painting.DATA_PAINTING_VARIANT_ID: a registry holder (id + 1). + if let (9, Value::Id(holder)) = (index, value) + && let Some(v) = self.remote_painting_variant(holder - 1) + && let Some(p) = self.paintings.iter_mut().find(|p| p.id == id) + { + p.variant = v.id; + p.width = v.width; + p.height = v.height; + } + } else if let Some(a) = self.armor_stands.iter_mut().find(|a| a.id == id) { + match (index, value) { + (0, Value::Byte(flags)) => a.invisible = flags & 0x20 != 0, + (9, Value::Float(health)) => a.health = *health, + // ArmorStand.DATA_CLIENT_FLAGS. + (15, Value::Byte(flags)) => { + a.small = flags & 1 != 0; + a.show_arms = flags & 4 != 0; + a.no_base_plate = flags & 8 != 0; + a.marker = flags & 16 != 0; + } + _ => {} + } + } else if let Some(b) = self.boats.iter_mut().find(|b| b.id == id) { + // VehicleEntity's hurt, direction and damage; the paddles. + match (index, value) { + (8, Value::Int(v)) => b.hurt_time = *v, + (9, Value::Int(v)) => b.hurt_dir = *v, + (10, Value::Float(v)) => b.damage = *v, + (11, Value::Bool(v)) => b.paddling[0] = *v, + (12, Value::Bool(v)) => b.paddling[1] = *v, + _ => {} + } + } else if let Some(c) = self.carts.iter_mut().find(|c| c.id == id) { + match (index, value) { + (8, Value::Int(v)) => c.hurt_time = *v, + (9, Value::Int(v)) => c.hurt_dir = *v, + (10, Value::Float(v)) => c.damage = *v, + _ => {} + } + } + } + } + + /// `handleSetEquipment` for an armor stand (EquipmentSlot ordinals 0 to + /// 5: main hand, off hand, feet, legs, chest, head, its storage order). + pub(super) fn remote_object_equipment( + &mut self, + id: i32, + slots: &[(u8, Option)], + ) { + if !self.armor_stands.iter().any(|a| a.id == id as u32) { + return; + } + let items: Vec<_> = slots + .iter() + .map(|(slot, stack)| (usize::from(*slot), self.to_stack(stack))) + .collect(); + if let Some(a) = self.armor_stands.iter_mut().find(|a| a.id == id as u32) { + for (slot, item) in items { + if let Some(s) = a.equipment.get_mut(slot) { + *s = item; + } + } + } + } + + /// A move's rotation and ground state for an object. + pub(super) fn turn_remote_object(&mut self, id: i32, yaw: Option, on_ground: bool) { + let id = id as u32; + if let Some(b) = self.boats.iter_mut().find(|b| b.id == id) { + if let Some(yaw) = yaw { + b.yaw = yaw; + } + b.on_ground = on_ground; + } else if let Some(c) = self.carts.iter_mut().find(|c| c.id == id) { + if let Some(yaw) = yaw { + c.yaw = yaw; + } + } else if let Some(a) = self.armor_stands.iter_mut().find(|a| a.id == id) { + if let Some(yaw) = yaw { + a.yaw = yaw; + } + a.on_ground = on_ground; + } + } + + /// One tick of interpolation: `step` moves a position a step toward + /// the entity's last sent one, if it has a move in progress. + pub(super) fn tick_remote_objects(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) { + for c in &mut self.carts { + c.previous = c.position; + c.previous_yaw = c.yaw; + c.position = step(c.id, c.position); + } + for b in &mut self.boats { + b.previous = b.position; + b.previous_yaw = b.yaw; + b.position = step(b.id, b.position); + } + for a in &mut self.armor_stands { + a.position = step(a.id, a.position); + } + } + + /// The boats, minecarts, armor stands, item frames and paintings in the + /// level (a server's client: the ones it was sent), for `status`. + pub(super) fn objects_status(&self) -> Vec { + use serde_json::json; + let at = |p: Vec3| [p.x, p.y, p.z]; + let mut out = Vec::new(); + for b in &self.boats { + out.push(json!({"id": b.id, "kind": b.entity_type(), "position": at(b.position), "yaw": b.yaw})); + } + for c in &self.carts { + out.push( + json!({"id": c.id, "kind": c.kind.id(), "position": at(c.position), "yaw": c.yaw}), + ); + } + for a in &self.armor_stands { + let items: Vec<_> = a + .equipment + .iter() + .map(|i| i.as_ref().map(|i| &*i.item)) + .collect(); + out.push(json!({"id": a.id, "kind": "minecraft:armor_stand", "position": at(a.position), "yaw": a.yaw, + "small": a.small, "arms": a.show_arms, "no_base_plate": a.no_base_plate, "equipment": items})); + } + for f in &self.item_frames { + out.push( + json!({"id": f.id, "kind": f.kind(), "position": f.pos, "facing": f.facing, + "item": f.item.as_ref().map(|i| &*i.item), "rotation": f.rotation}), + ); + } + for p in &self.paintings { + out.push(json!({"id": p.id, "kind": "minecraft:painting", "position": p.pos, "facing": p.facing, + "variant": &*p.variant})); + } + out + } + + /// Every object a server sent (a new connection, level or dimension). + pub(super) fn clear_remote_objects(&mut self) { + self.carts.clear(); + self.boats.clear(); + self.armor_stands.clear(); + self.item_frames.clear(); + self.paintings.clear(); + } + + pub(super) fn remove_remote_object(&mut self, id: u32) { + self.carts.retain(|c| c.id != id); + self.boats.retain(|b| b.id != id); + self.armor_stands.retain(|a| a.id != id); + self.item_frames.retain(|f| f.id != id); + self.paintings.retain(|p| p.id != id); + } +} diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs new file mode 100644 index 000000000..23cbb1913 --- /dev/null +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -0,0 +1,229 @@ +//! Primed TNT, falling blocks, projectiles, tridents, firework rockets and +//! end crystals on a server's client (`ClientPacketListener.handleAddEntity` +//! and `handleSetEntityData`): the server simulates them, the client draws +//! them where it says and interpolates their moves. +use super::{FallingBlock, Game}; +use horizon_client::projectiles::{Projectile, ProjectileKind}; +use horizon_core::{geometry::Vec3, position::BlockPos}; +use horizon_protocol::entity_data::Value; +use horizon_world::registry::BlockStateId; + +/// The projectile a type id names, as Horizon models it. +fn projectile_kind(kind: &str) -> Option { + Some(match kind { + "minecraft:arrow" | "minecraft:spectral_arrow" => ProjectileKind::Arrow { + base_damage: 2.0, + critical: false, + effect: None, + }, + "minecraft:snowball" => ProjectileKind::Snowball, + "minecraft:egg" => ProjectileKind::Egg, + "minecraft:ender_pearl" => ProjectileKind::EnderPearl, + "minecraft:small_fireball" => ProjectileKind::SmallFireball, + "minecraft:fireball" => ProjectileKind::LargeFireball { power: 1 }, + "minecraft:llama_spit" => ProjectileKind::LlamaSpit, + "minecraft:wind_charge" => ProjectileKind::WindCharge, + "minecraft:breeze_wind_charge" => ProjectileKind::BreezeWindCharge, + "minecraft:wither_skull" => ProjectileKind::WitherSkull { dangerous: false }, + _ => return None, + }) +} + +impl Game<'_> { + /// `handleAddEntity` for these types; false when `kind` isn't one. + pub(super) fn spawn_remote_projectile( + &mut self, + id: i32, + kind: &str, + position: [f64; 3], + rotation: (f32, f32), + velocity: [f64; 3], + data: i32, + ) -> bool { + let id = id as u32; + let at = Vec3::new(position[0], position[1], position[2]); + let velocity = Vec3::new(velocity[0], velocity[1], velocity[2]); + let (yaw, pitch) = rotation; + self.remove_remote_projectile(id); + match kind { + "minecraft:tnt" => self.tnts.push(super::tnt::PrimedTnt { + id, + position: at, + previous: at, + velocity, + fuse: 80, + on_ground: false, + }), + // FallingBlockEntity.recreateFromPacket: the block state is the data. + "minecraft:falling_block" => self.falling.push(FallingBlock { + id, + state: BlockStateId(data.max(0) as u32), + start_pos: BlockPos::default(), + position: at, + previous: at, + velocity, + age: 0, + no_gravity: false, + drop_item: false, + fall_distance: 0.0, + damage: Default::default(), + saved: None, + }), + "minecraft:trident" => { + let mut t = super::trident::ThrownTrident::remote(id, at, yaw, pitch); + t.velocity = velocity; + self.tridents.push(t); + } + "minecraft:firework_rocket" => { + self.rockets + .push(super::fireworks::Rocket::remote(id, at, velocity)); + } + "minecraft:end_crystal" => self.crystals.push(super::dragon::Crystal { + id, + position: at, + show_bottom: true, + time: 0, + beam: None, + invulnerable: false, + }), + _ => { + let Some(k) = projectile_kind(kind) else { + return false; + }; + let mut p = Projectile::new(k, at, None); + p.id = id; + p.velocity = velocity; + p.yaw = yaw; + p.pitch = pitch; + self.creatures.projectiles.push(p); + } + } + true + } + + /// `handleSetEntityData` for these types: what changes how they look. + pub(super) fn remote_projectile_data(&mut self, id: i32, values: &[(u8, i32, Value)]) { + let id = id as u32; + for (index, _, value) in values { + if let Some(t) = self.tnts.iter_mut().find(|t| t.id == id) { + // PrimedTnt.DATA_FUSE_ID. + if let (8, Value::Int(fuse)) = (index, value) { + t.fuse = *fuse; + } + } else if let Some(f) = self.falling.iter_mut().find(|f| f.id == id) { + // FallingBlockEntity.DATA_START_POS (the model's seed). + if let (8, Value::Pos(p)) = (index, value) { + f.start_pos = BlockPos::new(p[0], p[1], p[2]); + } + } else if let Some(c) = self.crystals.iter_mut().find(|c| c.id == id) { + // EndCrystal.DATA_BEAM_TARGET and DATA_SHOW_BOTTOM. + match (index, value) { + (8, Value::OptPos(beam)) => c.beam = *beam, + (9, Value::Bool(show)) => c.show_bottom = *show, + _ => {} + } + } else if let Some(p) = self.creatures.projectiles.iter_mut().find(|p| p.id == id) { + match (&mut p.kind, index, value) { + // AbstractArrow.ID_FLAGS (critical) and IN_GROUND. + (ProjectileKind::Arrow { critical, .. }, 8, Value::Byte(flags)) => { + *critical = flags & 1 != 0; + } + (ProjectileKind::Arrow { .. }, 10, Value::Bool(in_ground)) => { + p.stuck = *in_ground; + } + // WitherSkull.DATA_DANGEROUS. + (ProjectileKind::WitherSkull { dangerous }, 8, Value::Bool(d)) => { + *dangerous = *d; + } + _ => {} + } + } + } + } + + /// A move's rotation for a projectile or trident. + pub(super) fn turn_remote_projectile(&mut self, id: i32, rotation: Option<(f32, f32)>) { + let (id, Some((yaw, pitch))) = (id as u32, rotation) else { + return; + }; + if let Some(p) = self.creatures.projectiles.iter_mut().find(|p| p.id == id) { + p.yaw = yaw; + p.pitch = pitch; + } else if let Some(t) = self.tridents.iter_mut().find(|t| t.id == id) { + t.yaw = yaw; + t.pitch = pitch; + } + } + + /// One tick of interpolation, as `tick_remote_objects`. + pub(super) fn tick_remote_projectiles(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) { + for t in &mut self.tnts { + t.previous = t.position; + t.position = step(t.id, t.position); + } + for f in &mut self.falling { + f.previous = f.position; + f.age += 1; + f.position = step(f.id, f.position); + } + for p in &mut self.creatures.projectiles { + p.previous = p.position; + p.age += 1; + p.position = step(p.id, p.position); + } + for t in &mut self.tridents { + let id = t.id; + t.remote_step(|at| step(id, at)); + } + for r in &mut self.rockets { + let id = r.id; + r.remote_step(|at| step(id, at)); + } + for c in &mut self.crystals { + c.time += 1; + c.position = step(c.id, c.position); + } + } + + pub(super) fn remove_remote_projectile(&mut self, id: u32) { + self.tnts.retain(|t| t.id != id); + self.falling.retain(|f| f.id != id); + self.creatures.projectiles.retain(|p| p.id != id); + self.tridents.retain(|t| t.id != id); + self.rockets.retain(|r| r.id != id); + self.crystals.retain(|c| c.id != id); + } + + /// Every one a server sent (a new connection, level or dimension). + pub(super) fn clear_remote_projectiles(&mut self) { + self.tnts.clear(); + self.falling.clear(); + self.creatures.projectiles.clear(); + self.tridents.clear(); + self.rockets.clear(); + self.crystals.clear(); + } + + /// Their kind and place, for `status`. + pub(super) fn projectiles_status(&self) -> Vec { + use serde_json::json; + let at = |p: Vec3| [p.x, p.y, p.z]; + let mut out = Vec::new(); + for t in &self.tnts { + out.push(json!({"id": t.id, "kind": "minecraft:tnt", "position": at(t.position), "fuse": t.fuse})); + } + for f in &self.falling { + out.push(json!({"id": f.id, "kind": "minecraft:falling_block", "position": at(f.position), "state": f.state.0})); + } + for c in &self.crystals { + out.push(json!({"id": c.id, "kind": "minecraft:end_crystal", "position": at(c.position), "show_bottom": c.show_bottom})); + } + for t in &self.tridents { + out.push(json!({"id": t.id, "kind": "minecraft:trident", "position": at(t.position)})); + } + for p in &self.creatures.projectiles { + out.push(json!({"id": p.id, "kind": format!("{:?}", p.kind).split([' ', '{']).next().unwrap_or(""), "position": at(p.position)})); + } + out + } +} diff --git a/crates/horizon-client/src/game/render_control.rs b/crates/horizon-client/src/game/render_control.rs index e9a08c6a2..31a7a33a0 100644 --- a/crates/horizon-client/src/game/render_control.rs +++ b/crates/horizon-client/src/game/render_control.rs @@ -12,6 +12,7 @@ pub const HELP: &[&str] = &[ "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", + "section-cull [on|off] occlusion culling of solid sections (A/B checks); replies the mode", ]; impl Game<'_> { @@ -120,14 +121,14 @@ impl Game<'_> { let key = (int(1)?, int(2)?, int(3)?); let name = self .res - .facts + .facts() .get(self.world.block(key.0, key.1, key.2)) .name .clone(); let entity = horizon_client::containers::BlockEntity::for_block(&name) .filter(|e| matches!(e, horizon_client::containers::BlockEntity::Sign(_))) .ok_or("no sign there")?; - self.world.block_entities.entry(key).or_insert(entity); + self.world.block_entities.get_or_insert_with(key, || entity); self.open_sign_editor(key, words.get(4) != Some(&"back")); Ok(Some(json!({ "ok": true }))) } diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index 4ee10e6d2..b990869a5 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -66,15 +66,21 @@ impl Game<'_> { ) -> FogData { let forward = self.forward(); let at = [camera.x, camera.y, camera.z]; - let fog_type = fog_type(&self.world, &self.res.facts, at, forward); - let water = self.res.biomes.get(biome).water_fog; + let fog_type = fog_type(&self.world, self.res.facts(), at, forward); + let water = self.res.biomes().get(biome).water_fog; let (rain, thunder) = if self.dim == Dim::Overworld { self.world.weather.levels(self.clock.fraction() as f32) } else { (0.0, 0.0) }; + let title_fog = horizon_client::fog::FogTables::default(); + let tables = if self.title.is_some() { + &title_fog + } else { + self.res.fog() + }; horizon_client::fog::setup_fog( - &self.res.fog, + tables, &self.fog, &FogInputs { fog_type, @@ -117,7 +123,7 @@ impl Game<'_> { horizon_client::gfx::ShaderInputs { rain, thunder, - submerged: match fog_type(&self.world, &self.res.facts, at, self.forward()) { + submerged: match fog_type(&self.world, self.res.facts(), at, self.forward()) { FogType::Atmospheric => 0, FogType::Water => 1, FogType::Lava => 2, @@ -139,7 +145,7 @@ impl Game<'_> { camera.y < 63.0 && fog_type( &self.world, - &self.res.facts, + self.res.facts(), [camera.x, camera.y, camera.z], self.forward(), ) != FogType::Water @@ -170,7 +176,7 @@ impl Game<'_> { t[1].floor() as i32, t[2].floor() as i32, ); - let f = self.res.facts.get(state); + let f = self.res.facts().get(state); if f.render_shape != horizon_client::blocks::RenderShape::Invisible && f.solid_render && f.full_collision @@ -180,7 +186,7 @@ impl Game<'_> { } } let in_water = - fog_type(&self.world, &self.res.facts, eye, self.forward()) == FogType::Water; + fog_type(&self.world, self.res.facts(), eye, self.forward()) == FogType::Water; let water = (in_water && !spectator).then(|| (self.eye_brightness(eye), self.yaw, self.pitch)); // Hud.extractCameraOverlays; the spyglass scope (and its easing) is @@ -211,7 +217,7 @@ impl Game<'_> { let gui_overlays = hud_overlays::camera_overlays(size[0] as i32, size[1] as i32, &overlays, &mut scope); self.screen_fx.build(&ScreenInputs { - sprites: &self.atlas.sprites, + sprites: &self.gui.atlas.sprites, aspect: size[0] as f32 / size[1].max(1) as f32, partial, block_overlay, @@ -243,7 +249,7 @@ impl Game<'_> { self.screen_fx.tick(brightness, inside_portal); // LocalPlayer water vision and AtmosphericFogEnvironment rain fog. let in_water = - fog_type(&self.world, &self.res.facts, e, self.forward()) == FogType::Water; + fog_type(&self.world, self.res.facts(), e, self.forward()) == FogType::Water; self.fog.tick(in_water); let b = [ e[0].floor() as i32, @@ -260,7 +266,7 @@ impl Game<'_> { .chunks .get(&(b[0] >> 4, b[2] >> 4)) .map_or(0, |c| c.biome(b[0], b[1], b[2])); - let rains = self.res.biomes.get(biome).precipitation; + let rains = self.res.biomes().get(biome).precipitation; update_rain_fog( &mut self.fog, rain, @@ -278,8 +284,8 @@ impl Game<'_> { (0.0, 0.0) }; let world = &self.world; - let facts = &self.res.facts; - let biomes = &self.res.biomes; + let facts = self.res.facts(); + let biomes = self.res.biomes(); let raining = rain > 0.2; let raining_at = |p: [i32; 3]| { raining @@ -300,7 +306,7 @@ impl Game<'_> { e[1].floor() as i32, e[2].floor() as i32, ]; - animate_tick(&self.res.animate, &mut self.particles, &ctx, block); + animate_tick(self.res.animate(), &mut self.particles, &ctx, block); if rain > 0.0 { // ClientLevel.tickWeatherEffects: rain splashes (weather radius 10). let mut random = LegacyRandom::new(self.world.game_time.wrapping_mul(312_987_231)); @@ -336,7 +342,7 @@ impl Game<'_> { let smoke = f.fluid == Fluid::Lava || &*f.name == "minecraft:magma_block" || (f.name.ends_with("campfire") - && self.res.animate.is_lit_campfire(state.0)); + && self.res.animate().is_lit_campfire(state.0)); let ty = if smoke { ParticleType::Smoke } else { @@ -354,7 +360,7 @@ impl Game<'_> { } if let Some(r) = &self.renderer { campfire_particles( - &self.res.animate, + self.res.animate(), &mut self.particles, &ctx, r.block_entities(), diff --git a/crates/horizon-client/src/game/respawn_anchor.rs b/crates/horizon-client/src/game/respawn_anchor.rs index 5a31dfd5c..4604c076f 100644 --- a/crates/horizon-client/src/game/respawn_anchor.rs +++ b/crates/horizon-client/src/game/respawn_anchor.rs @@ -63,7 +63,7 @@ pub(super) enum AnchorUse { impl Game<'_> { fn is_anchor(&self, state: BlockStateId) -> bool { - &*self.res.facts.get(state).name == "minecraft:respawn_anchor" + &*self.res.facts().get(state).name == "minecraft:respawn_anchor" } fn anchor_charges(&self, state: BlockStateId) -> i32 { self.pack @@ -177,7 +177,7 @@ impl Game<'_> { } /// `RespawnAnchorBlock.isWaterThatWouldFlow`. fn water_would_flow(&self, p: [i32; 3]) -> bool { - let f = self.res.facts.get(self.world.block(p[0], p[1], p[2])); + let f = self.res.facts().get(self.world.block(p[0], p[1], p[2])); if f.fluid != Fluid::Water { return false; } @@ -188,7 +188,7 @@ impl Game<'_> { return false; } self.res - .facts + .facts() .get(self.world.block(p[0], p[1] - 1, p[2])) .fluid != Fluid::Water @@ -203,7 +203,7 @@ impl Game<'_> { .any(|d| self.water_would_flow([pos[0] + d[0], pos[1], pos[2] + d[2]])); let above = self .res - .facts + .facts() .get(self.world.block(pos[0], pos[1] + 1, pos[2])) .fluid == Fluid::Water; @@ -225,7 +225,7 @@ impl Game<'_> { /// halves and explodes; `StrawBedBlock` just falls apart. pub(super) fn destroy_bed_on_use(&mut self, head: [i32; 3]) -> Result<()> { let state = self.world.block(head[0], head[1], head[2]); - let name = self.res.facts.get(state).name.clone(); + let name = self.res.facts().get(state).name.clone(); let center = [ f64::from(head[0]) + 0.5, f64::from(head[1]) + 0.5, @@ -259,7 +259,7 @@ impl Game<'_> { let foot = [head[0] + back[0], head[1], head[2] + back[2]]; if self .res - .facts + .facts() .get(self.world.block(foot[0], foot[1], foot[2])) .name == name @@ -297,7 +297,7 @@ impl Game<'_> { /// climbable blocks and open trapdoors. fn non_climbable_shape(&self, p: [i32; 3]) -> VoxelShape { let state = self.world.block(p[0], p[1], p[2]); - let name = &self.res.facts.get(state).name; + let name = &self.res.facts().get(state).name; let open_trapdoor = name.ends_with("_trapdoor") && self .pack @@ -324,9 +324,9 @@ impl Game<'_> { ) .unwrap_or_else(|_| VoxelShape::empty()) } - fn block_in_tag(&self, tag: &str, block: &str) -> bool { + pub(super) fn block_in_tag(&self, tag: &str, block: &str) -> bool { self.res - .items + .items() .block_tags .get(tag) .is_some_and(|s| s.contains(block)) @@ -334,7 +334,7 @@ impl Game<'_> { /// `EntityType.isBlockDangerous` for the player. fn dangerous_for_player(&self, p: [i32; 3]) -> bool { let state = self.world.block(p[0], p[1], p[2]); - let name = &*self.res.facts.get(state).name; + let name = &*self.res.facts().get(state).name; let lit_campfire = (name == "minecraft:campfire" || name == "minecraft:soul_campfire") && self .pack @@ -397,7 +397,7 @@ impl Game<'_> { } let name = |q: [i32; 3]| { self.res - .facts + .facts() .get(self.world.block(q[0], q[1], q[2])) .name .clone() diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 4e715c7b7..99dae39a5 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -131,6 +131,7 @@ impl Game<'_> { pub(super) fn holder_name(&mut self, t: Target) -> Option { match t { Target::Player => Some(self.acting_player_name().to_owned()), + Target::Guest(conn) => self.command_guest(conn).map(|g| g.name.clone()), Target::Mob(id) | Target::Item(id) => Some(uuid_text(self.uuid_for(id))), _ => None, } @@ -179,7 +180,7 @@ impl Game<'_> { | Target::Cart(id) | Target::Other(id) => self.persist.raw.get(&id), Target::Player => self.level.player_extra.as_ref(), - Target::Orb(_) | Target::Arrow(_) => None, + Target::Guest(_) | Target::Orb(_) | Target::Arrow(_) => None, }; match raw.and_then(|r| r.get("Tags")) { Some(Tag::List(l)) => l @@ -584,11 +585,11 @@ impl Game<'_> { batch.height as i32, board, objective, - &self.atlas.font, + &self.gui.atlas.font, self.settings.text_background(0.3), self.settings.text_background(0.4), ); - hud_layout::paint(batch, &self.atlas, &draws); + hud_layout::paint(batch, &self.gui.atlas, &draws); } } @@ -648,8 +649,8 @@ impl Game<'_> { ), upside_down: &up, }; - let draws = self.tab_list.layout(&inputs, &self.atlas.font); - horizon_client::hud_layout::paint(batch, &self.atlas, &draws); + let draws = self.tab_list.layout(&inputs, &self.gui.atlas.font); + horizon_client::hud_layout::paint(batch, &self.gui.atlas, &draws); } } diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index 365dd5992..cecd8d46f 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -92,7 +92,7 @@ impl Game<'_> { let (world, quit) = self.pause_labels(); self.tick_friends(); let friends = self.friends_view(); - let mut ui = horizon_client::ui_theme::Ui::new(&self.atlas, batch, self.cursor); + let mut ui = horizon_client::ui_theme::Ui::new(&self.gui.atlas, batch, self.cursor); horizon_client::front::pause::draw( &mut ui, &world, @@ -104,7 +104,7 @@ impl Game<'_> { ui.finish(); return; } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); let title = Text::translate("menu.game", &[]); @@ -156,7 +156,7 @@ impl Game<'_> { let mut b = HudBatch::new(size); let (world, quit) = self.pause_labels(); horizon_client::front::pause::click( - &self.atlas, + &self.gui.atlas, &mut b, self.cursor.0, self.cursor.1, @@ -197,7 +197,7 @@ impl Game<'_> { } /// DeathScreen: gradient, the title at double size, the cause and score. pub(super) fn draw_death_screen(&mut self, batch: &mut HudBatch) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); // fillGradient(0x60500000 -> 0xA0803030). let rows = h.ceil() as i32; @@ -288,6 +288,11 @@ impl Game<'_> { if hit == Some(0) && self.remote.is_none() { let keep = self.ui.rules.bool("keep_inventory") || self.spectator(); self.experience.respawn(keep); + // The guests are sent the respawned host as a new entity, not the dead body. + if let Some(host) = self.lan.as_mut() { + let id = host.host_entity; + host.hub.respawned(id); + } // Autosaves keep a login position; death must resolve the respawn point instead. self.level.position = None; } diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index 04e02d360..de7ea6df2 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -6,13 +6,14 @@ use super::{Game, Result}; use horizon_client::{ containers::BlockEntity, + fast_hash::{FxHashMap, FxHashSet}, mobs::{Mob, Species, Who, warden}, particles::{ParticleOptions, ParticleType}, sculk::{self, Context, Info, SculkEntity, SculkKind, WardenSpawnTracker}, }; use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource}; use horizon_world::registry::BlockStateId; -use std::collections::{HashMap, HashSet}; +use std::collections::HashSet; use winit::keyboard::KeyCode; pub const HELP: &[&str] = &[ @@ -70,8 +71,9 @@ pub(super) struct SculkState { /// The sculk block entities in the order they were added. index: Index, pub known: HashSet<(i32, i32)>, - steps: HashMap, - damaged: HashMap, + // Keyed by mob ids the server gives out: the fast hasher is safe. + steps: FxHashMap, + damaged: FxHashMap, last_health: Option, /// The darkness effect's blend factor, previous and current tick. darkness: (f32, f32), @@ -275,7 +277,7 @@ impl Game<'_> { let n = registry.len(); let tag = |name: &str| { self.res - .items + .items() .block_tags .get(name) .cloned() @@ -294,7 +296,7 @@ impl Game<'_> { resonator: vec![false; n], }; for i in 0..n { - let facts = self.res.facts.get(BlockStateId(i as u32)); + let facts = self.res.facts().get(BlockStateId(i as u32)); let name: &str = &facts.name; t.kinds[i] = match name { "minecraft:sculk_sensor" => KIND_SENSOR, @@ -612,7 +614,7 @@ impl Game<'_> { }; !own && !calibrated_out && frequency != 0 - && self.res.behaviours.sculk_sensor_can_activate(state) + && self.res.behaviours().sculk_sensor_can_activate(state) } SculkKind::Shrieker => !self.shrieker_shrieking(state) && ctx.player, SculkKind::Catalyst => false, @@ -703,18 +705,10 @@ impl Game<'_> { } Ok(()) } - /// `ServerLevel.shouldTickBlocksAt`, as `tick_blocks` decides it. + /// `ServerLevel.shouldTickBlocksAt` in a block-ticking chunk, from every + /// player's tickets (`update_chunk_tickets`), once the chunk is lit. fn chunk_ticks(&self, cx: i32, cz: i32) -> bool { - let Some(p) = self.player.as_ref() else { - return false; - }; - let (pcx, pcz) = ( - (p.position.x.floor() as i32) >> 4, - (p.position.z.floor() as i32) >> 4, - ); - let simulation = self.settings.render_distance.min(8); - (cx - pcx).abs() <= simulation - && (cz - pcz).abs() <= simulation + self.tickets.levels().block_ticking(cx, cz) && self.world.chunks.get(&(cx, cz)).is_some_and(|c| c.lit) } fn tick_sculk_block(&mut self, key: (i32, i32, i32)) -> Result<()> { @@ -773,7 +767,7 @@ impl Game<'_> { match kind { SculkKind::Sensor | SculkKind::Calibrated => { let state = self.world.block(key.0, key.1, key.2); - if self.res.behaviours.sculk_sensor_can_activate(state) { + if self.res.behaviours().sculk_sensor_can_activate(state) { let frequency = sculk::frequency(info.event); if let Some(e) = self.sculk_entity(key) { e.last_frequency = frequency; @@ -863,7 +857,7 @@ impl Game<'_> { if self.mobs.iter().any(|m| m.id == id && m.species() == Species::Warden)); match self.kind_of_state(state.0) { KIND_SENSOR | KIND_CALIBRATED => { - if is_warden || !self.res.behaviours.sculk_sensor_can_activate(state) { + if is_warden || !self.res.behaviours().sculk_sensor_can_activate(state) { continue; } let calibrated = self.kind_of_state(state.0) == KIND_CALIBRATED; @@ -1006,7 +1000,7 @@ impl Game<'_> { if warning < 4 { return false; } - let Some(kind) = self.res.mob_types.get("minecraft:warden").cloned() else { + let Some(kind) = self.res.mob_types().get("minecraft:warden").cloned() else { return false; }; for _ in 0..20 { @@ -1049,7 +1043,7 @@ impl Game<'_> { /// `SpawnUtil.moveToPossibleSpawnPosition` with `ON_TOP_OF_COLLIDER`. fn spawn_position(&self, x: i32, y: i32, z: i32, range: i32) -> Option<(i32, i32, i32)> { use horizon_client::mobs::data; - let flags = |b: BlockStateId| self.res.mob_data.state(b); + let flags = |b: BlockStateId| self.res.mob_data().state(b); let mut search = y; let mut above = self.world.block(x, search, z); for _ in (-range..=range).rev() { @@ -1168,7 +1162,7 @@ impl Game<'_> { && let Some(eye) = self.eye_position() { let in_water = - horizon_client::fog::fog_type(&self.world, &self.res.facts, eye, self.forward()) + horizon_client::fog::fog_type(&self.world, self.res.facts(), eye, self.forward()) == FogType::Water; return self.fog.water_vision(in_water); } @@ -1333,7 +1327,7 @@ impl Game<'_> { .play("minecraft:block.sculk.charge", Some(c), 1.0, 1.0); let solid = self .res - .facts + .facts() .get(self.world.block(pos.x, pos.y, pos.z)) .full_collision; let (particles, spread) = if solid { (40, 0.45f32) } else { (20, 0.25f32) }; @@ -1528,7 +1522,7 @@ impl Game<'_> { } } } - let alive: HashSet = self.mobs.iter().map(|m| m.id).collect(); + let alive: FxHashSet = self.mobs.iter().map(|m| m.id).collect(); self.sculk.damaged.retain(|id, _| alive.contains(id)); self.sculk.steps.retain(|who, _| match who { Who::Player => true, @@ -1541,7 +1535,8 @@ impl Game<'_> { at[1].floor() as i32, at[2].floor() as i32, ); - self.res.facts.get(self.world.block(x, y, z)).fluid == horizon_client::blocks::Fluid::Water + self.res.facts().get(self.world.block(x, y, z)).fluid + == horizon_client::blocks::Fluid::Water } /// `Entity.move`'s emission: footsteps, swimming, landing and splashes. fn entity_motion_events( @@ -1588,13 +1583,13 @@ impl Game<'_> { at[2].floor() as i32, ); let state = self.world.block(block.0, block.1, block.2); - let air = self.res.facts.is_air(state); + let air = self.res.facts().is_air(state); let climbable = self .res - .items + .items() .block_tags .get("minecraft:climbable") - .is_some_and(|t| t.contains(&*self.res.facts.get(state).name)); + .is_some_and(|t| t.contains(&*self.res.facts().get(state).name)); let travelled = if climbable { ((dx * dx + dy * dy + dz * dz).sqrt() * f64::from(0.6f32)) as f32 } else { diff --git a/crates/horizon-client/src/game/sculk_fixture.rs b/crates/horizon-client/src/game/sculk_fixture.rs index 2ebdbcb2b..890e571b8 100644 --- a/crates/horizon-client/src/game/sculk_fixture.rs +++ b/crates/horizon-client/src/game/sculk_fixture.rs @@ -303,8 +303,8 @@ impl Game<'_> { } fn sculk_fixture_reset(&mut self, s: &Scenario) -> Result<()> { - self.world = World::new(self.res.facts.air, 0); - let plains = u32::from(self.res.biomes.id("minecraft:plains")); + self.world = World::new(self.res.facts().air, 0); + let plains = u32::from(self.res.biomes().id("minecraft:plains")); let layers = [ self.fixture_state("minecraft:bedrock")?, self.fixture_state("minecraft:dirt")?, @@ -439,7 +439,7 @@ impl Game<'_> { for spec in &s.mobs { let kind = self .res - .mob_types + .mob_types() .get(&spec.kind) .cloned() .ok_or_else(|| format!("unknown mob {}", spec.kind))?; @@ -696,6 +696,8 @@ impl Game<'_> { seed_fresh(m, 0x5eed + (named + i + 1) as i64); } } + // The player's tickets, as `tick_world` takes them. + self.update_chunk_tickets(); // Entities: the player's warden spawn tracker, then the mobs. self.tick_sculk_entities(); // (ServerChunkCache.tick, natural spawning and its chunk shuffle, is not run.) diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs index 6312254c7..56fdbaca5 100644 --- a/crates/horizon-client/src/game/server_travel.rs +++ b/crates/horizon-client/src/game/server_travel.rs @@ -22,6 +22,17 @@ pub(super) struct Trip { end: bool, /// The Nether portal plan, whose exit is found or built on arrival. plan: Option, + /// Sent by a command: the player is already where it goes. + placed: bool, +} + +/// `TeleportCommand` into another level for a server's player: where, and +/// the rotation it sets (none keeps the player's). +pub(super) struct LevelTeleport { + pub conn: u32, + pub dim: Dim, + pub at: [f64; 3], + pub rotation: Option<[f32; 2]>, } /// A player's box: Player's standing dimensions. @@ -177,7 +188,8 @@ impl Game<'_> { }; let at = [destination.x, destination.y, destination.z]; let ctx = self.server_ctx(); - host.hub.change_level(i, at, yaw, &ctx); + // TeleportTransition.PLAY_PORTAL_SOUND. + host.hub.change_level(i, at, yaw, None, true, &ctx); self.as_guest(host, conn, |g| g.trigger_dimension(source, target)); self.server_trips.push(Trip { conn, @@ -185,6 +197,7 @@ impl Game<'_> { target: destination, end, plan, + placed: false, }); if let Err(e) = self.enter_level(Some(host), source) { log::error!("could not reopen {}: {e}", source.id()); @@ -214,6 +227,9 @@ impl Game<'_> { continue; } let trip = self.server_trips.remove(k); + if trip.placed { + continue; + } self.resolve_arrivals(); let yaw = host.hub.guests[i].yaw; let (position, yaw) = if trip.end { @@ -248,9 +264,47 @@ impl Game<'_> { } } + /// The players the command just run sends to another level + /// (`ServerPlayer.teleport` from TeleportCommand): a Respawn packet + /// keeping all data and the teleport, with no portal sound. The server + /// leaves the body alone until the level has loaded around it. + pub(super) fn run_level_teleports(&mut self, host: &mut LanHost) { + for t in std::mem::take(&mut self.level_teleports) { + let Some(i) = host.hub.guests.iter().position(|g| g.conn == t.conn) else { + continue; + }; + let source = self.dim; + if let Err(e) = self.enter_level(Some(host), t.dim) { + log::error!("could not open {}: {e}", t.dim.id()); + continue; + } + let g = &mut host.hub.guests[i]; + let [yaw, pitch] = t.rotation.unwrap_or([g.yaw, g.pitch]); + // A new body there: no fall distance or motion carried over. + g.motion = None; + let ctx = self.server_ctx(); + host.hub + .change_level(i, t.at, yaw, Some(pitch), false, &ctx); + self.as_guest(host, t.conn, |g| g.trigger_dimension(source, t.dim)); + self.server_trips.retain(|trip| !trip.is(t.conn)); + self.server_trips.push(Trip { + conn: t.conn, + dim: t.dim, + target: Vec3::new(t.at[0], t.at[1], t.at[2]), + end: false, + plan: None, + placed: true, + }); + if let Err(e) = self.enter_level(Some(host), source) { + log::error!("could not reopen {}: {e}", source.id()); + } + } + } + /// The hub's view of the server for packets sent outside its own tick. pub(super) fn server_ctx(&mut self) -> TickCtx<'_> { let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); + let clock_rate = self.network_clock_rate(); TickCtx { world: &mut self.world, host: None, @@ -259,11 +313,7 @@ impl Game<'_> { spawn, difficulty: i32::from(self.ui.difficulty), difficulty_locked: self.level.difficulty_locked, - clock_rate: if self.ui.rules.bool("advance_time") { - self.ui.clock.rate - } else { - 0.0 - }, + clock_rate, tick_rate: self.clock.rate(), tick_frozen: self.clock.frozen(), collision: Some(self.collision), diff --git a/crates/horizon-client/src/game/shield.rs b/crates/horizon-client/src/game/shield.rs index 849c62958..c4f7f98d1 100644 --- a/crates/horizon-client/src/game/shield.rs +++ b/crates/horizon-client/src/game/shield.rs @@ -34,7 +34,7 @@ impl Game<'_> { &self, stack: &ItemStack, ) -> Option<&horizon_client::items::BlocksAttacks> { - self.res.items.get(&stack.item)?.blocks_attacks.as_ref() + self.res.items().get(&stack.item)?.blocks_attacks.as_ref() } /// `ShieldItem.use` (ItemUtils.startUsingInstantly) for the hand at `slot`; /// false when that hand holds no blocking item or it is on cooldown. @@ -64,7 +64,7 @@ impl Game<'_> { if (ticks as i32) < (component.delay_seconds * 20.0).round() as i32 { return None; } - let tags = &self.res.stations.enchantments.damage_tags; + let tags = &self.res.stations().enchantments.damage_tags; let matches = |spec: &str| match spec.strip_prefix('#') { Some(tag) => tags.get(tag).is_some_and(|t| t.contains(damage_type)), None => spec == damage_type, @@ -150,7 +150,11 @@ impl Game<'_> { }; if item_damage > 0 && !self.creative { let loss = self.durability_loss(&stack, item_damage as u32); - let max = self.res.items.get(&stack.item).map_or(0, |i| i.max_damage); + let max = self + .res + .items() + .get(&stack.item) + .map_or(0, |i| i.max_damage); let cell = self.stack_in_mut(slot); if let Some(s) = cell.as_mut() && max > 0 @@ -182,7 +186,7 @@ impl Game<'_> { .extra .main_hand .as_deref() - .and_then(|item| self.res.items.get(item)) + .and_then(|item| self.res.items().get(item)) .map_or(0.0, |i| i.disable_blocking_seconds); // Ravager.blockedByItem: stunned half the time (the defender pushed // apart), else the defender flung away; no roar in progress. diff --git a/crates/horizon-client/src/game/sign_edit.rs b/crates/horizon-client/src/game/sign_edit.rs index c0a780063..c679bad69 100644 --- a/crates/horizon-client/src/game/sign_edit.rs +++ b/crates/horizon-client/src/game/sign_edit.rs @@ -88,7 +88,7 @@ impl Game<'_> { return; }; let line = edit.line; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let width = |s: &str| HudBatch::text_width(atlas, s); let Some(key) = self.sign_edit.as_ref().map(|e| e.pos) else { return; @@ -130,7 +130,7 @@ impl Game<'_> { } else { &mut sign.back }; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; self.text_selection.apply( sign_line_id(front, line), &mut text.lines[line], @@ -163,7 +163,7 @@ impl Game<'_> { let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&edit.pos) else { return; }; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); batch.fill(atlas, 0.0, 0.0, w, h, rgba(16, 16, 16, 160)); let title = if sign.hanging { @@ -175,7 +175,7 @@ impl Game<'_> { batch.text(atlas, title, (w - tw) / 2.0, 40.0, u32::MAX, true); let name = self .res - .facts + .facts() .get(self.world.block(edit.pos.0, edit.pos.1, edit.pos.2)) .name .clone(); diff --git a/crates/horizon-client/src/game/sniffers.rs b/crates/horizon-client/src/game/sniffers.rs index 61325ede6..a30c0ba5c 100644 --- a/crates/horizon-client/src/game/sniffers.rs +++ b/crates/horizon-client/src/game/sniffers.rs @@ -93,7 +93,7 @@ impl Game<'_> { self.particles.push(particle); } if self.mobs[i].age.is_multiple_of(10) { - let hit = self.res.facts.get(below).sounds.hit.clone(); + let hit = self.res.facts().get(below).sounds.hit.clone(); self.audio.play(&hit, Some(at), 0.5, 0.5); } } diff --git a/crates/horizon-client/src/game/spawner.rs b/crates/horizon-client/src/game/spawner.rs index c42299c86..538cb39e7 100644 --- a/crates/horizon-client/src/game/spawner.rs +++ b/crates/horizon-client/src/game/spawner.rs @@ -45,7 +45,7 @@ impl Game<'_> { .as_ref() .is_some_and(|t| t.contains(id)) } - fn load_entity_types(&mut self) { + pub(super) fn load_entity_types(&mut self) { if self.spawners.entity_types.is_some() { return; } @@ -63,32 +63,27 @@ impl Game<'_> { .unwrap_or_default(); self.spawners.entity_types = Some(types); } - /// Every spawner's server tick, then its client tick. - pub(super) fn tick_spawners(&mut self) -> Result<()> { - self.load_entity_types(); - let keys: Vec = self - .world - .block_entities - .iter() - .filter(|(_, e)| matches!(e, BlockEntity::Spawner(_))) - .map(|(k, _)| *k) - .collect(); - for key in &keys { - let state = self.world.block(key.0, key.1, key.2); - if &*self.res.facts.get(state).name != "minecraft:spawner" { - continue; - } - let Some(BlockEntity::Spawner(mut spawner)) = self.world.block_entities.remove(key) - else { - continue; - }; - let result = self.server_tick_spawner(*key, &mut spawner); - self.world - .block_entities - .insert(*key, BlockEntity::Spawner(spawner)); - result?; + /// The server tick of the spawner at `key`, if its block is still a + /// spawner. Its client tick comes after every block entity's + /// (`client_tick_spawners`). + pub(super) fn tick_spawner(&mut self, key: Pos) -> Result<()> { + let state = self.world.block(key.0, key.1, key.2); + if &*self.res.facts().get(state).name != "minecraft:spawner" { + return Ok(()); } - for key in keys { + let Some(BlockEntity::Spawner(mut spawner)) = self.world.block_entities.take(&key) else { + return Ok(()); + }; + let result = self.server_tick_spawner(key, &mut spawner); + self.world + .block_entities + .put(key, BlockEntity::Spawner(spawner)); + result + } + /// The client ticks of these spawners, then the shown mobs of spawners + /// that are gone go. + pub(super) fn client_tick_spawners(&mut self, keys: &[Pos]) { + for &key in keys { self.client_tick_spawner(key); } let entities = &self.world.block_entities; @@ -98,7 +93,6 @@ impl Game<'_> { Some(BlockEntity::Spawner(_) | BlockEntity::TrialSpawner(_)) ) }); - Ok(()) } fn server_tick_spawner(&mut self, key: Pos, spawner: &mut Spawner) -> Result<()> { let pos = [key.0, key.1, key.2]; @@ -151,7 +145,7 @@ impl Game<'_> { r: &SpawnerSpawn, planned: &mut Vec, ) -> Option { - let kind = self.res.mob_types.get(r.id)?.clone(); + let kind = self.res.mob_types().get(r.id)?.clone(); let [x, y, z] = r.position; let at = Vec3::new(x, y, z); let bounds = if r.finalize { @@ -201,7 +195,7 @@ impl Game<'_> { tag.insert("PersistenceRequired".into(), Tag::Byte(1)); } let tag = Tag::Compound(tag); - let mob = horizon_client::entity_nbt::mob_from_nbt(&tag, &self.res.mob_types, 0)?; + let mob = horizon_client::entity_nbt::mob_from_nbt(&tag, self.res.mob_types(), 0)?; let bounds = mob.bounds(); planned.push(Planned::Loaded(tag)); bounds @@ -337,7 +331,7 @@ impl Game<'_> { .get(&key) .is_none_or(|(k, _)| *k != kind) { - let Some(t) = self.res.mob_types.get(&kind).cloned() else { + let Some(t) = self.res.mob_types().get(&kind).cloned() else { return false; }; let mob = Mob::new(u32::MAX, t, Vec3::ZERO, 0.0); @@ -357,7 +351,7 @@ impl Game<'_> { } _ => return None, }; - self.res.mob_types.contains_key(&id).then_some(id) + self.res.mob_types().contains_key(&id).then_some(id) } /// `SpawnEggItem.useOn` on a spawner: the egg sets its mob. None when the /// clicked block has no spawner. @@ -399,7 +393,7 @@ impl Game<'_> { alpha: f64, out: &mut Vec, ) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); for (key, (_, mob)) in &self.spawners.displays { let at = glam::DVec3::new(f64::from(key.0), f64::from(key.1), f64::from(key.2)); @@ -442,7 +436,7 @@ impl Game<'_> { origin, &lookup, packed, - &self.res.mob_data, + self.res.mob_data(), out, ); } diff --git a/crates/horizon-client/src/game/startup_menu.rs b/crates/horizon-client/src/game/startup_menu.rs new file mode 100644 index 000000000..9531b0f38 --- /dev/null +++ b/crates/horizon-client/src/game/startup_menu.rs @@ -0,0 +1,782 @@ +//! The interactive title before world resources exist. Uses only the menu +//! atlas/panorama; transfers the actual screen and queued entry to Game. +use super::*; +use horizon_client::{ + clipboard::{self, AppendSelection, SystemClipboard}, + options_ui::{Event, OptionsUi, Page}, +}; +use winit::{event::KeyEvent, keyboard::ModifiersState}; + +#[derive(Default)] +pub(super) struct StartupMenu { + title: Option, + options: OptionsUi, + options_open: bool, + root: PathBuf, + cursor: (f32, f32), + pointer: (f64, f64), + modifiers: ModifiersState, + physical_keys: HashSet<KeyCode>, + dragging: bool, + clipboard: SystemClipboard, + selection: AppendSelection, + pub pending: Option<PendingWorldEntry>, + pub reload_packs: bool, + pub perf: horizon_client::telemetry::Session, +} + +impl StartupMenu { + pub fn new(options: &Options, pack_error: Option<&str>) -> Result<Self> { + let pending = if let Some(address) = &options.server { + Some(PendingWorldEntry::Server { + address: address.clone(), + name: options.player_name(), + }) + } else { + options + .world + .as_ref() + .map(|folder| PendingWorldEntry::Local { + folder: folder.clone(), + name: None, + seed: Some(options.seed), + creative: options.creative, + create: None, + }) + }; + let mut menu = Self { + pending, + ..Default::default() + }; + menu.root = options.resources.clone(); + if let Some(error) = pack_error { + menu.options.open_at(false, Page::Packs); + menu.options.resource_error = Some(error.to_owned()); + menu.options_open = true; + } + if menu.pending.is_some() { + menu.perf.world_opening(); + } + Ok(menu) + } + + pub(super) fn set_root(&mut self, root: PathBuf, settings: &Settings) { + horizon_client::ui::load_metadata(&root); + horizon_client::lang::set(horizon_client::lang::Language::load( + &[&root], + &settings.language, + )); + self.root = root; + if self.title.is_none() { + let mut title = Title::new( + std::env::current_dir().unwrap_or_default().join("saves"), + &self.root, + ); + title.last_server = settings.file.string("lastServer"); + if horizon_client::ui_theme::horizon() { + title + .opening + .set(Some(horizon_client::front::Opening::new())); + } + self.title = Some(title); + } + } + + pub(super) fn handoff(&mut self, game: &mut Game<'_>) { + game.title = self.title.take(); + game.pending_entry = self.pending.take(); + game.cursor = self.cursor; + game.modifiers = self.modifiers; + game.physical_keys = std::mem::take(&mut self.physical_keys); + game.clipboard = std::mem::take(&mut self.clipboard); + game.text_selection = std::mem::take(&mut self.selection); + game.perf = std::mem::take(&mut self.perf); + // Preserve an existing resource-error screen opened by start_game. + if self.options_open { + let resource_error = game.ui.options.resource_error.take(); + game.ui.options = std::mem::take(&mut self.options); + game.ui.options.resource_error = + game.ui.options.resource_error.take().or(resource_error); + game.screen = Screen::Options; + game.options_from_title = true; + game.dragging = self.dragging; + } + } + + fn queue_entry(&mut self, action: Action, player_name: String) { + let entry = match action { + Action::Play { folder } => PendingWorldEntry::Local { + folder, + name: None, + seed: None, + creative: false, + create: None, + }, + Action::Create { + folder, + name, + seed, + creative, + options, + } => PendingWorldEntry::Local { + folder, + name: Some(name), + seed, + creative, + create: Some(Box::new(options)), + }, + Action::Connect { address } => PendingWorldEntry::Server { + address, + name: player_name, + }, + _ => return, + }; + self.pending = Some(entry); + self.perf.world_opening(); + } + + fn shortcut(&mut self, event: &KeyEvent) -> Option<clipboard::EditShortcut> { + let edit = if cfg!(target_os = "macos") { + self.modifiers.super_key() + } else { + self.modifiers.control_key() + }; + clipboard::edit_shortcut( + clipboard::shortcut_letter(&event.logical_key, event.physical_key), + edit, + self.modifiers.shift_key(), + self.modifiers.alt_key(), + ) + } + + fn title_key(&mut self, event: &KeyEvent) { + let shortcut = self.shortcut(event); + let Some(title) = &mut self.title else { return }; + if title.skip_opening() { + return; + } + if let Some(shortcut) = shortcut { + if title.has_caret_field() { + title.field_shortcut(shortcut, &mut self.clipboard); + } else if let Some((id, value, max)) = title.focused_field() + && self + .selection + .apply(id, value, shortcut, &mut self.clipboard, |v, t| { + clipboard::append_limited(v, t, max) + }) + { + title.search_changed(); + } + return; + } + match event.physical_key { + PhysicalKey::Code(KeyCode::Escape) => title.escape(), + PhysicalKey::Code(KeyCode::Tab) => title.tab(), + PhysicalKey::Code(KeyCode::Enter | KeyCode::NumpadEnter) => title.confirm_edit(), + PhysicalKey::Code( + key @ (KeyCode::Backspace + | KeyCode::Delete + | KeyCode::ArrowLeft + | KeyCode::ArrowRight + | KeyCode::Home + | KeyCode::End), + ) if title.has_caret_field() => { + title.field_key( + key, + self.modifiers.control_key(), + self.modifiers.shift_key(), + ); + } + _ => { + let cleared = !title.has_caret_field() + && title + .focused_field() + .is_some_and(|(id, value, _)| self.selection.take(id, value)); + if cleared { + title.search_changed(); + } + if event.physical_key == PhysicalKey::Code(KeyCode::Backspace) { + if !cleared { + title.backspace(); + } + } else if let Some(text) = &event.text { + title.type_text(text); + } + } + } + } +} + +/// Each generation has its own channel and progress. Pack changes wait for the +/// old tail before starting another generation, including cache/global writes. +pub(super) fn spawn_loader( + options: &Options, + settings: &Settings, + vanilla_root: &std::path::Path, + started: Instant, + progress: &Progress, +) -> Result<(Receiver<LoaderMsg>, JoinHandle<()>)> { + let (sender, receiver) = std::sync::mpsc::channel(); + let settings = settings.clone(); + let vanilla_root = vanilla_root.to_path_buf(); + let dev_mods = options.dev_mods.clone(); + let progress = progress.clone(); + let handle = std::thread::Builder::new() + .name("resource-loader".into()) + .spawn(move || { + let mut pack_error = None; + let root = packs::startup_root(&vanilla_root, &settings.resource_packs).unwrap_or_else( + |error| { + pack_error = Some(error.to_string()); + vanilla_root.clone() + }, + ); + let root = mods::content_root(&root, &settings.mods.enabled, &dev_mods); + let result = load_resources( + root, + &vanilla_root, + &settings, + started, + true, + &progress, + &mut |gui, root| { + let _ = sender.send(LoaderMsg::Ui(gui, root.to_path_buf())); + }, + ) + .map(|mut loaded| { + loaded.pack_error = loaded.pack_error.or(pack_error); + loaded + }) + .map_err(|error| error.to_string()); + let _ = sender.send(LoaderMsg::Done(result)); + })?; + Ok((receiver, handle)) +} + +impl Loading { + pub(super) fn poll_menu_resources(&mut self) -> Result<()> { + if self.loaded.is_none() { + loop { + match self.receiver.try_recv() { + Ok(LoaderMsg::Ui(gui, root)) => self.set_ui(gui, root), + Ok(LoaderMsg::Done(result)) => { + self.loaded = Some(result); + break; + } + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Disconnected) => { + if let Some(handle) = self.handle.take() { + let _ = handle.join(); + } + return Err("resource loader stopped before finishing".into()); + } + } + } + } + self.restart_menu_resources() + } + pub(super) fn apply_menu_settings(&mut self) { + if let Some(renderer) = &mut self.renderer { + self.settings + .clamp_gui_scale([renderer.config.width as i32, renderer.config.height as i32]); + renderer.gamma = self.settings.gamma; + renderer.set_present_mode(self.settings.vsync, self.settings.horizon.present_mode); + } + horizon_client::hud::GUI_SCALE.store(self.settings.gui_scale, Ordering::Relaxed); + if let Some(gui) = &mut self.gui { + gui.atlas.font.uniform = self.settings.force_unicode; + gui.atlas.font.japanese = self.settings.japanese_glyphs; + } + if let Some(window) = &self.window + && let Some(want) = self.fullscreen.request(self.settings.fullscreen) + { + window.set_fullscreen(want.then_some(winit::window::Fullscreen::Borderless(None))); + } + self.update_menu_cursor(); + } + + fn update_menu_cursor(&mut self) { + let batch = HudBatch::new(self.menu_size()); + self.menu.cursor = ( + self.menu.pointer.0 as f32 / batch.scale, + self.menu.pointer.1 as f32 / batch.scale, + ); + } + + fn menu_size(&self) -> [u32; 2] { + self.renderer + .as_ref() + .map_or([1280, 720], |r| [r.config.width, r.config.height]) + } + + fn save_menu_address(&mut self) { + if self + .menu + .title + .as_ref() + .is_some_and(|title| title.last_server != self.settings.file.string("lastServer")) + { + self.save_menu_settings(); + } + } + + fn save_menu_settings(&mut self) { + if let Some(title) = &self.menu.title { + self.settings.file.set( + "lastServer", + horizon_client::options_file::V::Str(title.last_server.clone()), + ); + } + self.settings.save(&Game::options_path()); + } + + fn open_menu_options(&mut self, page: Page) { + self.menu.options.open_at(false, page); + self.menu.options.languages = horizon_client::lang::available(&[&self.menu.root]); + self.menu.options.pack_infos = packs::pack_infos(&self.vanilla_root); + self.menu.options.pack_selection = self.settings.resource_packs.clone(); + self.menu.options.pack_screen = None; + self.menu.options_open = true; + } + + fn menu_option_events(&mut self, events: Vec<Event>) { + for event in events { + match event { + Event::Changed => { + self.save_menu_settings(); + self.apply_menu_settings(); + } + Event::Close if self.menu.options.resource_error.is_some() => {} + Event::Close => { + self.menu.options_open = false; + self.menu.dragging = false; + self.save_menu_settings(); + } + Event::Language(code) => { + horizon_client::lang::set(horizon_client::lang::Language::load( + &[&self.menu.root], + &code, + )); + self.save_menu_settings(); + } + Event::Packs(_) => { + self.save_menu_settings(); + self.menu.reload_packs = true; + } + Event::OpenPackFolder => { + let dir = packs::packs_dir(); + let _ = std::fs::create_dir_all(&dir); + packs::open_folder(&dir); + } + Event::OpenModFolder => { + let dir = Game::options_path().with_file_name(horizon_client::mod_list::DIR); + let _ = std::fs::create_dir_all(&dir); + packs::open_folder(&dir); + } + Event::ButtonClick => {} + } + } + } + + fn menu_options_click(&mut self, drag: bool, right: bool) { + let size = self.menu_size(); + let batch = HudBatch::new(size); + let Some(gui) = &self.gui else { return }; + let events = self.menu.options.click( + &mut self.settings, + &gui.atlas, + self.menu.cursor.0, + self.menu.cursor.1, + (batch.width, batch.height), + [size[0] as i32, size[1] as i32], + drag, + right, + ); + self.menu_option_events(events); + } + + fn menu_action(&mut self, event_loop: &ActiveEventLoop, action: Action) { + match action { + Action::Quit => event_loop.exit(), + Action::Options => self.open_menu_options(Page::Main), + Action::Accessibility => self.open_menu_options(Page::Accessibility), + Action::Language => self.open_menu_options(Page::Language), + action => { + let name = self + .options + .as_ref() + .map_or_else(|| "Player".into(), |o| o.player_name()); + self.menu.queue_entry(action, name); + } + } + self.save_menu_address(); + } + + pub(super) fn menu_event( + &mut self, + event_loop: &ActiveEventLoop, + event: WindowEvent, + ) -> Result<()> { + if let WindowEvent::MouseInput { + state, + button: MouseButton::Left, + .. + } = &event + { + horizon_client::ui_theme::set_pressed(*state == ElementState::Pressed); + } + if let WindowEvent::KeyboardInput { event, .. } = &event + && let PhysicalKey::Code(key) = event.physical_key + { + if event.state == ElementState::Pressed { + self.menu.physical_keys.insert(key); + } else { + self.menu.physical_keys.remove(&key); + } + } + match event { + WindowEvent::CloseRequested => { + self.save_menu_settings(); + event_loop.exit(); + } + WindowEvent::Resized(size) => { + if let Some(r) = &mut self.renderer { + r.resize(size.width, size.height); + } + self.apply_menu_settings(); + } + WindowEvent::RedrawRequested => self.draw(), + WindowEvent::ModifiersChanged(modifiers) => self.menu.modifiers = modifiers.state(), + WindowEvent::Focused(false) => { + self.menu.modifiers = ModifiersState::empty(); + self.menu.physical_keys.clear(); + horizon_client::ui_theme::set_pressed(false); + self.menu.dragging = false; + if let Some(title) = &mut self.menu.title { + title.release(); + title.release_field(); + } + let events = self.menu.options.release(); + self.menu_option_events(events); + } + WindowEvent::KeyboardInput { event, .. } + if event.state == ElementState::Pressed && self.menu.pending.is_some() => + { + if event.physical_key == PhysicalKey::Code(KeyCode::Escape) { + self.menu.pending = None; + self.menu.perf.cancel_world_opening(); + } + } + _ if self.gui.is_none() || self.menu.pending.is_some() => {} + WindowEvent::CursorMoved { position, .. } => { + self.menu.pointer = (position.x, position.y); + self.update_menu_cursor(); + if self.menu.options_open && self.menu.dragging { + self.menu_options_click(true, false); + } else if let Some(title) = &mut self.menu.title { + let size = self + .renderer + .as_ref() + .map_or([1280, 720], |r| [r.config.width, r.config.height]); + let b = HudBatch::new(size); + title.drag(self.menu.cursor, (b.width, b.height)); + title.drag_field(&self.gui.as_ref().unwrap().atlas, self.menu.cursor.0); + } + } + WindowEvent::MouseInput { state, button, .. } if self.menu.options_open => { + if state == ElementState::Pressed && self.menu.options.selected_key.is_some() { + let events = self.menu.options.bind_mouse(&mut self.settings, button); + self.menu_option_events(events); + } else if matches!(button, MouseButton::Left | MouseButton::Right) { + if state == ElementState::Pressed { + self.menu.dragging = button == MouseButton::Left; + self.menu_options_click(false, button == MouseButton::Right); + } else if button == MouseButton::Left { + self.menu.dragging = false; + let events = self.menu.options.release(); + self.menu_option_events(events); + } + } + } + WindowEvent::MouseInput { + state, + button: MouseButton::Left, + .. + } => { + let mut batch = HudBatch::new(self.menu_size()); + if let (Some(title), Some(gui)) = (&mut self.menu.title, &self.gui) { + if state == ElementState::Released { + title.release(); + title.release_field(); + } else { + let action = if horizon_client::ui_theme::horizon() { + let action = title.click_horizon( + &gui.atlas, + &mut batch, + self.menu.cursor.0, + self.menu.cursor.1, + ); + // Horizon's deeper world-management pages use classic fields. + title.press_field( + &gui.atlas, + self.menu.cursor, + (batch.width, batch.height), + self.menu.modifiers.shift_key(), + ); + action + } else { + let (action, _) = title.click( + self.menu.cursor.0, + self.menu.cursor.1, + (batch.width, batch.height), + ); + title.press_field( + &gui.atlas, + self.menu.cursor, + (batch.width, batch.height), + self.menu.modifiers.shift_key(), + ); + action + }; + self.menu_action(event_loop, action); + } + } + } + WindowEvent::MouseWheel { delta, .. } => { + let raw = match delta { + MouseScrollDelta::LineDelta(_, y) => y, + MouseScrollDelta::PixelDelta(p) => (p.y / 30.0) as f32, + }; + let amount = if self.settings.discrete_scroll { + horizon_client::mouse::java_signum(f64::from(raw)) as f32 + } else { + raw + } * self.settings.mouse_wheel_sensitivity; + let batch = HudBatch::new(self.menu_size()); + if self.menu.options_open { + self.menu.options.scroll_at( + &self.settings, + (batch.width, batch.height), + self.menu.cursor, + amount, + ); + } else if let Some(title) = &mut self.menu.title { + title.scroll_worlds(amount, self.menu.cursor, (batch.width, batch.height)); + } + } + WindowEvent::KeyboardInput { event, .. } if event.state == ElementState::Pressed => { + if event.physical_key == PhysicalKey::Code(KeyCode::F11) { + self.settings.fullscreen = !self.settings.fullscreen; + self.apply_menu_settings(); + self.save_menu_settings(); + } else if self.menu.options_open { + let shortcut = self.menu.shortcut(&event); + let atlas = &self.gui.as_ref().unwrap().atlas; + let handled = shortcut.is_some_and(|s| { + self.menu + .options + .shortcut(atlas, s, &mut self.menu.clipboard) + }); + if !handled && let PhysicalKey::Code(key) = event.physical_key { + let events = self.menu.options.key( + &mut self.settings, + atlas, + key, + event.text.as_deref(), + ); + self.menu_option_events(events); + } + } else { + self.menu.title_key(&event); + self.save_menu_address(); + } + } + _ => {} + } + Ok(()) + } + + pub(super) fn draw_menu(&mut self, batch: &mut HudBatch) { + let Some(gui) = &self.gui else { return }; + if self.menu.pending.is_some() { + horizon_client::level_loading::draw_progress( + batch, + &gui.atlas, + self.progress.line(), + self.progress.fraction(), + ); + } else if self.menu.options_open { + self.menu + .options + .draw(&self.settings, batch, &gui.atlas, self.menu.cursor); + } else if let Some(title) = &mut self.menu.title { + title.poll_backup(); + let _ = title.update_toast(self.settings.notification_display_time); + if horizon_client::ui_theme::horizon() { + let mut ui = horizon_client::ui_theme::Ui::new(&gui.atlas, batch, self.menu.cursor); + title.draw_horizon(&mut ui, 0.0); + ui.finish(); + } else { + title.draw( + &gui.atlas, + batch, + self.menu.cursor, + self.settings.file.bool("hideSplashTexts"), + ); + } + } + } + + pub(super) fn restart_menu_resources(&mut self) -> Result<()> { + if !self.menu.reload_packs || self.loaded.is_none() { + return Ok(()); + } + if let Some(Ok(loaded)) = &mut self.loaded { + if let Some(loader) = &loaded.rest_loader + && !loader.ready()? + { + return Ok(()); + } + if let Some(loader) = loaded.rest_loader.take() + && let Err(error) = loader.finish() + { + log::warn!("Horizon: replaced resource generation failed: {error}"); + } + } + self.loaded = None; + if let Some(handle) = self.handle.take() { + handle.join().map_err(|_| "resource loader panicked")?; + } + self.progress = Progress::new(); + let options = self.options.as_ref().ok_or("loading already finished")?; + let (receiver, handle) = spawn_loader( + options, + &self.settings, + &self.vanilla_root, + self.started, + &self.progress, + )?; + self.receiver = receiver; + self.handle = Some(handle); + self.menu.reload_packs = false; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn gui(root: &std::path::Path) -> UiResources { + UiResources { + atlas: HudAtlas::fonts(root).unwrap(), + panorama: Arc::new(horizon_client::gfx::panorama::Faces { + size: 1, + pixels: [96, 110, 111, 255].repeat(6), + }), + } + } + + fn loading(receiver: Receiver<LoaderMsg>) -> Loading { + Loading { + window: None, + renderer: None, + gui: None, + settings: Settings::default(), + fullscreen: horizon_client::window::FullscreenState::new(false), + options: None, + vanilla_root: PathBuf::new(), + pack_error: None, + started: Instant::now(), + progress: Progress::new(), + receiver, + loaded: None, + handle: None, + shown: false, + menu: StartupMenu::default(), + error: None, + } + } + + #[test] + fn menu_is_usable_while_the_core_worker_is_blocked() { + let root = std::env::temp_dir().join("horizon-startup-menu-no-world-resources"); + let (sender, receiver) = std::sync::mpsc::channel(); + let (release, wait) = std::sync::mpsc::channel(); + let (published, published_rx) = std::sync::mpsc::channel(); + let worker_root = root.clone(); + let worker = std::thread::spawn(move || { + sender + .send(LoaderMsg::Ui(gui(&worker_root), worker_root)) + .unwrap(); + published.send(()).unwrap(); + wait.recv().unwrap(); + sender + .send(LoaderMsg::Done(Err("core failure".into()))) + .unwrap(); + }); + published_rx.recv().unwrap(); + let mut loading = loading(receiver); + loading.poll_menu_resources().unwrap(); + assert!(loading.gui.is_some()); + assert!(loading.loaded.is_none()); + assert!(!worker.is_finished()); + // Navigate and enter a world name without a registry, biomes, pack + // tables or a Game. Replacing fallback artwork preserves this state. + let title = loading.menu.title.as_mut().unwrap(); + title.opening.set(None); + title.mode = horizon_client::title::Mode::Create { + name: String::new(), + seed: "42".into(), + creative: true, + focus: 0, + options: Default::default(), + }; + title.type_text("My world"); + loading.set_ui(gui(&root), root); + let action = loading.menu.title.as_ref().unwrap().create_action(); + loading.menu.queue_entry(action, "Player".into()); + assert!( + matches!(&loading.menu.pending, Some(PendingWorldEntry::Local { + name: Some(name), seed: Some(42), creative: true, create: Some(_), .. + }) if name == "My world") + ); + let mut batch = HudBatch::new([1280, 720]); + loading.draw_menu(&mut batch); + assert!( + !batch.vertices.is_empty(), + "queued entry draws loading progress" + ); + release.send(()).unwrap(); + worker.join().unwrap(); + loading.poll_menu_resources().unwrap(); + assert!(matches!(loading.loaded, Some(Err(ref error)) if error == "core failure")); + } + + #[test] + fn queued_server_keeps_address_and_player_identity() { + let mut menu = StartupMenu::default(); + menu.queue_entry( + Action::Connect { + address: "localhost:25565".into(), + }, + "Guest".into(), + ); + assert!( + matches!(menu.pending.take(), Some(PendingWorldEntry::Server { address, name }) + if address == "localhost:25565" && name == "Guest") + ); + assert!(menu.pending.take().is_none(), "an entry is consumed once"); + } + + #[test] + fn disconnected_core_worker_is_reported_instead_of_waiting_forever() { + let (sender, receiver) = std::sync::mpsc::channel(); + drop(sender); + let mut loading = loading(receiver); + assert_eq!( + loading.poll_menu_resources().unwrap_err().to_string(), + "resource loader stopped before finishing" + ); + } +} diff --git a/crates/horizon-client/src/game/station_control.rs b/crates/horizon-client/src/game/station_control.rs index 680939a4f..75ad9225e 100644 --- a/crates/horizon-client/src/game/station_control.rs +++ b/crates/horizon-client/src/game/station_control.rs @@ -126,7 +126,7 @@ impl Game<'_> { "enchant" => { let e = id(arg(1)?); let level: u32 = arg(2)?.parse()?; - if self.res.stations.enchantments.get(&e).is_none() { + if self.res.stations().enchantments.get(&e).is_none() { return Err(format!("unknown enchantment {e}").into()); } let held = self.inventory[self.selected] diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 8cd751548..e8872b159 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -263,7 +263,7 @@ fn argb(c: i32) -> u32 { impl Game<'_> { fn data(&self) -> &stations::StationData { - &self.res.stations + self.res.stations() } pub(super) fn translate(&self, key: &str, fallback: &str) -> String { self.data() @@ -376,9 +376,13 @@ impl Game<'_> { } } fn count_bookshelves(&self, pos: [i32; 3]) -> i32 { - let tags = &self.res.items.block_tags; + let tags = &self.res.items().block_tags; let is = |p: [i32; 3], tag: &str| { - let name = &self.res.facts.get(self.world.block(p[0], p[1], p[2])).name; + let name = &self + .res + .facts() + .get(self.world.block(p[0], p[1], p[2])) + .name; tags.get(tag).is_some_and(|t| t.contains(&**name)) }; stations::bookshelf_offsets() @@ -412,8 +416,8 @@ impl Game<'_> { return; }; let creative = self.creative; - let data = &self.res.stations; - let items = &self.res.items; + let data = self.res.stations(); + let items = self.res.items(); match s.kind { Kind::Enchanting => { s.bookcases = self.count_bookshelves(s.pos); @@ -494,7 +498,10 @@ impl Game<'_> { self.station = Some(s); } pub(super) fn max_stack(&self, stack: &ItemStack) -> u32 { - self.res.items.get(&stack.item).map_or(64, |i| i.max_stack) + self.res + .items() + .get(&stack.item) + .map_or(64, |i| i.max_stack) } /// `Slot.mayPlace` and `getMaxStackSize` for station and brewing slots. fn slot_rules(&self, slot: usize, stack: &ItemStack) -> (bool, u32) { @@ -518,7 +525,7 @@ impl Game<'_> { 3 => (data.brewing.is_reagent(stack), 64), _ => ( self.res - .items + .items() .get(&stack.item) .is_some_and(|i| i.brewing_fuel.is_some()), 64, @@ -548,7 +555,7 @@ impl Game<'_> { 64, ), Kind::Enchanting => (&*stack.item == "minecraft:lapis_lazuli", 64), - Kind::Grindstone => (stations::grindstone_accepts(&self.res.items, stack), 64), + Kind::Grindstone => (stations::grindstone_accepts(self.res.items(), stack), 64), Kind::Smithing => (data.recipes.smithing_accepts(i, stack), 64), _ => (true, 64), } @@ -667,7 +674,7 @@ impl Game<'_> { let data = self.data(); let fuel = self .res - .items + .items() .get(&stack.item) .is_some_and(|i| i.brewing_fuel.is_some()); let (reagent, bottle) = ( @@ -818,7 +825,7 @@ impl Game<'_> { if !self.creative && self.world.random.next_float() < 0.12 { // AnvilBlock.damage let state = self.world.block(pos[0], pos[1], pos[2]); - let name = self.res.facts.get(state).name.clone(); + let name = self.res.facts().get(state).name.clone(); let next = match &*name { "minecraft:anvil" => Some("minecraft:chipped_anvil"), "minecraft:chipped_anvil" => Some("minecraft:damaged_anvil"), @@ -848,7 +855,7 @@ impl Game<'_> { let (a, b) = (s.inputs[0].take(), s.inputs[1].take()); let mut random = LegacyRandom::new(self.world.random.next_long()); let xp = stations::grindstone_experience( - &self.res.stations.enchantments, + &self.res.stations().enchantments, &mut random, a.as_ref(), b.as_ref(), @@ -945,7 +952,7 @@ impl Game<'_> { Some(c) if c.same_item_same_components(&result) && c.count + result.count - <= self.res.items.get(&c.item).map_or(64, |i| i.max_stack) => + <= self.res.items().get(&c.item).map_or(64, |i| i.max_stack) => { c.count += result.count } @@ -988,8 +995,8 @@ impl Game<'_> { return; } let Some(enchanted) = stations::apply_enchantment( - &self.res.stations.enchantments, - &self.res.items, + &self.res.stations().enchantments, + self.res.items(), self.level.xp_seed, button, cost, @@ -1051,7 +1058,8 @@ impl Game<'_> { } } pub(super) fn station_click(&mut self, right: bool) -> bool { - if self.station.is_none() && !self.brewing_open() { + // A server's brewing stand: its slots are the server's. + if self.station.is_none() && (!self.brewing_open() || self.remote.is_some()) { return false; } let Some(size) = self @@ -1249,7 +1257,7 @@ impl Game<'_> { } /// Text in the Standard Galactic alphabet (`minecraft:alt`), cut to `max` pixels. fn galactic(&self, batch: &mut HudBatch, text: &str, x: f32, y: f32, max: f32, color: u32) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let Some(sheet) = atlas.sprites.get("font/ascii_sga").copied() else { batch.text(atlas, text, x, y, color, false); return; @@ -1325,7 +1333,7 @@ impl Game<'_> { let local = (self.cursor.0 - ox, self.cursor.1 - oy); let mut tooltip: Option<Vec<(String, u32)>> = None; { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; batch.fill( atlas, 0.0, @@ -1342,7 +1350,7 @@ impl Game<'_> { }; let (fuel, total_fuel, brew, total_brew) = (b.fuel, b.total_fuel, b.brew_time, b.total_brew_time); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; Self::part( batch, atlas, @@ -1396,6 +1404,7 @@ impl Game<'_> { .as_ref() .and_then(|s| self.world.block_names.get(&(s.pos[0], s.pos[1], s.pos[2]))) .cloned() + .or_else(|| self.remote_menu_title()) .unwrap_or(default); let tw = HudBatch::text_width(atlas, &title); batch.text( @@ -1417,7 +1426,7 @@ impl Game<'_> { if self.slot_mut(i).is_none() { let (sx, sy) = self.station_slot_position(i).unwrap_or_default(); batch.sprite( - &self.atlas, + &self.gui.atlas, &format!("gui/sprites/container/slot/{icon}"), ox + sx, oy + sy, @@ -1427,7 +1436,7 @@ impl Game<'_> { } else if let Some(kind) = self.station.as_ref().map(|s| s.kind) { let title = self.translate(kind.title_key(), ""); { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; Self::part( batch, atlas, @@ -1446,7 +1455,7 @@ impl Game<'_> { if kind == Kind::Loom { tooltip = self.draw_loom(batch, ox, oy, local); } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let s = self.station.as_ref().expect("open station"); let has_input = s.inputs.iter().any(Option::is_some); match kind { @@ -1552,7 +1561,7 @@ impl Game<'_> { ); -8323296 }; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let cw = HudBatch::text_width(atlas, &cost_text); batch.text( atlas, @@ -1566,7 +1575,7 @@ impl Game<'_> { if inside(local, bx, by, bw, 17.0) && let Some((id, l)) = &offers.clues[i] { - let e = &self.res.stations.enchantments; + let e = &self.res.stations().enchantments; let (name, _) = e.full_name(id, *l); let clue = self .translate("container.enchant.clue", "%s . . . ?") @@ -1679,7 +1688,7 @@ impl Game<'_> { ) }; if let Some(line) = line { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let tw = HudBatch::text_width(atlas, &line); let tx = 176.0 - 8.0 - tw - 2.0; batch.fill( @@ -1766,7 +1775,7 @@ impl Game<'_> { i, ItemStack { count: 1, - ..self.res.stations.recipes.stonecutting[s.recipes[i]] + ..self.res.stations().recipes.stonecutting[s.recipes[i]] .result .clone() }, @@ -1788,7 +1797,7 @@ impl Game<'_> { "recipe" }; batch.sprite_scaled( - &self.atlas, + &self.gui.atlas, &format!("gui/sprites/container/stonecutter/{sprite}"), ox + x, oy + y - 1.0, @@ -1816,7 +1825,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); batch.fill( - &self.atlas, + &self.gui.atlas, ox + sx, oy + sy, 16.0, @@ -1858,7 +1867,7 @@ impl Game<'_> { /// `ItemStack.getTooltipLines` subset: name in rarity colour, potion /// effects, enchantments (gray, curses red), stored enchantments, trims. pub(super) fn stack_tooltip(&self, stack: &ItemStack) -> Vec<(String, u32)> { - let e: &Enchantments = &self.res.stations.enchantments; + let e: &Enchantments = &self.res.stations().enchantments; let props = e.props(&stack.item); let rarity = horizon_client::item_tooltip::rarity( stack, @@ -1885,17 +1894,27 @@ impl Game<'_> { } else { self.pack.names.item(&stack.item) }; - let mut lines = vec![(name, color)]; + let display = horizon_client::item_tooltip::TooltipDisplay::for_stack(stack); + let mut lines = Vec::new(); + if display.name_visible(self.screen == Screen::Creative) { + lines.push((name, color)); + } let translate = |k: &str| e.translate(k).map(str::to_owned); // ItemContainerContents.addToTooltip. let hover_name = |s: &ItemStack| { s.custom_name() .map_or_else(|| self.pack.names.item(&s.item), str::to_owned) }; - for line in horizon_client::item_tooltip::container_lines(stack, &hover_name, &translate) { - lines.push((line, u32::MAX)); + if display.shows("minecraft:container") { + for line in + horizon_client::item_tooltip::container_lines(stack, &hover_name, &translate) + { + lines.push((line, u32::MAX)); + } } - if stack.item.ends_with("potion") || &*stack.item == "minecraft:tipped_arrow" { + if display.shows("minecraft:potion_contents") + && (stack.item.ends_with("potion") || &*stack.item == "minecraft:tipped_arrow") + { let scale = match &*stack.item { "minecraft:lingering_potion" => 0.25, "minecraft:tipped_arrow" => 0.125, @@ -1912,7 +1931,9 @@ impl Game<'_> { lines.push((line, c)); } } - if let Some((material, pattern)) = stack.data().and_then(|d| d.trim.clone()) { + if display.shows("minecraft:trim") + && let Some((material, pattern)) = stack.data().and_then(|d| d.trim.clone()) + { lines.push(( e.translate("item.minecraft.smithing_template.upgrade") .unwrap_or("Upgrade:") @@ -1929,30 +1950,44 @@ impl Game<'_> { lines.push((format!(" {p}"), rgba(170, 170, 170, 255))); lines.push((format!(" {m}"), rgba(170, 170, 170, 255))); } - for (text, curse) in e - .tooltip(stack.stored_enchantments()) - .into_iter() - .chain(e.tooltip(stack.enchantments())) - { - lines.push(( - text, - if curse { - rgba(255, 85, 85, 255) - } else { - rgba(170, 170, 170, 255) - }, - )); + if display.shows("minecraft:stored_enchantments") { + for (text, curse) in e.tooltip(stack.stored_enchantments()) { + lines.push(( + text, + if curse { + rgba(255, 85, 85, 255) + } else { + rgba(170, 170, 170, 255) + }, + )); + } + } + if display.shows("minecraft:enchantments") { + for (text, curse) in e.tooltip(stack.enchantments()) { + lines.push(( + text, + if curse { + rgba(255, 85, 85, 255) + } else { + rgba(170, 170, 170, 255) + }, + )); + } } // BannerPatternLayers.addToTooltip: up to six layer names. - for layer in horizon_client::banner::tooltip_layers(stack).iter().take(6) { - let key = self.res.stations.banners.layer_key(layer); - lines.push((self.translate(&key, &key), rgba(170, 170, 170, 255))); + if display.shows("minecraft:banner_patterns") { + for layer in horizon_client::banner::tooltip_layers(stack).iter().take(6) { + let key = self.res.stations().banners.layer_key(layer); + lines.push((self.translate(&key, &key), rgba(170, 170, 170, 255))); + } } // Spawner.appendHoverText: what a spawner or trial spawner item spawns. - if matches!( - &*stack.item, - "minecraft:spawner" | "minecraft:trial_spawner" - ) { + if display.shows("minecraft:block_entity_data") + && matches!( + &*stack.item, + "minecraft:spawner" | "minecraft:trial_spawner" + ) + { let gray = rgba(170, 170, 170, 255); match block_entity_item::spawner_entity(stack) { Some(id) => { @@ -1969,7 +2004,9 @@ impl Game<'_> { } } } - if let Some(info) = self.res.items.get(&stack.item) { + if display.shows("minecraft:attribute_modifiers") + && let Some(info) = self.res.items().get(&stack.item) + { let base = |name: &str, default| { self.player .as_ref() @@ -1997,7 +2034,8 @@ impl Game<'_> { &translate, )); } - if let Some(info) = self.res.items.get(&stack.item) + if display.shows("minecraft:damage") + && let Some(info) = self.res.items().get(&stack.item) && info.max_damage > 0 && stack.damage > 0 && self.options_advanced_tooltips() @@ -2039,7 +2077,7 @@ impl Game<'_> { _ => serde_json::Value::Null, }; }; - let recipes = &self.res.stations.recipes.stonecutting; + let recipes = &self.res.stations().recipes.stonecutting; serde_json::json!({ "costs": s.offers.costs, "clues": s.offers.clues.iter().map(|c| c.as_ref().map(|(e, l)| format!("{e} {l}"))).collect::<Vec<_>>(), @@ -2065,7 +2103,7 @@ impl Game<'_> { if lines.is_empty() { return; } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let w = lines .iter() .map(|(t, _)| HudBatch::text_width(atlas, t)) @@ -2144,22 +2182,22 @@ impl Game<'_> { // ---------------------------------------------------------------- brewing stand - /// Ticks every brewing stand (`BrewingStandBlockEntity.serverTick`). - pub(super) fn tick_brewing_stands(&mut self) -> horizon_client::Result<()> { - let mut changes = Vec::new(); - for (pos, entity) in self.world.block_entities.iter_mut() { - if let BlockEntity::Brewing(b) = entity { - let out = b.tick( - &self.res.stations.brewing, - &self.res.items, - &self.res.providers, - ); - if out != brewing::BrewTick::default() { - changes.push((*pos, out)); - } - } - } - for ((x, y, z), out) in changes { + /// `BrewingStandBlockEntity.serverTick` of the brewing stand at `pos`, in + /// its place among the level's block entity tickers. + pub(super) fn tick_brewing_stand( + &mut self, + pos: (i32, i32, i32), + ) -> horizon_client::Result<()> { + let Some(BlockEntity::Brewing(b)) = self.world.block_entities.get_mut(&pos) else { + return Ok(()); + }; + let out = b.tick( + &self.res.stations().brewing, + self.res.items(), + self.res.providers(), + ); + if out != brewing::BrewTick::default() { + let (x, y, z) = pos; self.world.modified.insert((x >> 4, z >> 4)); if out.brewed { self.play_at("minecraft:block.brewing_stand.brew", [x, y, z], 1.0, 1.0); diff --git a/crates/horizon-client/src/game/stats.rs b/crates/horizon-client/src/game/stats.rs index c36b99eaa..7a97416ca 100644 --- a/crates/horizon-client/src/game/stats.rs +++ b/crates/horizon-client/src/game/stats.rs @@ -20,22 +20,50 @@ pub(super) struct Stats { /// Statistic changes (type, key, amount; `None` = reset) for the /// scoreboard criteria to follow. pub(super) events: Vec<(String, String, Option<i32>)>, - /// Changed since the client was last sent them (`StatsCounter`'s dirty set). - pub(super) dirty: BTreeSet<(String, String)>, + /// Changed since the client was last sent them (`StatsCounter`'s dirty + /// set), by type. + dirty: BTreeMap<String, BTreeSet<String>>, } + +/// `minecraft:` and `name`, given to `f` from the stack when short: some +/// counters go up every tick for every player, and they are found without +/// a string made for each. +fn namespaced<T>(name: &str, f: impl FnOnce(&str) -> T) -> T { + const NAMESPACE: &str = "minecraft:"; + let mut buf = [0u8; 96]; + let len = NAMESPACE.len() + name.len(); + if len > buf.len() { + return f(&format!("{NAMESPACE}{name}")); + } + buf[..NAMESPACE.len()].copy_from_slice(NAMESPACE.as_bytes()); + buf[NAMESPACE.len()..len].copy_from_slice(name.as_bytes()); + // Two strings one after the other are one. + f(std::str::from_utf8(&buf[..len]).unwrap_or_default()) +} + +/// The map under `key`, made when missing, found without an owned key +/// when there. +fn entry<'a, V: Default>(map: &'a mut BTreeMap<String, V>, key: &str) -> &'a mut V { + if !map.contains_key(key) { + map.insert(key.to_owned(), V::default()); + } + map.get_mut(key).expect("just inserted") +} + impl Stats { pub(super) fn add(&mut self, ty: &str, key: &str, n: i32) { - let v = self - .values - .entry(format!("minecraft:{ty}")) - .or_default() - .entry(key.to_owned()) - .or_insert(0); - *v = v.saturating_add(n); - self.events - .push((format!("minecraft:{ty}"), key.to_owned(), Some(n))); - self.dirty - .insert((format!("minecraft:{ty}"), key.to_owned())); + namespaced(ty, |ty| { + let v = entry(entry(&mut self.values, ty), key); + *v = v.saturating_add(n); + self.events.push((ty.to_owned(), key.to_owned(), Some(n))); + self.mark_dirty(ty, key); + }); + } + fn mark_dirty(&mut self, ty: &str, key: &str) { + let keys = entry(&mut self.dirty, ty); + if !keys.contains(key) { + keys.insert(key.to_owned()); + } } pub(super) fn get(&self, ty: &str, key: &str) -> i32 { self.values @@ -48,20 +76,19 @@ impl Stats { if let Some(m) = self.values.get_mut(&format!("minecraft:{ty}")) { m.insert(key.to_owned(), 0); } - self.dirty - .insert((format!("minecraft:{ty}"), key.to_owned())); + self.mark_dirty(&format!("minecraft:{ty}"), key); self.events .push((format!("minecraft:{ty}"), key.to_owned(), None)); } pub(super) fn custom(&mut self, key: &str, n: i32) { - self.add("custom", &format!("minecraft:{key}"), n); + namespaced(key, |key| self.add("custom", key, n)); } /// `ServerStatsCounter.markAllDirty`: everything goes out on the next request. pub(super) fn mark_all_dirty(&mut self) { self.dirty = self .values .iter() - .flat_map(|(ty, m)| m.keys().map(|k| (ty.clone(), k.clone()))) + .map(|(ty, m)| (ty.clone(), m.keys().cloned().collect())) .collect(); } /// `ServerStatsCounter.sendStats`' entries: the dirty statistics and @@ -69,6 +96,7 @@ impl Stats { pub(super) fn take_dirty(&mut self) -> Vec<(String, String, i32)> { std::mem::take(&mut self.dirty) .into_iter() + .flat_map(|(ty, keys)| keys.into_iter().map(move |key| (ty.clone(), key))) .map(|(ty, key)| { let v = self.values.get(&ty).and_then(|m| m.get(&key)).copied(); (ty, key, v.unwrap_or(0)) @@ -216,14 +244,14 @@ impl Game<'_> { p.position.y.floor() as i32, p.position.z.floor() as i32, ]; - let eye_in_water = self.res.facts.get(self.world.block( + let eye_in_water = self.res.facts().get(self.world.block( feet[0], (p.position.y + f64::from(p.dimensions.eye_height)).floor() as i32, feet[2], )); let in_water = self .res - .facts + .facts() .get(self.world.block(feet[0], feet[1], feet[2])) .fluid == horizon_client::blocks::Fluid::Water; @@ -317,7 +345,11 @@ impl Game<'_> { pos[1] + 20 + r.next_int_bound(15).unwrap_or(0), pos[2] - 10 + r.next_int_bound(21).unwrap_or(10), ]; - if !self.res.facts.is_air(self.world.block(at[0], at[1], at[2])) { + if !self + .res + .facts() + .is_air(self.world.block(at[0], at[1], at[2])) + { return; } let group = 1 + self.world.random.next_int_bound(3).unwrap_or(0); @@ -335,8 +367,59 @@ impl Game<'_> { } fn can_see_sky(&self, pos: [i32; 3]) -> bool { (pos[1] + 1..pos[1] + 256).all(|y| { - let f = self.res.facts.get(self.world.block(pos[0], y, pos[2])); + let f = self.res.facts().get(self.world.block(pos[0], y, pos[2])); !f.full_collision && f.fluid == horizon_client::blocks::Fluid::None }) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn counters_events_and_dirty_entries() { + let mut s = Stats::default(); + s.custom("play_time", 1); + s.custom("play_time", 1); + s.add("mined", "minecraft:stone", 2); + s.custom(&"x".repeat(100), 3); + assert_eq!(s.get("custom", "minecraft:play_time"), 2); + assert_eq!(s.get("mined", "minecraft:stone"), 2); + assert_eq!( + s.get("custom", &format!("minecraft:{}", "x".repeat(100))), + 3 + ); + assert_eq!(s.events.len(), 4); + assert_eq!( + s.events[1], + ( + "minecraft:custom".into(), + "minecraft:play_time".into(), + Some(1) + ) + ); + let long = format!("minecraft:{}", "x".repeat(100)); + let sent = |v: &[(&str, &str, i32)]| -> Vec<(String, String, i32)> { + v.iter() + .map(|&(t, k, n)| (t.to_owned(), k.to_owned(), n)) + .collect() + }; + assert_eq!( + s.take_dirty(), + sent(&[ + ("minecraft:custom", "minecraft:play_time", 2), + ("minecraft:custom", &long, 3), + ("minecraft:mined", "minecraft:stone", 2), + ]) + ); + assert!(s.take_dirty().is_empty()); + s.reset("mined", "minecraft:stone"); + assert_eq!( + s.take_dirty(), + sent(&[("minecraft:mined", "minecraft:stone", 0)]) + ); + s.mark_all_dirty(); + assert_eq!(s.take_dirty().len(), 3); + } +} diff --git a/crates/horizon-client/src/game/stats_screen.rs b/crates/horizon-client/src/game/stats_screen.rs index 40b151453..5505d423d 100644 --- a/crates/horizon-client/src/game/stats_screen.rs +++ b/crates/horizon-client/src/game/stats_screen.rs @@ -222,7 +222,7 @@ impl Game<'_> { } pub(super) fn draw_stats(&mut self, batch: &mut HudBatch) { let (w, h) = (batch.width, batch.height); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); let (top, bottom) = (TAB_H, h - FOOTER); ui::separators(batch, atlas, top, bottom, true); @@ -333,13 +333,13 @@ impl Game<'_> { } let stack = ItemStack::new(item, 1); batch.sprite( - &self.atlas, + &self.gui.atlas, "gui/sprites/container/slot", left + 1.0, y + 1.0, ); self.draw_item(batch, &stack, left + 2.0, y + 2.0); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let color = if (i + 1) % 2 == 0 { u32::MAX } else { @@ -347,8 +347,12 @@ impl Game<'_> { }; for (c, (ty, _)) in COLUMNS.iter().enumerate() { let x = left + 75.0 + 40.0 * c as f32; - let block = - c == 0 && self.res.items.get(item).is_some_and(|i| i.block.is_some()); + let block = c == 0 + && self + .res + .items() + .get(item) + .is_some_and(|i| i.block.is_some()); let text = if c == 0 && !block { Text::translate("stats.none", &[]).plain() } else { @@ -400,7 +404,7 @@ impl Game<'_> { } } } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; ui::scrollbar( batch, atlas, @@ -413,7 +417,7 @@ impl Game<'_> { self.draw_stats_footer(batch, w, h); } fn draw_stats_footer(&self, batch: &mut HudBatch, w: f32, h: f32) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (bx, by) = ((w / 2.0 - 100.0).floor(), h - FOOTER + 6.0); let hover = ui::hovered(self.cursor, bx, by, 200.0, 20.0); ui::button( diff --git a/crates/horizon-client/src/game/storage.rs b/crates/horizon-client/src/game/storage.rs index 44b62e276..9b28ce26b 100644 --- a/crates/horizon-client/src/game/storage.rs +++ b/crates/horizon-client/src/game/storage.rs @@ -22,7 +22,7 @@ impl Game<'_> { (300..400).contains(&slot) && is_shulker_box(&stack.item) && self.container.is_some_and(|k| { - is_shulker_box(&self.res.facts.get(self.world.block(k.0, k.1, k.2)).name) + is_shulker_box(&self.res.facts().get(self.world.block(k.0, k.1, k.2)).name) }) } /// Opening an ender chest shows the player's ender inventory in its place. @@ -160,7 +160,7 @@ impl Game<'_> { let k = self.container?; Some( self.res - .facts + .facts() .get(self.world.block(k.0, k.1, k.2)) .name .clone(), @@ -211,7 +211,7 @@ impl Game<'_> { oy: f32, ) { use horizon_client::hud::rgba; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let grey = rgba(64, 64, 64, 255); if self .container_block() diff --git a/crates/horizon-client/src/game/subtitle_hud.rs b/crates/horizon-client/src/game/subtitle_hud.rs index cf89a4b15..f54ca874d 100644 --- a/crates/horizon-client/src/game/subtitle_hud.rs +++ b/crates/horizon-client/src/game/subtitle_hud.rs @@ -47,7 +47,7 @@ impl Game<'_> { width: batch.width as i32, height: batch.height as i32, }; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let draws = self .subtitles .overlay diff --git a/crates/horizon-client/src/game/sulfur_cubes.rs b/crates/horizon-client/src/game/sulfur_cubes.rs index c4cee6319..d1bf9def9 100644 --- a/crates/horizon-client/src/game/sulfur_cubes.rs +++ b/crates/horizon-client/src/game/sulfur_cubes.rs @@ -52,7 +52,7 @@ impl Game<'_> { } // 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 { + let Some(state) = self.res.items().get(item).and_then(|item| item.block) else { return; }; let start = out.len(); @@ -60,7 +60,7 @@ impl Game<'_> { state, 42, block_transform(base, mob.is_baby()), - block_light(light, self.res.facts.get(state).emission), + block_light(light, self.res.facts().get(state).emission), true, out, ); diff --git a/crates/horizon-client/src/game/titles.rs b/crates/horizon-client/src/game/titles.rs index 459aab503..70ade5595 100644 --- a/crates/horizon-client/src/game/titles.rs +++ b/crates/horizon-client/src/game/titles.rs @@ -16,10 +16,10 @@ impl Game<'_> { let (w, h) = (batch.width as i32, batch.height as i32); let partial = self.clock.fraction() as f32; let background = self.settings.text_background(0.0); - let font = &self.atlas.font; + let font = &self.gui.atlas.font; let mut draws = self.titles.overlay_message(w, h, partial, font, background); draws.extend(self.titles.title(w, h, partial, font, background)); - hud_layout::paint(batch, &self.atlas, &draws); + hud_layout::paint(batch, &self.gui.atlas, &draws); } /// The selected stack as `Hud.tick` compares it for the name highlight. fn held_name(&self) -> Option<HeldName> { @@ -54,9 +54,9 @@ impl Game<'_> { batch.width as i32, batch.height as i32, can_hurt, - &self.atlas.font, + &self.gui.atlas.font, self.settings.text_background(0.0), ); - hud_layout::paint(batch, &self.atlas, &draws); + hud_layout::paint(batch, &self.gui.atlas, &draws); } } diff --git a/crates/horizon-client/src/game/tnt.rs b/crates/horizon-client/src/game/tnt.rs index 78f107599..92da4a0bb 100644 --- a/crates/horizon-client/src/game/tnt.rs +++ b/crates/horizon-client/src/game/tnt.rs @@ -12,6 +12,8 @@ use horizon_world::level::flags as level_flags; #[derive(Clone, Debug)] pub(super) struct PrimedTnt { + /// The entity id a server tracks it by (0 until it is tracked). + pub id: u32, pub position: Vec3, pub previous: Vec3, pub velocity: Vec3, @@ -140,6 +142,7 @@ impl Game<'_> { f64::from(pos.z) + 0.5, ); self.tnts.push(PrimedTnt { + id: 0, position, previous: position, velocity: Vec3::new(-rot.sin() * 0.02, f64::from(0.2f32), -rot.cos() * 0.02), @@ -159,7 +162,7 @@ impl Game<'_> { &self.world, self.collision, &self.pack.assets, - &self.res.facts, + self.res.facts(), )?; if t.fuse <= 0 { let center = [ @@ -186,7 +189,7 @@ impl Game<'_> { return Ok(false); }; let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); - if &*self.res.facts.get(state).name != "minecraft:tnt" { + if &*self.res.facts().get(state).name != "minecraft:tnt" { return Ok(false); } let pos = BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]); @@ -216,7 +219,7 @@ impl Game<'_> { // Face sprites from the block model: up, down, north, south, west, east. let Ok(models) = self .pack - .assets + .render .model_catalog .collect(state, BlockPos::new(0, 0, 0)) else { @@ -238,10 +241,27 @@ impl Game<'_> { .pack .layer_names .get(&face.layer) - .and_then(|name| self.atlas.sprites.get(name).copied()); + .and_then(|name| self.gui.atlas.sprites.get(name).copied()); } } + let range = super::entity_culling::default_range( + glam::DVec3::splat(PrimedTnt::SIZE), + self.settings.entity_distance, + ); for t in &self.tnts { + // EntityRenderer.shouldRender. + if !self.standing_entity_in_view( + camera, + super::entity_culling::at(t.previous), + super::entity_culling::at(t.position), + alpha, + PrimedTnt::SIZE, + PrimedTnt::SIZE, + range, + 0.0, + ) { + continue; + } let fuse = t.fuse as f32 - alpha as f32 + 1.0; let scale = if fuse < 10.0 { let g = (1.0 - fuse / 10.0).clamp(0.0, 1.0); @@ -467,9 +487,10 @@ mod tests { return; } let assets = horizon_client::assets::Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let facts = horizon_client::blocks::BlockFacts::load(&root, assets.registry).unwrap(); let collision = horizon_client::collisions::load(&root, assets.registry).unwrap(); - let mut world = horizon_client::world::World::test_scene(&assets, 3).unwrap(); + let mut world = horizon_client::world::World::test_scene(&assets, &render, 3).unwrap(); let stone = assets.registry.default_state("minecraft:stone").unwrap(); let water = assets.registry.default_state("minecraft:water").unwrap(); let mut state = assets.registry.state(water).unwrap().clone(); @@ -484,6 +505,7 @@ mod tests { world.set(21, 4, 20, flowing).unwrap(); let at = Vec3::new(20.5, 4.0, 20.5); let mut tnt = PrimedTnt { + id: 0, position: at, previous: at, velocity: Vec3::ZERO, diff --git a/crates/horizon-client/src/game/trading.rs b/crates/horizon-client/src/game/trading.rs index ce389ac84..87e0c18c6 100644 --- a/crates/horizon-client/src/game/trading.rs +++ b/crates/horizon-client/src/game/trading.rs @@ -147,7 +147,7 @@ impl Game<'_> { variant: &str, origin: [f64; 3], ) -> Vec<MerchantOffer> { - let Some(sequence) = self.res.stations.trades.sequence(set) else { + let Some(sequence) = self.res.stations().trades.sequence(set) else { return Vec::new(); }; let mut random = self.rand_sequences.lend(&sequence, self.level.seed); @@ -160,15 +160,15 @@ impl Game<'_> { next_id: std::cell::Cell::new(next_map), }; let ctx = TradeContext { - items: &self.res.items, - enchantments: &self.res.stations.enchantments, + items: self.res.items(), + enchantments: &self.res.stations().enchantments, variant, origin, maps: Some(&maps), }; let offers = self .res - .stations + .stations() .trades .offers_from_set(&ctx, set, &mut random); let made = maps.made.into_inner(); @@ -205,7 +205,7 @@ impl Game<'_> { let profession = PROFESSIONS[m.extra.variant2 as usize % PROFESSIONS.len()]; let level = i32::from(m.extra.variant3.max(1)); let set = merchant::Trades::set_for(profession, level); - if self.res.stations.trades.sets.contains_key(&set) { + if self.res.stations().trades.sets.contains_key(&set) { self.offers_from_set(&set, &variant, origin) } else { Vec::new() @@ -284,7 +284,7 @@ impl Game<'_> { session.reputation = self.villager_reputation(id); session.hero = self.hero_amplifier(); for seq in merchant::Session::sequences_needed( - &self.res.stations.trades, + &self.res.stations().trades, &session.profession, level, ) { @@ -547,8 +547,8 @@ impl Game<'_> { m.focused, ); let offers = m.session.offers.clone(); - let costs: Vec<ItemStack> = offers.iter().map(|o| o.cost_a(&self.res.items)).collect(); - let atlas = &self.atlas; + let costs: Vec<ItemStack> = offers.iter().map(|o| o.cost_a(self.res.items())).collect(); + let atlas = &self.gui.atlas; batch.fill( atlas, 0.0, @@ -563,7 +563,7 @@ impl Game<'_> { r.v1 = r.v0 + 166.0 * dv; batch.rect_uv(ox + SHIFT, oy, 276.0, 166.0, r, u32::MAX); } - let e = &self.res.stations.enchantments; + let e = &self.res.stations().enchantments; let tr = |k: &str, f: &str| e.translate(k).unwrap_or(f).to_owned(); let name = custom.unwrap_or_else(|| { if progress { @@ -687,7 +687,7 @@ impl Game<'_> { } else { "gui/sprites/widget/button" }; - batch.sprite_scaled(&self.atlas, sprite, bx, by, 88.0, 20.0, u32::MAX); + batch.sprite_scaled(&self.gui.atlas, sprite, bx, by, 88.0, 20.0, u32::MAX); let y = oy + 16.0 + 1.0 + 20.0 * row as f32 + 2.0; let base = offer.base_cost_a.stack.clone(); let cost_a = costs[index].clone(); @@ -705,7 +705,7 @@ impl Game<'_> { x, y, ); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let t = base.count.to_string(); batch.text( atlas, @@ -740,7 +740,7 @@ impl Game<'_> { "trade_arrow" }; batch.sprite( - &self.atlas, + &self.gui.atlas, &format!("gui/sprites/container/villager/{arrow}"), ox + SHIFT + 60.0, y + 3.0, @@ -770,7 +770,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); batch.fill( - &self.atlas, + &self.gui.atlas, ox + sx, oy + sy, 16.0, @@ -794,7 +794,7 @@ impl Game<'_> { } else if deprecated { let text = self .res - .stations + .stations() .enchantments .translate("merchant.deprecated") .unwrap_or("Villagers restock up to two times per day.") diff --git a/crates/horizon-client/src/game/trial_spawner.rs b/crates/horizon-client/src/game/trial_spawner.rs index 4107e0859..42a26c6e4 100644 --- a/crates/horizon-client/src/game/trial_spawner.rs +++ b/crates/horizon-client/src/game/trial_spawner.rs @@ -106,34 +106,21 @@ impl TrialSpawnerLevel for GameLevel<'_, '_> { } impl Game<'_> { - /// Every trial spawner's server tick. - pub(super) fn tick_trial_spawners(&mut self) -> Result<()> { - let keys: Vec<Pos> = self - .world + /// The server tick of the trial spawner at `key`. Its client tick comes + /// after every block entity's. + pub(super) fn tick_trial_spawner(&mut self, key: Pos) -> Result<()> { + let Some((current, ominous)) = self.trial_spawner_block(key) else { + return Ok(()); + }; + let Some(BlockEntity::TrialSpawner(mut spawner)) = self.world.block_entities.take(&key) + else { + return Ok(()); + }; + let result = self.server_tick_trial_spawner(key, &mut spawner, current, ominous); + self.world .block_entities - .iter() - .filter(|(_, e)| matches!(e, BlockEntity::TrialSpawner(_))) - .map(|(k, _)| *k) - .collect(); - for &key in &keys { - let Some((current, ominous)) = self.trial_spawner_block(key) else { - continue; - }; - let Some(BlockEntity::TrialSpawner(mut spawner)) = - self.world.block_entities.remove(&key) - else { - continue; - }; - let result = self.server_tick_trial_spawner(key, &mut spawner, current, ominous); - self.world - .block_entities - .insert(key, BlockEntity::TrialSpawner(spawner)); - result?; - } - for key in keys { - self.client_tick_trial_spawner(key); - } - Ok(()) + .put(key, BlockEntity::TrialSpawner(spawner)); + result } /// The trial spawner block at `key`: its state and ominous flag. pub(super) fn trial_spawner_block(&self, key: Pos) -> Option<(TrialState, bool)> { diff --git a/crates/horizon-client/src/game/trial_visuals.rs b/crates/horizon-client/src/game/trial_visuals.rs index d32957fe1..cac28b5cc 100644 --- a/crates/horizon-client/src/game/trial_visuals.rs +++ b/crates/horizon-client/src/game/trial_visuals.rs @@ -237,7 +237,7 @@ impl Game<'_> { let shows = vault.display_item.is_some(); self.world .block_entities - .insert(key, BlockEntity::Vault(vault)); + .put(key, BlockEntity::Vault(vault)); let pos = [key.0, key.1, key.2]; if self.world.game_time % 20 == 0 { self.vault_connection_particles(pos); diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index 8c372fa46..b24f4540e 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -15,20 +15,48 @@ use horizon_core::{ }; pub(super) struct ThrownTrident { - stack: ItemStack, - position: Vec3, + /// The entity id a server tracks it by (0 until it is tracked). + pub id: u32, + pub(super) stack: ItemStack, + pub(super) position: Vec3, previous: Vec3, - velocity: Vec3, - yaw: f32, - pitch: f32, - in_ground: bool, + pub(super) velocity: Vec3, + pub(super) yaw: f32, + pub(super) pitch: f32, + pub(super) in_ground: bool, in_ground_time: u32, dealt_damage: bool, - loyalty: u32, - no_physics: bool, + pub(super) loyalty: u32, + pub(super) no_physics: bool, returning: u32, creative_only: bool, } +impl ThrownTrident { + /// A trident a server sent (`handleAddEntity`): placed and moved by it. + pub(super) fn remote(id: u32, position: Vec3, yaw: f32, pitch: f32) -> Self { + Self { + id, + stack: ItemStack::new("minecraft:trident", 1), + position, + previous: position, + velocity: Vec3::ZERO, + yaw, + pitch, + in_ground: false, + in_ground_time: 0, + dealt_damage: false, + loyalty: 0, + no_physics: false, + returning: 0, + creative_only: false, + } + } + /// One tick of a server's client: the previous position, then `step`. + pub(super) fn remote_step(&mut self, step: impl FnOnce(Vec3) -> Vec3) { + self.previous = self.position; + self.position = step(self.position); + } +} const HALF: f64 = 0.25; fn bounds(p: Vec3) -> Aabb { Aabb::new( @@ -70,7 +98,7 @@ impl Game<'_> { } let max = self .res - .items + .items() .get(&stack.item) .map_or(250, |i| i.max_damage); let riptide = stack.enchantment_level("minecraft:riptide") > 0; @@ -89,7 +117,7 @@ impl Game<'_> { p.position.y.floor() as i32, p.position.z.floor() as i32, ); - let water = self.res.facts.get(self.world.block(x, y, z)).fluid + let water = self.res.facts().get(self.world.block(x, y, z)).fluid == horizon_client::blocks::Fluid::Water; let sky = self.world.light(x, y + 1, z) >> 4 == 15; water || (self.world.weather.raining && sky) @@ -163,6 +191,7 @@ impl Game<'_> { on_ground, ); self.tridents.push(ThrownTrident { + id: 0, loyalty: thrown.enchantment_level("minecraft:loyalty"), stack: thrown, position: start, @@ -343,6 +372,7 @@ impl Game<'_> { return; }; let Some(uv) = self + .gui .atlas .sprites .get("entity/trident/trident") @@ -350,7 +380,26 @@ impl Game<'_> { else { return; }; + // AbstractArrow.shouldRenderAtSqrDistance: ten times the default. + let range = 10.0 + * super::entity_culling::default_range( + glam::DVec3::splat(2.0 * HALF), + self.settings.entity_distance, + ); for t in &self.tridents { + // EntityRenderer.shouldRender; ThrownTridentRenderer grows the box by 1.5. + if !self.standing_entity_in_view( + camera, + super::entity_culling::at(t.previous), + super::entity_culling::at(t.position), + alpha, + 2.0 * HALF, + 2.0 * HALF, + range, + 1.5, + ) { + continue; + } let p = glam::DVec3::new( t.previous.x + (t.position.x - t.previous.x) * alpha, t.previous.y + (t.position.y - t.previous.y) * alpha, diff --git a/crates/horizon-client/src/game/tweaks.rs b/crates/horizon-client/src/game/tweaks.rs index 018b6640b..681368cab 100644 --- a/crates/horizon-client/src/game/tweaks.rs +++ b/crates/horizon-client/src/game/tweaks.rs @@ -70,15 +70,7 @@ impl Game<'_> { /// One ordinary click on a game slot. False when nothing took it. pub(super) fn tweak_click(&mut self, slot: usize, button: i32, input: Input) -> bool { if self.remote.is_some() { - let ordinal = match input { - Input::Pickup => 0, - Input::QuickMove => 1, - Input::Swap => 2, - Input::Clone => 3, - Input::Throw => 4, - Input::QuickCraft => 5, - Input::PickupAll => 6, - }; + let ordinal = super::remote::input_ordinal(input); return self.remote_slot_click(slot, button as i8, ordinal); } if !self.menu_click(Some(slot), button, input) { @@ -331,7 +323,7 @@ impl Game<'_> { /// The sort buttons: a bordered square with three bars, lighter under /// the cursor. pub(super) fn draw_sort_buttons(&self, batch: &mut HudBatch, ox: f32, oy: f32) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; for ((x, y), _) in self.sort_buttons() { let (x, y) = (ox + x, oy + y); let (cx, cy) = self.cursor; diff --git a/crates/horizon-client/src/game/vault.rs b/crates/horizon-client/src/game/vault.rs index 31d7d3ea3..f3edfddb3 100644 --- a/crates/horizon-client/src/game/vault.rs +++ b/crates/horizon-client/src/game/vault.rs @@ -61,7 +61,7 @@ impl Game<'_> { .and_then(|s| VaultState::from_name(s)) .unwrap_or_default(); let ominous = block.properties.get("ominous").is_some_and(|v| v == "true"); - let Some(BlockEntity::Vault(vault)) = self.world.block_entities.remove(&key) else { + let Some(BlockEntity::Vault(vault)) = self.world.block_entities.take(&key) else { return None; }; Some((vault, current, ominous)) @@ -118,26 +118,20 @@ impl Game<'_> { self.rand_sequences = sequences; self.world .block_entities - .insert(key, BlockEntity::Vault(vault)); + .put(key, BlockEntity::Vault(vault)); Some(self.vault_events(key, events).map(|()| out)) } - /// Every vault's server tick, then its client tick. - pub(super) fn tick_vaults(&mut self) -> Result<()> { - let keys: Vec<Pos> = self - .world - .block_entities - .iter() - .filter(|(_, e)| matches!(e, BlockEntity::Vault(_))) - .map(|(k, _)| *k) - .collect(); - for key in keys { - let pos = [key.0, key.1, key.2]; - let ticked = self.with_vault(key, |v, l, random, state, ominous, roll, events| { - v.server_tick(l, random, pos, state, ominous, roll, events); - }); - if let Some(result) = ticked { - result?; - } + /// The server tick of the vault at `key`, then its client tick when there + /// is a window. + pub(super) fn tick_vault(&mut self, key: Pos) -> Result<()> { + let pos = [key.0, key.1, key.2]; + let ticked = self.with_vault(key, |v, l, random, state, ominous, roll, events| { + v.server_tick(l, random, pos, state, ominous, roll, events); + }); + if let Some(result) = ticked { + result?; + } + if self.options.dedicated.is_none() { self.client_tick_vault(key); } Ok(()) diff --git a/crates/horizon-client/src/game/villagers.rs b/crates/horizon-client/src/game/villagers.rs index 72fa2839a..5c6bed394 100644 --- a/crates/horizon-client/src/game/villagers.rs +++ b/crates/horizon-client/src/game/villagers.rs @@ -40,7 +40,7 @@ impl Game<'_> { .position(|m| m.id == id && m.species() == Species::Villager) } fn item_max_stack(&self, item: &str) -> u32 { - self.res.items.get(item).map_or(64, |i| i.max_stack) + self.res.items().get(item).map_or(64, |i| i.max_stack) } /// `BehaviorUtils.throwItem`: toss a stack from a villager's hand toward /// a point. @@ -57,7 +57,7 @@ impl Game<'_> { return; }; let now = self.world.game_time; - let items = &self.res.items; + let items = self.res.items(); let meeting = villager::meet(&mut self.mobs, ia, ib, now, |item| { items.get(item).map_or(64, |i| i.max_stack) }); @@ -121,13 +121,13 @@ impl Game<'_> { for _ in 0..=12 { y -= 1; let here = self.world.block(x, y, z); - let f = self.res.facts.get(here); - let above_f = self.res.facts.get(above); - let air_or_liquid = self.res.facts.is_air(above) + let f = self.res.facts().get(here); + let above_f = self.res.facts().get(above); + let air_or_liquid = self.res.facts().is_air(above) || above_f.fluid != horizon_client::blocks::Fluid::None; - let solid = self.res.mob_data.state(here).flags & horizon_client::mobs::data::SOLID - != 0 - || f.name.as_ref() == "minecraft:powder_snow"; + let solid = + self.res.mob_data().state(here).flags & horizon_client::mobs::data::SOLID != 0 + || f.name.as_ref() == "minecraft:powder_snow"; if golem_floor_ok(&f.name) && air_or_liquid && solid { found = Some(y + 1); break; @@ -137,7 +137,7 @@ impl Game<'_> { let Some(y) = found else { continue }; // IronGolem.checkSpawnRules: a floor and three free blocks. let free = |g: &Self, yy: i32| { - g.res.mob_data.state(g.world.block(x, yy, z)).flags + g.res.mob_data().state(g.world.block(x, yy, z)).flags & horizon_client::mobs::data::VALID_EMPTY_SPAWN != 0 }; @@ -260,7 +260,7 @@ impl Game<'_> { } let picks_up = self .res - .items + .items() .item_tags .get("minecraft:villager_picks_up") .cloned(); diff --git a/crates/horizon-client/src/game/wandering_trader.rs b/crates/horizon-client/src/game/wandering_trader.rs index b336cdf0b..d42ac662f 100644 --- a/crates/horizon-client/src/game/wandering_trader.rs +++ b/crates/horizon-client/src/game/wandering_trader.rs @@ -126,14 +126,14 @@ impl Game<'_> { } let biome = self.world.chunks.get(&(pos[0] >> 4, pos[2] >> 4)).map(|c| { self.res - .biomes + .biomes() .get(c.biome(pos[0], pos[1], pos[2])) .name .clone() }); if biome.is_some_and(|b| { self.res - .mob_data + .mob_data() .biome_has("minecraft:without_wandering_trader_spawns", &b) }) { return false; @@ -214,7 +214,7 @@ impl Game<'_> { (0..=1).all(|dz| { !self .res - .facts + .facts() .get(self.world.block(pos[0] + dx, pos[1] + dy, pos[2] + dz)) .full_collision }) @@ -230,7 +230,7 @@ impl Game<'_> { continue; } for y in (from[1] - range).max(horizon_client::chunk::MIN_Y)..=from[1] + range { - if &*self.res.facts.get(self.world.block(x, y, z)).name != "minecraft:bell" { + if &*self.res.facts().get(self.world.block(x, y, z)).name != "minecraft:bell" { continue; } let d = (x - from[0]).pow(2) + (y - from[1]).pow(2) + (z - from[2]).pow(2); diff --git a/crates/horizon-client/src/game/wind.rs b/crates/horizon-client/src/game/wind.rs index 07759944f..355b5b877 100644 --- a/crates/horizon-client/src/game/wind.rs +++ b/crates/horizon-client/src/game/wind.rs @@ -141,7 +141,7 @@ impl Game<'_> { fn wind_positions(&mut self, center: [f64; 3], radius: f32) -> Vec<[i32; 3]> { let stops = self .res - .items + .items() .block_tags .get("minecraft:blocks_wind_charge_explosions") .cloned() @@ -176,7 +176,7 @@ impl Game<'_> { } let name = &self .res - .facts + .facts() .get(self.world.block(pos[0], pos[1], pos[2])) .name; if stops.contains(&**name) { @@ -402,7 +402,7 @@ impl Game<'_> { /// buttons, levers and bells react as if used; candles go out. fn wind_trigger_block(&mut self, pos: [i32; 3]) -> Result<()> { let state = self.world.block(pos[0], pos[1], pos[2]); - let name = self.res.facts.get(state).name.clone(); + let name = self.res.facts().get(state).name.clone(); let prop = |game: &Self, key: &str| { game.pack .assets @@ -478,6 +478,7 @@ impl Game<'_> { }); let Some(model) = model else { return }; let Some(r) = self + .gui .atlas .sprites .get("entity/projectiles/wind_charge") diff --git a/crates/horizon-client/src/game/wither.rs b/crates/horizon-client/src/game/wither.rs index dfd215814..7b86dc527 100644 --- a/crates/horizon-client/src/game/wither.rs +++ b/crates/horizon-client/src/game/wither.rs @@ -10,14 +10,22 @@ use horizon_client::{ impl Game<'_> { fn is_wither_skull(&self, p: [i32; 3]) -> bool { - let name = &*self.res.facts.get(self.world.block(p[0], p[1], p[2])).name; + let name = &*self + .res + .facts() + .get(self.world.block(p[0], p[1], p[2])) + .name; matches!( name, "minecraft:wither_skeleton_skull" | "minecraft:wither_skeleton_wall_skull" ) } fn is_soul_base(&self, p: [i32; 3]) -> bool { - let name = &*self.res.facts.get(self.world.block(p[0], p[1], p[2])).name; + let name = &*self + .res + .facts() + .get(self.world.block(p[0], p[1], p[2])) + .name; matches!(name, "minecraft:soul_sand" | "minecraft:soul_soil") } /// After a wither skeleton skull is placed: the T of soul sand (or soul @@ -36,7 +44,7 @@ impl Game<'_> { && self.is_soul_base(at(1, 2)) && [0, 2].iter().all(|&c| { let p = at(c, 2); - self.res.facts.is_air(self.world.block(p[0], p[1], p[2])) + self.res.facts().is_air(self.world.block(p[0], p[1], p[2])) }); if !ok { continue; diff --git a/crates/horizon-client/src/gamepad.rs b/crates/horizon-client/src/gamepad.rs index a250f5e8c..220f74a5b 100644 --- a/crates/horizon-client/src/gamepad.rs +++ b/crates/horizon-client/src/gamepad.rs @@ -1009,6 +1009,7 @@ pub enum TriggerFeel { /// Mining a block of this hardness: a buzz, stronger and slower on harder blocks. Texture(f32), } +#[cfg(feature = "controllers")] impl TriggerFeel { /// The effect, for a trigger that presses its action at `threshold` (0..1) of its travel. pub fn effect(self, threshold: f32) -> horizon_dualsense::TriggerEffect { @@ -1044,6 +1045,7 @@ impl TriggerFeel { } } } +#[cfg(feature = "controllers")] impl PadSettings { /// The left and right triggers' effects: each feels the action bound to it, `key.use` or /// `key.attack`. @@ -1404,6 +1406,7 @@ mod tests { assert_eq!(w.observe(Some(1.0)), Some(1.0)); } + #[cfg(feature = "controllers")] #[test] fn triggers_feel_their_action() { use horizon_dualsense::{TRIGGER_OFF, trigger}; diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 3c232c755..8481fdcab 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -24,7 +24,7 @@ const CRUMBLING_BLEND: wgpu::BlendState = wgpu::BlendState { }; /// `TerrainVertex` for `vs_terrain`: position, UV, layer, light, colour. const TERRAIN_ATTRIBUTES: [wgpu::VertexAttribute; 5] = - wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint16,4=>Uint8x2,3=>Unorm8x4]; + wgpu::vertex_attr_array![0=>Float32x3,1=>Uint16x2,2=>Uint16,4=>Uint8x2,3=>Unorm8x4]; /// entity.wgsl after the OverlayTexture constants it reads. fn entity_shader() -> String { @@ -58,6 +58,7 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6] } mod arena; +mod cull; mod flat; mod java_stages; mod occlusion; @@ -69,6 +70,12 @@ pub mod translucency; pub(crate) mod upload; mod world_post; +/// A new value for `Renderer::block_entity_revision`. +fn next_block_entity_revision() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) +} + #[repr(C)] #[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] struct Globals { @@ -107,6 +114,12 @@ struct SectionGpu { } /// Line segments the hit outline can hold. const MAX_OUTLINE_EDGES: u64 = 256; +/// Staging buffer size for section meshes: a frame of uploads while +/// exploring fits in a few. +const SECTION_UPLOAD_CHUNK: u64 = 4 << 20; +/// Section copies are submitted early past this many staged bytes, which +/// bounds the staging memory frames that are not drawn can hold. +const SECTION_COPY_LIMIT: u64 = 64 << 20; pub struct Frame<'a> { pub camera: DVec3, pub yaw: f32, @@ -258,6 +271,9 @@ pub struct Renderer { flat: Option<flat::Flat>, /// `flat` draws this frame's sections (off: the per-section draws). flat_on: bool, + /// Occlusion culling of solid section draws, where multi-draw is native. + cull: Option<cull::Cull>, + cull_on: bool, sky: wgpu::RenderPipeline, dark_disc: wgpu::RenderPipeline, lines: wgpu::RenderPipeline, @@ -319,6 +335,13 @@ pub struct Renderer { lightmap_sampler: wgpu::Sampler, animations: AnimatedSprites, uploads: upload::Uploads, + /// Section meshes are staged through their own belt into + /// `section_copies`, which the next frame records its commands after: + /// `Queue::write_buffer` would make a staging buffer per write. + section_uploads: upload::Uploads, + section_copies: Option<wgpu::CommandEncoder>, + /// Bytes staged in `section_copies`. + section_copy_bytes: u64, /// Whether `lightmap` holds `lightmap_pixels` yet. lightmap_uploaded: bool, sprite_minimum_size: u32, @@ -346,8 +369,14 @@ pub struct Renderer { draws: Vec<[u32; 5]>, /// Vertex arena page and optional sorted index arena page of each draw. draw_pages: Vec<(u32, Option<u32>)>, + /// Solid draws left to occlusion culling's phase 2, while the list is + /// built, and their pages. + phase2_draws: Vec<[u32; 5]>, + phase2_pages: Vec<(u32, Option<u32>)>, /// Block-entity blocks per meshed section (world position, state id). block_entities: HashMap<SectionKey, Vec<([i32; 3], u32)>>, + /// Changes whenever `block_entities` does (unique across renderers). + block_entity_revision: u64, /// VisGraph face connectivity per meshed section (cave culling). occlusion: occlusion::Occlusion, /// Resolution scale and FXAA (Horizon settings). @@ -633,6 +662,7 @@ impl Renderer { // Mappable primary buffers: section pages that no // longer fit in video memory go to system memory. required_features: timing::GpuTimer::features(&adapter) + | cull::Cull::features(&adapter) | (adapter.features() & (wgpu::Features::INDIRECT_FIRST_INSTANCE | wgpu::Features::MAPPABLE_PRIMARY_BUFFERS)), @@ -1079,7 +1109,9 @@ impl Renderer { let instances = device.create_buffer(&wgpu::BufferDescriptor { label: Some("Section origins"), size: instance_capacity * 16, - usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + usage: wgpu::BufferUsages::VERTEX + | wgpu::BufferUsages::COPY_DST + | wgpu::BufferUsages::STORAGE, mapped_at_creation: false, }); let outline = device.create_buffer(&wgpu::BufferDescriptor { @@ -1724,8 +1756,18 @@ impl Renderer { let multi_draw = device .features() .contains(wgpu::Features::INDIRECT_FIRST_INSTANCE); + // HORIZON_GPU_CULL=0 turns occlusion culling off, `all` culls every + // frame however little it hides (A/B checks). + let cull_env = std::env::var("HORIZON_GPU_CULL"); + let cull = (cull_env.as_deref() != Ok("0") && cull::Cull::supported(&adapter, &device)) + .then(|| { + let mut cull = cull::Cull::new(&device, config.format.remove_srgb_suffix()); + cull.always = cull_env.as_deref() == Ok("all"); + cull + }); let world_post = world_post::Post::new(&device, config.format.remove_srgb_suffix()); let uploads = upload::Uploads::new(&device); + let section_uploads = upload::Uploads::with_chunk(&device, SECTION_UPLOAD_CHUNK); let panorama = panorama::Panorama::new( &device, &queue, @@ -1750,6 +1792,8 @@ impl Renderer { solid, translucent, flat_on: flat.is_some(), + cull_on: cull.is_some(), + cull, flat, sky, dark_disc, @@ -1800,6 +1844,9 @@ impl Renderer { lightmap_sampler, animations: AnimatedSprites::new(animations, sprite_size, sprite_mips), uploads, + section_uploads, + section_copies: None, + section_copy_bytes: 0, lightmap_uploaded: false, sprite_minimum_size, indices, @@ -1820,7 +1867,10 @@ impl Renderer { origins: Vec::new(), draws: Vec::new(), draw_pages: Vec::new(), + phase2_draws: Vec::new(), + phase2_pages: Vec::new(), block_entities: HashMap::new(), + block_entity_revision: next_block_entity_revision(), occlusion: occlusion::Occlusion::new(crate::chunk::HEIGHT / 16), world_post, pack: None, @@ -1972,18 +2022,50 @@ impl Renderer { self.flat_on = on; Ok(()) } + /// Whether solid sections are occlusion culled (`cull`). + pub fn section_cull(&self) -> bool { + self.cull_on + } + /// Switches occlusion culling, for A/B checks. + pub fn set_section_cull(&mut self, on: bool) -> Result<()> { + if on && self.cull.is_none() { + return Err("occlusion culling is off on this device".into()); + } + self.cull_on = on; + Ok(()) + } + /// Of the boxes occlusion culling's last test read back drew, how many + /// it did not see and how many it drew, and the share of solid indices + /// it hid. + pub fn culled_sections(&self) -> Option<([usize; 2], f32)> { + self.cull + .as_ref() + .filter(|_| self.cull_on) + .map(|c| c.hidden) + } pub fn section_count(&self) -> usize { self.sections.len() } pub fn has_section(&self, key: SectionKey) -> bool { self.sections.contains(key) } + /// Bring the cave culling graph up to date for `camera` without waiting: + /// a search this starts runs on its worker while the frame is prepared, + /// and `render` takes it if it has finished. + pub fn start_occlusion(&mut self, camera: DVec3, distance: f32) { + self.occlusion + .update(camera_section(camera), (distance / 16.0) as i32 + 2); + } pub fn upload(&mut self, key: SectionKey, mesh: &SectionMesh) { self.occlusion.set(key, mesh.visibility); - if mesh.block_entities.is_empty() { - self.block_entities.remove(&key); + let changed = if mesh.block_entities.is_empty() { + self.block_entities.remove(&key).is_some() } else { - self.block_entities.insert(key, mesh.block_entities.clone()); + let old = self.block_entities.insert(key, mesh.block_entities.clone()); + old.as_deref() != Some(&mesh.block_entities[..]) + }; + if changed { + self.block_entity_revision = next_block_entity_revision(); } let solid = (mesh.solid.len() / 4) as u32; let translucent = (mesh.translucent.len() / 4) as u32; @@ -1997,14 +2079,20 @@ impl Renderer { self.indices = Self::quad_indices(&self.device, self.index_quads); } let vertices = (mesh.solid.len() + mesh.translucent.len()) as u64; + let encoder = self.section_copies.get_or_insert_with(|| { + self.device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("Section uploads"), + }) + }); // With video and system memory both full, the section is not drawn. - let Some((page, start)) = self.arena.alloc(&self.device, &self.queue, vertices) else { + let Some((page, start)) = self.arena.alloc(&self.device, encoder, vertices) else { return; }; let sorted_indices = if translucent > 0 { let indices = self.sorted_indices - .alloc(&self.device, &self.queue, u64::from(translucent) * 6); + .alloc(&self.device, encoder, u64::from(translucent) * 6); if indices.is_none() { self.arena.release(page, start, vertices); return; @@ -2013,22 +2101,35 @@ impl Renderer { } else { None }; - let flat_id = self - .flat - .as_mut() - .map(|f| f.add(&self.device, &self.queue, page, start, vertices)); + let flat_id = self.flat.as_mut().map(|f| { + f.add( + &self.device, + encoder, + &mut self.section_uploads, + page, + start, + vertices, + ) + }); let stride = std::mem::size_of::<TerrainVertex>() as u64; for (offset, part) in [(0, &mesh.solid), (mesh.solid.len(), &mesh.translucent)] { if !part.is_empty() { let bytes: &[u8] = bytemuck::cast_slice(part); self.uploaded_bytes += bytes.len() as u64; - self.queue.write_buffer( + self.section_copy_bytes += bytes.len() as u64; + self.section_uploads.buffer( + encoder, self.arena.buffer(page), (start + offset as u64) * stride, bytes, ); } } + if self.section_copy_bytes >= SECTION_COPY_LIMIT + && let Some(copies) = self.take_section_copies() + { + self.queue.submit([copies]); + } self.sections.insert( key, SectionGpu { @@ -2050,11 +2151,26 @@ impl Renderer { }, ); } + /// The section copies recorded since the last submission, closed. + fn take_section_copies(&mut self) -> Option<wgpu::CommandBuffer> { + let encoder = self.section_copies.take()?; + self.section_copy_bytes = 0; + self.section_uploads.finish(&encoder); + Some(encoder.finish()) + } /// Draws `count` section draws from `first` with the arena and section /// origins bound: one indirect multi-draw, or a loop without it. /// Consecutive draws in one arena page share a vertex buffer binding, /// keeping the list's order (translucent sections go back to front). - fn draw_sections(&self, pass: &mut wgpu::RenderPass<'_>, first: u32, count: u32) { + /// `indirect` holds the list's draws from `base`. + fn draw_sections( + &self, + pass: &mut wgpu::RenderPass<'_>, + indirect: &wgpu::Buffer, + base: u32, + first: u32, + count: u32, + ) { let (mut i, end) = (first as usize, (first + count) as usize); while i < end { let (page, index_page) = self.draw_pages[i]; @@ -2066,7 +2182,8 @@ impl Renderer { let indices = index_page.map_or(&self.indices, |p| self.sorted_indices.buffer(p)); pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); if self.multi_draw { - pass.multi_draw_indexed_indirect(&self.indirect, i as u64 * 20, run as u32); + let offset = (i - base as usize) as u64 * 20; + pass.multi_draw_indexed_indirect(indirect, offset, run as u32); } else { for d in &self.draws[i..i + run] { pass.draw_indexed(d[2]..d[2] + d[0], d[3] as i32, d[4]..d[4] + 1); @@ -2092,8 +2209,13 @@ impl Renderer { pub fn block_entities(&self) -> impl Iterator<Item = &([i32; 3], u32)> { self.block_entities.values().flatten() } + /// A value that changes whenever `block_entities` gives something else. + pub fn block_entity_revision(&self) -> u64 { + self.block_entity_revision + } pub fn clear_sections(&mut self) { self.block_entities.clear(); + self.block_entity_revision = next_block_entity_revision(); self.sections.clear(); self.arena.clear(); if let Some(flat) = &mut self.flat { @@ -2104,7 +2226,9 @@ impl Renderer { self.occlusion.clear(); } pub fn remove(&mut self, key: SectionKey) { - self.block_entities.remove(&key); + if self.block_entities.remove(&key).is_some() { + self.block_entity_revision = next_block_entity_revision(); + } self.occlusion.remove(key); self.release_section(key); } @@ -2279,6 +2403,14 @@ impl Renderer { ); } pub fn render(&mut self, frame: &Frame) -> Result<bool> { + let rendered = self.draw_frame(frame); + // A frame that was not drawn still submits the section copies. + if let Some(copies) = self.take_section_copies() { + self.queue.submit([copies]); + } + rendered + } + fn draw_frame(&mut self, frame: &Frame) -> Result<bool> { self.arena.trim(); self.sorted_indices.trim(); if let Some(flat) = &mut self.flat { @@ -2316,14 +2448,21 @@ impl Renderer { Some(f) => f.texture.clone(), None => self.offscreen.clone().ok_or("no offscreen target")?, }; - let mut encoder = self - .device - .create_command_encoder(&wgpu::CommandEncoderDescriptor { - label: Some("Horizon frame"), - }); + // One command buffer for the frame, after the section copies staged + // since the last one: Metal commits every command buffer wgpu-core + // makes (one per run of copies and two per pass) on its own. + let section_copies = self.section_copies.take(); + let has_section_copies = section_copies.is_some(); + let mut encoder = section_copies.unwrap_or_else(|| { + self.device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("Horizon frame"), + }) + }); if self.animated_textures { self.animate(&mut encoder, frame.ticks); - self.hud.animate_fire(&self.queue, frame.ticks); + self.hud + .animate_fire(&mut self.uploads, &mut encoder, frame.ticks); } self.update_lightmap( &mut encoder, @@ -2466,17 +2605,10 @@ impl Renderer { planes: frustum(view_proj), }; let camera = frame.camera; - let camera_section = ( - (camera.x.floor() as i32) >> 4, - (camera.y.floor() as i32 - crate::chunk::MIN_Y) >> 4, - (camera.z.floor() as i32) >> 4, - ); + let camera_section = camera_section(camera); let culling = !frame.title && frame.cave_culling; if culling { - let radius = (frame.distance / 16.0) as i32 + 2; - crate::spans::time("occlusion", || { - self.occlusion.update(camera_section, radius) - }); + crate::spans::time("occlusion", || self.start_occlusion(camera, frame.distance)); } let reachable = &self.occlusion; let mut visible = std::mem::take(&mut self.visible); @@ -2496,7 +2628,9 @@ impl Renderer { self.instances = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("Section origins"), size: self.instance_capacity * 16, - usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + usage: wgpu::BufferUsages::VERTEX + | wgpu::BufferUsages::COPY_DST + | wgpu::BufferUsages::STORAGE, mapped_at_creation: false, }); } @@ -2525,15 +2659,48 @@ impl Renderer { let eye = (frame.bob * crate::camera::view_matrix(frame.yaw, frame.pitch)) .inverse() .transform_point3(Vec3::ZERO); + // Occlusion culling leaves the sections its last result did not see + // to phase 2, after the others, with instance counts of 0. + let mut cull = self + .cull + .as_mut() + .filter(|_| { + self.cull_on + && !frame.title + && self.multi_draw + && !(self.flat_on && self.flat.is_some()) + }) + .and_then(|cull| cull.begin(&self.device).then_some(cull)); + self.phase2_draws.clear(); + self.phase2_pages.clear(); for (i, v) in visible.iter().enumerate() { let s = self.sections.get(v.slot); + let first_phase = cull.as_ref().is_none_or(|c| c.first(v.slot)); + let (draws, pages) = if first_phase { + (&mut self.draws, &mut self.draw_pages) + } else { + (&mut self.phase2_draws, &mut self.phase2_pages) + }; + let start = draws.len(); + let instances = u32::from(first_phase); + let mut indices = 0; // Only the solid groups that can face the eye. s.faces.ranges(eye - Vec3::from(v.origin), |first, quads| { let first = s.start + u64::from(first) * 4; - self.draws.push([quads * 6, 1, 0, first as u32, i as u32]); - self.draw_pages.push((s.page, None)); + draws.push([quads * 6, instances, 0, first as u32, i as u32]); + pages.push((s.page, None)); + indices += quads * 6; }); + match &mut cull { + Some(c) if first_phase => c.drawn(i, v.slot, indices), + Some(c) => c.deferred(i, v.slot, start, draws.len() - start, indices), + None => {} + } } + let phase1_draws = self.draws.len() as u32; + self.draws.extend_from_slice(&self.phase2_draws); + self.draw_pages.extend_from_slice(&self.phase2_pages); + let culling = cull.is_some(); let solid_draws = self.draws.len() as u32; // LevelRenderer: nearby sections each frame, plus a rotating eighth // (at least 15) of the visible list. Cached views avoid needless sorts. @@ -2583,6 +2750,7 @@ impl Renderer { (0..self.draws.len()) .filter(|&i| { i == 0 + || i == phase1_draws as usize || i == solid_draws as usize || self.draw_pages[i] != self.draw_pages[i - 1] }) @@ -2590,48 +2758,6 @@ impl Renderer { } 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 { - label: Some("Section draws"), - size: self.indirect_capacity * 20, - usage: wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - } - self.uploads.buffer( - &mut encoder, - &self.indirect, - 0, - bytemuck::cast_slice(&self.draws), - ); - } let debug_depth = frame.debug_lines.len() as u32; let debug_top = frame.debug_lines_on_top.len() as u32; let crosshair = frame.debug_crosshair.len() as u32; @@ -2768,6 +2894,87 @@ impl Renderer { bytemuck::bytes_of(&uniform), ); } + // Every upload before the frame's first pass: a pass ends wgpu-core's + // command buffer, so copies between passes would need one more. + if !frame.screen.is_empty() { + let vertices: Vec<crate::screen_effects::ScreenVertex> = + frame.screen.iter().flat_map(|q| q.vertices).collect(); + if vertices.len() as u64 > self.screen_capacity { + self.screen_capacity = (vertices.len() as u64).next_power_of_two(); + self.screen_buffer = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Screen effect vertices"), + size: self.screen_capacity + * std::mem::size_of::<crate::screen_effects::ScreenVertex>() as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + } + self.uploads.buffer( + &mut encoder, + &self.screen_buffer, + 0, + bytemuck::cast_slice(&vertices), + ); + } + self.hud.prepare( + &self.device, + &mut self.uploads, + &mut encoder, + frame.hud, + [self.config.width, self.config.height], + ); + 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 { + label: Some("Section draws"), + size: self.indirect_capacity * 20, + usage: wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + } + self.uploads.buffer( + &mut encoder, + &self.indirect, + 0, + bytemuck::cast_slice(&self.draws), + ); + if culling && let Some(cull) = &mut self.cull { + cull.upload( + &self.device, + &mut self.uploads, + &mut encoder, + &self.draws[phase1_draws as usize..solid_draws as usize], + &self.instances, + &self.globals, + ); + } + } let view_target = target_texture.create_view(&wgpu::TextureViewDescriptor { format: Some(self.config.format.remove_srgb_suffix()), ..Default::default() @@ -2784,6 +2991,7 @@ impl Renderer { Some((color, depth)) => (color, depth), None => (&view_target, &self.depth), }; + let cull = self.cull.as_ref().filter(|_| culling && solid_draws > 0); { let attachments = [Some(wgpu::RenderPassColorAttachment { view: world_view, @@ -2812,8 +3020,9 @@ impl Renderer { view: world_depth, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(0.0), - // A shader pack reads the world's depth. - store: if pack { + // A shader pack reads the world's depth, and + // phase 2 of occlusion culling draws over it. + store: if pack || cull.is_some() { wgpu::StoreOp::Store } else { wgpu::StoreOp::Discard @@ -2863,7 +3072,59 @@ impl Renderer { 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 cull { + Some(cull) => { + // Phase 1 and the boxes against its depth, then + // what they found in sight, in a pass that loads + // both targets (it reads the test's results). + self.draw_sections(&mut pass, &self.indirect, 0, 0, phase1_draws); + cull.test(&mut pass); + drop(pass); + let attachments = [Some(wgpu::RenderPassColorAttachment { + view: world_view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }, + })]; + pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Horizon world, after culling"), + color_attachments: &attachments, + depth_stencil_attachment: Some( + wgpu::RenderPassDepthStencilAttachment { + view: world_depth, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Load, + store: if pack { + wgpu::StoreOp::Store + } else { + wgpu::StoreOp::Discard + }, + }), + stencil_ops: None, + }, + ), + ..Default::default() + }); + pass.set_bind_group(0, &self.group, &[]); + 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, + &cull.phase2, + phase1_draws, + phase1_draws, + solid_draws - phase1_draws, + ); + } + None => self.draw_sections(&mut pass, &self.indirect, 0, 0, solid_draws), + } } } if entity_quads > 0 { @@ -2915,7 +3176,13 @@ impl Renderer { 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); + self.draw_sections( + &mut pass, + &self.indirect, + 0, + solid_draws, + translucent_draws, + ); } } // LevelRenderer.executeClassicTransparency: translucent targets' @@ -3031,24 +3298,6 @@ impl Renderer { ); } if !frame.screen.is_empty() { - let vertices: Vec<crate::screen_effects::ScreenVertex> = - frame.screen.iter().flat_map(|q| q.vertices).collect(); - if vertices.len() as u64 > self.screen_capacity { - self.screen_capacity = (vertices.len() as u64).next_power_of_two(); - self.screen_buffer = self.device.create_buffer(&wgpu::BufferDescriptor { - label: Some("Screen effect vertices"), - size: self.screen_capacity - * std::mem::size_of::<crate::screen_effects::ScreenVertex>() as u64, - usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - } - self.uploads.buffer( - &mut encoder, - &self.screen_buffer, - 0, - bytemuck::cast_slice(&vertices), - ); let attachments = [Some(wgpu::RenderPassColorAttachment { view: &view_target, resolve_target: None, @@ -3141,15 +3390,15 @@ impl Renderer { ); } self.hud.draw( - &self.device, - &self.queue, - &mut self.uploads, &mut encoder, &view_target, &self.depth, frame.hud, [self.config.width, self.config.height], ); + if culling && let Some(cull) = &mut self.cull { + cull.end(&self.device, &mut encoder); + } if let Some(timer) = &mut self.gpu_timer { timer.end(&mut encoder); } @@ -3158,8 +3407,15 @@ impl Renderer { .take() .map(|path| (path, self.copy_frame(&mut encoder, &target_texture))); self.uploads.finish(&encoder); + if has_section_copies { + self.section_copy_bytes = 0; + self.section_uploads.finish(&encoder); + } let commands = crate::spans::time("encode", || encoder.finish()); let submission = crate::spans::time("submit", || self.queue.submit([commands])); + if let Some(cull) = &mut self.cull { + cull.submitted(); + } if let Some(timer) = &mut self.gpu_timer { timer.submitted(); timer.collect(&self.device, &mut self.gpu_times); @@ -3363,6 +3619,15 @@ enum Pack { Java(java_stages::JavaStages), } +/// The section the camera is in. +fn camera_section(camera: DVec3) -> SectionKey { + ( + (camera.x.floor() as i32) >> 4, + (camera.y.floor() as i32 - crate::chunk::MIN_Y) >> 4, + (camera.z.floor() as i32) >> 4, + ) +} + fn world_projection(fov_degrees: f32, aspect: f32, far: f32) -> Mat4 { Mat4::perspective_rh(fov_degrees.to_radians(), aspect, far, 0.05) } @@ -3437,7 +3702,7 @@ mod tests { (3, offset_of!(TerrainVertex, color)), ] ); - assert_eq!(std::mem::size_of::<TerrainVertex>(), 28); + assert_eq!(std::mem::size_of::<TerrainVertex>(), 24); } #[test] fn cracks_multiply_instead_of_covering_the_block() { diff --git a/crates/horizon-client/src/gfx/arena.rs b/crates/horizon-client/src/gfx/arena.rs index 74d3b98e9..8da835aa2 100644 --- a/crates/horizon-client/src/gfx/arena.rs +++ b/crates/horizon-client/src/gfx/arena.rs @@ -155,12 +155,14 @@ impl Arena { .buffer } /// A range of `vertices`: (page, first vertex). Grows the newest page - /// (copying its contents on the GPU) or starts a new one when nothing - /// free is large enough; `None` when no memory is left for it. + /// (copying its contents on the GPU, in `encoder`) or starts a new one + /// when nothing free is large enough; `None` when no memory is left for + /// it. Writes to the arena belong in `encoder` too, so that those + /// recorded before a grow reach the grown page. pub fn alloc( &mut self, device: &wgpu::Device, - queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, vertices: u64, ) -> Option<(u32, u64)> { let len = Self::span(vertices).min(self.page_limit); @@ -178,7 +180,7 @@ impl Arena { let current = page.capacity; let grown = (current * 2).max(current + len).min(self.page_limit); if (grown - current >= len || grown == self.page_limit) - && self.grow(device, queue, last, grown) + && self.grow(device, encoder, last, grown) && let Some(start) = self.pages[last].as_mut().unwrap().free.take(len) { return Some((last as u32, start)); @@ -228,7 +230,7 @@ impl Arena { fn grow( &mut self, device: &wgpu::Device, - queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, page: usize, capacity: u64, ) -> bool { @@ -237,12 +239,8 @@ impl Arena { return false; }; let old = self.pages[page].as_mut().expect("live arena page"); - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { - label: Some("Grow section arena"), - }); + // Copies recorded for the old buffer run before this one. encoder.copy_buffer_to_buffer(&old.buffer, 0, &buffer, 0, old.capacity * self.stride); - // Writes queued for the old buffer run before this copy. - queue.submit([encoder.finish()]); let previous = old.capacity; old.buffer = buffer; old.capacity = capacity; @@ -304,6 +302,50 @@ mod tests { .ok() } + /// `Arena::alloc`, with the copies of a grow submitted at once. + fn alloc( + arena: &mut Arena, + device: &wgpu::Device, + queue: &wgpu::Queue, + vertices: u64, + ) -> Option<(u32, u64)> { + let mut encoder = device.create_command_encoder(&Default::default()); + let range = arena.alloc(device, &mut encoder, vertices); + queue.submit([encoder.finish()]); + range + } + + #[test] + fn writes_recorded_before_a_grow_reach_the_grown_page() { + let Some((device, queue)) = device() else { + eprintln!("no GPU adapter: skipped"); + return; + }; + let mut arena = Arena::indices(&device, GRAIN, false); + let mut uploads = super::super::upload::Uploads::new(&device); + let mut encoder = device.create_command_encoder(&Default::default()); + let (page, start) = arena.alloc(&device, &mut encoder, GRAIN).unwrap(); + uploads.buffer( + &mut encoder, + arena.buffer(page), + start * 4, + &7u32.to_le_bytes(), + ); + // The page is full: the next range grows it, in the same encoder. + let (grown, next) = arena.alloc(&device, &mut encoder, GRAIN).unwrap(); + assert_eq!(grown, page); + uploads.buffer( + &mut encoder, + arena.buffer(grown), + next * 4, + &9u32.to_le_bytes(), + ); + uploads.finish(&encoder); + queue.submit([encoder.finish()]); + assert_eq!(read(&device, &queue, arena.buffer(page), start * 4), 7); + assert_eq!(read(&device, &queue, arena.buffer(page), next * 4), 9); + } + #[test] fn empty_pages_are_reclaimed_without_moving_live_ranges() { let Some((device, queue)) = device() else { @@ -313,9 +355,9 @@ mod tests { let mut arena = Arena::new(&device, 4, GRAIN); arena.page_limit = 2 * GRAIN; assert_eq!(arena.bytes(), 0); - let (first, a) = arena.alloc(&device, &queue, GRAIN).unwrap(); - let (_, b) = arena.alloc(&device, &queue, GRAIN).unwrap(); - let (live, c) = arena.alloc(&device, &queue, 2 * GRAIN).unwrap(); + let (first, a) = alloc(&mut arena, &device, &queue, GRAIN).unwrap(); + let (_, b) = alloc(&mut arena, &device, &queue, GRAIN).unwrap(); + let (live, c) = alloc(&mut arena, &device, &queue, 2 * GRAIN).unwrap(); let buffer = arena.buffer(live).clone(); let data = [1u8, 2, 3, 4]; queue.write_buffer(&buffer, c * 4, &data); @@ -327,7 +369,7 @@ mod tests { arena.trim(); assert_eq!(arena.bytes(), 2 * GRAIN * 4); assert_eq!(arena.buffer(live), &buffer); - let (reused, d) = arena.alloc(&device, &queue, GRAIN).unwrap(); + let (reused, d) = alloc(&mut arena, &device, &queue, GRAIN).unwrap(); assert_eq!(reused, first); let (tx, rx) = std::sync::mpsc::channel(); @@ -356,11 +398,11 @@ mod tests { Arena::new(&device, 28, GRAIN), Arena::indices(&device, GRAIN, false), ] { - arena.alloc(&device, &queue, GRAIN).unwrap(); + alloc(&mut arena, &device, &queue, GRAIN).unwrap(); assert_eq!(arena.bytes(), arena.stride * GRAIN); arena.clear(); assert_eq!(arena.bytes(), 0); - assert_eq!(arena.alloc(&device, &queue, GRAIN), Some((0, 0))); + assert_eq!(alloc(&mut arena, &device, &queue, GRAIN), Some((0, 0))); assert_eq!(arena.bytes(), arena.stride * GRAIN); } } @@ -414,12 +456,12 @@ mod tests { return; } let mut arena = Arena::indices(&device, GRAIN, false); - let (page, start) = arena.alloc(&device, &queue, GRAIN).unwrap(); + let (page, start) = alloc(&mut arena, &device, &queue, GRAIN).unwrap(); queue.write_buffer(arena.buffer(page), start * 4, &7u32.to_le_bytes()); arena.video_memory_full = true; // The full page can't grow in video memory: it moves to system // memory with its contents, and new ranges come from there. - let (grown, next) = arena.alloc(&device, &queue, GRAIN).unwrap(); + let (grown, next) = alloc(&mut arena, &device, &queue, GRAIN).unwrap(); assert!(arena.spilled); assert_eq!(grown, page); assert!( @@ -439,13 +481,13 @@ mod tests { return; }; let mut arena = Arena::indices(&device, GRAIN, false); - arena.alloc(&device, &queue, GRAIN).unwrap(); + alloc(&mut arena, &device, &queue, GRAIN).unwrap(); arena.video_memory_full = true; // Without mappable primary buffers nothing can spill: the request // fails, and the arena keeps what it has. - assert_eq!(arena.alloc(&device, &queue, GRAIN), None); + assert_eq!(alloc(&mut arena, &device, &queue, GRAIN), None); assert_eq!(arena.bytes(), GRAIN * 4); arena.release(0, 0, GRAIN); - assert_eq!(arena.alloc(&device, &queue, GRAIN), Some((0, 0))); + assert_eq!(alloc(&mut arena, &device, &queue, GRAIN), Some((0, 0))); } } diff --git a/crates/horizon-client/src/gfx/cull.rs b/crates/horizon-client/src/gfx/cull.rs new file mode 100644 index 000000000..6926aab70 --- /dev/null +++ b/crates/horizon-client/src/gfx/cull.rs @@ -0,0 +1,511 @@ +//! Occlusion culling of solid section draws, in two phases. +//! +//! Frustum and cave culling leave many sections that terrain in front hides +//! entirely (about half of the solid vertices drawn from the ground at render +//! distance 16, more at 32), and drawing fewer vertices is what helps an +//! integrated GPU. Phase 1 draws the sections that the last test read back +//! saw. Then, in the same pass, the box of every other section (and of a +//! share of phase 1's, to notice when they go out of sight) is drawn against +//! phase 1's depth with no writes but to the test's results. Phase 2, in a +//! second pass, draws the sections whose box was seen; the others' draws have +//! an instance count of 0. +//! +//! The picture stays the one without culling: the boxes (grown by a block, +//! the farthest a block model reaches out of its cell) are drawn front faces +//! only, so a fragment is the box's nearest point on its pixel, and the +//! fragment shader runs only where the depth test passes (forced early), so a +//! section is left out only where all of its fragments would fail the depth +//! test against the final depth, which is only nearer. What the CPU knows of +//! the results only sorts sections between the phases: a stale result draws +//! a hidden section in phase 1, or tests a section that is in sight. +//! +//! Every solid draw is an entry of one of the two lists, so the CPU records +//! as many draws as without culling: drivers that unroll an indirect +//! multi-draw on the CPU (Mesa's on Intel Gen9) pay per entry. Phase 2's +//! counts come from the GPU, which needs a native multi-draw and forced +//! early depth tests: Vulkan. Translucent draws are not culled. +use std::num::NonZeroU64; +use std::sync::{ + Arc, + atomic::{AtomicU8, Ordering}, +}; + +const WORDS: u64 = 5 * 4; +/// Phase 1's sections are each tested every `RETEST` frames. +const RETEST: u32 = 8; +/// Culling runs while the last result read back hid at least this share of +/// the frame's solid indices: below it the test and the second pass cost +/// more than they save. Else one frame in `PROBE` tests every section. +const MIN_SHARE: f32 = 0.1; +const PROBE: u32 = 64; +/// Boxes over more than this share of the screen count as seen untested. +const BIG: f32 = 0.25; +/// Results read back at once, some frames late so the CPU never waits. +const READBACKS: usize = 3; +const FREE: u8 = 0; +const PENDING: u8 = 1; +const MAPPED: u8 = 2; + +#[repr(C)] +#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] +struct Params { + stamp: u32, + big: f32, + pad: [u32; 2], +} + +/// One frame's results on their way back. +struct Readback { + buffer: wgpu::Buffer, + capacity: u64, + state: Arc<AtomicU8>, + stamp: u32, + /// The resident slot of each test, and its section's solid indices. + slots: Vec<u32>, + indices: Vec<u32>, + /// The frame's solid indices. + total: u64, +} + +/// The bind group and the buffers from outside it was made with. +struct Group { + origins: wgpu::Buffer, + globals: wgpu::Buffer, + group: wgpu::BindGroup, +} + +pub struct Cull { + pipeline: wgpu::RenderPipeline, + layout: wgpu::BindGroupLayout, + group: Option<Group>, + params: wgpu::Buffer, + /// Phase 2's draws: the solid draws after phase 1's in the frame's list. + pub phase2: wgpu::Buffer, + phase2_capacity: u64, + tests: wgpu::Buffer, + tests_capacity: u64, + /// This frame's tests: visible index, first phase 2 draw, phase 2 draws. + test_data: Vec<[u32; 4]>, + test_slots: Vec<u32>, + test_indices: Vec<u32>, + total: u64, + /// The frame tests every section, as culling was off. + probe: bool, + results: wgpu::Buffer, + readbacks: Vec<Readback>, + next: usize, + current: Option<usize>, + /// Per resident slot: whether the last result read back saw it. + seen: Vec<bool>, + stamp: u32, + /// Of the boxes the last test read back drew, how many it did not see + /// and how many it drew, and the share of solid indices hidden. + pub hidden: ([usize; 2], f32), + /// Cull every frame, whatever the hidden share (A/B checks). + pub always: bool, +} + +fn buffer( + device: &wgpu::Device, + label: &str, + size: u64, + usage: wgpu::BufferUsages, +) -> wgpu::Buffer { + device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size, + usage, + mapped_at_creation: false, + }) +} + +const PHASE2_USAGE: wgpu::BufferUsages = wgpu::BufferUsages::INDIRECT + .union(wgpu::BufferUsages::STORAGE) + .union(wgpu::BufferUsages::COPY_DST); +const TESTS_USAGE: wgpu::BufferUsages = + wgpu::BufferUsages::STORAGE.union(wgpu::BufferUsages::COPY_DST); +const RESULTS_USAGE: wgpu::BufferUsages = + wgpu::BufferUsages::STORAGE.union(wgpu::BufferUsages::COPY_SRC); +const READBACK_USAGE: wgpu::BufferUsages = + wgpu::BufferUsages::MAP_READ.union(wgpu::BufferUsages::COPY_DST); + +impl Cull { + /// The device feature culling needs, where the adapter has it. + pub fn features(adapter: &wgpu::Adapter) -> wgpu::Features { + adapter.features() & wgpu::Features::SHADER_EARLY_DEPTH_TEST + } + /// Whether the device draws an indirect multi-draw natively and runs + /// fragment shaders that write storage only past an early depth test. + pub fn supported(adapter: &wgpu::Adapter, device: &wgpu::Device) -> bool { + adapter.get_info().backend == wgpu::Backend::Vulkan + && device.features().contains( + wgpu::Features::SHADER_EARLY_DEPTH_TEST | wgpu::Features::INDIRECT_FIRST_INSTANCE, + ) + && adapter.get_downlevel_capabilities().flags.contains( + wgpu::DownlevelFlags::VERTEX_STORAGE + | wgpu::DownlevelFlags::FRAGMENT_WRITABLE_STORAGE, + ) + } + /// `color` is the world pass's colour format. + pub fn new(device: &wgpu::Device, color: wgpu::TextureFormat) -> Self { + let entry = |binding, visibility, ty| wgpu::BindGroupLayoutEntry { + binding, + visibility, + ty, + count: None, + }; + let storage = |read_only| wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only }, + has_dynamic_offset: false, + min_binding_size: None, + }; + let uniform = wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }; + let both = wgpu::ShaderStages::VERTEX_FRAGMENT; + let vertex = wgpu::ShaderStages::VERTEX; + let fragment = wgpu::ShaderStages::FRAGMENT; + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Section culling"), + entries: &[ + entry(0, both, storage(true)), + entry(1, fragment, storage(false)), + entry(2, fragment, storage(false)), + entry(3, vertex, storage(true)), + entry(4, vertex, uniform), + entry(5, both, uniform), + ], + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Section culling"), + source: wgpu::ShaderSource::Wgsl(include_str!("cull.wgsl").into()), + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Section culling"), + bind_group_layouts: &[Some(&layout)], + ..Default::default() + }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Section culling"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &module, + entry_point: Some("vs_box"), + compilation_options: Default::default(), + buffers: &[], + }, + primitive: wgpu::PrimitiveState { + cull_mode: Some(wgpu::Face::Back), + ..Default::default() + }, + // The world pass's reversed depth test, without writes. + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(false), + depth_compare: Some(wgpu::CompareFunction::GreaterEqual), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some("fs_box"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: color, + blend: None, + write_mask: wgpu::ColorWrites::empty(), + })], + }), + multiview_mask: None, + cache: None, + }); + Self { + pipeline, + layout, + group: None, + params: buffer( + device, + "Section culling parameters", + std::mem::size_of::<Params>() as u64, + wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + ), + phase2: buffer(device, "Section draws, phase 2", WORDS, PHASE2_USAGE), + phase2_capacity: 1, + tests: buffer(device, "Section tests", 16, TESTS_USAGE), + tests_capacity: 1, + test_data: Vec::new(), + test_slots: Vec::new(), + test_indices: Vec::new(), + total: 0, + probe: false, + results: buffer(device, "Section test results", 4, RESULTS_USAGE), + readbacks: (0..READBACKS) + .map(|_| Readback { + buffer: buffer(device, "Section test readback", 4, READBACK_USAGE), + capacity: 1, + state: Arc::new(AtomicU8::new(FREE)), + stamp: 0, + slots: Vec::new(), + indices: Vec::new(), + total: 0, + }) + .collect(), + next: 0, + current: None, + seen: Vec::new(), + stamp: 0, + hidden: ([0; 2], 1.0), + always: false, + } + } + + /// Start a frame: take in the results that came back, and tell whether + /// the frame culls. + pub fn begin(&mut self, device: &wgpu::Device) -> bool { + let _ = device.poll(wgpu::PollType::Poll); + for i in 0..READBACKS { + let r = &mut self.readbacks[(self.next + i) % READBACKS]; + if r.state.load(Ordering::Acquire) != MAPPED { + continue; + } + let mapped = r.buffer.slice(..r.slots.len() as u64 * 4); + if let Ok(data) = mapped.get_mapped_range() { + let results: &[u32] = bytemuck::cast_slice(&data); + let (mut hidden, mut indices) = (0, 0u64); + for (&result, &n) in results.iter().zip(&r.indices) { + if result != r.stamp { + hidden += 1; + indices += u64::from(n); + } + } + let share = indices as f32 / r.total.max(1) as f32; + self.hidden = ([hidden, results.len()], share); + for (&slot, &result) in r.slots.iter().zip(results) { + let slot = slot as usize; + if slot >= self.seen.len() { + self.seen.resize(slot + 1, false); + } + self.seen[slot] = result == r.stamp; + } + } + r.buffer.unmap(); + r.state.store(FREE, Ordering::Release); + } + self.stamp = self.stamp.wrapping_add(1).max(1); + self.test_data.clear(); + self.test_slots.clear(); + self.test_indices.clear(); + self.total = 0; + self.probe = !self.always && self.hidden.1 < MIN_SHARE; + !self.probe || self.stamp.is_multiple_of(PROBE) + } + + /// Whether phase 1 draws the section in resident `slot`. + pub fn first(&self, slot: u32) -> bool { + self.seen.get(slot as usize).copied().unwrap_or(false) + } + + /// A section phase 1 draws, `index` in the visible list, with `indices` + /// solid indices: tested in turn. + pub fn drawn(&mut self, index: usize, slot: u32, indices: u32) { + self.total += u64::from(indices); + if indices > 0 && (self.probe || slot.wrapping_add(self.stamp).is_multiple_of(RETEST)) { + self.push([index as u32, 0, 0, 0], slot, indices); + } + } + + /// A section left to phase 2: its `draws` from phase 2's `first`. + pub fn deferred(&mut self, index: usize, slot: u32, first: usize, draws: usize, indices: u32) { + self.total += u64::from(indices); + if draws > 0 { + self.push([index as u32, first as u32, draws as u32, 0], slot, indices); + } + } + + fn push(&mut self, test: [u32; 4], slot: u32, indices: u32) { + self.test_data.push(test); + self.test_slots.push(slot); + self.test_indices.push(indices); + } + + /// Stage this frame's inputs: phase 2's draws, with instance counts of 0, + /// and the tests, which read the frame's camera-relative `origins` and + /// view projection (the start of `globals`). + pub fn upload( + &mut self, + device: &wgpu::Device, + uploads: &mut super::upload::Uploads, + encoder: &mut wgpu::CommandEncoder, + phase2: &[[u32; 5]], + origins: &wgpu::Buffer, + globals: &wgpu::Buffer, + ) { + let draws = phase2.len() as u64; + if draws > self.phase2_capacity { + self.phase2_capacity = draws.next_power_of_two(); + self.phase2 = buffer( + device, + "Section draws, phase 2", + self.phase2_capacity * WORDS, + PHASE2_USAGE, + ); + self.group = None; + } + let tests = self.test_data.len() as u64; + if tests > self.tests_capacity { + self.tests_capacity = tests.next_power_of_two(); + self.tests = buffer( + device, + "Section tests", + self.tests_capacity * 16, + TESTS_USAGE, + ); + self.results = buffer( + device, + "Section test results", + self.tests_capacity * 4, + RESULTS_USAGE, + ); + self.group = None; + } + if draws > 0 { + uploads.buffer(encoder, &self.phase2, 0, bytemuck::cast_slice(phase2)); + } + if tests > 0 { + uploads.buffer( + encoder, + &self.tests, + 0, + bytemuck::cast_slice(&self.test_data), + ); + } + let params = Params { + stamp: self.stamp, + big: BIG, + pad: [0; 2], + }; + uploads.buffer(encoder, &self.params, 0, bytemuck::bytes_of(¶ms)); + if !self + .group + .as_ref() + .is_some_and(|g| g.origins == *origins && g.globals == *globals) + { + self.group = Some(self.make_group(device, origins, globals)); + } + } + + /// In the world pass after phase 1: draw the tested boxes against its + /// depth. Leaves the pass's pipeline and group 0 changed. + pub fn test(&self, pass: &mut wgpu::RenderPass<'_>) { + let Some(Group { group, .. }) = &self.group else { + return; + }; + if self.test_data.is_empty() { + return; + } + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, group, &[]); + pass.draw(0..36, 0..self.test_data.len() as u32); + } + + /// After the world passes: copy the results for reading back, when a + /// readback buffer is free. + pub fn end(&mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder) { + let tests = self.test_data.len() as u64; + let r = &mut self.readbacks[self.next]; + if tests == 0 || r.state.load(Ordering::Acquire) != FREE { + return; + } + if tests > r.capacity { + r.capacity = tests.next_power_of_two(); + r.buffer = buffer( + device, + "Section test readback", + r.capacity * 4, + READBACK_USAGE, + ); + } + encoder.copy_buffer_to_buffer(&self.results, 0, &r.buffer, 0, tests * 4); + r.stamp = self.stamp; + r.slots.clear(); + r.slots.extend_from_slice(&self.test_slots); + r.indices.clear(); + r.indices.extend_from_slice(&self.test_indices); + r.total = self.total; + self.current = Some(self.next); + } + + /// After the frame's submission: start reading its results back. + pub fn submitted(&mut self) { + let Some(i) = self.current.take() else { + return; + }; + let r = &self.readbacks[i]; + let state = r.state.clone(); + state.store(PENDING, Ordering::Release); + r.buffer + .slice(..r.slots.len() as u64 * 4) + .map_async(wgpu::MapMode::Read, move |result| { + state.store( + if result.is_ok() { MAPPED } else { FREE }, + Ordering::Release, + ); + }); + self.next = (i + 1) % READBACKS; + } + + fn make_group( + &self, + device: &wgpu::Device, + origins: &wgpu::Buffer, + globals: &wgpu::Buffer, + ) -> Group { + fn whole(binding: u32, buffer: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> { + wgpu::BindGroupEntry { + binding, + resource: buffer.as_entire_binding(), + } + } + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Section culling"), + layout: &self.layout, + entries: &[ + whole(0, &self.tests), + whole(1, &self.results), + whole(2, &self.phase2), + whole(3, origins), + wgpu::BindGroupEntry { + binding: 4, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: globals, + offset: 0, + size: NonZeroU64::new(64), + }), + }, + whole(5, &self.params), + ], + }); + Group { + origins: origins.clone(), + globals: globals.clone(), + group, + } + } +} + +#[cfg(test)] +mod tests { + #[test] + fn shader_validates() { + let module = naga::front::wgsl::parse_str(include_str!("cull.wgsl")).unwrap(); + naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::all(), + ) + .validate(&module) + .unwrap(); + } +} diff --git a/crates/horizon-client/src/gfx/cull.wgsl b/crates/horizon-client/src/gfx/cull.wgsl new file mode 100644 index 000000000..faa495caf --- /dev/null +++ b/crates/horizon-client/src/gfx/cull.wgsl @@ -0,0 +1,101 @@ +// Occlusion culling of solid section draws (gfx/cull.rs). + +struct Params { + // This frame's test: a test that sees its box stores the number. + stamp: u32, + // Boxes covering more than this share of the screen count as seen. + big: f32, +} +// The leading member of terrain.wgsl's Globals. +struct Globals { + view_proj: mat4x4<f32>, +} + +// One test per section: its visible index (which names its origin), its +// first draw in `phase2` and how many draws it has there (0: phase 1 drew +// it, and the test only tells whether it is still in sight). +@group(0) @binding(0) var<storage, read> tests: array<vec4<u32>>; +// Per test: the stamp of the frame whose test saw the box. +@group(0) @binding(1) var<storage, read_write> results: array<u32>; +// Phase 2's draws, 5 words each, with instance counts of 0 until seen. +@group(0) @binding(2) var<storage, read_write> phase2: array<u32>; +// Camera-relative origin of each visible section. +@group(0) @binding(3) var<storage, read> origins: array<vec4<f32>>; +@group(0) @binding(4) var<uniform> globals: Globals; +@group(0) @binding(5) var<uniform> params: Params; + +// The corners (bit 0: x, bit 1: y, bit 2: z) of the box's 12 triangles, +// counter-clockwise seen from outside. +const CORNERS = array<u32, 36>( + 0u, 6u, 2u, 0u, 4u, 6u, 1u, 3u, 7u, 1u, 7u, 5u, 0u, 1u, 5u, 0u, 5u, 4u, + 2u, 7u, 3u, 2u, 6u, 7u, 0u, 3u, 1u, 0u, 2u, 3u, 4u, 5u, 7u, 4u, 7u, 6u, +); + +struct Box { + @builtin(position) position: vec4<f32>, + @location(0) @interpolate(flat) test: u32, +} + +fn corner(origin: vec3<f32>, c: u32) -> vec3<f32> { + return origin + vec3( + select(-1.0, 17.0, (c & 1u) != 0u), + select(-1.0, 17.0, (c & 2u) != 0u), + select(-1.0, 17.0, (c & 4u) != 0u), + ); +} + +// Each tested section's box, grown by a block (block models reach one block +// out of their cell), drawn after phase 1 against its depth with back faces +// culled: a front face fragment that passes the depth test is the box's +// nearest point on that pixel in front of phase 1's depth, so the section +// may show there. A box failing everywhere would have every fragment of its +// section fail the depth test against the final depth, which is only nearer. +@vertex +fn vs_box(@builtin(vertex_index) v: u32, @builtin(instance_index) t: u32) -> Box { + let origin = origins[tests[t].x].xyz; + var out: Box; + out.test = t; + // The box's screen rectangle, from the corners in front of the camera. + var lo = vec2(1e30); + var hi = vec2(-1e30); + var behind = false; + for (var c = 0u; c < 8u; c++) { + let p = globals.view_proj * vec4(corner(origin, c), 1.0); + behind = behind || p.w <= 0.0; + let q = p.xy / max(p.w, 1e-6); + lo = min(lo, q); + hi = max(hi, q); + } + let size = max(min(hi, vec2(1.0)) - max(lo, vec2(-1.0)), vec2(0.0)); + // A box within a block of the camera may cross the near plane, which + // clips its front faces away, and a box over a large part of the screen + // is nearly always in sight and costly to test: both count as seen, + // through a small triangle in the top left corner at the nearest depth. + let near = all(origin < vec3(2.0)) && all(origin > vec3(-18.0)); + if near || (!behind && size.x * size.y > params.big * 4.0) { + var p = vec2(-1.0, 1.0); + if v == 1u { + p.y -= 0.05; + } else if v == 2u { + p.x += 0.05; + } + out.position = select(vec4(0.0, 0.0, 0.0, 1.0), vec4(p, 1.0, 1.0), v < 3u); + return out; + } + out.position = globals.view_proj * vec4(corner(origin, CORNERS[v]), 1.0); + return out; +} + +// Runs only for fragments that pass the depth test (forced early). +@fragment +@early_depth_test(force) +fn fs_box(in: Box) -> @location(0) vec4<f32> { + if results[in.test] != params.stamp { + results[in.test] = params.stamp; + let test = tests[in.test]; + for (var k = 0u; k < test.z; k++) { + phase2[(test.y + k) * 5u + 1u] = 1u; + } + } + return vec4(0.0); +} diff --git a/crates/horizon-client/src/gfx/flat.rs b/crates/horizon-client/src/gfx/flat.rs index b867a42c2..ff58e3ca6 100644 --- a/crates/horizon-client/src/gfx/flat.rs +++ b/crates/horizon-client/src/gfx/flat.rs @@ -262,11 +262,12 @@ impl Flat { } } /// A section uploaded to `vertices` vertices from `start` of `page`: its - /// id, which its blocks now name. + /// id, which its blocks now name (written through `uploads` in `encoder`). pub fn add( &mut self, device: &wgpu::Device, - queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + uploads: &mut super::upload::Uploads, page: u32, start: u64, vertices: u64, @@ -290,7 +291,12 @@ impl Flat { }); 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)); + uploads.buffer( + encoder, + &table.blocks, + first * 4, + bytemuck::cast_slice(&ids), + ); id } pub fn remove(&mut self, id: u32) { diff --git a/crates/horizon-client/src/gfx/occlusion.rs b/crates/horizon-client/src/gfx/occlusion.rs index e871c50c0..b63e7eae5 100644 --- a/crates/horizon-client/src/gfx/occlusion.rs +++ b/crates/horizon-client/src/gfx/occlusion.rs @@ -2,11 +2,18 @@ //! faces. Breadth-first from the camera section through the faces each //! section's VisGraph connects, never stepping back towards the camera. //! -//! The search runs over dense arrays around the camera rather than hash sets, -//! so it stays cheap enough to redo whenever a section is meshed. +//! As in vanilla, the full search runs off the render thread: a worker keeps +//! its own copy of every section's connectivity and searches over dense +//! arrays around the camera. Frames use the last finished graph and never wait +//! for the next one. A section meshed in between propagates into the graph the +//! frame has (vanilla's partial update), so what it opens shows at once; what +//! it closes goes at the next full search. use super::SectionKey; +use crate::mesher::ALL_VISIBLE; use std::collections::{HashMap, VecDeque}; +use std::sync::mpsc::{self, Receiver, Sender, TryRecvError}; +/// Vanilla's `Direction` order: down, up, north, south, west, east. const STEPS: [(i32, i32, i32); 6] = [ (0, -1, 0), (0, 1, 0), @@ -15,74 +22,92 @@ const STEPS: [(i32, i32, i32); 6] = [ (-1, 0, 0), (1, 0, 0), ]; +/// In `Graph::directions`: the cell has a node. +const REACHED: u8 = 1 << 7; +/// In `Graph::entered`: the camera's own section, entered through no face. const NONE: u8 = 6; -pub struct Occlusion { - /// VisGraph connectivity per column, one entry per section (bottom first). - columns: HashMap<(i32, i32), Box<[u64]>>, +/// VisGraph connectivity per column, one entry per section (bottom first). +/// A missing column or section connects every face. +struct Columns { sections: i32, - dirty: bool, - from: Option<SectionKey>, + map: HashMap<(i32, i32), Box<[u64]>>, +} + +impl Columns { + fn new(sections: i32) -> Self { + Self { + sections, + map: HashMap::new(), + } + } + /// Whether the section's connectivity changed. + fn set(&mut self, key: SectionKey, vis: u64) -> bool { + if !(0..self.sections).contains(&key.1) { + return false; + } + let column = match self.map.get_mut(&(key.0, key.2)) { + Some(column) => column, + None if vis == ALL_VISIBLE => return false, + None => self + .map + .entry((key.0, key.2)) + .or_insert_with(|| vec![ALL_VISIBLE; self.sections as usize].into()), + }; + let slot = &mut column[key.1 as usize]; + if *slot == vis { + return false; + } + *slot = vis; + if vis == ALL_VISIBLE && column.iter().all(|&v| v == ALL_VISIBLE) { + self.map.remove(&(key.0, key.2)); + } + true + } + fn get(&self, key: SectionKey) -> u64 { + self.map + .get(&(key.0, key.2)) + .and_then(|column| column.get(usize::try_from(key.1).ok()?)) + .copied() + .unwrap_or(ALL_VISIBLE) + } + fn apply(&mut self, edit: Edit) { + match edit { + Edit::Set(key, vis) => { + self.set(key, vis); + } + Edit::Clear => self.map.clear(), + } + } +} + +#[derive(Clone, Copy)] +enum Edit { + Set(SectionKey, u64), + Clear, +} + +/// One search's result over the box around the camera: vanilla's +/// `GraphStorage.sectionToNodeMap`, as dense arrays. +#[derive(Default)] +struct Graph { + from: SectionKey, radius: i32, /// The searched box: lowest section y and its height in sections. y0: i32, height: i32, - reached: Vec<bool>, - vis: Vec<u64>, - queue: VecDeque<(u32, u8, u8)>, + /// Per cell: `REACHED`, and the directions travelled from the camera to + /// it (`Node.directions`). + directions: Vec<u8>, + /// Per cell: the face it was first entered through (`NONE` for the + /// camera's). Vanilla's `Node.sourceDirections` also keeps the faces it is + /// reached through later; Horizon keeps the first only. + entered: Vec<u8>, } -impl Occlusion { - pub fn new(sections: i32) -> Self { - Self { - columns: HashMap::new(), - sections, - dirty: true, - from: None, - radius: 0, - y0: 0, - height: 0, - reached: Vec::new(), - vis: Vec::new(), - queue: VecDeque::new(), - } - } - pub fn set(&mut self, key: SectionKey, vis: u64) { - if !(0..self.sections).contains(&key.1) { - return; - } - let sections = self.sections as usize; - let column = self - .columns - .entry((key.0, key.2)) - .or_insert_with(|| vec![crate::mesher::ALL_VISIBLE; sections].into()); - let slot = &mut column[key.1 as usize]; - if *slot != vis { - *slot = vis; - self.dirty = true; - } - } - pub fn remove(&mut self, key: SectionKey) { - let Some(column) = self.columns.get_mut(&(key.0, key.2)) else { - return; - }; - if let Some(slot) = column.get_mut(key.1 as usize) - && *slot != crate::mesher::ALL_VISIBLE - { - *slot = crate::mesher::ALL_VISIBLE; - self.dirty = true; - } - if column.iter().all(|&v| v == crate::mesher::ALL_VISIBLE) { - self.columns.remove(&(key.0, key.2)); - } - } - pub fn clear(&mut self) { - self.columns.clear(); - self.dirty = true; - } +impl Graph { fn index(&self, key: SectionKey) -> Option<usize> { - let from = self.from?; - let (dx, dz, dy) = (key.0 - from.0, key.2 - from.2, key.1 - self.y0); + let (dx, dz, dy) = (key.0 - self.from.0, key.2 - self.from.2, key.1 - self.y0); let side = 2 * self.radius + 1; if dx.abs() > self.radius || dz.abs() > self.radius || !(0..self.height).contains(&dy) { return None; @@ -90,86 +115,331 @@ impl Occlusion { Some((((dz + self.radius) * side + dx + self.radius) * self.height + dy) as usize) } fn key(&self, index: usize) -> SectionKey { - let from = self.from.expect("searched"); let side = 2 * self.radius + 1; let i = index as i32; - let dy = i % self.height; let column = i / self.height; ( - from.0 + column % side - self.radius, - self.y0 + dy, - from.2 + column / side - self.radius, + self.from.0 + column % side - self.radius, + self.y0 + i % self.height, + self.from.2 + column / side - self.radius, ) } - pub fn contains(&self, key: SectionKey) -> bool { - self.index(key).is_some_and(|i| self.reached[i]) + fn contains(&self, key: SectionKey) -> bool { + self.index(key) + .is_some_and(|i| self.directions[i] & REACHED != 0) } - /// Search again when sections changed or the camera moved to another section. - pub fn update(&mut self, from: SectionKey, radius: i32) { - if !self.dirty && self.from == Some(from) && self.radius == radius { - return; - } - self.from = Some(from); + /// The full search from `from` (vanilla's `scheduleFullUpdate`). + fn search( + &mut self, + columns: &Columns, + from: SectionKey, + radius: i32, + vis: &mut Vec<u64>, + queue: &mut VecDeque<u32>, + ) { + self.from = from; self.radius = radius; self.y0 = from.1.min(-1); - self.height = from.1.max(self.sections) - self.y0 + 1; + self.height = from.1.max(columns.sections) - self.y0 + 1; let side = (2 * radius + 1) as usize; let size = side * side * self.height as usize; - self.reached.clear(); - self.reached.resize(size, false); - self.vis.clear(); - self.vis.resize(size, crate::mesher::ALL_VISIBLE); + self.directions.clear(); + self.directions.resize(size, 0); + self.entered.clear(); + self.entered.resize(size, NONE); + vis.clear(); + vis.resize(size, ALL_VISIBLE); for dz in -radius..=radius { for dx in -radius..=radius { - let Some(column) = self.columns.get(&(from.0 + dx, from.2 + dz)) else { + let Some(column) = columns.map.get(&(from.0 + dx, from.2 + dz)) else { continue; }; let base = self .index((from.0 + dx, 0, from.2 + dz)) .expect("column inside the searched box"); - self.vis[base..base + column.len()].copy_from_slice(column); + vis[base..base + column.len()].copy_from_slice(column); } } let start = self.index(from).expect("camera inside the searched box"); - self.reached[start] = true; - self.queue.clear(); - self.queue.push_back((start as u32, NONE, 0)); - while let Some((index, entered, travelled)) = self.queue.pop_front() { - let vis = self.vis[index as usize]; - let key = self.key(index as usize); + self.directions[start] = REACHED; + queue.clear(); + queue.push_back(start as u32); + self.propagate(queue, columns.sections, |i, _| vis[i]); + } + /// Vanilla's `runUpdates`: take nodes from the queue and step through + /// every face their entry face connects to, away from the camera. + fn propagate( + &mut self, + queue: &mut VecDeque<u32>, + sections: i32, + vis: impl Fn(usize, SectionKey) -> u64, + ) { + while let Some(index) = queue.pop_front() { + let i = index as usize; + let key = self.key(i); + let directions = self.directions[i]; + let entered = self.entered[i]; + let exits = if entered == NONE { + 0x3f + } else { + (vis(i, key) >> (u32::from(entered) * 6)) as u8 & 0x3f + }; for (d, step) in STEPS.iter().enumerate() { - let opposite = d ^ 1; - if travelled & (1 << opposite) != 0 { - continue; - } - if entered != NONE && vis & (1 << (usize::from(entered) * 6 + d)) == 0 { + if exits & (1 << d) == 0 || directions & (1 << (d ^ 1)) != 0 { continue; } let next = (key.0 + step.0, key.1 + step.1, key.2 + step.2); - if next.1 < -1 || next.1 > self.sections { + if next.1 < -1 || next.1 > sections { continue; } let Some(n) = self.index(next) else { continue }; - if !self.reached[n] { - self.reached[n] = true; - self.queue - .push_back((n as u32, opposite as u8, travelled | (1 << d))); + if self.directions[n] & REACHED == 0 { + self.directions[n] = directions | 1 << d; + self.entered[n] = (d ^ 1) as u8; + queue.push_back(n as u32); } } } + } +} + +struct Job { + edits: Vec<Edit>, + from: SectionKey, + radius: i32, + /// Buffers to reuse. + graph: Graph, +} + +/// The thread that runs full searches over its own copy of the columns. +struct Worker { + jobs: Sender<Job>, + done: Receiver<(Graph, Vec<Edit>)>, +} + +impl Worker { + fn spawn(sections: i32) -> Option<Self> { + let (jobs, job_rx) = mpsc::channel::<Job>(); + let (done_tx, done) = mpsc::channel(); + std::thread::Builder::new() + .name("occlusion".into()) + .spawn(move || { + let mut columns = Columns::new(sections); + let (mut vis, mut queue) = (Vec::new(), VecDeque::new()); + while let Ok(mut job) = job_rx.recv() { + for edit in job.edits.drain(..) { + columns.apply(edit); + } + job.graph + .search(&columns, job.from, job.radius, &mut vis, &mut queue); + if done_tx.send((job.graph, job.edits)).is_err() { + break; + } + } + }) + .ok()?; + Some(Self { jobs, done }) + } +} + +pub struct Occlusion { + /// The render thread's copy, for partial updates (and searches when the + /// worker is gone). + columns: Columns, + /// Edits the worker has not been sent yet. + edits: Vec<Edit>, + /// A full search is due: sections changed since the last one started. + dirty: bool, + /// The last finished search; `None` until one finishes, or after the + /// columns were cleared. + graph: Option<Graph>, + spare: Graph, + worker: Option<Worker>, + /// The camera section and radius of the running search. + running: Option<(SectionKey, i32)>, + /// The running search started before the columns were cleared: drop it. + discard: bool, + /// The camera section and radius `graph`'s search started from (or is + /// starting from). + searched: Option<(SectionKey, i32)>, + /// Sections changed since `graph`'s search started, to propagate from. + changed: Vec<SectionKey>, + /// Sections changed since the running search started: they propagate into + /// its graph when it lands. + changed_late: Vec<SectionKey>, + vis: Vec<u64>, + queue: VecDeque<u32>, +} + +impl Occlusion { + pub fn new(sections: i32) -> Self { + Self { + columns: Columns::new(sections), + edits: Vec::new(), + dirty: true, + graph: None, + spare: Graph::default(), + worker: Worker::spawn(sections), + running: None, + discard: false, + searched: None, + changed: Vec::new(), + changed_late: Vec::new(), + vis: Vec::new(), + queue: VecDeque::new(), + } + } + pub fn set(&mut self, key: SectionKey, vis: u64) { + if self.columns.set(key, vis) { + self.edits.push(Edit::Set(key, vis)); + self.dirty = true; + self.changed.push(key); + if self.running.is_some() { + self.changed_late.push(key); + } + } + } + pub fn remove(&mut self, key: SectionKey) { + self.set(key, ALL_VISIBLE); + } + pub fn clear(&mut self) { + self.columns.map.clear(); + self.edits.clear(); + self.edits.push(Edit::Clear); + self.dirty = true; + // Another world: the old graph says nothing about it. + if let Some(graph) = self.graph.take() { + self.spare = graph; + } + self.searched = None; + self.discard = self.running.is_some(); + self.changed.clear(); + self.changed_late.clear(); + } + /// Whether `key` is visible from the camera. Without a usable graph + /// (before the first search lands, or with the camera somewhere the graph + /// never reached) every section is. + pub fn contains(&self, key: SectionKey) -> bool { + self.graph.as_ref().is_none_or(|g| g.contains(key)) + } + /// Take a finished search, propagate changed sections into the graph, + /// and start a search when sections changed or the camera moved to + /// another section. Never waits for the worker. + pub fn update(&mut self, from: SectionKey, radius: i32) { + self.collect(false); + self.propagate_changes(); + if self.running.is_none() && (self.dirty || self.searched != Some((from, radius))) { + self.start(from, radius); + } + // A graph that never reached the camera's section hides everything + // around it: until the new one lands, cull by the frustum alone. + if self + .graph + .as_ref() + .is_some_and(|g| g.from != from && !g.contains(from)) + && let Some(graph) = self.graph.take() + { + self.spare = graph; + } + } + fn start(&mut self, from: SectionKey, radius: i32) { self.dirty = false; + self.searched = Some((from, radius)); + let graph = std::mem::take(&mut self.spare); + if let Some(worker) = &self.worker { + let job = Job { + edits: std::mem::take(&mut self.edits), + from, + radius, + graph, + }; + if worker.jobs.send(job).is_ok() { + self.running = Some((from, radius)); + self.changed_late.clear(); + return; + } + log::warn!("Horizon: the occlusion worker stopped; culling on the render thread"); + self.worker = None; + } + self.edits.clear(); + let mut graph = Graph::default(); + graph.search(&self.columns, from, radius, &mut self.vis, &mut self.queue); + self.land(graph); + } + fn collect(&mut self, wait: bool) { + let Some(worker) = &self.worker else { return }; + if self.running.is_none() { + return; + } + let result = if wait { + worker.done.recv().map_err(|_| TryRecvError::Disconnected) + } else { + worker.done.try_recv() + }; + match result { + Ok((graph, edits)) => { + self.running = None; + if self.edits.is_empty() { + self.edits = edits; + } + if std::mem::take(&mut self.discard) { + self.spare = graph; + return; + } + self.land(graph); + self.changed.clear(); + self.changed.append(&mut self.changed_late); + } + Err(TryRecvError::Empty) => {} + Err(TryRecvError::Disconnected) => { + // The edits it held are lost with it: search here from now on. + self.worker = None; + self.running = None; + self.discard = false; + self.dirty = true; + } + } + } + fn land(&mut self, graph: Graph) { + if let Some(old) = self.graph.replace(graph) { + self.spare = old; + } + } + /// Vanilla's `runPartialUpdate`: what changed sections now connect to. + fn propagate_changes(&mut self) { + let Some(graph) = &mut self.graph else { + self.changed.clear(); + return; + }; + self.queue.clear(); + for key in self.changed.drain(..) { + if let Some(i) = graph.index(key) + && graph.directions[i] & REACHED != 0 + { + self.queue.push_back(i as u32); + } + } + let columns = &self.columns; + graph.propagate(&mut self.queue, columns.sections, |_, key| columns.get(key)); + } + /// Wait for the running search: tests, and A/B timing of the old + /// blocking search. + #[cfg(test)] + fn settle(&mut self, from: SectionKey, radius: i32) { + self.update(from, radius); + self.collect(true); + self.propagate_changes(); } } #[cfg(test)] mod tests { use super::*; - use crate::mesher::ALL_VISIBLE; #[test] fn open_space_reaches_the_whole_box() { let mut o = Occlusion::new(4); - o.update((0, 1, 0), 2); + o.settle((0, 1, 0), 2); for x in -2..=2 { for z in -2..=2 { for y in -1..=4 { @@ -186,11 +456,155 @@ mod tests { for (dx, dy, dz) in STEPS { o.set((dx, 1 + dy, dz), 0); } - o.update((0, 1, 0), 3); + o.settle((0, 1, 0), 3); assert!(o.contains((1, 1, 0)), "a neighbour is seen"); assert!(!o.contains((2, 1, 0)), "nothing shows through it"); o.set((1, 1, 0), ALL_VISIBLE); - o.update((0, 1, 0), 3); + o.settle((0, 1, 0), 3); assert!(o.contains((2, 1, 0))); } + + #[test] + fn frames_never_wait_and_partial_updates_open_at_once() { + let mut o = Occlusion::new(4); + for (dx, dy, dz) in STEPS { + o.set((dx, 1 + dy, dz), 0); + } + o.settle((0, 1, 0), 3); + assert!(!o.contains((2, 1, 0))); + // Opening the wall shows what is behind it in the same frame, from the + // graph the frame has, whether or not the full search has finished. + o.set((1, 1, 0), ALL_VISIBLE); + o.update((0, 1, 0), 3); + assert!(o.contains((2, 1, 0))); + assert!(o.contains((3, 1, 0))); + // Closing it again lasts until the next full search lands. + o.set((1, 1, 0), 0); + o.settle((0, 1, 0), 3); + o.settle((0, 1, 0), 3); + assert!(!o.contains((2, 1, 0))); + } + + #[test] + fn a_graph_that_lost_the_camera_culls_nothing() { + let mut o = Occlusion::new(4); + for (dx, dy, dz) in STEPS { + o.set((dx, 1 + dy, dz), 0); + } + o.settle((0, 1, 0), 3); + assert!(!o.contains((3, 1, 0))); + // The camera jumped past the wall; the next search is still running. + let o = &mut o; + o.update((3, 1, 0), 3); + if o.running.is_some() { + assert!(o.contains((3, 1, 0))); + } + o.settle((3, 1, 0), 3); + assert!(o.contains((3, 1, 0))); + assert!( + !o.contains((0, 1, 0)), + "the old camera section is walled in" + ); + } + + /// The search before it moved to the worker (main at ce38c8d7), over the + /// same box: whether each cell is reached. + fn reference(columns: &Columns, from: SectionKey, radius: i32) -> Vec<bool> { + let y0 = from.1.min(-1); + let height = from.1.max(columns.sections) - y0 + 1; + let side = 2 * radius + 1; + let index = |k: SectionKey| { + let (dx, dz, dy) = (k.0 - from.0, k.2 - from.2, k.1 - y0); + (dx.abs() <= radius && dz.abs() <= radius && (0..height).contains(&dy)) + .then(|| (((dz + radius) * side + dx + radius) * height + dy) as usize) + }; + let size = (side * side * height) as usize; + let mut reached = vec![false; size]; + let start = index(from).unwrap(); + reached[start] = true; + let mut queue = VecDeque::from([(from, NONE, 0u8)]); + while let Some((key, entered, travelled)) = queue.pop_front() { + let vis = columns.get(key); + for (d, step) in STEPS.iter().enumerate() { + let opposite = d ^ 1; + if travelled & (1 << opposite) != 0 { + continue; + } + if entered != NONE && vis & (1 << (usize::from(entered) * 6 + d)) == 0 { + continue; + } + let next = (key.0 + step.0, key.1 + step.1, key.2 + step.2); + if next.1 < -1 || next.1 > columns.sections { + continue; + } + let Some(n) = index(next) else { continue }; + if !reached[n] { + reached[n] = true; + queue.push_back((next, opposite as u8, travelled | (1 << d))); + } + } + } + reached + } + + fn random_world(o: &mut Occlusion, seed: u64, count: usize) { + let mut seed = seed; + let mut next = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + for _ in 0..count { + let r = next(); + let key = ( + (r % 13) as i32 - 6, + ((r >> 8) % 6) as i32, + ((r >> 16) % 13) as i32 - 6, + ); + // Open, half open or nearly closed sections. + let vis = match r >> 40 & 3 { + 0 => next() & next() & next(), + 1 => next(), + _ => next() | next(), + }; + o.set(key, vis & ALL_VISIBLE); + } + } + + /// The graph is the search the render thread did before, cell for cell. + #[test] + fn same_sections_as_before() { + let mut hidden = 0; + for seed in [0x9e37_79b9, 7, 0xdead_beef] { + let mut o = Occlusion::new(6); + random_world(&mut o, seed, 900); + for from in [(0, 2, 0), (3, 0, -2), (-5, 5, 4), (1, -1, 1), (0, 7, 0)] { + o.settle(from, 6); + o.settle(from, 6); + let graph = o.graph.as_ref().expect("searched"); + let reached: Vec<bool> = + graph.directions.iter().map(|&d| d & REACHED != 0).collect(); + assert_eq!(reached, reference(&o.columns, from, 6), "{seed} {from:?}"); + hidden += reached.iter().filter(|&&r| !r).count(); + } + } + assert!(hidden > 1000, "the worlds hide sections ({hidden})"); + } + + /// The worker's graph is the one the render thread would compute. + #[test] + fn the_worker_matches_a_search_on_the_render_thread() { + let mut o = Occlusion::new(6); + random_world(&mut o, 0x9e37_79b9, 800); + for from in [(0, 2, 0), (3, 0, -2), (-5, 5, 4)] { + o.settle(from, 6); + o.settle(from, 6); + let mut local = Graph::default(); + local.search(&o.columns, from, 6, &mut Vec::new(), &mut VecDeque::new()); + let graph = o.graph.as_ref().expect("searched"); + assert_eq!(graph.directions, local.directions); + assert_eq!(graph.entered, local.entered); + } + } } diff --git a/crates/horizon-client/src/gfx/upload.rs b/crates/horizon-client/src/gfx/upload.rs index d42958862..0d56c73a0 100644 --- a/crates/horizon-client/src/gfx/upload.rs +++ b/crates/horizon-client/src/gfx/upload.rs @@ -14,8 +14,13 @@ pub struct Uploads { impl Uploads { pub fn new(device: &wgpu::Device) -> Self { + Self::with_chunk(device, CHUNK) + } + /// A belt whose staging buffers hold `chunk` bytes (larger writes get + /// a buffer of their own). + pub fn with_chunk(device: &wgpu::Device, chunk: u64) -> Self { Self { - belt: wgpu::util::StagingBelt::new(device.clone(), CHUNK), + belt: wgpu::util::StagingBelt::new(device.clone(), chunk), } } /// Copy tightly packed RGBA8 `pixels` (`width` by `height`) into one mip @@ -31,7 +36,9 @@ impl Uploads { let row = width as usize * 4; debug_assert_eq!(pixels.len(), row * height as usize); let padded = row.next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize); - let size = NonZeroU64::new((padded * height as usize) as u64).expect("non-empty texture"); + let Some(size) = NonZeroU64::new((padded * height as usize) as u64) else { + return; + }; let alignment = NonZeroU64::new(u64::from(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)) .expect("non-zero alignment"); let slice = self.belt.allocate(size, alignment); diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index be4bdb52e..0cc99b07b 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -977,7 +977,12 @@ impl HudRenderer { capacity, }) } - pub fn animate_fire(&mut self, queue: &wgpu::Queue, tick: u64) { + pub fn animate_fire( + &mut self, + uploads: &mut crate::gfx::upload::Uploads, + encoder: &mut wgpu::CommandEncoder, + tick: u64, + ) { let Some(texture) = &self.atlas_texture else { return; }; @@ -987,7 +992,8 @@ impl HudRenderer { continue; } let pixels = animation.resized_pixels(frame, rect.w, rect.h); - queue.write_texture( + uploads.texture( + encoder, wgpu::TexelCopyTextureInfo { texture, mip_level: 0, @@ -998,35 +1004,27 @@ impl HudRenderer { }, aspect: wgpu::TextureAspect::All, }, + rect.w, + rect.h, &pixels, - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(rect.w * 4), - rows_per_image: Some(rect.h), - }, - wgpu::Extent3d { - width: rect.w, - height: rect.h, - depth_or_array_layers: 1, - }, ); *previous = frame; } } - pub fn draw( + /// Stage the batch's atlas patches, vertices and uniform: before the + /// frame's first pass, so the copies share one command buffer. + pub fn prepare( &mut self, device: &wgpu::Device, - queue: &wgpu::Queue, uploads: &mut crate::gfx::upload::Uploads, encoder: &mut wgpu::CommandEncoder, - target: &wgpu::TextureView, - depth: &wgpu::TextureView, batch: &HudBatch, size: [u32; 2], ) { if let Some(texture) = &self.atlas_texture { for p in &batch.patches { - queue.write_texture( + uploads.texture( + encoder, wgpu::TexelCopyTextureInfo { texture, mip_level: 0, @@ -1037,17 +1035,9 @@ impl HudRenderer { }, aspect: wgpu::TextureAspect::All, }, + p.width, + p.height, &p.rgba, - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(p.width * 4), - rows_per_image: None, - }, - wgpu::Extent3d { - width: p.width, - height: p.height, - depth_or_array_layers: 1, - }, ); } } @@ -1078,6 +1068,19 @@ impl HudRenderer { size: [size[0] as f32, size[1] as f32, batch.scale, 0.0], }), ); + } + /// Draw the batch `prepare` staged. + pub fn draw( + &self, + encoder: &mut wgpu::CommandEncoder, + target: &wgpu::TextureView, + depth: &wgpu::TextureView, + batch: &HudBatch, + size: [u32; 2], + ) { + if batch.vertices.is_empty() || size.contains(&0) { + return; + } let attachments = [Some(wgpu::RenderPassColorAttachment { view: target, resolve_target: None, diff --git a/crates/horizon-client/src/interaction_input.rs b/crates/horizon-client/src/interaction_input.rs new file mode 100644 index 000000000..d17cb938c --- /dev/null +++ b/crates/horizon-client/src/interaction_input.rs @@ -0,0 +1,186 @@ +//! The mouse-key portion of Minecraft.handleKeybinds. Events only count clicks; +//! the client tick consumes them before player movement and CLIENT_TICK_END. +#[derive(Default)] +pub struct InteractionInput { + clicks: [u32; 3], +} + +#[derive(Clone, Copy)] +pub enum Button { + Attack, + Use, + Pick, +} + +pub trait InteractionWorld { + fn using_item(&self) -> bool; + fn release_using(&mut self); + fn start_attack(&mut self) -> bool; + fn start_use(&mut self); + fn pick(&mut self); + fn use_delay(&self) -> u32; + fn continue_attack(&mut self, down: bool); +} + +/// Minecraft.startUseItem dispatches one hit result per hand. A passing +/// entity interaction falls back to the item, without trying a block behind it. +pub trait TargetUseWorld { + fn use_entity(&mut self) -> bool; + fn use_block(&mut self) -> bool; + fn use_item(&mut self); +} + +pub fn use_on_target(world: &mut impl TargetUseWorld, entity: bool) { + let consumed = if entity { + world.use_entity() + } else { + world.use_block() + }; + if !consumed { + world.use_item(); + } +} + +impl InteractionInput { + pub fn press(&mut self, button: Button) { + self.clicks[button as usize] += 1; + } + + pub fn tick(&mut self, world: &mut impl InteractionWorld, attack_down: bool, use_down: bool) { + let [attack, use_item, pick] = std::mem::take(&mut self.clicks); + let mut instant = false; + if world.using_item() { + if !use_down { + world.release_using(); + } + // Vanilla drains all three click queues while using an item, + // including the tick that releases it. + } else { + for _ in 0..attack { + instant |= world.start_attack(); + } + for _ in 0..use_item { + world.start_use(); + } + for _ in 0..pick { + world.pick(); + } + } + if use_down && world.use_delay() == 0 && !world.using_item() { + world.start_use(); + } + world.continue_attack(!instant && attack_down); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Default)] + struct World { + using: bool, + destroying: bool, + delay: u32, + begin_using: bool, + events: Vec<&'static str>, + } + impl InteractionWorld for World { + fn using_item(&self) -> bool { + self.using + } + fn release_using(&mut self) { + self.events.push("release"); + self.using = false; + } + fn start_attack(&mut self) -> bool { + self.events.push("attack"); + false + } + fn start_use(&mut self) { + if !self.destroying { + self.events.push("use"); + self.delay = 4; + self.using = self.begin_using; + } + } + fn pick(&mut self) { + self.events.push("pick"); + } + fn use_delay(&self) -> u32 { + self.delay + } + fn continue_attack(&mut self, _: bool) { + self.events.push("continue"); + } + } + + #[test] + fn quick_clicks_wait_for_a_tick_and_follow_keybind_order() { + let mut input = InteractionInput::default(); + let mut world = World::default(); + input.press(Button::Use); + input.press(Button::Pick); + input.press(Button::Attack); + assert!(world.events.is_empty()); + // Both edges can arrive between ticks; the press still acts once. + input.tick(&mut world, false, false); + assert_eq!(world.events, ["attack", "use", "pick", "continue"]); + world.events.clear(); + input.tick(&mut world, false, false); + assert_eq!( + world.events, + ["continue"], + "no spurious release or repeated click" + ); + } + + #[test] + fn releasing_actual_item_use_discards_clicks_for_that_tick() { + let mut input = InteractionInput::default(); + let mut world = World { + using: true, + ..Default::default() + }; + for button in [Button::Attack, Button::Use, Button::Pick] { + input.press(button); + } + input.tick(&mut world, true, false); + assert_eq!(world.events, ["release", "continue"]); + } + + #[test] + fn holding_use_respects_the_delay_and_active_digging() { + let mut input = InteractionInput::default(); + let mut world = World { + destroying: true, + ..Default::default() + }; + input.press(Button::Use); + input.tick(&mut world, true, true); + assert_eq!(world.events, ["continue"]); + world.destroying = false; + world.events.clear(); + input.tick(&mut world, false, true); + assert_eq!(world.events, ["use", "continue"]); + world.events.clear(); + input.tick(&mut world, false, true); + assert_eq!(world.events, ["continue"]); + } + + #[test] + fn a_quick_use_click_releases_on_the_following_tick() { + let mut input = InteractionInput::default(); + let mut world = World { + begin_using: true, + ..Default::default() + }; + input.press(Button::Use); + input.tick(&mut world, false, false); + assert_eq!(world.events, ["use", "continue"]); + assert!(world.using); + world.events.clear(); + input.tick(&mut world, false, false); + assert_eq!(world.events, ["release", "continue"]); + } +} diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index d54564b7a..adc4e0f18 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -110,6 +110,16 @@ pub const OMINOUS_LAYERS: [(&str, &str); 8] = [ ("circle", "light_gray"), ("border", "black"), ]; + +/// The raid captain banner's default tooltip setting, stored by vanilla as a +/// component but represented by `StackData::ominous_banner` in Horizon. +fn ominous_tooltip_display() -> Tag { + Tag::compound([( + "hidden_components", + Tag::List(vec![Tag::String("minecraft:banner_patterns".into())]), + )]) +} + /// `WrittenBookContent` with the pages as plain text. #[derive(Clone, Debug, Default, PartialEq)] pub struct WrittenBook { @@ -610,13 +620,9 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> { "minecraft:banner_patterns", Tag::List(OMINOUS_LAYERS.iter().map(|(p, c)| layer(p, c)).collect()), )); - entries.push(( - "minecraft:tooltip_display", - Tag::compound([( - "hidden_components", - Tag::List(vec![Tag::String("minecraft:banner_patterns".into())]), - )]), - )); + if d.other("minecraft:tooltip_display").is_none() { + entries.push(("minecraft:tooltip_display", ominous_tooltip_display())); + } entries.push(( "minecraft:item_name", Tag::compound([( @@ -793,10 +799,8 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option<Box<StackData for (k, v) in map { let key = k.to_string_lossy(); let ominous_part = data.ominous_banner - && matches!( - key.as_str(), - "minecraft:item_name" | "minecraft:rarity" | "minecraft:tooltip_display" - ); + && (matches!(key.as_str(), "minecraft:item_name" | "minecraft:rarity") + || (key == "minecraft:tooltip_display" && v == &ominous_tooltip_display())); if !MODELLED.contains(&key.as_str()) && !ominous_part { data.other.push((key, v.clone())); } @@ -882,7 +886,19 @@ mod tests { let tag = encode_components(&banner).unwrap(); assert!(tag.get("minecraft:banner_patterns").is_some()); let (_, back) = decode_components(Some(&tag)); - assert!(back.unwrap().ominous_banner); + let back = back.unwrap(); + assert!(back.ominous_banner); + assert!(back.other("minecraft:tooltip_display").is_none()); + + banner.data_mut().set_other( + "minecraft:tooltip_display", + Some(Tag::Compound(Default::default())), + ); + let (_, custom_display) = decode_components(encode_components(&banner).as_ref()); + assert_eq!( + custom_display.unwrap().other("minecraft:tooltip_display"), + Some(&Tag::Compound(Default::default())) + ); let mut bottle = ItemStack::new("minecraft:ominous_bottle", 1); bottle.data_mut().ominous_amplifier = Some(3); let (_, back) = decode_components(encode_components(&bottle).as_ref()); diff --git a/crates/horizon-client/src/item_tooltip.rs b/crates/horizon-client/src/item_tooltip.rs index 77abbf8cf..114a57ad0 100644 --- a/crates/horizon-client/src/item_tooltip.rs +++ b/crates/horizon-client/src/item_tooltip.rs @@ -4,6 +4,64 @@ use crate::{ hud::rgba, items::{ItemInfo, ItemStack}, }; +use horizon_world::nbt::Tag; + +/// The `minecraft:tooltip_display` component applied by `ItemStack` while it +/// builds a hover tooltip. +pub struct TooltipDisplay<'a> { + component: Option<&'a Tag>, + ominous_banner: bool, +} + +impl<'a> TooltipDisplay<'a> { + pub fn for_stack(stack: &'a ItemStack) -> Self { + Self { + component: stack + .data() + .and_then(|data| data.other("minecraft:tooltip_display")), + ominous_banner: stack.data().is_some_and(|data| data.ominous_banner), + } + } + + fn hides_tooltip(&self) -> bool { + matches!( + self.component.and_then(|display| display.get("hide_tooltip")), + Some(Tag::Byte(value)) if *value != 0 + ) + } + + /// `ItemStack.getTooltipLines`: `hide_tooltip` suppresses the name unless + /// the tooltip flag is creative. + pub fn name_visible(&self, creative: bool) -> bool { + creative || !self.hides_tooltip() + } + + /// `TooltipDisplay.shows`: whether details for a data component are shown. + pub fn shows(&self, component: &str) -> bool { + if self.hides_tooltip() { + return false; + } + // `item_data::decode_components` models the raid captain banner's + // default hidden pattern tooltip as `ominous_banner` instead of + // retaining its redundant `tooltip_display` component. + if self.ominous_banner + && self.component.is_none() + && component == "minecraft:banner_patterns" + { + return false; + } + let Some(Tag::List(hidden)) = self + .component + .and_then(|display| display.get("hidden_components")) + else { + return true; + }; + let component = horizon_world::nbt::JavaString::from(component); + !hidden + .iter() + .any(|tag| matches!(tag, Tag::String(id) if id == &component)) + } +} /// `EquipmentSlotGroup` in declaration order, the order tooltips list them in. const SLOT_GROUPS: [&str; 11] = [ @@ -348,6 +406,49 @@ pub fn lines( mod tests { use super::*; + #[test] + fn tooltip_display_controls_name_and_component_visibility() { + let mut stack = ItemStack::new("minecraft:diamond_sword", 1); + let display = TooltipDisplay::for_stack(&stack); + assert!(display.name_visible(false)); + assert!(display.shows("minecraft:attribute_modifiers")); + + stack.data_mut().set_other( + "minecraft:tooltip_display", + Some(Tag::compound([( + "hidden_components", + Tag::List(vec![Tag::String("minecraft:attribute_modifiers".into())]), + )])), + ); + let display = TooltipDisplay::for_stack(&stack); + assert!(display.name_visible(false)); + assert!(!display.shows("minecraft:attribute_modifiers")); + assert!(display.shows("minecraft:enchantments")); + + stack.data_mut().set_other( + "minecraft:tooltip_display", + Some(Tag::compound([("hide_tooltip", Tag::Byte(1))])), + ); + let display = TooltipDisplay::for_stack(&stack); + assert!(!display.name_visible(false)); + assert!(display.name_visible(true)); + assert!(!display.shows("minecraft:attribute_modifiers")); + } + + #[test] + fn ominous_banner_keeps_its_default_hidden_pattern_tooltip() { + let mut banner = crate::mobs::raider::ominous_banner(); + let display = TooltipDisplay::for_stack(&banner); + assert!(!display.shows("minecraft:banner_patterns")); + + banner.data_mut().set_other( + "minecraft:tooltip_display", + Some(Tag::Compound(Default::default())), + ); + let display = TooltipDisplay::for_stack(&banner); + assert!(display.shows("minecraft:banner_patterns")); + } + #[test] fn ominous_banner_name_and_rarity_use_the_stack() { let translate = |key: &str| match key { diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 2782d254f..7f2782c72 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -54,7 +54,8 @@ pub enum ConsumeEffect { }, ClearAllEffects, RemoveEffects(Vec<String>), - TeleportRandomly, + /// `TeleportRandomlyConsumeEffect`. + TeleportRandomly(horizon_world::teleport_consume::TeleportConsume), PlaySound(String), } @@ -67,10 +68,15 @@ pub struct ItemInfo { pub block: Option<BlockStateId>, pub tool: Vec<ToolRule>, pub tool_default_speed: f32, + /// The `tool` component's `damage_per_block`, when the item has the + /// component (a mace or trident has one without rules). + pub tool_damage_per_block: Option<u32>, pub food: Option<(u32, f32)>, pub can_always_eat: bool, - pub consumable: bool, - pub consume_effects: Vec<ConsumeEffect>, + /// `consumable`: its timing, sound, particles and `on_consume_effects`. + pub consumable: Option<horizon_world::consumable::Consumable<String, ConsumeEffect>>, + /// `use_remainder`: what a finished use leaves (`UseRemainder`). + pub use_remainder: Option<String>, pub model: String, /// Main-hand `attack_damage` / `attack_speed` modifier amounts. pub attack_damage: f32, @@ -504,7 +510,18 @@ impl Items { consume_effects.push(ConsumeEffect::RemoveEffects(targets)); } Some("minecraft:teleport_randomly") => { - consume_effects.push(ConsumeEffect::TeleportRandomly); + consume_effects.push(ConsumeEffect::TeleportRandomly( + horizon_world::teleport_consume::TeleportConsume { + diameter: effect + .get("diameter") + .and_then(Value::as_f64) + .map_or(16.0, |d| d as f32), + directional_particles: effect + .get("directional_particles") + .and_then(Value::as_bool) + .unwrap_or(true), + }, + )); } Some("minecraft:play_sound") => { if let Some(sound) = effect.get("sound").and_then(|s| s.as_str()) { @@ -528,10 +545,27 @@ impl Items { tool_default_speed: c["minecraft:tool"]["default_mining_speed"] .as_f64() .unwrap_or(1.0) as f32, + tool_damage_per_block: c + .get("minecraft:tool") + .map(|t| t["damage_per_block"].as_u64().unwrap_or(1) as u32), food, can_always_eat, - consumable: c.get("minecraft:consumable").is_some(), - consume_effects, + // Consumable.CODEC's defaults. + consumable: c.get("minecraft:consumable").map(|cons| { + horizon_world::consumable::Consumable { + seconds: cons["consume_seconds"].as_f64().map_or(1.6, |s| s as f32), + animation: crate::first_person::consumable_animation(cons), + sound: cons["sound"] + .as_str() + .unwrap_or("minecraft:entity.generic.eat") + .to_owned(), + particles: cons["has_consume_particles"].as_bool().unwrap_or(true), + effects: std::mem::take(&mut consume_effects), + } + }), + use_remainder: c["minecraft:use_remainder"]["id"] + .as_str() + .map(str::to_owned), model: c["minecraft:item_model"] .as_str() .unwrap_or(name) @@ -694,6 +728,10 @@ impl Items { songs: HashMap::new(), } } + /// Whether `block` is in the block tag `tag` (`minecraft:fire`, no `#`). + pub fn block_in_tag(&self, tag: &str, block: &str) -> bool { + self.block_tags.get(tag).is_some_and(|s| s.contains(block)) + } fn block_matches(&self, spec: &str, block: &str) -> bool { match spec.strip_prefix('#') { Some(tag) => self.block_tags.get(tag).is_some_and(|s| s.contains(block)), @@ -1607,18 +1645,63 @@ mod tests { let apple = items.get("minecraft:golden_apple").expect("golden apple"); assert!(apple.can_always_eat); assert!(apple.food.is_some()); - assert!(!apple.consume_effects.is_empty()); + assert!(!apple.consumable.as_ref().unwrap().effects.is_empty()); let enchanted = items .get("minecraft:enchanted_golden_apple") .expect("enchanted golden apple"); assert!(enchanted.can_always_eat); assert!(enchanted.food.is_some()); - assert!(!enchanted.consume_effects.is_empty()); + assert!(!enchanted.consumable.as_ref().unwrap().effects.is_empty()); let beef = items.get("minecraft:cooked_beef").expect("cooked beef"); assert!(!beef.can_always_eat); assert!(beef.food.is_some()); + + // Consumables without food, their style and their remainders. + use horizon_world::consumable::UseAnimation; + let milk = items.get("minecraft:milk_bucket").expect("milk bucket"); + let drink = milk.consumable.as_ref().unwrap(); + assert!(milk.food.is_none()); + assert_eq!(drink.effects, [ConsumeEffect::ClearAllEffects]); + assert_eq!((drink.ticks(), drink.animation), (32, UseAnimation::Drink)); + assert_eq!(drink.sound, "minecraft:entity.generic.drink"); + assert!(!drink.particles); + assert_eq!(milk.use_remainder.as_deref(), Some("minecraft:bucket")); + let honey = items.get("minecraft:honey_bottle").expect("honey bottle"); + let sip = honey.consumable.as_ref().unwrap(); + assert_eq!(sip.ticks(), 40); + assert_eq!(sip.sound, "minecraft:item.honey_bottle.drink"); + assert_eq!( + sip.effects, + [ConsumeEffect::RemoveEffects(vec![ + "minecraft:poison".into() + ])] + ); + assert_eq!( + honey.use_remainder.as_deref(), + Some("minecraft:glass_bottle") + ); + let kelp = items.get("minecraft:dried_kelp").unwrap(); + let bite = kelp.consumable.as_ref().unwrap(); + assert_eq!((bite.ticks(), bite.animation), (16, UseAnimation::Eat)); + assert_eq!(bite.sound, "minecraft:entity.generic.eat"); + assert!(bite.particles && kelp.use_remainder.is_none()); + let chorus = items.get("minecraft:chorus_fruit").unwrap(); + assert_eq!( + chorus.consumable.as_ref().unwrap().effects, + [ConsumeEffect::TeleportRandomly( + horizon_world::teleport_consume::TeleportConsume { + diameter: 16.0, + directional_particles: true, + } + )] + ); + let chicken = items.get("minecraft:chicken").unwrap(); + assert!(matches!( + chicken.consumable.as_ref().unwrap().effects[..], + [ConsumeEffect::ApplyEffects { probability, .. }] if probability == 0.3 + )); } } diff --git a/crates/horizon-client/src/lan/attributes.rs b/crates/horizon-client/src/lan/attributes.rs new file mode 100644 index 000000000..bc208b6f9 --- /dev/null +++ b/crates/horizon-client/src/lan/attributes.rs @@ -0,0 +1,143 @@ +//! `ClientboundUpdateAttributesPacket`: the attribute instances a server syncs +//! to its clients. `ServerEntity.sendPairingData` sends every client-syncable +//! instance an entity has (`AttributeMap.getSyncableAttributes`: the instances +//! created so far, not the type's defaults), `sendDirtyEntityData` the ones +//! changed since (`getAttributesToSync`), to the trackers and the player itself. +use horizon_protocol::packets::play::{AttributeModifier, AttributeSnapshot}; +use horizon_world::attributes::{ + Instance, Operation, + entity::{AttributeId, EntityAttributes}, + live::LiveAttributes, +}; + +/// `AttributeModifier.Operation.id`. +pub fn operation_id(op: Operation) -> i32 { + match op { + Operation::AddValue => 0, + Operation::AddMultipliedBase => 1, + Operation::AddMultipliedTotal => 2, + } +} + +/// An `Operation`'s serialized name (`add_value` ...) as its id. +pub fn operation_named(name: &str) -> i32 { + match name { + "add_multiplied_base" => 1, + "add_multiplied_total" => 2, + _ => 0, + } +} + +/// `AttributeSnapshot`: the base and every modifier, in the order they were added. +pub fn snapshot(attribute: AttributeId, instance: &Instance) -> AttributeSnapshot { + AttributeSnapshot { + attribute: attribute.registry_id(), + base: instance.base_value(), + modifiers: instance + .modifiers() + .iter() + .map(|m| AttributeModifier { + id: m.id().to_owned(), + amount: m.amount(), + operation: operation_id(m.operation()), + }) + .collect(), + } +} + +/// `AttributeMap.getSyncableAttributes` of a live map (a player's). +pub fn syncable<G: FnMut() -> i32>(map: &LiveAttributes<G>) -> Vec<AttributeSnapshot> { + let catalog = map.catalog(); + map.instances() + .filter(|(_, key, _)| catalog.attribute(key.attribute()).syncable) + .map(|(_, key, instance)| snapshot(key.attribute(), instance)) + .collect() +} + +/// `getAttributesToSync`, cleared once read (`ServerEntity.sendDirtyEntityData`). +pub fn take_dirty<G: FnMut() -> i32>(map: &mut LiveAttributes<G>) -> Vec<AttributeSnapshot> { + if map.sync().is_empty() { + return Vec::new(); + } + let handles: Vec<_> = map.sync().values().flatten().cloned().collect(); + map.sync_mut().clear(); + handles + .iter() + .filter_map(|h| { + let key = map.attribute(h).ok()?; + Some(snapshot(key.attribute(), map.instance(h).ok()?)) + }) + .collect() +} + +/// The client-syncable instances of a generic attribute map. +pub fn generic_syncable(map: &EntityAttributes) -> impl Iterator<Item = AttributeSnapshot> + '_ { + let catalog = map.catalog(); + catalog + .attributes() + .filter(|(_, a)| a.syncable) + .filter_map(move |(id, _)| map.instance(id).map(|i| snapshot(id, i))) +} + +/// Adds a modifier to the snapshot of `attribute`, creating it with `base`. +pub fn add_modifier( + out: &mut Vec<AttributeSnapshot>, + attribute: i32, + base: f64, + modifier: AttributeModifier, +) { + let snapshot = instance(out, attribute, base); + match snapshot.modifiers.iter_mut().find(|m| m.id == modifier.id) { + Some(m) => *m = modifier, + None => snapshot.modifiers.push(modifier), + } +} + +/// The snapshot of `attribute`, created with `base` if it isn't there yet. +pub fn instance( + out: &mut Vec<AttributeSnapshot>, + attribute: i32, + base: f64, +) -> &mut AttributeSnapshot { + let i = match out.iter().position(|a| a.attribute == attribute) { + Some(i) => i, + None => { + out.push(AttributeSnapshot { + attribute, + base, + modifiers: Vec::new(), + }); + out.len() - 1 + } + }; + &mut out[i] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn modifiers_replace_by_id_and_instances_are_created_once() { + let mut out = Vec::new(); + let m = |id: &str, amount| AttributeModifier { + id: id.into(), + amount, + operation: 0, + }; + add_modifier(&mut out, 1, 0.0, m("minecraft:armor.helmet", 3.0)); + add_modifier(&mut out, 1, 5.0, m("minecraft:armor.chestplate", 8.0)); + add_modifier(&mut out, 1, 5.0, m("minecraft:armor.helmet", 2.0)); + assert_eq!(out.len(), 1); + assert_eq!(out[0].base, 0.0); + assert_eq!( + out[0].modifiers, + [ + m("minecraft:armor.helmet", 2.0), + m("minecraft:armor.chestplate", 8.0) + ] + ); + instance(&mut out, 26, 0.7); + assert_eq!(out.len(), 2); + } +} diff --git a/crates/horizon-client/src/lan/chunks.rs b/crates/horizon-client/src/lan/chunks.rs index d6a7dc3a1..35339a05c 100644 --- a/crates/horizon-client/src/lan/chunks.rs +++ b/crates/horizon-client/src/lan/chunks.rs @@ -15,7 +15,13 @@ use horizon_protocol::{ registry::{Builtin, ceil_log2}, }; use horizon_world::nbt::Tag; -use std::{collections::HashMap, sync::Arc}; +use std::{ + collections::HashMap, + sync::{ + Arc, OnceLock, + atomic::{AtomicUsize, Ordering}, + }, +}; const NON_AIR: u8 = 1; const FLUID: u8 = 2; @@ -83,12 +89,10 @@ pub fn block_entity_type(name: &str) -> Option<&'static str> { /// Per-state facts and registry ids for encoding chunks. pub struct ChunkEncoder { - flags: Vec<u8>, + /// What encoding a section needs, shared with the warm-up threads. + coder: Arc<SectionCoder>, /// Block entity type id per state (-1 for none). entity_types: Vec<i16>, - /// Network biome id per internal biome index. - pub biome_ids: Vec<i32>, - biome_bits: u8, /// The block registry id of each state's block, for BlockEvent. pub block_ids: Vec<i32>, /// The save's tables, for the heightmaps. @@ -104,6 +108,14 @@ pub struct ChunkEncoder { sky: bool, } +/// Per-state flags and biome ids: all a section's encoding reads. +struct SectionCoder { + flags: Vec<u8>, + /// Network biome id per internal biome index. + biome_ids: Vec<i32>, + biome_bits: u8, +} + /// A column's client heightmaps, valid while it holds the same sections. struct Heights { sections: Vec<std::sync::Weak<Section>>, @@ -170,8 +182,151 @@ impl Layers { } } +impl SectionCoder { + /// LevelChunkSection.write, and its block entity blocks. + fn wire(&self, section: &Section) -> (Arc<[u8]>, Entities) { + let (encoded, entities) = self.section(section); + let mut w = horizon_protocol::buf::Writer::new(); + encoded.write(&mut w); + (w.data.into(), entities.into()) + } + + 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, 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 { + fluids += n; + } + } + f & ENTITY != 0 + }; + // One block everywhere (all air, mostly): what from_values would give. + let uniform = section.blocks.uniform(); + if let Some(v) = uniform { + if count(v, BLOCKS as i16) { + entities = (0..BLOCKS as u16).map(|i| (i, v)).collect(); + } + } else { + let mut unpacked = [0u32; BLOCKS]; + section.unpack(&mut unpacked); + 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<i32> = (0..BIOMES) + .map(|j| { + let internal = section.biomes.get(j) as u16; + self.biome_ids + .get(usize::from(internal)) + .copied() + .unwrap_or(0) + }) + .collect(); + ( + horizon_protocol::chunk::Section { + non_empty, + fluids, + states: match uniform { + Some(v) => Paletted { + bits: 0, + palette: vec![v as i32], + data: Vec::new(), + }, + None => Paletted::from_values( + &values, + Strategy::Blocks, + crate::chunk::block_strategy().global_bits, + ), + }, + biomes: Paletted::from_values(&biome_values, Strategy::Biomes, self.biome_bits), + }, + entities, + ) + } +} + /// Sections kept before the ones no longer resident are dropped. const CACHE_SWEEP: usize = 1 << 15; + +/// Uncached sections below which a batch is encoded on the tick's thread +/// alone: waking the warm-up threads costs more than a few sections. +const WARM_MIN: usize = 16; + +/// Sections a batch needs, each taken by whichever thread is free first, +/// and what each gave: its wire bytes and, with varying light, its layers. +struct Warm { + coder: Arc<SectionCoder>, + sections: Vec<Arc<Section>>, + next: AtomicUsize, + done: Vec<OnceLock<Warmed>>, +} +type Warmed = ((Arc<[u8]>, Entities), Option<Arc<Layers>>); +impl Warm { + /// Encode sections until none is left to take. + fn run(&self) { + loop { + let i = self.next.fetch_add(1, Ordering::Relaxed); + let Some(s) = self.sections.get(i) else { + return; + }; + let light = matches!(s.light, Light::Full(_)).then(|| Arc::new(Layers::of(&s.light))); + let _ = self.done[i].set((self.coder.wire(s), light)); + } + } +} + +/// The warm-up threads (one per core besides the tick's) and the job they +/// take: its number, and the job while it has sections left to take. +struct WarmPool { + job: std::sync::Mutex<(u64, Option<Arc<Warm>>)>, + ready: std::sync::Condvar, +} + +/// The warm-up threads, started the first time; none on a single core or +/// when no thread could start. +fn warm_pool() -> Option<&'static WarmPool> { + static POOL: OnceLock<Option<Arc<WarmPool>>> = OnceLock::new(); + POOL.get_or_init(|| { + let threads = std::thread::available_parallelism().map_or(1, |n| n.get()) - 1; + let pool = Arc::new(WarmPool { + job: Default::default(), + ready: Default::default(), + }); + let started = (0..threads) + .filter(|i| { + let pool = pool.clone(); + std::thread::Builder::new() + .name(format!("horizon-chunk-encode-{i}")) + .spawn(move || { + let mut done = 0; + loop { + let job = { + let mut slot = pool.job.lock().unwrap(); + while slot.0 == done { + slot = pool.ready.wait(slot).unwrap(); + } + done = slot.0; + slot.1.clone() + }; + if let Some(job) = job { + job.run(); + } + } + }) + .is_ok() + }) + .count(); + (started > 0).then_some(pool) + }) + .as_deref() +} impl ChunkEncoder { /// `biome_names`: the internal biome list in order; `biome_registry`: /// the synchronized biome entries in network order. @@ -218,10 +373,12 @@ impl ChunkEncoder { }) .collect(); Self { - flags, + coder: Arc::new(SectionCoder { + flags, + biome_ids, + biome_bits: ceil_log2(biome_registry.len()), + }), entity_types, - biome_ids, - biome_bits: ceil_log2(biome_registry.len()), block_ids, tables: None, cache: Default::default(), @@ -297,7 +454,8 @@ impl ChunkEncoder { /// LevelChunkSection.hasOnlyAir, negated. fn non_air(&self, section: &Section) -> bool { - let non_air = |v: u32| self.flags.get(v as usize).copied().unwrap_or(0) & NON_AIR != 0; + let non_air = + |v: u32| self.coder.flags.get(v as usize).copied().unwrap_or(0) & NON_AIR != 0; // The palette first: most sections are all air, or one block. if !section.blocks.maybe_has(non_air) { false @@ -314,10 +472,7 @@ impl ChunkEncoder { 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]>, Entities) = (w.data.into(), entities.into()); + let wire = self.coder.wire(section); self.cached(section, |e| e.wire = Some(wire.clone())); wire } @@ -340,71 +495,12 @@ impl ChunkEncoder { .map(|t| i32::from(*t)) } pub fn is_air(&self, state: u32) -> bool { - self.flags + self.coder + .flags .get(state as usize) .is_none_or(|f| f & NON_AIR == 0) } - 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, 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 { - fluids += n; - } - } - f & ENTITY != 0 - }; - // One block everywhere (all air, mostly): what from_values would give. - let uniform = section.blocks.uniform(); - if let Some(v) = uniform { - if count(v, BLOCKS as i16) { - entities = (0..BLOCKS as u16).map(|i| (i, v)).collect(); - } - } else { - let mut unpacked = [0u32; BLOCKS]; - section.unpack(&mut unpacked); - 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<i32> = (0..BIOMES) - .map(|j| { - let internal = section.biomes.get(j) as u16; - self.biome_ids - .get(usize::from(internal)) - .copied() - .unwrap_or(0) - }) - .collect(); - ( - horizon_protocol::chunk::Section { - non_empty, - fluids, - states: match uniform { - Some(v) => Paletted { - bits: 0, - palette: vec![v as i32], - data: Vec::new(), - }, - None => Paletted::from_values( - &values, - Strategy::Blocks, - crate::chunk::block_strategy().global_bits, - ), - }, - biomes: Paletted::from_values(&biome_values, Strategy::Biomes, self.biome_bits), - }, - entities, - ) - } - /// The chunk column with its light and block entities. /// The non-air sections of a column as bits (LevelChunkSection.hasOnlyAir). fn occupied(&self, chunk: &Chunk) -> u64 { @@ -442,6 +538,65 @@ impl ChunkEncoder { self.body(chunk, &world.block_entities, self.around(chunk, world)) } + /// Encode the sections of these columns not cached yet before their + /// bodies are made, shared out to the warm-up threads: a batch of new + /// terrain costs mostly its sections' first encoding. This thread takes + /// sections too until none is left, then caches what is done; it never + /// waits for the other threads (they keep their results to themselves + /// until then), and a section one of them is still on is encoded again + /// by `body_in`, with the same bytes. + pub fn warm(&self, columns: &[&Chunk]) { + let sections: Vec<Arc<Section>> = { + let cache = self.cache.lock().unwrap(); + columns + .iter() + .flat_map(|c| &c.sections[self.sections.clone()]) + .filter(|s| { + cache + .get(&(Arc::as_ptr(s) as usize)) + .is_none_or(|e| e.wire.is_none()) + }) + .cloned() + .collect() + }; + if sections.len() < WARM_MIN { + return; + } + let Some(pool) = warm_pool() else { + return; + }; + let job = Arc::new(Warm { + coder: self.coder.clone(), + done: sections.iter().map(|_| OnceLock::new()).collect(), + sections, + next: AtomicUsize::new(0), + }); + { + let mut slot = pool.job.lock().unwrap(); + slot.0 += 1; + slot.1 = Some(job.clone()); + } + pool.ready.notify_all(); + job.run(); + // Every section is claimed: the job leaves the slot. + { + let mut slot = pool.job.lock().unwrap(); + if slot.1.as_ref().is_some_and(|j| Arc::ptr_eq(j, &job)) { + slot.1 = None; + } + } + let mut cache = self.cache.lock().unwrap(); + for (s, done) in job.sections.iter().zip(&job.done) { + if let Some((wire, light)) = done.get() { + let e = self.entry(&mut cache, s); + e.wire = Some(wire.clone()); + if light.is_some() { + e.light = light.clone(); + } + } + } + } + fn body( &self, chunk: &Chunk, @@ -480,6 +635,33 @@ impl ChunkEncoder { w.data } + /// ClientboundLightUpdatePacket for the light sections over `changed` (a + /// bit per section of the column, `sectionLightChanged`), as vanilla's + /// `ClientboundLightUpdatePacketData` writes them, with both kinds of + /// each section (Horizon's light engine doesn't tell them apart; the + /// client keeps the same light either way). A section changed as its + /// last block went (light dimming around a removed block) is sent too: + /// a client not tracking the block would otherwise keep its old light. + pub fn light_update(&self, chunk: &Chunk, changed: u32) -> Vec<u8> { + let first = self.sections.start; + let lights: Vec<(usize, SectionLight)> = self + .light_sections(chunk, u64::MAX) + .into_iter() + .filter(|&(b, _)| { + // Light section b holds the column's section first + b - 1. + (1..=self.sections.len()).contains(&b) && changed >> (first + b - 1) & 1 != 0 + }) + .collect(); + horizon_protocol::packets::play::Clientbound::LightUpdate( + horizon_protocol::packets::play::LightUpdate { + x: chunk.x, + z: chunk.z, + light: light_data_of(&lights, self.sky), + }, + ) + .encode() + } + pub fn encode( &self, chunk: &Chunk, @@ -903,7 +1085,7 @@ mod tests { /// The bytes on the wire for a section, encoded afresh. fn fresh(encoder: &ChunkEncoder, section: &Section) -> Vec<u8> { let mut w = horizon_protocol::buf::Writer::new(); - encoder.section(section).0.write(&mut w); + encoder.coder.section(section).0.write(&mut w); w.data } @@ -1050,6 +1232,67 @@ mod tests { ); } + /// Columns whose sections the warm-up threads encoded give the bytes + /// each gives on its own, also with a column twice and its neighbours' + /// sections deciding the light layers. + #[test] + fn warmed_columns_give_the_same_bodies() { + let builtin = Builtin::parse( + r#"{"minecraft:block_entity_type": {"entries": { + "minecraft:sign": {"protocol_id": 7}}}}"#, + ) + .unwrap(); + let states = [ + "minecraft:air", + "minecraft:stone", + "minecraft:water", + "minecraft:oak_sign", + ] + .map(|n| (Arc::<str>::from(n), n.ends_with("water"))); + let mut world = crate::world::World::new(horizon_world::registry::BlockStateId(0), 0); + for x in -2..2 { + for z in -2..2 { + let mut chunk = Chunk::empty(x, z); + let n = (x * 7 + z * 13).rem_euclid(17); + for i in 0..40 + n * 30 { + let (bx, bz) = ((i * 5 + n) % 16, (i * 11) % 16); + chunk.set(bx, MIN_Y + (i * 37 + n * 50) % 384, bz, 1 + (i % 3) as u32); + } + let mut light = Box::new([0u8; 4096]); + for (i, v) in light.iter_mut().enumerate() { + *v = (i * 31 + n as usize) as u8; + } + Arc::make_mut(&mut chunk.sections[(n % 24) as usize]).light = Light::Full(light); + world.block_entities.insert( + (x * 16 + 2, 70, z * 16 + 3), + BlockEntity::Sign(crate::signs::SignData::default()), + ); + chunk.set(2, 70, 3, 3); + world.chunks.insert((x, z), Arc::new(chunk)); + } + } + let mut keys: Vec<(i32, i32)> = + (-2..2).flat_map(|x| (-2..2).map(move |z| (x, z))).collect(); + keys.push(keys[5]); + let chunks: Vec<&Chunk> = keys + .iter() + .map(|k| &**world.chunks.get(k).unwrap()) + .collect(); + let alone = ChunkEncoder::new(states.clone(), &builtin, &[], &[]); + let expected: Vec<Vec<u8>> = chunks.iter().map(|c| alone.body_in(c, &world)).collect(); + let warmed = ChunkEncoder::new(states, &builtin, &[], &[]); + let bodies = |encoder: &ChunkEncoder| -> Vec<Vec<u8>> { + chunks.iter().map(|c| encoder.body_in(c, &world)).collect() + }; + assert!(chunks.len() * SECTIONS >= WARM_MIN); + warmed.warm(&chunks); + assert_eq!(bodies(&warmed), expected); + // Again, from the cache, with nothing left to warm. + warmed.warm(&chunks); + assert_eq!(bodies(&warmed), expected); + warmed.warm(&[]); + } + #[test] fn a_nether_column_sends_its_sixteen_sections_without_sky_light() { let chunk = Chunk::empty(0, 0); diff --git a/crates/horizon-client/src/lan/conn.rs b/crates/horizon-client/src/lan/conn.rs index 5c448d8ab..2805cf1da 100644 --- a/crates/horizon-client/src/lan/conn.rs +++ b/crates/horizon-client/src/lan/conn.rs @@ -174,6 +174,19 @@ impl PlayerSender { self.deliver(Out::Packet(body)); } } + /// Several packets in order, as [`Self::send`] each: under one lock + /// while the tick holds them. + pub fn send_many(&self, bodies: impl IntoIterator<Item = Vec<u8>>) { + if !HOLDING.get() { + bodies.into_iter().for_each(|body| self.send(body)); + return; + } + let mut held = self.held(); + for body in bodies { + self.pending.fetch_add(body.len(), Ordering::Relaxed); + held.push(body); + } + } /// Hand the held packets to the writer thread. pub fn flush(&self) { let held = std::mem::take(&mut *self.held()); diff --git a/crates/horizon-client/src/lan/containers.rs b/crates/horizon-client/src/lan/containers.rs index 3ecd58b80..66fbfe4b6 100644 --- a/crates/horizon-client/src/lan/containers.rs +++ b/crates/horizon-client/src/lan/containers.rs @@ -109,6 +109,33 @@ impl Hub { ); } + /// `ServerLevel.broadcastDamageEvent`: the clients around show the hurt + /// entity's flash and hear its hurt sound. + pub fn damage_event( + &self, + id: i32, + kind: &str, + cause: Option<i32>, + direct: Option<i32>, + at: [f64; 3], + ) { + let Some(source_type) = self.sync.id("minecraft:damage_type", kind) else { + return; + }; + self.broadcast_near( + at, + 128.0, + &C::DamageEvent(play::DamageEvent { + id, + source_type, + cause, + direct, + position: None, + }), + None, + ); + } + pub fn swing(&self, id: i32, hand: i32, at: [f64; 3], except: Option<u32>) { self.broadcast_near( at, @@ -428,15 +455,17 @@ impl Hub { let Slots::Block(pos) = m.slots else { return; }; - let Some(BlockEntity::Furnace(f)) = world.block_entities.get(&pos) else { - return; - }; - let data = [ - f.lit_remaining, - f.lit_total, - f.cooking_timer, - f.cooking_total, - ] + // AbstractFurnaceBlockEntity.dataAccess, BrewingStandBlockEntity.dataAccess. + let data = match world.block_entities.get(&pos) { + Some(BlockEntity::Furnace(f)) => [ + f.lit_remaining, + f.lit_total, + f.cooking_timer, + f.cooking_total, + ], + Some(BlockEntity::Brewing(b)) => [b.brew_time, b.fuel, b.total_brew_time, b.total_fuel], + _ => return, + } .map(|v| v as i16); m.sent_data.resize(data.len(), i16::MIN); let window = m.window; diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index a37010d79..9082e01fa 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -1,20 +1,38 @@ //! Entity tracking (ChunkMap.TrackedEntity / ServerEntity): the game describes -//! every entity it simulates as an `EntityState` each tick; a `Tracker` -//! remembers what one client has been told and produces the spawn, movement, -//! motion, metadata, equipment and removal packets that bring it up to date, -//! at the entity type's update interval (`tracking`). +//! every entity it simulates as an `EntityState` each tick. A level's +//! `Entities` remember what its clients were last told about each entity, +//! once for all of them as vanilla's ServerEntity does, and produce the +//! movement, motion, metadata and equipment packets that bring them up to +//! date at the entity type's update interval (`tracking`); each client's +//! `Tracker` is the set of entities it has been paired with. use super::tracking; use horizon_protocol::{ buf::pack_degrees, - entity_data::Value, + entity_data::{Value, serializer}, item::Stack, packets::play::{ - self, AddEntity, EntityPositionSync, MoveEntity, MoveEntityPos, MoveEntityPosRot, - MoveEntityRot, PositionPath, RotateHead, SetEntityData, SetEntityMotion, SetEquipment, - VecDelta, + self, AddEntity, AttributeSnapshot, EntityPositionSync, MoveEntity, MoveEntityPos, + MoveEntityPosRot, MoveEntityRot, PositionPath, RotateHead, SetEntityData, SetEntityMotion, + SetEquipment, SetPassengers, UpdateAttributes, VecDelta, }, }; +/// The attribute instances of `now` that differ from what `sent` held (an +/// instance is never removed: one that disappears is left as it was sent). +pub fn changed_attributes( + now: &[AttributeSnapshot], + sent: &[AttributeSnapshot], +) -> Vec<AttributeSnapshot> { + now.iter() + .filter(|a| { + sent.iter() + .find(|b| b.attribute == a.attribute) + .is_none_or(|b| b != *a) + }) + .cloned() + .collect() +} + /// What the game says about one entity this tick. #[derive(Clone, Debug)] pub struct EntityState { @@ -35,10 +53,79 @@ pub struct EntityState { /// EquipmentSlot ordinals (0 main hand, 1 off hand, 2 feet, 3 legs, /// 4 chest, 5 head, 6 body, 7 saddle) and their stacks. pub equipment: Vec<(u8, Option<Stack>)>, + /// A living entity's client-syncable attribute instances + /// (`AttributeMap.getSyncableAttributes`), by registry id. + pub attributes: Vec<AttributeSnapshot>, + /// `Entity.getRequiresPrecisePosition` (primed TNT and falling blocks + /// touching a block): moves are sent as full position syncs. + pub precise: bool, } -/// What a client was last told about one entity (ServerEntity's fields). -struct Sent { +/// `AbstractArrow`: every update sends its position and rotation. +fn is_arrow(kind: &str) -> bool { + matches!( + kind, + "minecraft:arrow" | "minecraft:spectral_arrow" | "minecraft:trident" + ) +} + +/// `AbstractHurtingProjectile.accelerationPower` (0.1, none for wind +/// charges), sent with each velocity update. +fn acceleration_power(kind: &str) -> Option<f64> { + match kind { + "minecraft:fireball" + | "minecraft:small_fireball" + | "minecraft:dragon_fireball" + | "minecraft:wither_skull" => Some(0.1), + "minecraft:wind_charge" | "minecraft:breeze_wind_charge" => Some(0.0), + _ => None, + } +} + +/// Who rides what this tick (`Entity.getPassengers`, `isPassenger`). +#[derive(Default)] +pub struct Riding { + /// Each vehicle's passengers, in order. + pub passengers: crate::fast_hash::FxHashMap<i32, Vec<i32>>, + /// Each passenger's vehicle. + pub vehicle: crate::fast_hash::FxHashMap<i32, i32>, +} + +impl Riding { + pub fn clear(&mut self) { + self.passengers.clear(); + self.vehicle.clear(); + } + /// `passenger` rides `vehicle`, after the ones already riding it. + pub fn add(&mut self, vehicle: i32, passenger: i32) { + self.passengers.entry(vehicle).or_default().push(passenger); + self.vehicle.insert(passenger, vehicle); + } + pub fn passengers(&self, id: i32) -> &[i32] { + self.passengers.get(&id).map_or(&[], Vec::as_slice) + } + fn set_passengers(&self, vehicle: i32) -> play::Clientbound { + play::Clientbound::SetPassengers(SetPassengers { + vehicle, + passengers: self.passengers(vehicle).to_vec(), + }) + } +} + +/// What a level's clients were last told about one entity (ServerEntity's +/// fields), shared by every client that tracks it. +struct ServerEntity { + /// The registry id of its type (None: a type the clients don't know, + /// never paired). + kind: Option<i32>, + /// The type's tracking range in chunks, update interval (0: never), + /// whether velocity is tracked, whether it is an `AbstractArrow` and its + /// `AbstractHurtingProjectile.accelerationPower`. + range: i32, + interval: u32, + track_deltas: bool, + arrow: bool, + power: Option<f64>, /// VecDeltaCodec's base: the last position sent. base: [f64; 3], /// lastSentYRot / lastSentXRot / lastSentYHeadRot. @@ -46,19 +133,31 @@ struct Sent { head: i8, /// lastSentMovement. velocity: [f64; 3], + /// trackedDataValues: the entity data the clients hold. meta: Vec<(u8, i32, Value)>, equipment: Vec<(u8, Option<Stack>)>, + /// The attribute instances the clients hold. + attributes: Vec<AttributeSnapshot>, was_on_ground: bool, tick: u32, teleport_delay: u32, - /// The type's update interval (0: never) and whether velocity is tracked. - interval: u32, - track_deltas: bool, + /// lastPassengers, and wasRiding: a passenger's position isn't synced, + /// and the first update after it dismounts is a full position sync. + passengers: Vec<i32>, + was_riding: bool, + /// The level tick it was last seen in, its place in that tick's list, and + /// whether it was added in it (its first update is the next tick's). + seen: u32, + index: usize, + added: bool, + /// TrackedEntity.lastSectionPos: its pairs are checked again when it + /// moves to another section. + section: [i32; 3], } -#[derive(Default)] -pub struct Tracker { - sent: crate::fast_hash::FxHashMap<i32, Sent>, +/// SectionPos.of(entity). +fn section_of(position: [f64; 3]) -> [i32; 3] { + position.map(|v| (v.floor() as i32) >> 4) } /// VecDeltaCodec.encode. @@ -66,98 +165,127 @@ fn encode(v: f64) -> i64 { (v * 4096.0).round() as i64 } -/// 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 { - pub fn is_tracking(&self, id: i32) -> bool { - self.sent.contains_key(&id) - } - pub fn ids(&self) -> Vec<i32> { - self.sent.keys().copied().collect() - } - pub fn forget(&mut self, id: i32) { - self.sent.remove(&id); - } - pub fn clear(&mut self) { - self.sent.clear(); - } - pub fn len(&self) -> usize { - self.sent.len() - } - pub fn is_empty(&self) -> bool { - self.sent.is_empty() +impl ServerEntity { + /// `new ServerEntity`: the entity as it is when it joins the level. + fn new(e: &EntityState, kind: Option<i32>, riding: &Riding) -> Self { + let (range, interval, track_deltas) = tracking::settings(&e.kind); + Self { + kind, + range: i32::from(range), + interval, + track_deltas, + arrow: is_arrow(&e.kind), + power: acceleration_power(&e.kind), + base: e.position, + rotation: (pack_degrees(e.pitch), pack_degrees(e.yaw)), + head: pack_degrees(e.head_yaw), + velocity: e.velocity, + meta: e.meta.clone(), + equipment: e.equipment.clone(), + attributes: e.attributes.clone(), + was_on_ground: e.on_ground, + tick: 0, + teleport_delay: 0, + passengers: riding.passengers(e.id).to_vec(), + was_riding: false, + seen: 0, + index: 0, + added: true, + section: section_of(e.position), + } } - /// The packets that introduce an entity (ServerEntity.sendPairingData). - pub fn spawn(&mut self, e: &EntityState, entity_type: i32) -> Vec<play::Clientbound> { - let rotation = (pack_degrees(e.pitch), pack_degrees(e.yaw)); - let head = pack_degrees(e.head_yaw); - let (_, interval, track_deltas) = tracking::settings(&e.kind); - let mut out = vec![play::Clientbound::AddEntity(AddEntity { + /// ServerEntity.sendPairingData: the packets that introduce the entity + /// to a client that starts tracking it. + fn pairing( + &self, + e: &EntityState, + kind: i32, + riding: &Riding, + out: &mut Vec<play::Clientbound>, + ) { + out.push(play::Clientbound::AddEntity(AddEntity { id: e.id, uuid: e.uuid, - kind: entity_type, + kind, position: e.position, velocity: e.velocity, - pitch: rotation.0, - yaw: rotation.1, - head_yaw: head, + pitch: pack_degrees(e.pitch), + yaw: pack_degrees(e.yaw), + head_yaw: pack_degrees(e.head_yaw), data: e.data, - })]; - if !e.meta.is_empty() { + })); + if !self.meta.is_empty() { out.push(play::Clientbound::SetEntityData(SetEntityData { id: e.id, - values: e.meta.clone(), + values: self.meta.clone(), })); } - if !e.equipment.is_empty() { + // getSyncableAttributes: the instances as they are now. + if !e.attributes.is_empty() { + out.push(play::Clientbound::UpdateAttributes(UpdateAttributes { + id: e.id, + values: e.attributes.clone(), + })); + } + if !self.equipment.is_empty() { out.push(play::Clientbound::SetEquipment(SetEquipment { id: e.id, - slots: e.equipment.clone(), + slots: self.equipment.clone(), })); } - self.sent.insert( - e.id, - Sent { - base: e.position, - rotation, - head, - velocity: e.velocity, - meta: e.meta.clone(), - equipment: e.equipment.clone(), - was_on_ground: e.on_ground, - tick: 0, - teleport_delay: 0, - interval, - track_deltas, - }, - ); - out + if !riding.passengers(e.id).is_empty() { + out.push(riding.set_passengers(e.id)); + } + if let Some(&vehicle) = riding.vehicle.get(&e.id) { + out.push(riding.set_passengers(vehicle)); + } } /// Changes since the last update (ServerEntity.sendChanges): movement and /// rotation every update interval (positions at least every 60 ticks, a /// full position sync every 400 or when the entity lands or leaves the /// ground), velocity for types that track it, changed data at once. - pub fn update(&mut self, e: &EntityState) -> Vec<play::Clientbound> { - let Some(s) = self.sent.get_mut(&e.id) else { - return Vec::new(); - }; - let mut out = Vec::new(); - let dirty = e.meta != s.meta; - let due = s.interval != 0 && s.tick.is_multiple_of(s.interval); + fn send_changes(&mut self, e: &EntityState, riding: &Riding, out: &mut Vec<play::Clientbound>) { + let passengers = riding.passengers(e.id); + if passengers != self.passengers.as_slice() { + out.push(riding.set_passengers(e.id)); + self.passengers.clear(); + self.passengers.extend_from_slice(passengers); + } + // SynchedEntityData.isDirty: once for every client. + let dirty = e.meta != self.meta; + let due = self.interval != 0 && self.tick.is_multiple_of(self.interval); if due || dirty { let rotation = (pack_degrees(e.pitch), pack_degrees(e.yaw)); let turned = |a: i8, b: i8| (i32::from(a) - i32::from(b)).abs() >= 1; - let rotate = turned(rotation.1, s.rotation.1) || turned(rotation.0, s.rotation.0); - s.teleport_delay += 1; - let d: f64 = (0..3).map(|k| (e.position[k] - s.base[k]).powi(2)).sum(); - let send_position = d >= 7.629_394_5e-6 || s.tick.is_multiple_of(60); + let rotate = self.arrow + || turned(rotation.1, self.rotation.1) + || turned(rotation.0, self.rotation.0); + if riding.vehicle.contains_key(&e.id) { + // A passenger: its rotation alone (its vehicle places it). + if rotate { + out.push(play::Clientbound::MoveEntityRot(MoveEntityRot( + MoveEntity { + id: e.id, + delta: None, + rotation: Some((rotation.1, rotation.0)), + on_ground: e.on_ground, + }, + ))); + self.rotation = rotation; + } + self.base = e.position; + self.was_riding = true; + self.send_dirty(e, dirty, out); + self.send_head(e, out); + self.tick += 1; + self.send_equipment(e, out); + return; + } + self.teleport_delay += 1; + let d: f64 = (0..3).map(|k| (e.position[k] - self.base[k]).powi(2)).sum(); + let send_position = self.arrow || d >= 7.629_394_5e-6 || self.tick.is_multiple_of(60); let sync = EntityPositionSync { id: e.id, path: PositionPath::Linear(e.position), @@ -166,12 +294,17 @@ impl Tracker { on_ground: e.on_ground, }; // ServerEntity.createMovePacket. - let packet = if s.teleport_delay > 400 || s.was_on_ground != e.on_ground { - s.was_on_ground = e.on_ground; - s.teleport_delay = 0; + let packet = if e.precise + || self.teleport_delay > 400 + || self.was_riding + || self.was_on_ground != e.on_ground + { + self.was_on_ground = e.on_ground; + self.teleport_delay = 0; + self.was_riding = false; Some(play::Clientbound::EntityPositionSync(sync)) } else if send_position { - let delta = [0, 1, 2].map(|k| encode(e.position[k]) - encode(s.base[k])); + let delta = [0, 1, 2].map(|k| encode(e.position[k]) - encode(self.base[k])); if delta.iter().any(|v| i16::try_from(*v).is_err()) { Some(play::Clientbound::EntityPositionSync(sync)) } else { @@ -199,17 +332,30 @@ impl Tracker { } else { None }; - if s.track_deltas { + if self.track_deltas { let diff: f64 = (0..3) - .map(|k| (e.velocity[k] - s.velocity[k]).powi(2)) + .map(|k| (e.velocity[k] - self.velocity[k]).powi(2)) .sum(); let still = e.velocity.iter().all(|v| *v == 0.0); if diff > 1.0e-7 || diff > 0.0 && still { - s.velocity = e.velocity; - out.push(play::Clientbound::SetEntityMotion(SetEntityMotion { + self.velocity = e.velocity; + let motion = play::Clientbound::SetEntityMotion(SetEntityMotion { id: e.id, velocity: e.velocity, - })); + }); + match self.power { + // A bundle: the motion and the projectile's power. + Some(power) => out.extend([ + play::Clientbound::BundleDelimiter(horizon_protocol::packets::Empty), + motion, + play::Clientbound::ProjectilePower(play::ProjectilePower { + id: e.id, + power, + }), + play::Clientbound::BundleDelimiter(horizon_protocol::packets::Empty), + ]), + None => out.push(motion), + } } } if let Some(packet) = packet { @@ -221,48 +367,85 @@ impl Tracker { }; out.push(packet); if position { - s.base = e.position; + self.base = e.position; } if rotated { - s.rotation = rotation; + self.rotation = rotation; } } - // ServerEntity.sendDirtyEntityData. - if dirty { - let changed: Vec<_> = e - .meta - .iter() - .filter(|m| !s.meta.contains(m)) - .cloned() - .collect(); - if !changed.is_empty() { - out.push(play::Clientbound::SetEntityData(SetEntityData { - id: e.id, - values: changed, - })); - } - s.meta = e.meta.clone(); - } - let head = pack_degrees(e.head_yaw); - if turned(head, s.head) { - out.push(play::Clientbound::RotateHead(RotateHead { - id: e.id, - head_yaw: head, - })); - s.head = head; - } + self.send_dirty(e, dirty, out); + self.send_head(e, out); } - s.tick += 1; - // LivingEntity.detectEquipmentUpdates: changed slots every tick. - if e.equipment != s.equipment { + self.tick += 1; + self.send_equipment(e, out); + } + + /// ServerEntity.sendDirtyEntityData: the changed entity data, then the + /// attribute instances that changed since they were last sent + /// (`AttributeMap.getAttributesToSync`). + fn send_dirty(&mut self, e: &EntityState, dirty: bool, out: &mut Vec<play::Clientbound>) { + if dirty { + let mut changed: Vec<_> = e + .meta + .iter() + .filter(|m| !self.meta.contains(m)) + .cloned() + .collect(); + // A value back at its default is left out of the state, but the + // clients still hold the old one: Entity's shared flags and pose go + // back to 0 (a player standing up again, a mob no longer on fire). + for (index, kind, _) in &self.meta { + let default = match (*index, *kind) { + (0, serializer::BYTE) => Value::Byte(0), + (6, serializer::POSE) => Value::Id(0), + _ => continue, + }; + if !e.meta.iter().any(|m| m.0 == *index) { + changed.push((*index, *kind, default)); + } + } + if !changed.is_empty() { + out.push(play::Clientbound::SetEntityData(SetEntityData { + id: e.id, + values: changed, + })); + } + self.meta.clone_from(&e.meta); + } + if e.attributes != self.attributes { + let changed = changed_attributes(&e.attributes, &self.attributes); + if !changed.is_empty() { + out.push(play::Clientbound::UpdateAttributes(UpdateAttributes { + id: e.id, + values: changed, + })); + } + self.attributes.clone_from(&e.attributes); + } + } + + fn send_head(&mut self, e: &EntityState, out: &mut Vec<play::Clientbound>) { + let head = pack_degrees(e.head_yaw); + if (i32::from(head) - i32::from(self.head)).abs() >= 1 { + out.push(play::Clientbound::RotateHead(RotateHead { + id: e.id, + head_yaw: head, + })); + self.head = head; + } + } + + /// LivingEntity.detectEquipmentUpdates: changed slots every tick. + fn send_equipment(&mut self, e: &EntityState, out: &mut Vec<play::Clientbound>) { + if e.equipment != self.equipment { // Cleared slots are sent as empty stacks. let mut slots: Vec<(u8, Option<Stack>)> = e .equipment .iter() - .filter(|m| !s.equipment.contains(m)) + .filter(|m| !self.equipment.contains(m)) .cloned() .collect(); - for (slot, _) in &s.equipment { + for (slot, _) in &self.equipment { if !e.equipment.iter().any(|(k, _)| k == slot) { slots.push((*slot, None)); } @@ -273,9 +456,314 @@ impl Tracker { slots, })); } - s.equipment = e.equipment.clone(); + self.equipment.clone_from(&e.equipment); } - out + } +} + +/// The entities one client tracks (`TrackedEntity.seenBy`, from the +/// client's side). +#[derive(Default)] +pub struct Tracker { + seen: crate::fast_hash::FxHashSet<i32>, +} + +impl Tracker { + pub fn is_tracking(&self, id: i32) -> bool { + self.seen.contains(&id) + } + pub fn ids(&self) -> Vec<i32> { + self.seen.iter().copied().collect() + } + pub fn clear(&mut self) { + self.seen.clear(); + } + /// Stop tracking `id` without a packet: the caller removes it from the + /// client, and the next tick pairs it again if it is still in range. + pub fn forget(&mut self, id: i32) -> bool { + self.seen.remove(&id) + } + pub fn len(&self) -> usize { + self.seen.len() + } + pub fn is_empty(&self) -> bool { + self.seen.is_empty() + } +} + +/// Who a level's entities are tracked by this tick: a client's position, +/// view distance and chunks. +pub struct Viewer<'a> { + pub entity_id: i32, + /// It accepted a move since the last tick (ChunkMap.move): every pair + /// of it is checked again. + pub moved: bool, + pub position: [f64; 3], + pub view_distance: i32, + pub chunks: &'a crate::fast_hash::FxHashSet<(i32, i32)>, + pub tracker: &'a mut Tracker, + /// What the tick sends it, in order. + pub out: &'a mut Vec<Vec<u8>>, +} + +/// One entity as this tick's range checks read it: where it is +/// horizontally, its id, its type's tracking range in chunks and the chunk +/// it is in (an index into the tick's chunks). +#[derive(Clone, Copy)] +struct Probe { + x: f64, + z: f64, + id: i32, + range: i32, + chunk: u32, +} + +/// TrackedEntity.updatePlayer: within the type's range (capped by the view +/// distance) horizontally, in a chunk the client has. `held` remembers for +/// each of the tick's chunks whether the client has it (0: not looked up +/// yet, 1: no, 2: yes), so each chunk is looked up once per client. +fn sees(v: &Viewer, p: &Probe, chunks: &[(i32, i32)], held: &mut [u8]) -> bool { + let range = f64::from(p.range.min(v.view_distance) * 16); + let (dx, dz) = (v.position[0] - p.x, v.position[2] - p.z); + dx * dx + dz * dz <= range * range && { + let held = &mut held[p.chunk as usize]; + if *held == 0 { + *held = 1 + u8::from(v.chunks.contains(&chunks[p.chunk as usize])); + } + *held == 2 + } +} + +/// One level's tracked entities (ChunkMap.entityMap). +#[derive(Default)] +pub struct Entities { + states: crate::fast_hash::FxHashMap<i32, ServerEntity>, + /// The level tick, stamped on every entity still in the level. + tick: u32, + /// This tick's entities as the range checks read them, the chunks they + /// are in (and each one's index), whether the client being checked has + /// each chunk, and what each client makes of each entity ([`SEES`], + /// [`TRACKS`]), kept between ticks. + probes: Vec<Probe>, + chunks: Vec<(i32, i32)>, + chunk_index: crate::fast_hash::FxHashMap<(i32, i32), u32>, + held: Vec<u8>, + flags: Vec<Vec<u8>>, + /// Whether a client starts tracking each entity this tick. + pairs: Vec<bool>, + /// The entities that appeared or moved to another section this tick + /// (their pairs with every client are checked again), in order and as a + /// flag per entity. + moved: Vec<usize>, + is_moved: Vec<bool>, + /// One entity's packets and their bodies, kept between entities. + packets: Vec<play::Clientbound>, + bodies: Vec<Vec<u8>>, +} + +/// The client sees the entity this tick, and already tracked it. +const SEES: u8 = 1; +const TRACKS: u8 = 2; + +fn encode_all(packets: &[play::Clientbound], bodies: &mut Vec<Vec<u8>>) { + bodies.clear(); + bodies.extend(packets.iter().map(play::Clientbound::encode)); +} + +impl Entities { + pub fn len(&self) -> usize { + self.states.len() + } + pub fn is_empty(&self) -> bool { + self.states.is_empty() + } + + /// One tick of ChunkMap.tick for the entities in the level now and the + /// clients in it: each client first loses the entities that left its + /// range or the level (one ClientboundRemoveEntitiesPacket), then each + /// entity's changes are made once and go to every client tracking it, + /// and the clients that start tracking it are paired with it. A client + /// never tracks its own entity. `kind` names a type's registry id. + pub fn tick( + &mut self, + entities: &[&EntityState], + riding: &Riding, + viewers: &mut [Viewer], + mut kind: impl FnMut(&str) -> Option<i32>, + ) { + self.tick = self.tick.wrapping_add(1); + let now = self.tick; + self.probes.clear(); + self.chunks.clear(); + self.chunk_index.clear(); + self.moved.clear(); + self.is_moved.clear(); + self.is_moved.resize(entities.len(), false); + for (index, e) in entities.iter().enumerate() { + let mut added = false; + let s = self.states.entry(e.id).or_insert_with(|| { + added = true; + ServerEntity::new(e, kind(&e.kind), riding) + }); + s.seen = now; + s.index = index; + // ChunkMap.addEntity, and ChunkMap.tick's section change: + // updatePlayers. + let section = section_of(e.position); + if added || section != s.section { + s.section = section; + self.moved.push(index); + self.is_moved[index] = true; + } + let at = ( + (e.position[0].floor() as i32) >> 4, + (e.position[2].floor() as i32) >> 4, + ); + let next = self.chunks.len() as u32; + let chunk = *self.chunk_index.entry(at).or_insert(next); + if chunk == next { + self.chunks.push(at); + } + self.probes.push(Probe { + x: e.position[0], + z: e.position[2], + id: e.id, + range: s.range, + chunk, + }); + } + self.flags.resize_with(viewers.len(), Vec::new); + self.pairs.clear(); + self.pairs.resize(entities.len(), false); + for (v, flags) in viewers.iter_mut().zip(&mut self.flags) { + flags.clear(); + self.held.clear(); + self.held.resize(self.chunks.len(), 0); + let (chunks, held, pairs) = (&self.chunks, &mut self.held, &mut self.pairs); + let mut kept = 0; + // A client that moved (ChunkMap.move), or whose own entity + // appeared or changed section (ChunkMap.tick's movedPlayers), has + // every pair checked again. + let all = v.moved + || self + .states + .get(&v.entity_id) + .is_none_or(|s| s.seen != now || self.is_moved[s.index]); + if all { + flags.extend(self.probes.iter().zip(pairs.iter_mut()).map(|(p, pairs)| { + if p.id == v.entity_id || !sees(v, p, chunks, held) { + 0 + } else if v.tracker.seen.contains(&p.id) { + kept += 1; + SEES | TRACKS + } else { + *pairs = true; + SEES + } + })); + } else if v.tracker.seen.len() * 4 > self.probes.len() { + // Otherwise its pairs stay as they were, but for the entities + // that appeared or changed section; a client tracking much + // of the level goes through it in order. + let is_moved = &self.is_moved; + flags.extend(self.probes.iter().zip(pairs.iter_mut()).zip(is_moved).map( + |((p, pairs), &moved)| { + let tracks = v.tracker.seen.contains(&p.id); + if p.id == v.entity_id || (moved && !sees(v, p, chunks, held)) { + 0 + } else if tracks { + kept += 1; + SEES | TRACKS + } else if moved { + *pairs = true; + SEES + } else { + 0 + } + }, + )); + } else { + // One tracking little of it, from what it tracks. + flags.resize(self.probes.len(), 0); + for id in &v.tracker.seen { + if let Some(s) = self.states.get(id).filter(|s| s.seen == now) { + flags[s.index] = SEES | TRACKS; + kept += 1; + } + } + for &index in &self.moved { + let p = &self.probes[index]; + let tracks = flags[index] & TRACKS != 0; + if p.id != v.entity_id && sees(v, p, chunks, held) { + if !tracks { + flags[index] = SEES; + pairs[index] = true; + } + } else if tracks { + flags[index] = 0; + kept -= 1; + } + } + } + // Usually the client still sees all it tracks. + let mut removed = Vec::new(); + if kept != v.tracker.seen.len() { + let states = &self.states; + v.tracker.seen.retain(|id| match states.get(id) { + Some(s) if s.seen == now && flags[s.index] & TRACKS != 0 => true, + _ => { + removed.push(*id); + false + } + }); + } + if !removed.is_empty() { + v.out.push( + play::Clientbound::RemoveEntities(play::RemoveEntities { ids: removed }) + .encode(), + ); + } + } + for (index, e) in entities.iter().enumerate() { + let Some(s) = self.states.get_mut(&e.id) else { + continue; + }; + self.packets.clear(); + if !s.added { + s.send_changes(e, riding, &mut self.packets); + } + s.added = false; + // Nothing to send: no changes, and nobody starts tracking it. + if self.packets.is_empty() && !self.pairs[index] { + continue; + } + let mut encoded = false; + let mut pairing: Option<Vec<Vec<u8>>> = None; + for (v, flags) in viewers.iter_mut().zip(&self.flags) { + let f = flags[index]; + if f & TRACKS != 0 { + if self.packets.is_empty() { + continue; + } + if !encoded { + encode_all(&self.packets, &mut self.bodies); + encoded = true; + } + v.out.extend(self.bodies.iter().cloned()); + } else if f & SEES != 0 + && let Some(kind) = s.kind + { + let bodies = pairing.get_or_insert_with(|| { + let mut packets = Vec::new(); + s.pairing(e, kind, riding, &mut packets); + packets.iter().map(play::Clientbound::encode).collect() + }); + v.out.extend(bodies.iter().cloned()); + v.tracker.seen.insert(e.id); + } + } + } + self.states.retain(|_, s| s.seen == now); } } @@ -297,57 +785,176 @@ mod tests { data: 0, meta: Vec::new(), equipment: Vec::new(), + attributes: Vec::new(), + precise: false, } } + /// The entity as added this tick, then its updates (one a tick). + fn added(e: &EntityState) -> ServerEntity { + ServerEntity::new(e, Some(100), &Riding::default()) + } + fn changes(s: &mut ServerEntity, e: &EntityState) -> Vec<play::Clientbound> { + let mut out = Vec::new(); + s.send_changes(e, &Riding::default(), &mut out); + out + } + #[test] fn moves_go_out_every_update_interval() { - let mut t = Tracker::default(); - let spawn = t.spawn(&state(0.0), 100); - assert!(matches!(spawn[0], play::Clientbound::AddEntity(_))); + let mut s = added(&state(0.0)); + let mut spawn = Vec::new(); + s.pairing(&state(0.0), 100, &Riding::default(), &mut spawn); + assert!(matches!(spawn[..], [play::Clientbound::AddEntity(_)])); // Tick 0 is due and a multiple of 60: the position goes out unchanged. assert!(matches!( - t.update(&state(0.0))[..], + changes(&mut s, &state(0.0))[..], [play::Clientbound::MoveEntityPos(_)] )); // A zombie updates every third tick. - assert!(t.update(&state(0.5)).is_empty()); - assert!(t.update(&state(0.5)).is_empty()); + assert!(changes(&mut s, &state(0.5)).is_empty()); + assert!(changes(&mut s, &state(0.5)).is_empty()); assert!(matches!( - t.update(&state(0.5))[..], + changes(&mut s, &state(0.5))[..], [play::Clientbound::MoveEntityPos(_)] )); for _ in 0..2 { - t.update(&state(40.0)); + changes(&mut s, &state(40.0)); } - let jump = t.update(&state(40.0)); + let jump = changes(&mut s, &state(40.0)); assert!(matches!(jump[0], play::Clientbound::EntityPositionSync(_))); } #[test] - fn landing_sends_a_position_sync() { - let mut t = Tracker::default(); + fn fireballs_bundle_their_motion_with_their_power() { let mut e = state(0.0); - t.spawn(&e, 100); - t.update(&e); + e.kind = "minecraft:fireball".into(); e.on_ground = false; - t.update(&e); - t.update(&e); + let mut s = added(&e); + e.velocity = [0.0, 0.0, 0.5]; + let out = changes(&mut s, &e); assert!(matches!( - t.update(&e)[..], + out[..], + [ + play::Clientbound::BundleDelimiter(_), + play::Clientbound::SetEntityMotion(_), + play::Clientbound::ProjectilePower(play::ProjectilePower { power, .. }), + play::Clientbound::BundleDelimiter(_), + play::Clientbound::MoveEntityPos(_), + ] if power == 0.1 + )); + } + + #[test] + fn arrows_send_position_and_rotation_every_update() { + let mut e = state(0.0); + e.kind = "minecraft:arrow".into(); + let mut s = added(&e); + assert!(matches!( + changes(&mut s, &e)[..], + [play::Clientbound::MoveEntityPosRot(_)] + )); + } + + #[test] + fn precise_entities_sync_their_position() { + let mut e = state(0.0); + e.kind = "minecraft:tnt".into(); + e.precise = true; + let mut s = added(&e); + assert!(matches!( + changes(&mut s, &e)[..], [play::Clientbound::EntityPositionSync(_)] )); } #[test] - fn metadata_and_equipment_send_only_the_changes() { - let mut t = Tracker::default(); + fn landing_sends_a_position_sync() { let mut e = state(0.0); - t.spawn(&e, 100); - t.update(&e); + let mut s = added(&e); + changes(&mut s, &e); + e.on_ground = false; + changes(&mut s, &e); + changes(&mut s, &e); + assert!(matches!( + changes(&mut s, &e)[..], + [play::Clientbound::EntityPositionSync(_)] + )); + } + + #[test] + fn attributes_pair_whole_then_send_the_changed_instances_when_due() { + let speed = |base| AttributeSnapshot { + attribute: 26, + base, + modifiers: Vec::new(), + }; + let armor = AttributeSnapshot { + attribute: 1, + base: 0.0, + modifiers: Vec::new(), + }; + let mut e = state(0.0); + e.attributes = vec![speed(0.23), armor]; + let mut s = added(&e); + let mut spawn = Vec::new(); + s.pairing(&e, 100, &Riding::default(), &mut spawn); + let Some(play::Clientbound::UpdateAttributes(p)) = spawn.get(1) else { + panic!("expected the attributes after the add"); + }; + assert_eq!(p.values, e.attributes); + changes(&mut s, &e); + e.attributes[0] = speed(0.3); + // Not due (a zombie's interval is 3): sendDirtyEntityData waits for the update. + assert!(changes(&mut s, &e).is_empty()); + assert!(changes(&mut s, &e).is_empty()); + let out = changes(&mut s, &e); + let Some(play::Clientbound::UpdateAttributes(p)) = out + .iter() + .find(|p| matches!(p, play::Clientbound::UpdateAttributes(_))) + else { + panic!("expected the changed attribute"); + }; + assert_eq!(p.values, vec![speed(0.3)]); + } + + #[test] + fn cleared_flags_and_pose_go_back_to_their_default() { + let mut e = state(0.0); + let mut s = added(&e); + changes(&mut s, &e); + // A crouching player: the crouch flag and the crouching pose. + e.meta = vec![ + (0, serializer::BYTE, Value::Byte(2)), + (6, serializer::POSE, Value::Id(5)), + ]; + changes(&mut s, &e); + e.meta.clear(); + let data = changes(&mut s, &e) + .into_iter() + .find_map(|p| match p { + play::Clientbound::SetEntityData(d) => Some(d), + _ => None, + }) + .expect("standing up is sent"); + assert_eq!( + data.values, + vec![ + (0, serializer::BYTE, Value::Byte(0)), + (6, serializer::POSE, Value::Id(0)), + ] + ); + assert!(changes(&mut s, &e).is_empty()); + } + + #[test] + fn metadata_and_equipment_send_only_the_changes() { + let mut e = state(0.0); + let mut s = added(&e); + changes(&mut s, &e); e.meta.push((0, 0, Value::Byte(1))); e.equipment.push((0, Some(Stack::new(5, 1)))); - let out = t.update(&e); + let out = changes(&mut s, &e); assert!( out.iter() .any(|p| matches!(p, play::Clientbound::SetEntityData(_))) @@ -356,12 +963,210 @@ mod tests { out.iter() .any(|p| matches!(p, play::Clientbound::SetEquipment(_))) ); - assert!(t.update(&e).is_empty()); + assert!(changes(&mut s, &e).is_empty()); e.equipment.clear(); - let out = t.update(&e); + let out = changes(&mut s, &e); let Some(play::Clientbound::SetEquipment(eq)) = out.first() else { panic!("expected equipment"); }; assert_eq!(eq.slots, vec![(0, None)]); } + + /// Two clients at the origin; the chunks they hold. + struct Clients { + chunks: crate::fast_hash::FxHashSet<(i32, i32)>, + trackers: [Tracker; 2], + out: [Vec<Vec<u8>>; 2], + positions: [[f64; 3]; 2], + moved: [bool; 2], + } + + impl Clients { + fn new() -> Self { + Self { + chunks: (-4..4).flat_map(|x| (-4..4).map(move |z| (x, z))).collect(), + trackers: Default::default(), + out: Default::default(), + positions: [[0.0, 64.0, 0.0]; 2], + moved: [false; 2], + } + } + fn tick(&mut self, level: &mut Entities, entities: &[&EntityState]) { + for out in &mut self.out { + out.clear(); + } + let [t0, t1] = &mut self.trackers; + let [o0, o1] = &mut self.out; + let mut viewers = [ + Viewer { + entity_id: 1, + moved: self.moved[0], + position: self.positions[0], + view_distance: 10, + chunks: &self.chunks, + tracker: t0, + out: o0, + }, + Viewer { + entity_id: 2, + moved: self.moved[1], + position: self.positions[1], + view_distance: 10, + chunks: &self.chunks, + tracker: t1, + out: o1, + }, + ]; + level.tick(entities, &Riding::default(), &mut viewers, |_| Some(100)); + } + } + + fn body(p: play::Clientbound) -> Vec<u8> { + p.encode() + } + + /// ChunkMap checks a pair again only when one side moves: a zombie + /// walking into range within its section isn't paired with a client + /// standing still until the client moves, and one walking out stays + /// tracked until it changes section. + #[test] + fn pairs_are_checked_again_when_a_side_moves() { + let mut level = Entities::default(); + let mut clients = Clients::new(); + clients.positions[0] = [-108.0, 64.0, 0.0]; + let mut me = state(-108.0); + (me.id, me.kind) = (1, "minecraft:player".into()); + // 128.5 blocks away: past a zombie's 8 chunks. + let tracks = |clients: &Clients| clients.trackers[0].is_tracking(7); + clients.tick(&mut level, &[&me, &state(20.5)]); + assert!(!tracks(&clients)); + // 127.5 blocks away, in the same section: not checked again. + clients.tick(&mut level, &[&me, &state(19.5)]); + assert!(!tracks(&clients)); + // The client's move checks every pair of it. + clients.moved[0] = true; + clients.tick(&mut level, &[&me, &state(19.5)]); + assert!(tracks(&clients)); + clients.moved[0] = false; + clients.tick(&mut level, &[&me, &state(20.5)]); + assert!(tracks(&clients)); + // Into the next section, out of range: no longer tracked. + clients.tick(&mut level, &[&me, &state(40.0)]); + assert!(!tracks(&clients)); + // The other client (at the origin, its entity not in the level) + // checks every pair each tick. + assert!(clients.trackers[1].is_tracking(7)); + } + + #[test] + fn every_client_gets_the_same_changes_and_late_ones_are_paired() { + let mut level = Entities::default(); + let mut c = Clients::new(); + // The second client is out of range at first. + c.positions[1] = [500.0, 64.0, 0.0]; + let mut e = state(0.0); + c.tick(&mut level, &[&e]); + assert!(c.trackers[0].is_tracking(7) && !c.trackers[1].is_tracking(7)); + assert!(c.out[1].is_empty()); + // Tick 0's forced position goes to the client tracking it. + c.tick(&mut level, &[&e]); + assert_eq!(c.out[0].len(), 1); + // The second client comes in range: paired with the entity as it is, + // then sent the same changes as the first. + c.positions[1] = [0.0, 64.0, 0.0]; + e.position[0] = 1.0; + c.tick(&mut level, &[&e]); + assert!(c.trackers[1].is_tracking(7)); + assert!(c.out[0].is_empty()); + assert_eq!(c.out[1].len(), 1); + c.tick(&mut level, &[&e]); + e.position[0] = 2.0; + c.tick(&mut level, &[&e]); + assert!(!c.out[0].is_empty()); + assert_eq!(c.out[0], c.out[1]); + } + + #[test] + fn clients_lose_what_leaves_range_or_the_level_and_never_track_themselves() { + let mut level = Entities::default(); + let mut c = Clients::new(); + let mut me = state(0.0); + me.id = 1; + me.kind = "minecraft:player".into(); + let mut e = state(0.0); + c.tick(&mut level, &[&me, &e]); + assert!(!c.trackers[0].is_tracking(1) && c.trackers[1].is_tracking(1)); + assert!(c.trackers[0].is_tracking(7)); + // Out of the zombie's 8 chunks. + e.position[0] = 200.0; + c.tick(&mut level, &[&me, &e]); + assert!(!c.trackers[0].is_tracking(7)); + let removed = body(play::Clientbound::RemoveEntities(play::RemoveEntities { + ids: vec![7], + })); + assert_eq!(c.out[0].first(), Some(&removed)); + // Gone from the level: the other client loses it too, and so does + // the level. + e.position[0] = 0.0; + c.tick(&mut level, &[&me, &e]); + assert!(c.trackers[0].is_tracking(7)); + c.tick(&mut level, &[&me]); + assert!(!c.trackers[0].is_tracking(7) && !c.trackers[1].is_tracking(7)); + assert_eq!(c.out[0].first(), Some(&removed)); + assert_eq!(level.len(), 1); + } + + #[test] + fn entities_in_chunks_a_client_lacks_wait_for_them() { + let mut level = Entities::default(); + let mut c = Clients::new(); + // Two zombies in range in chunk (4, 0), which the clients don't have + // yet, and one in chunk (0, 0). + let mut far = state(70.0); + let mut near = state(66.0); + near.id = 8; + let mut home = state(1.0); + home.id = 9; + c.tick(&mut level, &[&far, &near, &home]); + for t in &c.trackers { + assert!(!t.is_tracking(7) && !t.is_tracking(8) && t.is_tracking(9)); + } + // The chunk arrives: both are paired, in order. + c.chunks.insert((4, 0)); + c.tick(&mut level, &[&far, &near, &home]); + for t in &c.trackers { + assert!(t.is_tracking(7) && t.is_tracking(8) && t.is_tracking(9)); + } + // One walks back into chunk (3, 0) and the other out of range. + far.position[0] = 200.0; + near.position[0] = 60.0; + c.tick(&mut level, &[&far, &near, &home]); + for t in &c.trackers { + assert!(!t.is_tracking(7) && t.is_tracking(8) && t.is_tracking(9)); + } + } + + #[test] + fn a_forgotten_entity_is_paired_again_at_the_next_tick() { + // A respawned player: the hub removes it from the other clients and + // forgets it, and the next tick pairs it again as a new entity. + let mut level = Entities::default(); + let mut c = Clients::new(); + let mut player = state(0.0); + player.id = 1; + player.kind = "minecraft:player".into(); + c.tick(&mut level, &[&player]); + c.tick(&mut level, &[&player]); + assert!(c.trackers[1].forget(1)); + assert!(!c.trackers[1].forget(1)); + c.tick(&mut level, &[&player]); + assert!(c.trackers[1].is_tracking(1)); + let paired = c.out[1] + .first() + .and_then(|p| play::Clientbound::decode(i32::from(p[0]), &p[1..]).ok()); + assert!( + matches!(paired, Some(play::Clientbound::AddEntity(ref a)) if a.id == 1), + "{paired:?}" + ); + } } diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 545bb6ace..91bf2709f 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -37,6 +37,12 @@ pub struct Guest { pub last_action_tick: u64, /// The next ClientboundPlayerChatPacket.globalIndex for this connection. pub chat_index: i32, + /// Secure chat (ServerGamePacketListenerImpl): the player's message + /// chain, keyed once it sends a chat session; the messages its + /// acknowledgements cover; the signatures its client caches. + pub chain: horizon_protocol::secure_chat::Chain, + pub last_seen: horizon_protocol::secure_chat::LastSeenValidator, + pub signatures: horizon_protocol::secure_chat::SignatureCache, /// The hub tick the player was placed on: chunks go out from the tick /// after next, behind the first doTick's packets, as vanilla's do. pub placed_at: u64, @@ -69,6 +75,17 @@ pub struct Guest { pub fall_flying: bool, pub flying: bool, pub sleeping: bool, + /// `LivingEntity.DATA_LIVING_ENTITY_FLAGS`: 1 while using an item, 2 if + /// it is in the off hand. + pub living_flags: i8, + /// The bed (its head) the player sleeps in (`LivingEntity.getSleepingPos`), + /// `Player.sleepCounter`, and the bed last told to the player itself. + pub bed: Option<[i32; 3]>, + pub sleep_timer: u32, + pub sent_bed: Option<[i32; 3]>, + /// Where the player respawns (a bed's spot; `ServerPlayer.respawnConfig`), + /// None for the world spawn. + pub spawn: Option<[f64; 3]>, /// Pending ClientboundPlayerPositionPacket id; movement is ignored until /// the client accepts it (ServerGamePacketListenerImpl.awaitingPositionFromClient). pub awaiting_teleport: Option<(i32, [f64; 3])>, @@ -85,6 +102,9 @@ pub struct Guest { /// A position move arrived since the client's last ClientTickEnd /// (receivedPositionThisTick): a second one is a protocol error. pub position_this_tick: bool, + /// It accepted a move since the last entity range checks + /// (ServerChunkCache.move), which then check all of its pairs again. + pub moved: bool, /// The client finished loading terrain (ServerboundPlayerLoadedPacket). pub loaded: bool, // Chunks. @@ -129,7 +149,8 @@ pub struct Guest { /// What the client believes the inventory menu holds (for change detection). pub menu_sent: Vec<Option<ItemStack>>, pub menu_state: i32, - pub sent_health: Option<(f32, i32, f32)>, + /// `lastSentHealth`, `lastSentFood` and `lastFoodSaturationZero`. + pub sent_health: Option<(f32, i32, bool)>, pub sent_xp: Option<(f32, i32, i32)>, /// Where the player last died (Player.lastDeathLocation), sent with the respawn. pub last_death: Option<[i32; 3]>, @@ -179,6 +200,9 @@ impl Guest { address: j.address, last_action_tick: 0, chat_index: 0, + chain: Default::default(), + last_seen: Default::default(), + signatures: Default::default(), placed_at: 0, center_sent: None, left_reason: String::new(), @@ -204,6 +228,11 @@ impl Guest { fall_flying: false, flying: false, sleeping: false, + living_flags: 0, + bed: None, + sleep_timer: 0, + sent_bed: None, + spawn: None, awaiting_teleport: None, teleport_counter: 0, teleport_tick: 0, @@ -211,6 +240,7 @@ impl Guest { received_moves: 0, known_moves: 0, position_this_tick: false, + moved: false, loaded: false, center: None, sent_chunks: Default::default(), diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 1b0d8229a..625f18eff 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -8,10 +8,11 @@ use super::{ Lan, NetEvent, chunks::ChunkEncoder, data::SyncData, - entity::EntityState, + entity::{Entities, EntityState, Viewer}, guest::{Guest, SentEffect, stack_to_network}, }; use crate::{ + chunk::Chunk, collisions::SceneCollisions, effects::{EffectInstance, PlayerEffects}, items::ItemStack, @@ -33,6 +34,8 @@ use horizon_world::{ use std::sync::{Arc, atomic::Ordering}; /// GameEvent types (ClientboundGameEventPacket). +pub mod chat; + pub mod game_event { pub const START_RAINING: u8 = 1; pub const STOP_RAINING: u8 = 2; @@ -78,6 +81,10 @@ pub struct HostState { pub sprinting: bool, pub equipment: [Option<ItemStack>; 6], pub health: f32, + /// The host player's client-syncable attribute instances. + pub attributes: Vec<play::AttributeSnapshot>, + /// `LivingEntity.DATA_LIVING_ENTITY_FLAGS` (the item in use). + pub living_flags: i8, } /// Everything the hub needs from the game for one tick. @@ -108,10 +115,16 @@ pub enum HostEvent { /// A guest left (state to save, entities to drop). Left(Box<Guest>), Packet(u32, Box<S>), - /// A chat line to show on the host (already broadcast to the guests). - Chat(String), + /// A chat line to show on the host (already broadcast to the guests); + /// a dedicated server logs it, `[Not Secure]` unless signed and fresh. + Chat { + line: String, + secure: bool, + }, /// A server log warning (ServerGamePacketListenerImpl's LOGGER.warn). Warn(String), + /// A server log error (LOGGER.error). + Error(String), } pub struct Hub { @@ -124,6 +137,11 @@ pub struct Hub { /// The `player_movement_check` and `elytra_movement_check` game rules, /// set by the game before each tick. pub movement_checks: (bool, bool), + /// An integrated server's owner (`MinecraftServer.isSingleplayerOwner`), + /// whose moves are never checked. + pub singleplayer_owner: Option<u128>, + /// Who rides what, set by the game before each tick. + pub riding: super::entity::Riding, last_clock: i64, last_rate: f32, ticking: (f32, bool), @@ -138,6 +156,10 @@ pub struct Hub { clock_ids: Vec<i32>, item_ids: std::collections::HashMap<Arc<str>, i32>, entity_types: std::collections::HashMap<String, i32>, + /// Each level's tracked entities, by dimension. + entities: std::collections::HashMap<String, Entities>, + /// What one tick of entity tracking sends each guest, kept between ticks. + entity_out: Vec<Vec<Vec<u8>>>, } fn string(s: &str) -> Tag { @@ -191,6 +213,20 @@ fn yellow_names(key: &str, names: Vec<Tag>) -> Tag { ]) } +/// An entity type's registry id, remembered once looked up. +fn entity_type( + types: &mut std::collections::HashMap<String, i32>, + sync: &SyncData, + kind: &str, +) -> Option<i32> { + if let Some(id) = types.get(kind) { + return Some(*id); + } + let id = sync.builtin.get("minecraft:entity_type")?.id(kind)?; + types.insert(kind.to_owned(), id); + Some(id) +} + /// ChunkTrackingView.contains: the chunks a player at (cx, cz) with view /// distance `r` is sent (isWithinDistance with the neighbours' buffer). fn tracked(cx: i32, cz: i32, r: i32, x: i32, z: i32) -> bool { @@ -237,6 +273,8 @@ impl Hub { sync, ticks: 0, movement_checks: (true, true), + singleplayer_owner: None, + riding: Default::default(), last_clock: i64::MIN, last_rate: 0.0, ticking: (20.0, false), @@ -248,6 +286,8 @@ impl Hub { clock_ids, item_ids: Default::default(), entity_types: Default::default(), + entities: Default::default(), + entity_out: Vec::new(), } } @@ -281,14 +321,6 @@ impl Hub { let sync = self.sync.clone(); stack_to_network(|_| id, |name| sync.id("minecraft:enchantment", name), s) } - fn entity_type(&mut self, kind: &str) -> Option<i32> { - if let Some(id) = self.entity_types.get(kind) { - return Some(*id); - } - let id = self.sync.builtin.get("minecraft:entity_type")?.id(kind)?; - self.entity_types.insert(kind.to_owned(), id); - Some(id) - } pub fn broadcast(&self, packet: &C) { let body = packet.encode(); @@ -296,6 +328,22 @@ impl Hub { g.sender.send(body.clone()); } } + /// PlayerList.setViewDistance: every player is told the new radius, + /// and each one's chunks follow it, up to what they asked for + /// (ChunkMap.getPlayerViewDistance). + pub fn set_view_distance(&mut self, distance: i32) { + self.config.view_distance = distance; + self.broadcast(&C::SetChunkCacheRadius(play::Distance { distance })); + for g in &mut self.guests { + g.view_distance = i32::from(g.info.view_distance).clamp(2, distance); + g.center = None; + } + } + /// PlayerList.setSimulationDistance. + pub fn set_simulation_distance(&mut self, distance: i32) { + self.config.simulation_distance = distance; + self.broadcast(&C::SetSimulationDistance(play::Distance { distance })); + } /// 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 @@ -408,56 +456,23 @@ impl Hub { }, })); } - /// PlayerList.broadcastChatMessage of a guest's unsigned message - /// (PlayerChatMessage.unsigned): a ClientboundPlayerChatPacket to every - /// player, each connection numbering its messages. - pub fn player_chat(&mut self, from: usize, text: &str) { - let (uuid, name) = (self.guests[from].uuid, self.guests[from].name.clone()); - let timestamp = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |d| d.as_millis() as i64); - let bound = play::ChatTypeBound { - chat_type: self.chat_type, - name: display_name(uuid, &name), - target: None, - }; - for g in self.guests.iter_mut().filter(|g| g.placed) { - let packet = C::PlayerChat(play::PlayerChat { - global_index: g.chat_index, - sender: uuid, - index: 0, - signature: None, - content: text.to_owned(), - timestamp, - salt: 0, - last_seen: Vec::new(), - unsigned_content: None, - filter: (0, Vec::new()), - chat_type: bound.clone(), - }); - g.chat_index += 1; - g.send(&packet); - } - } - /// Disconnect a guest with a reason (ServerGamePacketListenerImpl.disconnect). pub fn kick(&mut self, conn: u32, reason: Tag) { - if let Some(g) = self.guest(conn) { + // The log's "lost connection" line gives the reason, as vanilla's. + let text = self.english(&reason); + if let Some(g) = self.guest_mut(conn) { + g.left_reason = text; g.sender.disconnect(reason); } } fn player_info(&self, uuid: u128, name: &str, mode: i32, latency: i32) -> play::PlayerInfo { + let guest = self.guests.iter().find(|g| g.uuid == uuid); play::PlayerInfo { uuid, name: Some(name.to_owned()), - properties: self - .guests - .iter() - .find(|g| g.uuid == uuid) - .map(|g| g.properties.clone()) - .unwrap_or_default(), - chat_session: None, + properties: guest.map(|g| g.properties.clone()).unwrap_or_default(), + chat_session: guest.and_then(|g| g.chain.session()).map(|s| s.data()), game_mode: Some(mode), listed: Some(true), latency: Some(latency), @@ -550,8 +565,9 @@ impl Hub { show_death_screen: true, limited_crafting: false, spawn: self.spawn_info(mode), - online_mode: false, - enforces_secure_chat: false, + // MinecraftServer.usesAuthentication, enforceSecureProfile. + online_mode: self.lan.shared.config.online.is_some(), + enforces_secure_chat: self.enforces_secure_chat(), })); g.send(&C::ChangeDifficulty(play::ChangeDifficulty { difficulty: ctx.difficulty, @@ -675,6 +691,16 @@ impl Hub { /// onEffectsRemoved, from what changed since the client was told: an /// effect that only counted down is not sent again, except at every /// 600 ticks left (`LivingEntity.tickEffects`). + /// `sync_effects` for every player at once: what a command changed + /// leaves with its feedback (ServerPlayer.onEffectAdded sends at once), + /// not after the tick's countdown. + pub fn sync_all_effects(&mut self) { + for i in 0..self.guests.len() { + if self.guests[i].placed { + self.sync_effects(i); + } + } + } fn sync_effects(&mut self, i: usize) { let g = &self.guests[i]; if g.effects.list.is_empty() && g.sent_effects.is_empty() { @@ -987,24 +1013,31 @@ impl Hub { } } if !self.guests.iter().any(|g| self.here(g)) { + // ServerTickRateManager broadcasts a change to the players there + // are; one who joins later is sent the state as it is then + // (`updateJoiningPlayer`). + if !self.guests.iter().any(|g| g.placed) { + self.ticking = (ctx.tick_rate, ctx.tick_frozen); + } if !self .guests .iter() .any(|g| g.dimension == self.config.dimension) { let _ = ctx.world.block_log.take(); + let _ = ctx.world.light_log.take(); } return events; } if ctx.world.block_log.is_none() { ctx.world.block_log = Some(Vec::new()); } - self.sync_world(ctx); - for i in 0..self.guests.len() { - if self.here(&self.guests[i]) { - self.update_chunks(i, ctx); - } + if ctx.world.light_log.is_none() { + ctx.world.light_log = Some(Default::default()); } + self.sync_world(ctx); + crate::spans::time("lan_chunks", || self.update_chunks(ctx)); + self.broadcast_light_changes(ctx.world); self.broadcast_block_changes(ctx.world); // ServerGamePacketListenerImpl.tick: the actions handled since the last tick are // acknowledged after the block changes they made were sent, so a client's predicted @@ -1053,7 +1086,9 @@ impl Hub { fn remove_guest(&mut self, i: usize, reason: &str) -> Guest { let mut g = self.guests.remove(i); - g.left_reason = reason.to_owned(); + if g.left_reason.is_empty() { + g.left_reason = reason.to_owned(); + } if std::env::var_os("HORIZON_NET_DEBUG").is_some() { log::info!("[lan] {} left: {reason}", g.name); } @@ -1140,86 +1175,140 @@ impl Hub { // ---- chunks -------------------------------------------------------- - fn update_chunks(&mut self, i: usize, ctx: &TickCtx) { + /// Every player's chunks here: their views, then the next batch of each + /// (PlayerChunkSender.sendNextChunks). The batches are chosen first, the + /// columns in them encoded once each, their new sections on the warm-up + /// threads too (`ChunkEncoder::warm`), then sent: nothing changes the + /// level in between, and each player's packets keep their order. + fn update_chunks(&mut self, ctx: &TickCtx) { + let world = &*ctx.world; + let mut batches = Vec::new(); + for i in 0..self.guests.len() { + if self.here(&self.guests[i]) { + self.update_view(i); + if let Some(batch) = self.next_batch(i, world) { + batches.push((i, batch)); + } + } + } + if batches.is_empty() { + return; + } + // Each column once, however many players it goes to, with the + // number of batches that take it. + let (mut columns, mut uses): (Vec<&Chunk>, Vec<usize>) = Default::default(); + let mut index = crate::fast_hash::FxHashMap::default(); + let batches: Vec<(usize, Vec<usize>, Vec<usize>)> = batches + .into_iter() + .map(|(i, batch)| { + let (taken, bodies) = batch + .into_iter() + .map(|(idx, chunk)| { + let j = *index.entry((chunk.x, chunk.z)).or_insert_with(|| { + columns.push(chunk); + uses.push(0); + columns.len() - 1 + }); + uses[j] += 1; + (idx, j) + }) + .unzip(); + (i, taken, bodies) + }) + .collect(); + self.encoder.warm(&columns); + let mut bodies: Vec<Vec<u8>> = columns + .iter() + .map(|c| self.encoder.body_in(c, world)) + .collect(); + for (i, taken, batch) in batches { + let g = &mut self.guests[i]; + let size = batch.len(); + g.batch_quota -= size as f32; + g.send(&C::ChunkBatchStart(horizon_protocol::packets::Empty)); + g.sender.send_many(batch.into_iter().map(|j| { + uses[j] -= 1; + if uses[j] == 0 { + std::mem::take(&mut bodies[j]) + } else { + bodies[j].clone() + } + })); + g.send(&C::ChunkBatchFinished(play::ChunkBatchFinished { + size: size as i32, + })); + g.unacknowledged += 1; + for idx in taken.into_iter().rev() { + let key = g.chunk_queue.remove(idx); + g.sent_chunks.insert(key); + } + } + } + + /// ChunkMap.move's view change: the new centre, the chunks that left + /// the view forgotten and the ones that entered it queued, closest first. + fn update_view(&mut self, i: usize) { let (cx, cz) = self.guests[i].chunk(); let r = self.guests[i].view_distance; let g = &mut self.guests[i]; - if g.center != Some((cx, cz)) { - g.center = Some((cx, cz)); - if g.center_sent.take() != Some((cx, cz)) { - g.send(&C::SetChunkCacheCenter(play::SetChunkCacheCenter { - x: cx, - z: cz, - })); - } - // Chunks that left the view. - let forget: Vec<_> = g - .sent_chunks - .iter() - .copied() - .filter(|&(x, z)| !tracked(cx, cz, r, x, z)) - .collect(); - for (x, z) in forget { - g.sent_chunks.remove(&(x, z)); - g.send(&C::ForgetLevelChunk(play::ForgetLevelChunk { pos: [x, z] })); - } - g.chunk_queue.retain(|&(x, z)| tracked(cx, cz, r, x, z)); - for dz in -r - 2..=r + 2 { - for dx in -r - 2..=r + 2 { - let key = (cx + dx, cz + dz); - if tracked(cx, cz, r, key.0, key.1) - && !g.sent_chunks.contains(&key) - && !g.chunk_queue.contains(&key) - { - g.chunk_queue.push(key); - } + if g.center == Some((cx, cz)) { + return; + } + g.center = Some((cx, cz)); + if g.center_sent.take() != Some((cx, cz)) { + g.send(&C::SetChunkCacheCenter(play::SetChunkCacheCenter { + x: cx, + z: cz, + })); + } + // Chunks that left the view. + let forget: Vec<_> = g + .sent_chunks + .iter() + .copied() + .filter(|&(x, z)| !tracked(cx, cz, r, x, z)) + .collect(); + for (x, z) in forget { + g.sent_chunks.remove(&(x, z)); + g.send(&C::ForgetLevelChunk(play::ForgetLevelChunk { pos: [x, z] })); + } + g.chunk_queue.retain(|&(x, z)| tracked(cx, cz, r, x, z)); + for dz in -r - 2..=r + 2 { + for dx in -r - 2..=r + 2 { + let key = (cx + dx, cz + dz); + if tracked(cx, cz, r, key.0, key.1) + && !g.sent_chunks.contains(&key) + && !g.chunk_queue.contains(&key) + { + g.chunk_queue.push(key); } } - g.chunk_queue - .sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2)); } - // PlayerChunkSender.sendNextChunks: ready chunks, closest first, in - // batches the client's acknowledgements pace. + g.chunk_queue + .sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2)); + } + + /// PlayerChunkSender.sendNextChunks' choice: ready chunks, closest first, + /// as many as the batch quota the client's acknowledgements pace allows, + /// with their places in the queue. + fn next_batch<'w>(&mut self, i: usize, world: &'w World) -> Option<Vec<(usize, &'w Chunk)>> { + let g = &mut self.guests[i]; if self.ticks <= g.placed_at + 1 || g.unacknowledged >= g.max_unacknowledged { - return; + return None; } 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; + return None; } 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() { - if packets.len() >= budget { - break; - } - let Some(chunk) = ctx.world.chunks.get(key) else { - continue; - }; - if !chunk.lit { - continue; - } - packets.push(self.encoder.body_in(chunk, ctx.world)); - taken.push(idx); - } - if packets.is_empty() { - return; - } - let size = packets.len(); - g.batch_quota -= size as f32; - g.send(&C::ChunkBatchStart(horizon_protocol::packets::Empty)); - for body in packets { - g.sender.send(body); - } - g.send(&C::ChunkBatchFinished(play::ChunkBatchFinished { - size: size as i32, - })); - g.unacknowledged += 1; - for idx in taken.into_iter().rev() { - let key = g.chunk_queue.remove(idx); - g.sent_chunks.insert(key); - } + let batch: Vec<_> = g + .chunk_queue + .iter() + .enumerate() + .filter_map(|(idx, key)| Some((idx, &**world.chunks.get(key).filter(|c| c.lit)?))) + .take(budget) + .collect(); + (!batch.is_empty()).then_some(batch) } /// Resend a chunk to everyone who has it (a block entity changed, relight). @@ -1237,6 +1326,42 @@ impl Hub { } } + /// `ChunkHolder.broadcastChanges`' light part: the light sections that + /// changed in a column go to the players for whom it is on the border of + /// what they track (`ChunkMap.isChunkOnTrackedBorder`); the others light + /// the blocks they are sent themselves. + fn broadcast_light_changes(&mut self, world: &mut World) { + let Some(log) = world.light_log.as_mut() else { + return; + }; + if log.is_empty() { + return; + } + let mut changes: Vec<((i32, i32), u32)> = log.drain().collect(); + changes.sort_unstable(); + for ((x, z), sections) in changes { + let tracked = |g: &Guest, x: i32, z: i32| g.sent_chunks.contains(&(x, z)); + let viewers: Vec<usize> = (0..self.guests.len()) + .filter(|&i| { + let g = &self.guests[i]; + self.here(g) + && tracked(g, x, z) + && (-1..=1).any(|dz| (-1..=1).any(|dx| !tracked(g, x + dx, z + dz))) + }) + .collect(); + if viewers.is_empty() { + continue; + } + let Some(chunk) = world.chunks.get(&(x, z)) else { + continue; + }; + let body = self.encoder.light_update(chunk, sections); + for &i in &viewers { + self.guests[i].sender.send(body.clone()); + } + } + } + fn broadcast_block_changes(&mut self, world: &mut World) { let Some(log) = world.block_log.as_mut() else { return; @@ -1325,9 +1450,11 @@ impl Hub { rot: (f32, f32, f32), on_ground: bool, flags: (bool, bool, bool, bool), + living_flags: i8, skin: u8, health: f32, equipment: Vec<(u8, Option<horizon_protocol::item::Stack>)>, + attributes: Vec<play::AttributeSnapshot>, ) -> EntityState { let (sneaking, sprinting, gliding, sleeping) = flags; let mut shared = 0i8; @@ -1356,6 +1483,9 @@ impl Hub { if pose != 0 { meta.push((6, serializer::POSE, Value::Id(pose))); } + // Always there: the trackers send the entries that changed, and an + // item no longer in use is a change back to 0. + meta.push((8, serializer::BYTE, Value::Byte(living_flags))); if (health - 1.0).abs() > f32::EPSILON && health != 20.0 { meta.push((9, serializer::FLOAT, Value::Float(health))); } @@ -1375,6 +1505,8 @@ impl Hub { data: 0, meta, equipment, + attributes, + precise: false, } } @@ -1418,9 +1550,11 @@ impl Hub { (h.yaw, h.pitch, h.head_yaw), h.on_ground, (h.sneaking, h.sprinting, false, false), + h.living_flags, 0x7F, h.health, equipment, + h.attributes.clone(), )); } let placed: Vec<usize> = (0..self.guests.len()) @@ -1447,78 +1581,93 @@ impl Hub { (g.yaw, g.pitch, g.head_yaw), g.on_ground, (g.sneaking, g.sprinting, g.fall_flying, g.sleeping), + g.living_flags, g.info.model_customisation, g.health, equipment, + g.motion + .as_ref() + .map(|m| super::attributes::syncable(&m.attributes)) + .unwrap_or_default(), ) }) .collect(); all.extend(guest_states); - all.extend(ctx.entities.iter().cloned()); - let by_id: std::collections::HashMap<i32, usize> = - 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<i32> = all - .iter() - .map(|e| super::entity::tracking_chunks(&e.kind)) + let entities: Vec<&EntityState> = all.iter().chain(ctx.entities).collect(); + // ChunkMap.tick: the level's entities, once for all its players. + let mut level = self + .entities + .remove(&self.config.dimension) + .unwrap_or_default(); + let mut outs = std::mem::take(&mut self.entity_out); + let dimension = &self.config.dimension; + let here = |g: &Guest| g.placed && g.dimension == *dimension; + outs.resize_with(self.guests.iter().filter(|g| here(g)).count(), Vec::new); + let mut viewers: Vec<Viewer> = self + .guests + .iter_mut() + .filter(|g| here(g)) + .zip(outs.iter_mut()) + .map(|(g, out)| Viewer { + entity_id: g.entity_id, + moved: std::mem::take(&mut g.moved), + position: g.position, + view_distance: g.view_distance, + chunks: &g.sent_chunks, + tracker: &mut g.tracker, + out, + }) .collect(); - for gi in 0..self.guests.len() { - if !self.here(&self.guests[gi]) { - continue; - } - let view = self.guests[gi].view_distance; - let me = self.guests[gi].entity_id; - 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, 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, - (e.position[2].floor() as i32) >> 4, - ); - dx * dx + dz * dz <= range * range && g.sent_chunks.contains(&chunk) - }; - // Forget what disappeared or left range. - 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], ei) => {} - _ => removed.push(id), - } - } - if !removed.is_empty() { - for id in &removed { - self.guests[gi].tracker.forget(*id); - } - self.guests[gi].send(&C::RemoveEntities(play::RemoveEntities { ids: removed })); - } - 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], ei) { - let Some(kind) = self.entity_type(&e.kind) else { - continue; - }; - // Players need their list entry first; guests got it at join. - let packets = self.guests[gi].tracker.spawn(e, kind); - self.guests[gi].send_all(&packets); - } - } + let (types, sync) = (&mut self.entity_types, &self.sync); + level.tick(&entities, &self.riding, &mut viewers, |kind| { + entity_type(types, sync, kind) + }); + drop(viewers); + for (g, out) in self.guests.iter().filter(|g| here(g)).zip(outs.iter_mut()) { + g.sender.send_many(out.drain(..)); } + self.entity_out = outs; + self.entities.insert(self.config.dimension.clone(), level); + } + + /// ServerPlayer.stopSleepInBed: the wake-up animation goes to the player + /// and those around, the pose is standing again and the sleep counter + /// starts the wake-up fade (100). + pub fn wake(&mut self, i: usize) { + let g = &mut self.guests[i]; + if g.bed.take().is_none() && !g.sleeping { + return; + } + g.sleeping = false; + g.sleep_timer = 100; + let (id, at) = (g.entity_id, g.position); + // ClientboundAnimatePacket.WAKE_UP. + self.broadcast_near( + at, + 128.0, + &C::Animate(play::Animate { id, action: 0 }), + None, + ); } // ---- per-player state ------------------------------------------------ /// ServerPlayer.doTick: health, food, experience and the inventory menu. fn sync_player_state(&mut self, i: usize) { + // LivingEntity.startSleeping / stopSleeping: the pose and the bed go + // to the player too (its client lies down in the bed from them). + let g = &mut self.guests[i]; + if g.bed != g.sent_bed { + g.sent_bed = g.bed; + let pose = if g.bed.is_some() { 2 } else { 0 }; + g.send(&C::SetEntityData(play::SetEntityData { + id: g.entity_id, + values: vec![ + (6, serializer::POSE, Value::Id(pose)), + (14, serializer::OPTIONAL_BLOCK_POS, Value::OptPos(g.bed)), + ], + })); + } // ServerEntity.sendDirtyEntityData on the player's first tick: the // health its creation set is still dirty, and goes to the player too. if self.guests[i].sent_health.is_none() { @@ -1551,17 +1700,28 @@ impl Hub { self.flush_advancements(i, true); } } - let health = { - let g = &self.guests[i]; - (g.health, g.food, g.saturation) - }; - // A dead player's health isn't sent (the death screen shows from the combat kill). - if self.guests[i].sent_health != Some(health) && !self.guests[i].dead { - let g = &mut self.guests[i]; + // ServerEntity.sendDirtyEntityData: the player's changed attribute + // instances go to the player too (its trackers get them from + // track_entities). + let g = &mut self.guests[i]; + if let Some(m) = g.motion.as_mut() { + let values = super::attributes::take_dirty(&mut m.attributes); + if !values.is_empty() { + g.send(&C::UpdateAttributes(play::UpdateAttributes { + id: g.entity_id, + values, + })); + } + } + // Sent when the health or the food level changes, or the saturation + // reaches or leaves zero; a dead player's health of 0 too. + let g = &mut self.guests[i]; + let health = (g.health, g.food, g.saturation == 0.0); + if g.sent_health != Some(health) { g.send(&C::SetHealth(play::SetHealth { - health: health.0, - food: health.1, - saturation: health.2, + health: g.health, + food: g.food, + saturation: g.saturation, })); g.sent_health = Some(health); } @@ -1767,17 +1927,13 @@ impl Hub { 1 => self.guests[i].sprinting = true, 2 => self.guests[i].sprinting = false, 6 => self.guests[i].fall_flying = true, - 0 => self.guests[i].sleeping = false, + // STOP_SLEEPING. + 0 => self.wake(i), _ => {} }, - S::Chat(c) => { - let text: String = c.message.chars().filter(|c| !c.is_control()).collect(); - if !text.is_empty() { - let name = self.guests[i].name.clone(); - self.player_chat(i, &text); - events.push(HostEvent::Chat(format!("<{name}> {text}"))); - } - } + S::Chat(c) => self.handle_chat(i, c, events), + S::ChatAck(p) => self.chat_ack(i, p.offset, events), + S::ChatSessionUpdate(p) => self.chat_session_update(i, p, events), other => events.push(HostEvent::Packet(conn, Box::new(other))), } } @@ -1839,6 +1995,7 @@ impl Hub { ) { let (frozen, (check, elytra_check)) = (self.ticking.1, self.movement_checks); let g = &mut self.guests[i]; + let owner = self.singleplayer_owner == Some(g.uuid); let to = [ to[0].clamp(-3.0E7, 3.0E7), to[1].clamp(-2.0E7, 2.0E7), @@ -1862,9 +2019,10 @@ impl Hub { 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) { + // shouldCheckPlayerMovement (never the single-player owner). + // The server holds no velocity for a guest (getDeltaMovement), + // so nothing is expected. + if !owner && 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!( @@ -1894,6 +2052,8 @@ impl Hub { let g = &mut self.guests[i]; g.previous_position = g.position; g.position = to; + // ServerChunkCache.move: its pairs are checked again. + g.moved = true; 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; @@ -2052,6 +2212,18 @@ impl Hub { .map(str::to_owned) } + /// ServerLevel.removePlayerImmediately, then addRespawnedPlayer: the other players + /// lose the dead player's entity (ServerEntity.removePairing) and are sent the + /// respawned one as a new entity at the next tick. Their clients would otherwise keep + /// the dead body, lying down, wherever the player goes. + pub fn respawned(&mut self, id: i32) { + for g in &mut self.guests { + if g.entity_id != id && g.tracker.forget(id) { + g.send(&C::RemoveEntities(play::RemoveEntities { ids: vec![id] })); + } + } + } + /// PlayerList.respawn: back to `at` with a fresh start. The vanilla client waits on its /// level loading screen from the Respawn packet until the level info's "level chunks load /// start" event and the chunk under the player, so the packets follow vanilla's order. @@ -2078,6 +2250,9 @@ impl Hub { g.tracker.clear(); g.sent_chunks.clear(); g.chunk_queue.clear(); + let id = g.entity_id; + self.respawned(id); + let g = &mut self.guests[i]; // ServerPlayer.restoreFrom: the game mode again (onUpdateAbilities). g.send(&C::PlayerAbilities(play::PlayerAbilities { flags: g.ability_flags(), @@ -2164,7 +2339,15 @@ impl Hub { /// names (`set_dimension`): ClientboundRespawnPacket keeping all data, /// then vanilla's packet order. Nothing tracked in the old level is /// removed one by one: the client drops its whole level. - pub fn change_level(&mut self, i: usize, at: [f64; 3], yaw: f32, ctx: &TickCtx) { + pub fn change_level( + &mut self, + i: usize, + at: [f64; 3], + yaw: f32, + pitch: Option<f32>, + portal_sound: bool, + ctx: &TickCtx, + ) { let mode = self.guests[i].game_mode; let info = self.spawn_info(mode); self.close_container_for(i); @@ -2175,6 +2358,9 @@ impl Hub { g.chunk_queue.clear(); g.center = None; g.yaw = yaw; + if let Some(pitch) = pitch { + g.pitch = pitch; + } g.position = at; g.previous_position = at; g.send(&C::Respawn(play::Respawn { @@ -2206,12 +2392,14 @@ impl Hub { // ServerPlayer.sendPostEffects. g.send(&raw(ids::POST_EFFECTS, vec![0])); // TeleportTransition.PLAY_PORTAL_SOUND. - g.send(&C::LevelEvent(play::LevelEvent { - kind: 1032, - pos: [0, 0, 0], - data: 0, - global: false, - })); + if portal_sound { + g.send(&C::LevelEvent(play::LevelEvent { + kind: 1032, + pos: [0, 0, 0], + data: 0, + global: false, + })); + } // lastSentExp, lastSentHealth and lastSentFood. g.sent_health = None; g.sent_xp = None; diff --git a/crates/horizon-client/src/lan/hub/chat.rs b/crates/horizon-client/src/lan/hub/chat.rs new file mode 100644 index 000000000..7e75c84c5 --- /dev/null +++ b/crates/horizon-client/src/lan/hub/chat.rs @@ -0,0 +1,500 @@ +//! Chat on the server side, as ServerGamePacketListenerImpl and PlayerList +//! handle it: chat sessions validated against the services' keys, signed +//! messages checked link by link, the acknowledged window, and messages +//! relayed with each connection's numbering and signature cache. +use super::{HostEvent, Hub, display_name}; +use horizon_protocol::{ + packets::play::{self, Clientbound as C}, + secure_chat::{self, Body, Chain, ChatSession, DecodeError, ProfileKey, Signature, Unpacked}, + text::{literal, translatable}, +}; +use horizon_world::nbt::{JavaString, Tag}; + +/// Now, in epoch milliseconds (Instant.now()). +pub fn now_millis() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as i64) +} + +/// StringUtil.isAllowedChatCharacter. +fn allowed(c: char) -> bool { + c != '\u{a7}' && c >= ' ' && c != '\u{7f}' +} + +/// A translatable message in red. +fn red(key: &str) -> Tag { + let mut t = translatable(key, &[]); + if let Tag::Compound(map) = &mut t { + map.insert( + JavaString::from("color"), + Tag::String(JavaString::from("red")), + ); + } + t +} + +/// PlayerChatMessage as the server relays it. +#[derive(Clone, Debug, PartialEq)] +pub struct ChatMessage { + pub sender: u128, + /// The link's index in the sender's chain (0 when unsigned). + pub index: i32, + pub signature: Option<Signature>, + pub content: String, + /// Epoch milliseconds. + pub timestamp: i64, + pub salt: i64, + pub last_seen: Vec<Signature>, + /// What clients show instead of the signed text (withUnsignedContent). + pub unsigned_content: Option<Tag>, +} + +impl ChatMessage { + /// The message a chain let through: a signed one keeps its body; + /// PlayerChatMessage.unsigned takes the time now, no salt, nothing seen. + pub fn new(sender: u128, unpacked: Unpacked, body: &Body, now: i64) -> Self { + let (index, signature, timestamp, salt, last_seen) = match unpacked { + Unpacked::Unsigned => (0, None, now, 0, Vec::new()), + Unpacked::Signed { index, signature } => ( + index, + Some(signature), + body.timestamp, + body.salt, + body.last_seen.to_vec(), + ), + }; + Self { + sender, + index, + signature, + content: body.content.to_owned(), + timestamp, + salt, + last_seen, + unsigned_content: None, + } + } + /// hasExpiredServer. + pub fn expired(&self, now: i64) -> bool { + now > self.timestamp + secure_chat::EXPIRES_AFTER_SERVER + } + /// PlayerList.verifyChatTrusted: signed and not expired. + pub fn trusted(&self, now: i64) -> bool { + self.signature.is_some() && !self.expired(now) + } +} + +impl Hub { + /// MinecraftServer.enforceSecureProfile. + pub fn enforces_secure_chat(&self) -> bool { + self.lan.shared.config.enforces_secure_chat() + } + + /// Component.getString in the server's language, for the log. + pub(crate) fn english(&self, tag: &Tag) -> String { + match &self.lan.shared.config.log { + Some(log) => horizon_protocol::text::plain(tag, &log.lang), + None => horizon_protocol::text::plain(tag, &Default::default()), + } + } + + /// tryHandleChat: an illegal character disconnects; with chat hidden a + /// message (not a command) is refused. Whether to go on. + pub fn try_handle_chat(&mut self, i: usize, message: &str, command: bool) -> bool { + let conn = self.guests[i].conn; + if !message.chars().all(allowed) { + self.kick( + conn, + translatable("multiplayer.disconnect.illegal_characters", &[]), + ); + return false; + } + // ChatVisiblity.HIDDEN. + if !command && self.guests[i].info.chat_visibility == 2 { + self.guests[i].send(&C::SystemChat(play::SystemChat { + content: red("chat.disabled.options"), + overlay: false, + })); + return false; + } + true + } + + /// unpackAndApplyLastSeen: the acknowledged messages, or a disconnect. + pub fn apply_last_seen( + &mut self, + i: usize, + update: &play::LastSeenUpdate, + events: &mut Vec<HostEvent>, + ) -> Option<Vec<Signature>> { + let g = &mut self.guests[i]; + match g + .last_seen + .apply_update(update.offset, update.acknowledged, update.checksum) + { + Ok(seen) => Some(seen), + // Vanilla logs the ValidationException's stack trace after the line. + Err(_) => { + events.push(HostEvent::Error(format!( + "Failed to validate message acknowledgements from {}", + g.name + ))); + let conn = g.conn; + self.kick( + conn, + translatable("multiplayer.disconnect.chat_validation_failed", &[]), + ); + None + } + } + } + + /// handleChatAck. + pub(super) fn chat_ack(&mut self, i: usize, offset: i32, events: &mut Vec<HostEvent>) { + let g = &mut self.guests[i]; + if g.last_seen.apply_offset(offset).is_err() { + events.push(HostEvent::Error(format!( + "Failed to validate message acknowledgement offset from {}", + g.name + ))); + let conn = g.conn; + self.kick( + conn, + translatable("multiplayer.disconnect.chat_validation_failed", &[]), + ); + } + } + + /// handleMessageDecodeFailure: logged, and the reason in red for the player. + pub fn decode_failure(&mut self, i: usize, e: DecodeError, events: &mut Vec<HostEvent>) { + let reason = red(e.key()); + events.push(HostEvent::Warn(format!( + "Failed to update secure chat state for {}: '{}'", + self.guests[i].name, + self.english(&reason) + ))); + self.guests[i].send(&C::SystemChat(play::SystemChat { + content: reason, + overlay: false, + })); + } + + /// handleChat: the acknowledgements, then the message through the + /// sender's chain, then to everyone. + pub(super) fn handle_chat(&mut self, i: usize, c: play::Chat, events: &mut Vec<HostEvent>) { + let Some(last_seen) = self.apply_last_seen(i, &c.last_seen, events) else { + return; + }; + if !self.try_handle_chat(i, &c.message, false) { + return; + } + let (enforce, now) = (self.enforces_secure_chat(), now_millis()); + let body = Body { + content: &c.message, + timestamp: c.timestamp, + salt: c.salt, + last_seen: &last_seen, + }; + let signature = c.signature.as_deref().and_then(secure_chat::signature); + let g = &mut self.guests[i]; + let (uuid, name) = (g.uuid, g.name.clone()); + let message = match g + .chain + .unpack(uuid, signature.as_ref(), &body, enforce, now) + { + Ok(unpacked) => ChatMessage::new(uuid, unpacked, &body, now), + Err(e) => return self.decode_failure(i, e, events), + }; + if message.signature.is_some() && message.expired(now) { + events.push(HostEvent::Warn(format!( + "Received expired chat: '{}'. Is the client/server system time unsynchronized?", + message.content + ))); + } + let bound = play::ChatTypeBound { + chat_type: self.chat_type, + name: display_name(uuid, &name), + target: None, + }; + let line = format!("<{name}> {}", message.content); + self.broadcast_chat(&message, &bound, line, events); + } + + /// handleChatSessionUpdate: a new profile key, validated against the + /// services' keys, starts a new chain and is announced to everyone. + pub(super) fn chat_session_update( + &mut self, + i: usize, + p: play::ChatSessionUpdate, + events: &mut Vec<HostEvent>, + ) { + let key = ProfileKey { + expires_at: p.expires_at, + key: p.key, + signature: p.key_signature, + }; + let g = &self.guests[i]; + let (conn, uuid) = (g.conn, g.uuid); + let old = g.chain.session().map(|s| s.profile_key.expires_at); + if g.chain.session().is_some_and(|s| s.profile_key == key) { + return; + } + if old.is_some_and(|old| key.expires_at < old) { + self.kick( + conn, + translatable("multiplayer.disconnect.expired_public_key", &[]), + ); + return; + } + let secure = self.lan.shared.config.secure_chat.clone(); + let keys = secure.as_deref().map_or(&[][..], |s| s.keys()); + if keys.is_empty() { + events.push(HostEvent::Warn(format!( + "Ignoring chat session from {} due to missing Services public key", + g.name + ))); + return; + } + match ChatSession::validate(p.session, key, keys, uuid) { + Ok(session) => { + let data = session.data(); + self.guests[i].chain = Chain::keyed(session); + // resetPlayerChatState: INITIALIZE_CHAT to every player. + self.broadcast(&C::PlayerInfoUpdate(play::PlayerInfoUpdate { + actions: 2, + entries: vec![play::PlayerInfo { + uuid, + chat_session: Some(data), + ..Default::default() + }], + })); + } + Err(reason) => { + events.push(HostEvent::Error( + "Failed to validate profile key".to_owned(), + )); + self.kick(conn, translatable(reason, &[])); + } + } + } + + /// PlayerList.broadcastChatMessage: logged (`[Not Secure]` unless signed + /// and fresh), then sent to every player. + pub fn broadcast_chat( + &mut self, + message: &ChatMessage, + bound: &play::ChatTypeBound, + line: String, + events: &mut Vec<HostEvent>, + ) { + let secure = message.trusted(now_millis()); + events.push(HostEvent::Chat { line, secure }); + for k in 0..self.guests.len() { + if self.guests[k].placed { + self.send_chat(k, message, bound); + } + } + } + + /// ServerPlayer.sendChatMessage (players who show chat) and + /// sendPlayerChatMessage: numbered for the connection, the last seen + /// packed against its cache; a signed message joins the cache and the + /// messages the player must acknowledge. + pub fn send_chat(&mut self, k: usize, message: &ChatMessage, bound: &play::ChatTypeBound) { + let g = &mut self.guests[k]; + if g.info.chat_visibility != 0 { + return; + } + let last_seen = message + .last_seen + .iter() + .map(|s| g.signatures.pack(s)) + .collect(); + g.send(&C::PlayerChat(play::PlayerChat { + global_index: g.chat_index, + sender: message.sender, + index: message.index, + signature: message.signature.map(|s| s.to_vec()), + content: message.content.clone(), + timestamp: message.timestamp, + salt: message.salt, + last_seen, + unsigned_content: message.unsigned_content.clone(), + filter: (0, Vec::new()), + chat_type: bound.clone(), + })); + g.chat_index += 1; + if let Some(signature) = &message.signature { + g.signatures.push(&message.last_seen, Some(signature)); + g.last_seen.add_pending(signature); + if g.last_seen.tracked_count() > 4096 { + let conn = g.conn; + self.kick( + conn, + translatable("multiplayer.disconnect.too_many_pending_chats", &[]), + ); + } + } + } + + /// sendChatMessage of a system message: a disguised chat, to players + /// who show chat. + fn send_disguised(&self, k: usize, message: Tag, chat_type: play::ChatTypeBound) { + let g = &self.guests[k]; + if g.info.chat_visibility == 0 { + g.send(&C::DisguisedChat(play::DisguisedChat { + message, + chat_type, + })); + } + } + + /// collectSignedArguments, or collectUnsignedArguments when the client + /// signed none: each of the command's message arguments (`parsed`, by + /// name) through the sender's chain. + pub fn signed_arguments( + &mut self, + i: usize, + p: &play::ChatCommandSigned, + parsed: &[(String, String)], + last_seen: &[Signature], + events: &mut Vec<HostEvent>, + ) -> Result<Vec<(String, ChatMessage)>, DecodeError> { + let (enforce, now) = (self.enforces_secure_chat(), now_millis()); + let g = &mut self.guests[i]; + let uuid = g.uuid; + let mut out = Vec::new(); + if p.arguments.is_empty() { + for (name, value) in parsed { + // SignedMessageBody.unsigned. + let body = Body { + content: value, + timestamp: now, + salt: 0, + last_seen: &[], + }; + let unpacked = g.chain.unpack(uuid, None, &body, enforce, now)?; + out.push((name.clone(), ChatMessage::new(uuid, unpacked, &body, now))); + } + return Ok(out); + } + let mismatch = |events: &mut Vec<HostEvent>| { + let names = |l: &mut dyn Iterator<Item = &String>| { + l.map(String::as_str).collect::<Vec<_>>().join(", ") + }; + events.push(HostEvent::Error(format!( + "Signed command mismatch between server and client ('{}'): got [{}] from client, but expected [{}]", + p.command, + names(&mut p.arguments.iter().map(|a| &a.0)), + names(&mut parsed.iter().map(|a| &a.0)), + ))); + DecodeError::InvalidCommandSignature + }; + for (name, signature) in &p.arguments { + let Some((_, value)) = parsed.iter().find(|(n, _)| n == name) else { + g.chain.set_broken(); + return Err(mismatch(events)); + }; + let body = Body { + content: value, + timestamp: p.timestamp, + salt: p.salt, + last_seen, + }; + let signature = secure_chat::signature(signature); + let unpacked = g + .chain + .unpack(uuid, signature.as_ref(), &body, enforce, now)?; + out.push((name.clone(), ChatMessage::new(uuid, unpacked, &body, now))); + } + if parsed.iter().any(|(n, _)| !out.iter().any(|(o, _)| o == n)) { + return Err(mismatch(events)); + } + Ok(out) + } + + /// A message command's chat (SayCommand, EmoteCommands): to everyone, + /// bound to `chat_type` and the sender's name. + pub fn broadcast_command_chat( + &mut self, + i: usize, + chat_type: &str, + message: Option<ChatMessage>, + text: &str, + events: &mut Vec<HostEvent>, + ) { + let (uuid, name) = (self.guests[i].uuid, self.guests[i].name.clone()); + let bound = play::ChatTypeBound { + chat_type: self.chat_type_id(chat_type), + name: display_name(uuid, &name), + target: None, + }; + let line = match chat_type { + "say_command" => format!("[{name}] {text}"), + _ => format!("* {name} {text}"), + }; + match message { + Some(message) => self.broadcast_chat(&message, &bound, line, events), + // An unsigned command packet (no signing context): + // PlayerChatMessage.system, a disguised chat. + None => { + events.push(HostEvent::Chat { + line, + secure: false, + }); + for k in 0..self.guests.len() { + if self.guests[k].placed { + self.send_disguised(k, literal(text), bound.clone()); + } + } + } + } + } + + /// MsgCommand.sendMessage to each target: the outgoing line for the + /// sender, the incoming one for the target. Nothing is logged. + pub fn whisper( + &mut self, + i: usize, + targets: &[usize], + message: Option<ChatMessage>, + text: &str, + ) { + let (uuid, name) = (self.guests[i].uuid, self.guests[i].name.clone()); + let (outgoing, incoming) = ( + self.chat_type_id("msg_command_outgoing"), + self.chat_type_id("msg_command_incoming"), + ); + for &t in targets { + let target = display_name(self.guests[t].uuid, &self.guests[t].name); + let out = play::ChatTypeBound { + chat_type: outgoing, + name: display_name(uuid, &name), + target: Some(target), + }; + let inc = play::ChatTypeBound { + chat_type: incoming, + name: display_name(uuid, &name), + target: None, + }; + match &message { + Some(m) => { + self.send_chat(i, m, &out); + self.send_chat(t, m, &inc); + } + None => { + self.send_disguised(i, literal(text), out); + self.send_disguised(t, literal(text), inc); + } + } + } + } + + /// A chat type's registry id. + fn chat_type_id(&self, name: &str) -> i32 { + self.sync + .id("minecraft:chat_type", &format!("minecraft:{name}")) + .unwrap_or(self.chat_type) + } +} diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index 7a1d921a4..c2f35bc8e 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -5,6 +5,7 @@ //! ever exchanges decoded packets with these threads through channels, so a //! world that is not open to the network pays nothing. mod advancements; +pub mod attributes; pub mod chunks; mod command_order; pub mod command_suggestions; @@ -122,8 +123,8 @@ pub struct NetConfig { pub hide_online_players: bool, /// server-icon.png (64x64 PNG bytes). pub favicon: Option<Vec<u8>>, - /// MinecraftServer.enforceSecureProfile. - pub enforces_secure_chat: bool, + /// Secure chat (a dedicated server; none on a LAN world). + pub secure_chat: Option<Arc<SecureChat>>, pub accepts_transfers: bool, /// LanServerPinger: announce the world on the local network. pub announce: bool, @@ -138,6 +139,10 @@ pub struct NetConfig { pub log: Option<NetLog>, } impl NetConfig { + /// MinecraftServer.enforceSecureProfile. + pub fn enforces_secure_chat(&self) -> bool { + self.secure_chat.as_ref().is_some_and(|s| s.enforced()) + } /// IntegratedServer.publishServer. pub fn lan(port: u16, motd: String, max_players: usize) -> Self { Self { @@ -149,7 +154,7 @@ impl NetConfig { enable_status: true, hide_online_players: false, favicon: None, - enforces_secure_chat: false, + secure_chat: None, accepts_transfers: false, announce: true, listen: true, @@ -161,6 +166,46 @@ impl NetConfig { } } +/// A dedicated server's secure chat (DedicatedServer.enforceSecureProfile, +/// Services.profileKeySignatureValidator): the services' profile-key keys, +/// fetched in the background from startup and waited for by their first +/// use, as authlib's RetryableFetch does. +pub struct SecureChat { + /// enforce-secure-profile, in online mode. + pub enforce: bool, + keys: std::sync::OnceLock<Vec<horizon_protocol::rsa::RsaPublicKey>>, + fetch: Mutex<Option<JoinHandle<Vec<horizon_protocol::rsa::RsaPublicKey>>>>, +} + +impl SecureChat { + pub fn new( + enforce: bool, + fetch: impl FnOnce() -> Vec<horizon_protocol::rsa::RsaPublicKey> + Send + 'static, + ) -> Self { + let handle = std::thread::Builder::new() + .name("Services keys".into()) + .spawn(fetch) + .ok(); + Self { + enforce, + keys: std::sync::OnceLock::new(), + fetch: Mutex::new(handle), + } + } + /// The keys players' chat keys must be signed by (none when the + /// services couldn't be reached). + pub fn keys(&self) -> &[horizon_protocol::rsa::RsaPublicKey] { + self.keys.get_or_init(|| { + let handle = self.fetch.lock().ok().and_then(|mut h| h.take()); + handle.and_then(|h| h.join().ok()).unwrap_or_default() + }) + } + /// enforceSecureProfile: enforced, and able to check keys. + pub fn enforced(&self) -> bool { + self.enforce && !self.keys().is_empty() + } +} + /// State shared with the connection threads. pub struct Shared { pub sync: Arc<data::SyncData>, @@ -301,7 +346,7 @@ impl Shared { Json::String(format!("data:image/png;base64,{}", base64(icon))), )); } - if self.config.enforces_secure_chat { + if self.config.enforces_secure_chat() { status.push(("enforcesSecureChat".to_owned(), Json::Bool(true))); } Json::Object(status).compact() diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index 44b269a8f..d7dc097dd 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -68,7 +68,9 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.xp_total = level.xp_total; guest.effects = crate::effects::PlayerEffects::from_saved(&level.active_effects); guest.game_mode = level.mode(); + guest.flying = level.flying; guest.selected = (level.selected_slot.max(0) as usize).min(8); + guest.spawn = level.spawn.map(|s| [s[0] + 0.5, s[1], s[2] + 0.5]); guest.saved = level.player_extra.clone(); guest.recipe_book = level.recipe_book.clone(); guest.dimension = match level.dimension.as_str() { @@ -128,7 +130,9 @@ pub fn store(guest: &Guest, level: &mut Level) { level.active_effects = guest.effects.saved(); level.game_mode = guest.game_mode; level.creative = guest.game_mode == 1; + level.flying = guest.flying; level.selected_slot = guest.selected as i32; + level.spawn = guest.spawn.map(|s| [s[0] - 0.5, s[1], s[2] - 0.5]); level.on_ground = guest.on_ground; level.player_extra = guest.saved.clone(); level.recipe_book = guest.recipe_book.clone(); diff --git a/crates/horizon-client/src/lan/waypoints.rs b/crates/horizon-client/src/lan/waypoints.rs index a8797dbaf..852cfc4fb 100644 --- a/crates/horizon-client/src/lan/waypoints.rs +++ b/crates/horizon-client/src/lan/waypoints.rs @@ -10,10 +10,10 @@ //! `waypoint_transmit_range` and tracks or untracks the waypoint, as //! `LivingEntity.onAttributeUpdated` does; joining or leaving a team remakes the //! connections with the team's colour (`ServerScoreboard.updatePlayerWaypoint`). +use crate::fast_hash::FxHashMap as HashMap; use horizon_protocol::packets::play::{ Clientbound as C, TrackedWaypoint, WaypointId, WaypointTarget, waypoint_operation, }; -use std::collections::HashMap; /// `Player.createAttributes`: both waypoint ranges. pub const PLAYER_RANGE: f64 = 6.0e7; @@ -160,7 +160,7 @@ struct Tick<'a> { out: Vec<(u32, C)>, } -impl Tick<'_> { +impl<'a> Tick<'a> { fn send( &mut self, receiver: u128, @@ -172,16 +172,8 @@ impl Tick<'_> { let Some(conn) = self.players.get(&receiver).and_then(|p| p.conn) else { return; }; - self.out.push(( - conn, - C::TrackedWaypoint(TrackedWaypoint { - operation, - id: WaypointId::Uuid(source), - style: icon.style.clone(), - color: icon.color, - target, - }), - )); + self.out + .push((conn, waypoint(source, operation, icon, target))); } fn connect(&mut self, receiver: u128, source: u128, c: &Connection) { let target = match c.kind { @@ -230,11 +222,13 @@ impl Tick<'_> { let d = [0, 1, 2].map(|k| receiver.position[k] - source.position[k]); horizon_core::geometry::trig::atan2(d[0], -d[2]) as f32 } + /// The source and the receiver, if both are in the level this tick. + fn pair(&self, source: u128, receiver: u128) -> Option<(&'a Player, &'a Player)> { + Some((*self.players.get(&source)?, *self.players.get(&receiver)?)) + } /// `LivingEntity.makeWaypointConnectionWith`. - fn make(&self, source: u128, receiver: u128) -> Option<Connection> { - let (s, r) = (self.players.get(&source)?, self.players.get(&receiver)?); - if s.first_tick || self.fresh.contains(&source) || source == receiver || self.ignores(s, r) - { + fn make(&self, (s, r): (&Player, &Player)) -> Option<Connection> { + if s.first_tick || self.fresh.contains(&s.uuid) || s.uuid == r.uuid || self.ignores(s, r) { return None; } // Waypoint.Icon.cloneAndAssignStyle: the icon's colour, else the team's. @@ -244,7 +238,7 @@ impl Tick<'_> { } let kind = if Self::really_far(s, r) { Kind::Azimuth(Self::azimuth(s, r)) - } else if !self.chunk_visible(s.chunk(), receiver) { + } else if !self.chunk_visible(s.chunk(), r.uuid) { Kind::Chunk(s.chunk()) } else { Kind::Block(s.block()) @@ -252,10 +246,8 @@ impl Tick<'_> { Some(Connection { kind, icon }) } /// `Connection.isBroken` for each kind. - fn broken(&self, c: &Connection, source: u128, receiver: u128) -> bool { - let (Some(s), Some(r)) = (self.players.get(&source), self.players.get(&receiver)) else { - return true; - }; + fn broken(&self, c: &Connection, (s, r): (&Player, &Player)) -> bool { + let receiver = r.uuid; match c.kind { Kind::Block(last) => { let now = s.block(); @@ -274,10 +266,7 @@ impl Tick<'_> { } } /// `Connection.update`: the packet when the waypoint moved. - fn update(&mut self, c: &mut Connection, source: u128, receiver: u128) { - let (Some(s), Some(r)) = (self.players.get(&source), self.players.get(&receiver)) else { - return; - }; + fn update(&mut self, c: &mut Connection, (s, r): (&Player, &Player)) { let target = match &mut c.kind { Kind::Block(last) => { let now = s.block(); @@ -304,19 +293,26 @@ impl Tick<'_> { WaypointTarget::Azimuth(now) } }; - let icon = c.icon.clone(); - self.send(receiver, source, waypoint_operation::UPDATE, &icon, target); + if let Some(conn) = r.conn { + self.out.push(( + conn, + waypoint(s.uuid, waypoint_operation::UPDATE, &c.icon, target), + )); + } } } +fn waypoint(source: u128, operation: i32, icon: &Icon, target: WaypointTarget) -> C { + C::TrackedWaypoint(TrackedWaypoint { + operation, + id: WaypointId::Uuid(source), + style: icon.style.clone(), + color: icon.color, + target, + }) +} + impl Waypoints { - fn connection(&mut self, receiver: u128, source: u128) -> Option<&mut Connection> { - self.connections - .get_mut(&receiver)? - .iter_mut() - .find(|(s, _)| *s == source) - .map(|(_, c)| c) - } fn put(&mut self, receiver: u128, source: u128, c: Connection) { let row = self.connections.entry(receiver).or_default(); match row.iter_mut().find(|(s, _)| *s == source) { @@ -335,7 +331,7 @@ impl Waypoints { if receiver == source || !t.enabled { return; } - match t.make(source, receiver) { + match t.pair(source, receiver).and_then(|pair| t.make(pair)) { Some(c) => { t.connect(receiver, source, &c); self.put(receiver, source, c); @@ -347,27 +343,35 @@ impl Waypoints { } } } - /// `updateConnection`. - fn update_connection(&mut self, t: &mut Tick, receiver: u128, source: u128) { + /// The receiver's connection to the source updated in its place + /// (`updateConnection`), or made if it has none (`createConnection`). + fn update_or_create(&mut self, t: &mut Tick, receiver: u128, source: u128) { if receiver == source || !t.enabled { return; } - let Some(mut c) = self.connection(receiver, source).cloned() else { - return; + let Some(row) = self.connections.get_mut(&receiver) else { + return self.create_connection(t, receiver, source); }; - if !t.broken(&c, source, receiver) { - t.update(&mut c, source, receiver); - self.put(receiver, source, c); + let Some(i) = row.iter().position(|(s, _)| *s == source) else { + return self.create_connection(t, receiver, source); + }; + let c = &mut row[i].1; + // A connection to a player who isn't in the level is broken. + let pair = t.pair(source, receiver); + if let Some(pair) = pair + && !t.broken(c, pair) + { + t.update(c, pair); return; } - match t.make(source, receiver) { + match pair.and_then(|pair| t.make(pair)) { Some(new) => { t.connect(receiver, source, &new); - self.put(receiver, source, new); + *c = new; } None => { t.disconnect(receiver, source); - self.take(receiver, source); + row.remove(i); } } } @@ -385,12 +389,9 @@ impl Waypoints { if !self.waypoints.contains(&source) { return; } - for receiver in self.players.clone() { - if self.connection(receiver, source).is_some() { - self.update_connection(t, receiver, source); - } else { - self.create_connection(t, receiver, source); - } + // Connections change; the players don't. + for k in 0..self.players.len() { + self.update_or_create(t, self.players[k], source); } } /// `untrackWaypoint`. @@ -416,12 +417,9 @@ impl Waypoints { } /// `updatePlayer`. fn update_player(&mut self, t: &mut Tick, player: u128) { - for source in self.waypoints.clone() { - if self.connection(player, source).is_some() { - self.update_connection(t, player, source); - } else { - self.create_connection(t, player, source); - } + // Connections change; the waypoints don't. + for k in 0..self.waypoints.len() { + self.update_or_create(t, player, self.waypoints[k]); } } /// `removePlayer`. @@ -454,7 +452,7 @@ impl Waypoints { ) -> Vec<(u32, C)> { let mut t = Tick { players: players.iter().map(|p| (p.uuid, p)).collect(), - view: HashMap::new(), + view: HashMap::default(), fresh: respawned, enabled: locator_bar, out: Vec::new(), diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 45e09a6a3..a3b4be279 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -16,6 +16,7 @@ pub mod banner; pub mod beehive; pub mod benchmark; pub mod biome; +pub mod block_entities; pub mod block_entity_anim; pub mod block_entity_item; pub mod block_entity_nbt; @@ -84,6 +85,7 @@ pub mod hud_layout; pub mod hud_overlays; pub mod hunger; pub mod input; +pub mod interaction_input; pub mod inv_sort; pub mod inventory_effects; pub mod item_data; @@ -132,7 +134,9 @@ pub mod particles; pub mod patrol; pub mod perf_overlay; pub mod pick_item; +pub mod player_sync; pub mod poi_sections; +pub mod portal_sections; pub mod pose; pub mod post; pub mod projectiles; @@ -170,6 +174,7 @@ pub mod telemetry; pub mod testgen; pub mod text; pub mod tick_chunk_membership; +pub mod ticket_levels; pub mod title; pub mod title_edition; pub mod toasts; diff --git a/crates/horizon-client/src/light.rs b/crates/horizon-client/src/light.rs index 595efd9b2..d7ea7d7fd 100644 --- a/crates/horizon-client/src/light.rs +++ b/crates/horizon-client/src/light.rs @@ -14,6 +14,7 @@ //! most 15 blocks, so the 48-wide region determines the centre exactly. //! `relight_block` applies vanilla's incremental decrease/increase passes //! directly to resident chunks after a block change. +use crate::fast_hash::FxHashMap; use crate::{ blocks::BlockFacts, chunk::{Chunk, HEIGHT, Light, MIN_Y, SECTIONS, index}, @@ -44,11 +45,19 @@ pub struct LightTables { /// `faceShapeOccludes(a, b)` for every pair of distinct face shapes. occludes: Vec<bool>, faces: usize, + /// Number of distinct `(shaped, faces)` configurations. + types: usize, + /// Per state: `emission << 16 | type << 4 | dampening`. The low 16 bits are + /// what `light_chunk` stores per cell, so a cell costs 2 bytes and the + /// flood fill never reads the (large) `cells` table. + info: Vec<u32>, + /// `blocked(type_a, type_b, direction)` as a bit per direction. + block_masks: Vec<u8>, } impl LightTables { /// Dampening and emission only: every occlusion face is empty. pub fn new(facts: &BlockFacts) -> Self { - Self { + let mut tables = Self { cells: facts .states .iter() @@ -61,21 +70,64 @@ impl LightTables { .collect(), occludes: vec![false, true, true, true], faces: 2, + types: 1, + info: Vec::new(), + block_masks: Vec::new(), + }; + tables.rebuild_cache(); + tables + } + /// Build the packed per-cell info and the per-configuration blocking masks + /// used by `light_chunk`'s flood fill. + fn rebuild_cache(&mut self) { + let empty: (bool, [u16; 6]) = (false, [EMPTY; 6]); + let mut by_config: HashMap<(bool, [u16; 6]), u16> = HashMap::new(); + by_config.insert(empty, 0); + let mut configs: Vec<(bool, [u16; 6])> = vec![empty]; + let mut info = vec![0u32; self.cells.len()]; + for (id, cell) in self.cells.iter().enumerate() { + let ty = *by_config + .entry((cell.shaped, cell.faces)) + .or_insert_with(|| { + configs.push((cell.shaped, cell.faces)); + (configs.len() - 1) as u16 + }); + let packed = u32::from(ty) << 4 | u32::from(cell.dampening.min(15)); + info[id] = u32::from(cell.emission.min(15)) << 16 | packed; } + let types = configs.len(); + debug_assert!( + types <= 4096, + "light tables: {types} cell configurations exceed the 12-bit type field" + ); + let mut block_masks = vec![0u8; types * types]; + for a in 0..types { + for b in 0..types { + let (shaped_a, faces_a) = configs[a]; + let (shaped_b, faces_b) = configs[b]; + // `blocked`: an unshaped pair covers no face; otherwise the two + // face shapes are compared through the `occludes` table. + if !shaped_a && !shaped_b { + continue; + } + let mut mask = 0u8; + for d in 0..6 { + if self.occludes[faces_a[d] as usize * self.faces + faces_b[d ^ 1] as usize] { + mask |= 1 << d; + } + } + block_masks[a * types + b] = mask; + } + } + self.types = types; + self.info = info; + self.block_masks = block_masks; } /// Full tables with the vanilla occlusion shapes from `occlusion.nbt`. pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> crate::Result<Self> { - use horizon_world::{ - collision::CachedCollisionRegistry, - nbt::{self, Limits}, - }; - let data = nbt::read_named( - &std::fs::read(root.join("occlusion.nbt"))?, - Limits::tables(), - )? - .0 - .tag; - let occlusion = CachedCollisionRegistry::from_nbt(&data, registry)?; + use horizon_world::{collision::CachedCollisionRegistry, registry::BlockTableFile}; + let file = BlockTableFile::open(&root.join("occlusion.nbt"), registry)?; + let occlusion = CachedCollisionRegistry::from_table(file.table("occlusion")?)?; let mut tables = Self::new(facts); let block = VoxelShape::block(); let mut shapes: Vec<VoxelShape> = vec![VoxelShape::empty(), block.clone()]; @@ -147,8 +199,23 @@ impl LightTables { } tables.occludes = occludes; tables.faces = n; + tables.rebuild_cache(); Ok(tables) } + /// Assembled tables (tests and benchmarks): derives the packed light cache. + #[allow(dead_code)] + fn from_parts(cells: Vec<Cell>, occludes: Vec<bool>, faces: usize) -> Self { + let mut tables = Self { + cells, + occludes, + faces, + types: 0, + info: Vec::new(), + block_masks: Vec::new(), + }; + tables.rebuild_cache(); + tables + } /// `LightEngine.shapeOccludes(from, to, direction)`. #[inline] fn blocked(&self, from: usize, to: usize, direction: usize) -> bool { @@ -160,11 +227,21 @@ impl LightTables { let fb = b.faces[direction ^ 1] as usize; self.occludes[fa * self.faces + fb] } + /// `blocked` for two packed cells (`type << 4 | dampening`). + #[inline] + fn packed_blocked(&self, a: u16, b: u16, direction: usize) -> bool { + self.block_masks[(a >> 4) as usize * self.types + (b >> 4) as usize] & (1 << direction) != 0 + } /// `ChunkSkyLightSources.isEdgeOccluded(top, bottom)`. #[inline] fn edge_occluded(&self, top: usize, bottom: usize) -> bool { self.cells[bottom].dampening != 0 || self.blocked(top, bottom, Direction::Down as usize) } + /// `edge_occluded` for two packed cells. + #[inline] + fn packed_edge_occluded(&self, top: u16, bottom: u16) -> bool { + bottom & 0xF != 0 || self.packed_blocked(top, bottom, Direction::Down as usize) + } pub fn emission(&self, state: u32) -> u8 { self.cells[state as usize].emission } @@ -211,7 +288,9 @@ 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![0u32; W * W * h]; + // Packed cells (`type << 4 | dampening`), not state ids: the flood fill + // then never touches the large `LightTables::cells` table. + let mut states = vec![0u16; W * W * h]; let mut sky = vec![0u8; W * W * h]; let mut block = vec![0u8; W * W * h]; let mut queue = VecDeque::new(); @@ -228,10 +307,11 @@ pub fn light_chunk( for (i, &id) in ids.iter().enumerate() { let (lx, lz, ly) = (i & 15, (i >> 4) & 15, i >> 8); let p = at(dx * 16 + lx, si * 16 + ly, dz * 16 + lz); - states[p] = id; - let emission = tables.cells[id as usize].emission; + let info = tables.info[id as usize]; + states[p] = info as u16; + let emission = info >> 16; if emission > 0 { - block[p] = emission; + block[p] = emission as u8; queue.push_back(p as u32); } } @@ -239,20 +319,25 @@ pub fn light_chunk( } } // Columns of missing neighbour chunks neither hold nor pass light. - let present = |x: usize, z: usize| region[z / 16][x / 16].is_some(); + let mut present = vec![false; W * W]; + for z in 0..W { + for x in 0..W { + present[z * W + x] = region[z / 16][x / 16].is_some(); + } + } let mut lowest = vec![h as i32; W * W]; for z in 0..W { for x in 0..W { - if !present(x, z) || !sky_light { + if !present[z * W + x] || !sky_light { continue; } // The top layer (above the occupied range) is always open sky. let mut y = h as i32 - 1; sky[at(x, y as usize, z)] = 15; while y > 0 - && !tables.edge_occluded( - states[at(x, y as usize, z)] as usize, - states[at(x, y as usize - 1, z)] as usize, + && !tables.packed_edge_occluded( + states[at(x, y as usize, z)], + states[at(x, y as usize - 1, z)], ) { y -= 1; @@ -263,7 +348,7 @@ pub fn light_chunk( } for z in 0..W { for x in 0..W { - if !present(x, z) || !sky_light { + if !present[z * W + x] || !sky_light { continue; } let own = lowest[z * W + x]; @@ -274,7 +359,7 @@ pub fn light_chunk( (x, z.wrapping_sub(1)), (x, z + 1), ] { - if nx < W && nz < W && present(nx, nz) { + if nx < W && nz < W && present[nz * W + nx] { deepest = deepest.max(lowest[nz * W + nx]); } } @@ -298,24 +383,40 @@ pub fn light_chunk( let x = p % W; let z = (p / W) % W; let y = p / (W * W); - let from = states[p] as usize; - for (d, (ox, oy, oz)) in OFFSETS.iter().enumerate() { - let (nx, ny, nz) = (x as i32 + ox, y as i32 + oy, z as i32 + oz); - if nx < 0 || nz < 0 || ny < 0 || nx >= W as i32 || nz >= W as i32 || ny >= h as i32 - { - continue; - } - let (nx, ny, nz) = (nx as usize, ny as usize, nz as usize); - if !present(nx, nz) { - continue; - } - let q = at(nx, ny, nz); - let to = states[q] as usize; - let next = level.saturating_sub(tables.cells[to].dampening.max(1)); - if next > light[q] && !tables.blocked(from, to, d) { - light[q] = next; - queue.push_back(q as u32); - } + let from = states[p]; + let col = z * W + x; + // Neighbours by linear offset; `present` only depends on the + // column, and the axis bounds rule out wrapping. + macro_rules! neighbour { + ($d:expr, $q:expr, $ncol:expr) => {{ + if present[$ncol] { + let q = $q; + let to = states[q]; + let next = level.saturating_sub((to & 0xF).max(1) as u8); + if next > light[q] && !tables.packed_blocked(from, to, $d) { + light[q] = next; + queue.push_back(q as u32); + } + } + }}; + } + if y > 0 { + neighbour!(0, p - W * W, col); + } + if y + 1 < h { + neighbour!(1, p + W * W, col); + } + if z > 0 { + neighbour!(2, p - W, col - W); + } + if z + 1 < W { + neighbour!(3, p + W, col + W); + } + if x > 0 { + neighbour!(4, p - 1, col - 1); + } + if x + 1 < W { + neighbour!(5, p + 1, col + 1); } } }; @@ -364,10 +465,8 @@ pub fn apply_lighting(chunk: &mut Chunk, lights: Vec<Light>) { } /// `apply_lighting` for a chunk lit before: writes only the sections whose -/// light changed and returns the block positions that changed. -pub fn apply_relighting(chunk: &mut Chunk, lights: Vec<Light>) -> Vec<(i32, i32, i32)> { - let mut changed = Vec::new(); - let (bx, bz) = (chunk.x * 16, chunk.z * 16); +/// light changed and adds the cells that changed to `changed`. +pub fn apply_relighting(chunk: &mut Chunk, lights: Vec<Light>, changed: &mut LightChanges) { for (sy, (section, light)) in chunk.sections.iter_mut().zip(lights).enumerate() { let old = §ion.light; if let (Light::Uniform(a), Light::Uniform(b)) = (old, &light) @@ -375,17 +474,92 @@ pub fn apply_relighting(chunk: &mut Chunk, lights: Vec<Light>) -> Vec<(i32, i32, { continue; } - let before = changed.len(); + let mut classes = 0; for i in 0..4096 { if old.get(i) != light.get(i) { - let y = MIN_Y + sy as i32 * 16 + (i >> 8) as i32; - changed.push((bx + (i & 15) as i32, y, bz + (i >> 4 & 15) as i32)); + let (x, y, z) = (i as i32 & 15, (i >> 8) as i32, (i >> 4) as i32 & 15); + classes |= 1 << LightChanges::class(x, y, z); } } - if changed.len() > before { + if classes != 0 { + changed.add((chunk.x, sy as i32, chunk.z), classes); Arc::make_mut(section).light = light; } } +} + +/// `DataLayer.get`: the nibble at index `i` (`y << 8 | z << 4 | x`), low first. +#[inline] +fn nibble(layer: &[u8], i: usize) -> u8 { + (layer[i >> 1] >> ((i & 1) * 4)) & 15 +} + +/// A column's light as vanilla stores it, two DataLayers per section (sky, +/// block; `layers[i]` for section `i`, `None` where no layer is stored), into +/// the sections' packed light, which then needs no light job. A missing sky +/// layer repeats the bottom layer of the nearest stored one above it, and +/// `above` (per `z << 4 | x`) above the highest +/// (`SkyLightSectionStorage.getLightValue`); a missing block layer is dark. +pub fn light_from_layers<L: AsRef<[u8]>>( + chunk: &mut Chunk, + layers: &[(Option<L>, Option<L>)], + mut above: [u8; 256], + sky_light: bool, +) { + for (si, (sky, block)) in layers.iter().enumerate().take(SECTIONS).rev() { + let sky = sky.as_ref().filter(|_| sky_light); + let section = Arc::make_mut(&mut chunk.sections[si]); + if sky.is_none() && block.is_none() && above.iter().all(|&v| v == above[0]) { + section.light = Light::Uniform(above[0] << 4); + section.compact(); + continue; + } + let mut data = Box::new([0u8; 4096]); + for (i, packed) in data.iter_mut().enumerate() { + let s = sky.map_or(above[i & 255], |a| nibble(a.as_ref(), i)); + let b = block.as_ref().map_or(0, |a| nibble(a.as_ref(), i)); + *packed = s << 4 | b; + } + for (i, a) in above.iter_mut().enumerate() { + *a = data[i] >> 4; + } + section.light = Light::Full(data); + section.compact(); + } + chunk.lit = true; + chunk.light_loaded = true; +} + +/// A light update's layers (`LevelLightEngine.queueSectionData`): each one +/// given replaces that kind of light in its section, the other kind stays. +/// Returns the sections whose light changed. +pub fn update_light_layers<L: AsRef<[u8]>>( + chunk: &mut Chunk, + layers: &[(Option<L>, Option<L>)], + sky_light: bool, +) -> Vec<usize> { + let mut changed = Vec::new(); + for (si, (sky, block)) in layers.iter().enumerate().take(SECTIONS) { + let sky = sky.as_ref().filter(|_| sky_light); + if sky.is_none() && block.is_none() { + continue; + } + let old = &chunk.sections[si].light; + let mut data = Box::new([0u8; 4096]); + for (i, packed) in data.iter_mut().enumerate() { + let was = old.get(i); + let s = sky.map_or(was >> 4, |a| nibble(a.as_ref(), i)); + let b = block.as_ref().map_or(was & 15, |a| nibble(a.as_ref(), i)); + *packed = s << 4 | b; + } + if (0..4096).all(|i| old.get(i) == data[i]) { + continue; + } + let section = Arc::make_mut(&mut chunk.sections[si]); + section.light = Light::Full(data); + section.compact(); + changed.push(si); + } changed } @@ -432,6 +606,90 @@ impl<S: std::hash::BuildHasher> LightWorld for HashMap<(i32, i32), Arc<Chunk>, S } } type Pos = (i32, i32, i32); +/// Changed light by section, as vanilla's light engine reports it to +/// `LevelRenderer` (`setSectionDirty`) instead of cell by cell: for each +/// section (x, section index, z), a bit per class of position the changed +/// cells take in it, `3 * 3 * 3` classes for the low face, the inside and the +/// high face of each axis. Meshes sample light one block across a face, so the +/// class says which neighbouring sections a change dirties too. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct LightChanges { + sections: FxHashMap<Pos, u32>, +} +impl LightChanges { + /// A cell whose stored light changed. + #[inline] + pub fn push(&mut self, (x, y, z): Pos) { + let key = (x >> 4, (y - MIN_Y) >> 4, z >> 4); + *self.sections.entry(key).or_default() |= 1 << Self::class(x, y, z); + } + /// Cells of section `key` (x, section index, z) in the given classes. + fn add(&mut self, key: Pos, classes: u32) { + *self.sections.entry(key).or_default() |= classes; + } + /// The class of a cell in its section: per axis 0 on the low face, 1 + /// inside, 2 on the high face. + fn class(x: i32, y: i32, z: i32) -> u32 { + let axis = |v: i32| match v & 15 { + 0 => 0, + 15 => 2, + _ => 1, + }; + axis(x) + 3 * axis(y) + 9 * axis(z) + } + pub fn is_empty(&self) -> bool { + self.sections.is_empty() + } + /// The sections (x, section index, z) holding changed cells. + pub fn sections(&self) -> impl Iterator<Item = Pos> + '_ { + self.sections.keys().copied() + } + /// Every section (x, section index, z) whose cells lie within one block + /// of a changed cell, section indexes outside `0..SECTIONS` left out (a + /// section next to several changed ones comes once for each). + pub fn dirty_sections(&self, mut out: impl FnMut(Pos)) { + // Per class, the bit set of neighbour offsets (dx, dy, dz in -1..=1, + // bit (dx + 1) + 3 (dy + 1) + 9 (dz + 1)) its cells reach. + const REACH: [u32; 27] = { + let mut reach = [0; 27]; + let mut class = 0; + while class < 27 { + let axis = [class % 3, class / 3 % 3, class / 9]; + let mut offset = 0; + while offset < 27 { + let d = [offset % 3, offset / 3 % 3, offset / 9]; + // Every class reaches its own section (d = 1, offset 0); + // the low face also -1 (d = 0), the high face +1 (d = 2). + if (d[0] == 1 || d[0] == axis[0]) + && (d[1] == 1 || d[1] == axis[1]) + && (d[2] == 1 || d[2] == axis[2]) + { + reach[class] |= 1 << offset; + } + offset += 1; + } + class += 1; + } + reach + }; + for (&(x, sy, z), &classes) in &self.sections { + let mut offsets = 0; + let mut rest = classes; + while rest != 0 { + offsets |= REACH[rest.trailing_zeros() as usize]; + rest &= rest - 1; + } + while offsets != 0 { + let o = offsets.trailing_zeros() as i32; + offsets &= offsets - 1; + let s = sy + o / 3 % 3 - 1; + if (0..SECTIONS as i32).contains(&s) { + out((x + o % 3 - 1, s, z + o / 9 - 1)); + } + } + } + } +} fn level(world: &impl LightWorld, sky: bool, p: Pos) -> Option<u8> { world .light(p.0, p.1, p.2) @@ -470,8 +728,8 @@ pub fn lowest_sky_source(world: &impl LightWorld, tables: &LightTables, x: i32, /// Vanilla's `checkBlock` + `runLightUpdates` for changed positions on /// resident, lit chunks: clear the light that may have come through or from /// the old states (decrease pass), then re-seed sources and propagate back in -/// from the brighter boundary (increase pass). Returns every position whose -/// stored light changed, for remeshing. `force` clears around each position +/// from the brighter boundary (increase pass). Adds every position whose +/// stored light changed to `changed`, for remeshing. `force` clears around each position /// as if it had been fully lit, for light computed from outdated blocks. pub fn relight( world: &mut impl LightWorld, @@ -479,16 +737,9 @@ pub fn relight( sky_light: bool, positions: &[Pos], force: bool, -) -> Vec<Pos> { - let mut changed = Vec::new(); - relight_layer( - world, - tables, - false, - positions.to_vec(), - force, - &mut changed, - ); + changed: &mut LightChanges, +) { + relight_layer(world, tables, false, positions.to_vec(), force, changed); if sky_light { let mut seeds = positions.to_vec(); let mut columns: HashMap<(i32, i32), i32> = HashMap::new(); @@ -511,11 +762,8 @@ pub fn relight( y -= 1; } } - relight_layer(world, tables, true, seeds, force, &mut changed); + relight_layer(world, tables, true, seeds, force, changed); } - changed.sort_unstable(); - changed.dedup(); - changed } fn relight_layer( world: &mut impl LightWorld, @@ -523,7 +771,7 @@ fn relight_layer( sky: bool, seeds: Vec<Pos>, force: bool, - changed: &mut Vec<Pos>, + changed: &mut LightChanges, ) { let mut decrease: VecDeque<(Pos, u8)> = VecDeque::new(); let mut cleared: Vec<Pos> = Vec::new(); @@ -624,17 +872,17 @@ mod tests { shaped: faces.iter().any(|f| *f != EMPTY), faces, }; - LightTables { - cells: vec![ + LightTables::from_parts( + vec![ cell(0, 0, [EMPTY; 6]), cell(15, 0, [FULL; 6]), cell(0, 14, [EMPTY; 6]), cell(0, 0, [FULL, EMPTY, 2, 2, 2, 2]), ], // empty, full, half: only pairs with a full face cover the square. - occludes: vec![false, true, false, true, true, true, false, true, false], - faces: 3, - } + vec![false, true, false, true, true, true, false, true, false], + 3, + ) } fn world(edit: impl Fn(&mut Chunk)) -> HashMap<(i32, i32), Arc<Chunk>> { let mut chunks = HashMap::new(); @@ -719,7 +967,14 @@ mod tests { ]; for ((x, y, z), state) in edits { Arc::make_mut(w.get_mut(&(0, 0)).unwrap()).set(x, y, z, state); - relight(&mut w, &tables(), true, &[(x, y, z)], false); + relight( + &mut w, + &tables(), + true, + &[(x, y, z)], + false, + &mut LightChanges::default(), + ); } let region: [[Option<&Chunk>; 3]; 3] = std::array::from_fn(|dz| { std::array::from_fn(|dx| w.get(&(dx as i32 - 1, dz as i32 - 1)).map(|c| &**c)) @@ -765,7 +1020,16 @@ mod tests { assert_eq!(edited_snapshot.sections[0].light(index(8, MIN_Y, 8)), 0xF0); let mut world = HashMap::from([((0, 0), Arc::new(current))]); // Streaming replays edits made after the job snapshot with force=true. - relight(&mut world, &tables(), true, &[(8, MIN_Y, 8)], true); + let mut changed = LightChanges::default(); + relight( + &mut world, + &tables(), + true, + &[(8, MIN_Y, 8)], + true, + &mut changed, + ); + assert!(!changed.is_empty()); let region = [[None; 3], [None, Some(&*world[&(0, 0)]), None], [None; 3]]; let fresh = light_chunk(®ion, &tables(), true); for (section, light) in world[&(0, 0)].sections.iter().zip(fresh) { @@ -788,7 +1052,9 @@ mod tests { let sections: Vec<_> = chunk.sections.iter().map(Arc::as_ptr).collect(); // The same light again: nothing changes and no section is copied. let light = lit(&chunk); - assert!(apply_relighting(&mut chunk, light).is_empty()); + let mut changed = LightChanges::default(); + apply_relighting(&mut chunk, light, &mut changed); + assert!(changed.is_empty()); assert_eq!( sections, chunk.sections.iter().map(Arc::as_ptr).collect::<Vec<_>>() @@ -796,8 +1062,8 @@ mod tests { let before = chunk.clone(); chunk.set(3, MIN_Y + 20, 5, STONE); let light = lit(&chunk); - let changed = apply_relighting(&mut chunk, light); - let mut expected = Vec::new(); + apply_relighting(&mut chunk, light, &mut changed); + let mut expected = LightChanges::default(); for (sy, (old, new)) in before.sections.iter().zip(&chunk.sections).enumerate() { for i in 0..4096 { if old.light(i) != new.light(i) { @@ -817,6 +1083,95 @@ mod tests { assert!(copied <= 3, "{copied} sections copied"); } + #[test] + fn changes_dirty_the_sections_within_a_block_of_each_cell() { + // Cells inside sections, on each face and corner, at the bottom and + // top of the world, on negative coordinates. + let mut cells = Vec::new(); + for x in [-17, -16, -1, 0, 7, 15, 16, 31] { + for y in [ + MIN_Y, + MIN_Y + 15, + MIN_Y + 16, + 70, + 79, + 80, + MIN_Y + HEIGHT - 1, + ] { + for z in [-33, -32, 5, 15] { + cells.push((x, y, z)); + } + } + } + for n in [1, 2, cells.len()] { + for start in 0..cells.len().min(8) { + let some: Vec<Pos> = cells.iter().copied().cycle().skip(start).take(n).collect(); + let mut changes = LightChanges::default(); + some.iter().for_each(|&c| changes.push(c)); + let mut dirty = std::collections::BTreeSet::new(); + changes.dirty_sections(|s| { + dirty.insert(s); + }); + let mut expected = std::collections::BTreeSet::new(); + for &(x, y, z) in &some { + for (dx, dy, dz) in (-1..=1) + .flat_map(|a| (-1..=1).flat_map(move |b| (-1..=1).map(move |c| (a, b, c)))) + { + let s = (y + dy - MIN_Y) >> 4; + if (0..SECTIONS as i32).contains(&s) { + expected.insert(((x + dx) >> 4, s, (z + dz) >> 4)); + } + } + } + assert_eq!(dirty, expected, "{some:?}"); + let sections: std::collections::BTreeSet<_> = changes.sections().collect(); + let own: std::collections::BTreeSet<_> = some + .iter() + .map(|&(x, y, z)| (x >> 4, (y - MIN_Y) >> 4, z >> 4)) + .collect(); + assert_eq!(sections, own); + } + } + } + + #[test] + fn stored_layers_fill_the_column_as_vanilla_reads_them() { + // Section 10's sky layer is 7 on its bottom row and 3 above; no + // layers anywhere else; a block layer of 5 in section 2. + let mut sky = vec![0x33u8; 2048]; + sky[..128].fill(0x77); + let mut layers: Vec<(Option<Vec<u8>>, Option<Vec<u8>>)> = vec![(None, None); SECTIONS]; + layers[10].0 = Some(sky); + layers[2].1 = Some(vec![0x55; 2048]); + let mut chunk = Chunk::empty(0, 0); + light_from_layers(&mut chunk, &layers, [15; 256], true); + let at = |c: &Chunk, si: usize, i: usize| c.sections[si].light(i); + assert!(chunk.lit && chunk.light_loaded); + assert!( + matches!(chunk.sections[11].light, Light::Uniform(0xF0)), + "above: open sky" + ); + assert_eq!((at(&chunk, 10, 0), at(&chunk, 10, 4095)), (0x70, 0x30)); + // Below, each section repeats the bottom row of the stored one above. + assert!(matches!(chunk.sections[9].light, Light::Uniform(0x70))); + assert_eq!(at(&chunk, 2, 100), 0x75, "block light only where stored"); + assert!(matches!(chunk.sections[0].light, Light::Uniform(0x70))); + + // A light update replaces one kind of light in the sections it names. + let mut update: Vec<(Option<Vec<u8>>, Option<Vec<u8>>)> = vec![(None, None); SECTIONS]; + update[2].1 = Some(vec![0; 2048]); + update[3].0 = Some(vec![0x77; 2048]); + let changed = update_light_layers(&mut chunk, &update, true); + assert_eq!(changed, vec![2]); + assert!(matches!(chunk.sections[2].light, Light::Uniform(0x70))); + update[3].0 = Some(vec![0xFF; 2048]); + assert_eq!( + update_light_layers(&mut chunk, &update, false), + Vec::<usize>::new(), + "no sky storage" + ); + } + #[test] fn empty_chunk_missing_neighbours_and_no_sky() { let mut chunk = Chunk::empty(0, 0); diff --git a/crates/horizon-client/src/logging.rs b/crates/horizon-client/src/logging.rs index c434c8efb..cb7638f26 100644 --- a/crates/horizon-client/src/logging.rs +++ b/crates/horizon-client/src/logging.rs @@ -330,6 +330,14 @@ pub fn write_only(level: log::Level, message: &str) { } } +/// Writes `message` to the log file only, under the thread vanilla names for it (`Server thread` for +/// a login refused on a connection's own thread), as the console line beside it shows. +pub fn write_as(thread: &str, level: log::Level, message: &str) { + if let Some(logger) = LOGGER.get() { + logger.write(thread, level, message); + } +} + /// The last lines written, oldest first (for crash reports). pub fn recent_lines() -> Vec<String> { LOGGER.get().map_or_else(Vec::new, |l| { diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 5e57edcfc..64286b1fe 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -1668,6 +1668,18 @@ impl Menu { env: &Env, clicked: usize, moved: &ItemStack, + ) -> Result<(), &'static str> { + self.quick_move_all_each(env, clicked, moved, &mut |_, _| {}) + } + + /// `quick_move_all`, calling `each` with the menu and the slot after each + /// QUICK_MOVE (a server's client sends every one of them). + pub fn quick_move_all_each( + &mut self, + env: &Env, + clicked: usize, + moved: &ItemStack, + each: &mut dyn FnMut(&Self, usize), ) -> Result<(), &'static str> { if clicked >= self.slots.len() || !self.can_take_for_pick_all(clicked) { return Ok(()); @@ -1680,6 +1692,7 @@ impl Menu { && self.quick_replace(t, moved, env) { self.click(env, t as i32, 0, Input::QuickMove)?; + each(self, t); } } Ok(()) diff --git a/crates/horizon-client/src/mesher.rs b/crates/horizon-client/src/mesher.rs index c3990f598..2a4efd592 100644 --- a/crates/horizon-client/src/mesher.rs +++ b/crates/horizon-client/src/mesher.rs @@ -7,7 +7,7 @@ mod facing; mod fluid; mod lighting; use crate::{ - assets::Assets, + assets::{Assets, RenderAssets}, biome::Biomes, blocks::{BlockFacts, RenderShape}, chunk::{Chunk, MIN_Y}, @@ -39,16 +39,22 @@ pub struct Vertex { /// RGBA8_SNORM face normal; w = -127 for two-sided lighting, 0 to keep baked/unlit colour. pub normal: [i8; 4], } -/// A section vertex, 28 bytes like vanilla's `DefaultVertexFormat.BLOCK` -/// (position, colour, UV0, UV2) with the sprite's array layer beside the -/// light. Terrain has no normal: `ModelBlockRenderer` bakes the face shade -/// into the colour and `terrain.vsh` only multiplies it by the lightmap. +/// A section vertex: vanilla's `DefaultVertexFormat.BLOCK` (position, colour, +/// UV0, UV2) with the sprite's array layer beside the light, in 24 bytes +/// rather than vanilla's 28: the UV is fixed point, which holds model UVs +/// (multiples of 1/16 and their halves) exactly. The position stays a float: +/// fixed point would move the edges of offset plants and rotated elements by +/// a fraction of a pixel. Terrain has no normal: `ModelBlockRenderer` bakes +/// the face shade into the colour and `terrain.vsh` only multiplies it by the +/// lightmap. #[repr(C)] #[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct TerrainVertex { /// Section-relative position. pub pos: [f32; 3], - pub uv: [f32; 2], + /// UV within the sprite, `UV_STEPS` per unit (`TerrainVertex::new`, + /// `terrain.wgsl`'s `terrain_uv`). + pub(crate) uv: [u16; 2], /// Sprite array layer, with `OPAQUE_LAYER` for opaque leaves. pub layer: u16, /// Smooth light, 16x fixed point: sky in the low byte, block in the high one. @@ -56,6 +62,44 @@ pub struct TerrainVertex { /// RGBA8: tint multiplied by directional shade and ambient occlusion. pub color: u32, } +/// Fixed-point steps per unit of `TerrainVertex` UVs, which span `[0, 2)`. +pub const UV_STEPS: f32 = 32768.0; +impl TerrainVertex { + pub fn new(pos: [f32; 3], uv: [f32; 2], layer: u16, color: u32, light: u16) -> Self { + Self { + pos, + uv: uv.map(|v| (v * UV_STEPS).round().clamp(0.0, f32::from(u16::MAX)) as u16), + layer, + light, + color, + } + } + /// The UV the GPU samples. + pub fn uv(&self) -> [f32; 2] { + self.uv.map(|v| f32::from(v) / UV_STEPS) + } +} +#[cfg(test)] +mod vertex_tests { + use super::TerrainVertex; + #[test] + fn model_uvs_pack_exactly() { + for i in 0..=32 { + let u = i as f32 / 32.0; + let v = TerrainVertex::new([0.0; 3], [u, 1.0 - u], 0, 0, 0); + assert_eq!(v.uv(), [u, 1.0 - u]); + } + } + #[test] + fn other_uvs_round_within_a_step() { + // A flowing fluid's rotated UV. + let uv = [0.5 + 0.25 * 0.3f32.sin(), 0.5 - 0.25 * 0.3f32.cos()]; + let packed = TerrainVertex::new([0.0; 3], uv, 0, 0, 0).uv(); + for (a, b) in packed.iter().zip(uv) { + assert!((a - b).abs() <= 0.5 / 32768.0, "{a} {b}"); + } + } +} pub struct SectionMesh { pub solid: Vec<TerrainVertex>, /// `solid`'s quads by the side they face (`facing`). @@ -258,18 +302,19 @@ fn redstone_color(power: u8) -> u32 { impl MeshTables { pub fn new( assets: &Assets, + render: &RenderAssets, facts: &BlockFacts, visibility: FaceVisibility, ) -> crate::Result<Self> { // Terrain vertices keep the sprite layer below `OPAQUE_LAYER`. - let layers = assets.sprite_layers.values().max().map_or(0, |l| l + 1); + let layers = render.sprite_layers.values().max().map_or(0, |l| l + 1); if layers > u32::from(OPAQUE_LAYER) { return Err( format!("{layers} block sprites, terrain vertices index {OPAQUE_LAYER}").into(), ); } let layer = |name: &str| -> crate::Result<u16> { - assets + render .sprite_layers .get(name) .map(|&l| l as u16) @@ -594,6 +639,7 @@ pub struct Mesher<'a> { /// CardinalLighting.NETHER: brighter up/down faces. pub nether_shading: bool, pub assets: &'a Assets, + pub render: &'a RenderAssets, pub tables: &'a MeshTables, pub biomes: &'a Biomes, pub visibility: FaceVisibility, @@ -663,7 +709,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), world) + let Ok(models) = self.render.model_catalog.collect(BlockStateId(id), world) else { continue; }; @@ -786,18 +832,18 @@ impl Mesher<'_> { None => [g; 3], }; let p = q.positions[i]; - target.push(TerrainVertex { - pos: [p[0] + origin[0], p[1] + origin[1], p[2] + origin[2]], - uv: q.uv[i], + target.push(TerrainVertex::new( + [p[0] + origin[0], p[1] + origin[1], p[2] + origin[2]], + q.uv[i], // Opaque leaves (forceOpaque) draw in the solid layer: no alpha cutout. - layer: if !self.cutout_leaves && state.leaves { + if !self.cutout_leaves && state.leaves { face.layer as u16 | OPAQUE_LAYER } else { face.layer as u16 }, - color: pack_rgb(rgb), - light: pack_coords(lighting::with_emission(coords[i], q.light_emission)), - }); + pack_rgb(rgb), + pack_coords(lighting::with_emission(coords[i], q.light_emission)), + )); } } } diff --git a/crates/horizon-client/src/mesher/facing.rs b/crates/horizon-client/src/mesher/facing.rs index 2a7f0ba61..e82ad6a06 100644 --- a/crates/horizon-client/src/mesher/facing.rs +++ b/crates/horizon-client/src/mesher/facing.rs @@ -175,13 +175,7 @@ mod tests { use super::*; fn vertex(pos: [f32; 3], layer: u16) -> TerrainVertex { - TerrainVertex { - pos, - uv: [0.0; 2], - layer, - light: 0, - color: 0, - } + TerrainVertex::new(pos, [0.0; 2], layer, 0, 0) } /// A unit quad in the plane `axis = plane`, wound to face `sign`, tagged /// with `layer` so tests can follow it. diff --git a/crates/horizon-client/src/mesher/fluid.rs b/crates/horizon-client/src/mesher/fluid.rs index c29f2b92c..6e42685ba 100644 --- a/crates/horizon-client/src/mesher/fluid.rs +++ b/crates/horizon-client/src/mesher/fluid.rs @@ -306,13 +306,7 @@ pub(super) fn tesselate( }; let mut quad = |v: [([f32; 3], [f32; 2]); 4], layer: u16, color: u32, light: u16, back: bool| { - let vertex = |(pos, uv): ([f32; 3], [f32; 2])| TerrainVertex { - pos, - uv, - layer, - color, - light, - }; + let vertex = |(pos, uv)| TerrainVertex::new(pos, uv, layer, color, light); target.extend(v.map(vertex)); if back { target.extend([v[0], v[3], v[2], v[1]].map(vertex)); diff --git a/crates/horizon-client/src/mesher/leaf_culling_tests.rs b/crates/horizon-client/src/mesher/leaf_culling_tests.rs index 9369a1ba2..679b19090 100644 --- a/crates/horizon-client/src/mesher/leaf_culling_tests.rs +++ b/crates/horizon-client/src/mesher/leaf_culling_tests.rs @@ -9,9 +9,10 @@ fn leaf_culling_removes_only_internal_leaf_and_root_faces() { return; } let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let facts = BlockFacts::load(&root, assets.registry).unwrap(); let visibility = crate::models::load_visibility(&root, assets.registry).unwrap(); - let tables = MeshTables::new(&assets, &facts, visibility.clone()).unwrap(); + let tables = MeshTables::new(&assets, &render, &facts, visibility.clone()).unwrap(); let biomes = Biomes::load(&root).unwrap(); let state = |name| assets.registry.default_state(name).unwrap().0; let oak = state("minecraft:oak_leaves"); @@ -31,6 +32,7 @@ fn leaf_culling_removes_only_internal_leaf_and_root_faces() { Mesher { nether_shading: false, assets: &assets, + render: &render, tables: &tables, biomes: &biomes, visibility: visibility.clone(), @@ -49,7 +51,7 @@ fn leaf_culling_removes_only_internal_leaf_and_root_faces() { // preserving every other quad and its full vertex attributes. let without_face = |at: [i32; 3], id, direction| { let vertices = mesh(&[(at, id)], false, true); - let models = assets + let models = render .model_catalog .collect(BlockStateId(id), BlockPos::new(at[0], at[1], at[2])) .unwrap(); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 0611f0c85..3fe743fab 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1400,6 +1400,9 @@ pub struct PlayerView { /// The mobs on the player's team (`isAlliedTo`): combat targeting /// leaves the player alone. pub allies: std::sync::Arc<std::collections::HashSet<u32>>, + /// A LAN guest: its own client moves it, and touching mobs push it there + /// (`EntitySelector.pushableBy` on the client). + pub remote: bool, } pub struct MobWorld<'a> { pub world: &'a World, diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 9ab29d0a5..709a57619 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -429,7 +429,7 @@ pub fn tick( true } /// LivingEntity.updateSwingTime (6-tick swing duration). -fn tick_swing(m: &mut Mob) { +pub fn tick_swing(m: &mut Mob) { if m.ai.swinging { m.ai.swing_time += 1; if m.ai.swing_time >= 6 { @@ -822,10 +822,14 @@ fn push_entities(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) { za *= pow; xa *= f64::from(0.05_f32); za *= f64::from(0.05_f32); - events.push(MobEvent::Push { - target: who, - velocity: [-xa, 0.0, -za], - }); + // A guest's server-side push never reaches its client (ServerPlayer + // motion is synced only when hurt): its client pushes it itself. + if who != Who::Player || w.player.as_ref().is_none_or(|p| !p.remote) { + events.push(MobEvent::Push { + target: who, + velocity: [-xa, 0.0, -za], + }); + } if self_pushable { m.velocity = Vec3::new(m.velocity.x + xa, m.velocity.y, m.velocity.z + za); } @@ -1022,14 +1026,11 @@ fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool { || super::nautilus::is_nautilus(m.species()) && m.extra.tame || m.species() == Species::SulfurCube && (super::sulfur_cube::has_body(m) || m.extra.scratch[3] != 0); - // removeWhenFarAway: animals, wardens, allays, patrols and raiders, - // zombie villagers being cured and ridden mobs stay; the wither's - // checkDespawn never removes it for distance. + // removeWhenFarAway: animals, villagers, golems, patrols and raiders, + // zombie villagers being cured and ridden mobs stay. let creature = m.kind.category == "creature"; - let removable = !(matches!( - m.species(), - Species::Warden | Species::Allay | Species::Wither - ) || creature && m.kind.flags.animal && !m.extra.jockey + let removable = !(never_removed_when_far(m.species()) + || creature && m.kind.flags.animal && !m.extra.jockey || super::raider::keeps_alive(m, d) || super::zombie_villager::keeps_alive(m) || super::riders::keeps_alive(m)); @@ -1055,6 +1056,24 @@ fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool { } true } +/// The types whose `removeWhenFarAway` is always false (`Villager`, +/// `WanderingTrader`, `AbstractGolem`: iron, snow and copper golems and +/// shulkers; `Allay`, `Warden`), and the wither, whose `checkDespawn` never +/// removes it for distance. +fn never_removed_when_far(s: Species) -> bool { + matches!( + s, + Species::Villager + | Species::WanderingTrader + | Species::IronGolem + | Species::SnowGolem + | Species::CopperGolem + | Species::Shulker + | Species::Allay + | Species::Warden + | Species::Wither + ) +} /// Movement speed bonus multiplier (baby zombies are 50% faster, etc.). pub fn speed_bonus(m: &Mob) -> f64 { match m.species() { @@ -1575,3 +1594,25 @@ mod bucket_axolotl_tests { assert_eq!(family(Species::Axolotl), Family::Aquatic); } } +#[cfg(test)] +mod despawn_tests { + use super::*; + /// Village villagers are placed without PersistenceRequired (unlike the + /// village's iron golem), so they must never despawn for distance. + #[test] + fn villagers_traders_and_golems_never_despawn_for_distance() { + for s in [ + Species::Villager, + Species::WanderingTrader, + Species::IronGolem, + Species::SnowGolem, + Species::CopperGolem, + Species::Shulker, + ] { + assert!(never_removed_when_far(s), "{s:?}"); + } + for s in [Species::Zombie, Species::ZombieVillager, Species::Pillager] { + assert!(!never_removed_when_far(s), "{s:?}"); + } + } +} diff --git a/crates/horizon-client/src/mobs/cube.rs b/crates/horizon-client/src/mobs/cube.rs index 3986ffb93..ea8a05392 100644 --- a/crates/horizon-client/src/mobs/cube.rs +++ b/crates/horizon-client/src/mobs/cube.rs @@ -47,14 +47,24 @@ pub fn register(m: &mut Mob) { m.extra.vector[0] = f64::from(180.0 * m.yaw / std::f32::consts::PI); set_size(m, 1); } -/// AbstractCubeMob.setSize: health size^2, speed 0.2 + 0.1 * size, damage size. +/// AbstractCubeMob.setSize(size, true): the max health (size^2), movement +/// speed (0.2 + 0.1 * size, in floats) and attack damage (size) bases, a +/// magma cube's armor (size * 3), then the health back to the max. pub fn set_size(m: &mut Mob, size: i32) { + use super::finalize::{Attr, set_base}; let size = size.clamp(1, 127); m.extra.size = size; - m.attrs.max_health = (size * size) as f32; - m.attrs.speed = 0.2 + 0.1 * f64::from(size); - m.attrs.attack_damage = size as f32; - m.health = m.attrs.max_health; + set_base(m, Attr::MaxHealth, f64::from(size * size)); + set_base( + m, + Attr::MovementSpeed, + f64::from(0.2f32 + 0.1f32 * size as f32), + ); + set_base(m, Attr::AttackDamage, f64::from(size)); + if m.species() == super::Species::MagmaCube { + set_base(m, Attr::Armor, f64::from(size * 3)); + } + m.health = super::finalize::max_health(m); } /// AbstractCubeMob.setSpawnSize: 1, 2 or 4 (normal difficulty special multiplier 0). pub fn finalize(m: &mut Mob) { diff --git a/crates/horizon-client/src/mobs/finalize.rs b/crates/horizon-client/src/mobs/finalize.rs index a3db1ee52..ae6a864cc 100644 --- a/crates/horizon-client/src/mobs/finalize.rs +++ b/crates/horizon-client/src/mobs/finalize.rs @@ -483,7 +483,7 @@ pub fn base_value(m: &Mob, a: Attr) -> f64 { .unwrap_or(if a == Attr::BurningTime { 1.0 } else { 0.0 }) } /// The transient modifiers of the mob's state (`SPEED_MODIFIER_BABY`). -fn transient(m: &Mob, a: Attr) -> Option<(f64, Op)> { +pub fn transient(m: &Mob, a: Attr) -> Option<(f64, Op)> { if a != Attr::MovementSpeed || !m.is_baby() { return None; } @@ -1961,19 +1961,7 @@ fn sulfur_size(m: &mut Mob, size: i32) { m.health = max_health(m); } fn cube_size(m: &mut Mob, size: i32) { - let size = size.clamp(1, 127); - m.extra.size = size; - set_base(m, Attr::MaxHealth, f64::from(size * size)); - set_base( - m, - Attr::MovementSpeed, - f64::from(0.2f32 + 0.1f32 * size as f32), - ); - set_base(m, Attr::AttackDamage, f64::from(size)); - if m.species() == Species::MagmaCube { - set_base(m, Attr::Armor, f64::from(size * 3)); - } - m.health = max_health(m); + super::cube::set_size(m, size); } /// The index the game keeps for a variant registry entry. pub fn variant_index(s: Species, name: &str) -> u8 { diff --git a/crates/horizon-client/src/mobs/spawn_rules.rs b/crates/horizon-client/src/mobs/spawn_rules.rs index 22f9206af..1cdca41b9 100644 --- a/crates/horizon-client/src/mobs/spawn_rules.rs +++ b/crates/horizon-client/src/mobs/spawn_rules.rs @@ -589,11 +589,7 @@ impl SpawnLevel for super::MobWorld<'_> { self.sea_level } fn world_surface(&self, x: i32, z: i32) -> i32 { - let top = crate::chunk::MIN_Y + crate::chunk::HEIGHT; - (crate::chunk::MIN_Y..top) - .rev() - .find(|&y| !self.facts.is_air(self.world.block(x, y, z))) - .map_or(crate::chunk::MIN_Y, |y| y + 1) + self.world.world_surface(x, z, |id| self.facts.is_air(id)) } fn peaceful(&self) -> bool { self.difficulty.effective == 0.0 diff --git a/crates/horizon-client/src/mod_content.rs b/crates/horizon-client/src/mod_content.rs index 25df87352..c396c3333 100644 --- a/crates/horizon-client/src/mod_content.rs +++ b/crates/horizon-client/src/mod_content.rs @@ -674,6 +674,100 @@ pub fn tag_namespaces(root: &Path) -> Vec<String> { /// Bundles of block tag files (tag id → the tag file's text). const TAG_BUNDLES: [&str; 2] = ["block-tags.json", "worldgen/block_tags.json"]; +/// The worldgen loader's bundle of biome tags. +const BIOME_TAGS: &str = "worldgen/biome_tags.json"; +/// Worldgen registries a content mod may add to, and the bundle the +/// worldgen loader reads each from (id → the file's text): what structure +/// mods hold. Biomes, noise and density functions change the terrain and +/// are not read from mods. +const WORLDGEN_BUNDLES: [(&str, &str); 6] = [ + ("structure", "worldgen/structures.json"), + ("structure_set", "worldgen/structure_sets.json"), + ("template_pool", "worldgen/template_pools.json"), + ("processor_list", "worldgen/processor_lists.json"), + ("configured_feature", "worldgen/features.json"), + ("placed_feature", "worldgen/placed_features.json"), +]; + +/// A mod file that adds to a worldgen bundle: (bundle, id). +fn worldgen_entry(file: &str) -> Option<(&'static str, String)> { + let (ns, rest) = file.strip_prefix("data/")?.split_once("/worldgen/")?; + let (kind, path) = rest.split_once('/')?; + let (_, bundle) = WORLDGEN_BUNDLES.iter().find(|(k, _)| *k == kind)?; + Some((bundle, format!("{ns}:{}", path.strip_suffix(".json")?))) +} + +/// The key of a mod's structure set or template pool file that adds its +/// entries to other sets or pools (vanilla's, another mod's) instead of +/// being one of its own. Vanilla data never has it. +const ADD_TO: &str = "horizon:add_to"; +/// The bundles a mod may add to, and the list each entry goes into. +const ADDABLE: [(&str, &str); 2] = [ + ("worldgen/structure_sets.json", "structures"), + ("worldgen/template_pools.json", "elements"), +]; + +/// A mod file's additions (`horizon:add_to`): its entries appended to the +/// list of each set or pool it names, as lithostitched's +/// `add_structure_set_entries` and `add_template_pool_elements` do for +/// NeoForge and Fabric packs. +struct Addition { + targets: Vec<String>, + list: &'static str, + entries: Vec<J>, +} +impl Addition { + /// What a mod file of `bundle` adds, if it is an addition file. + fn read(bundle: &str, text: &str) -> Result<Option<Self>> { + let Some((_, list)) = ADDABLE.iter().find(|(b, _)| *b == bundle) else { + return Ok(None); + }; + if !text.contains(ADD_TO) { + return Ok(None); + } + let doc: J = serde_json::from_str(text)?; + let Some(targets) = doc.get(ADD_TO) else { + return Ok(None); + }; + let targets = match targets { + J::Str(s) => vec![s.clone()], + J::Arr(a) => a + .iter() + .map(|v| match v { + J::Str(s) => Some(s.clone()), + _ => None, + }) + .collect::<Option<_>>() + .ok_or(format!("{ADD_TO}: not a list of ids"))?, + _ => return Err(format!("{ADD_TO}: not an id or a list of ids").into()), + }; + let Some(J::Arr(entries)) = doc.get(list) else { + return Err(format!("{ADD_TO} without a {list} list").into()); + }; + Ok(Some(Self { + targets, + list, + entries: entries.clone(), + })) + } + /// Appends the entries to each target in the bundle `doc` (id → the + /// file's text). A target nobody defines is skipped, as a tag entry + /// naming an unknown id is. + fn apply(&self, doc: &mut J) -> Result<()> { + for target in &self.targets { + let Some(J::Str(text)) = doc.get(target) else { + continue; + }; + let mut v: J = serde_json::from_str(text).map_err(|e| format!("{target}: {e}"))?; + let Some(J::Arr(list)) = v.get_mut(self.list) else { + continue; + }; + list.extend(self.entries.iter().cloned()); + doc.set(target, J::Str(serde_json::to_string(&v)?)); + } + Ok(()) + } +} /// The overlay being written: `out` mirrors `base` through links, and a /// directory becomes real only when something inside it is written. @@ -773,6 +867,9 @@ fn merge_tag(text: Option<&str>, more: &[J], what: &str) -> Result<String> { struct Known { blocks: std::collections::BTreeSet<String>, items: std::collections::BTreeSet<String>, + /// The worldgen loader's biomes and biome tags. + biomes: std::collections::BTreeSet<String>, + biome_tags: std::collections::BTreeSet<String>, /// `data/<ns>/tags/<kind>/<path>.json` files the mods add. tag_files: std::collections::BTreeSet<String>, } @@ -786,14 +883,27 @@ impl Known { items.extend(o.into_iter().map(|(k, _)| k)); } items.extend(plan.items.iter().map(|i| i.rename.to.clone())); + let keys = |name: &str| -> Result<std::collections::BTreeSet<String>> { + Ok(match base.join(name).exists() { + true => match read_json(&base.join(name))? { + J::Obj(o) => o.into_iter().map(|(k, _)| k).collect(), + _ => Default::default(), + }, + false => Default::default(), + }) + }; Ok(Known { blocks, items, + biomes: keys("worldgen/biomes.json")?, + biome_tags: keys(BIOME_TAGS)?, tag_files: tags.keys().cloned().collect(), }) } /// Whether tag `file` keeps entry `v`: a known id or an existing tag, - /// for block and item tags (other registries are kept as they are). + /// for block, item and biome tags (other registries are kept as they + /// are). The worldgen loader refuses a biome tag naming what it lacks + /// (another mod's biomes, a loader's tags), so those entries go. fn keeps(&self, file: &str, v: &J) -> bool { let id = match v { J::Str(s) => s.as_str(), @@ -803,23 +913,32 @@ impl Known { }, _ => return true, }; - let Some(kind) = file + let Some(rest) = file .strip_prefix("data/") .and_then(|r| r.split_once("/tags/")) - .and_then(|(_, rest)| Some(rest.split_once('/')?.0)) + .map(|(_, rest)| rest) else { return true; }; + let kind = match rest.strip_prefix("worldgen/biome/") { + Some(_) => "worldgen/biome", + None => rest.split_once('/').map_or("", |(k, _)| k), + }; let ids = match kind { "block" => &self.blocks, "item" => &self.items, + "worldgen/biome" => &self.biomes, _ => return true, }; match id.strip_prefix('#') { Some(tag) => { let (tns, path) = tag.split_once(':').unwrap_or(("minecraft", tag)); let rel = format!("data/{tns}/tags/{kind}/{path}.json"); - self.tag_files.contains(&rel) || tns == "minecraft" + self.tag_files.contains(&rel) + || match kind { + "worldgen/biome" => self.biome_tags.contains(&format!("{tns}:{path}")), + _ => tns == "minecraft", + } } None => ids.contains(id), } @@ -856,6 +975,8 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { } // Mod files, and every tag addition gathered per tag file. let mut tags: BTreeMap<String, Vec<J>> = BTreeMap::new(); + let mut worldgen: BTreeMap<&str, Vec<(String, String)>> = BTreeMap::new(); + let mut additions: BTreeMap<&str, Vec<Addition>> = BTreeMap::new(); for m in mods { let declarations = format!("data/{}/horizon/", m.id); for file in &m.content.files { @@ -878,6 +999,22 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { .extend(values.iter().cloned()); } else if !file.starts_with(&declarations) { overlay.write(file, &bytes)?; + if let Some((bundle, id)) = worldgen_entry(file) { + let text = String::from_utf8(bytes).map_err(|e| format!("{file}: {e}"))?; + let entries = worldgen.entry(bundle).or_default(); + match Addition::read(bundle, &text).map_err(|e| format!("{file}: {e}"))? { + Some(addition) => additions.entry(bundle).or_default().push(addition), + None => entries.push((id, text)), + } + } else if let Some(template) = file + .strip_prefix("data/") + .and_then(|r| r.split_once("/structure/")) + .filter(|(_, path)| path.ends_with(".nbt")) + { + // The worldgen loader's templates: worldgen/structure/<ns>/<path>.nbt. + let (ns, path) = template; + overlay.write(&format!("worldgen/structure/{ns}/{path}"), &bytes)?; + } } } } @@ -921,6 +1058,44 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { for (name, doc) in &bundles { overlay.write(name, &serde_json::to_vec(doc)?)?; } + // Biome tags, merged into the worldgen loader's bundle as block tags are. + let biome_tags: Vec<(String, &Vec<J>)> = tags + .iter() + .filter_map(|(file, values)| { + let (ns, path) = file + .strip_prefix("data/")? + .split_once("/tags/worldgen/biome/")?; + Some((format!("{ns}:{}", path.strip_suffix(".json")?), values)) + }) + .collect(); + if !biome_tags.is_empty() && base.join(BIOME_TAGS).exists() { + let mut doc = read_json(&base.join(BIOME_TAGS))?; + for (id, values) in biome_tags { + let text = match doc.get(&id) { + Some(J::Str(t)) => Some(t.clone()), + _ => None, + }; + doc.set(&id, J::Str(merge_tag(text.as_deref(), values, BIOME_TAGS)?)); + } + overlay.write(BIOME_TAGS, &serde_json::to_vec(&doc)?)?; + } + // Structures and the pools, sets, processors and features they use, then + // what mods add to sets and pools, in mod and file order. + for (bundle, entries) in &worldgen { + if !base.join(bundle).exists() { + continue; + } + let mut doc = read_json(&base.join(bundle))?; + for (id, text) in entries { + doc.set(id, J::Str(text.clone())); + } + for addition in additions.get(bundle).into_iter().flatten() { + addition + .apply(&mut doc) + .map_err(|e| format!("{bundle}: {e}"))?; + } + overlay.write(bundle, &serde_json::to_vec(&doc)?)?; + } // A block without its own blockstate looks like its template, so every // state still has a model. for m in mods { @@ -943,15 +1118,75 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { /// The root to load: `base` itself with no content, else the mods' overlay /// over it, built in `cache/mod-content`. +/// +/// The root is built once and kept: later starts with the same build, base +/// and mod files reuse it. With ATM10's carried mods a build takes about +/// 25 s and peaks above 3 GB, more than everything the game keeps. pub fn resource_root(base: &Path, mods: &[ContentMod], cache: &Path) -> Result<PathBuf> { if mods.iter().all(|m| m.content.is_empty()) { return Ok(base.to_owned()); } let out = cache.join("mod-content"); + let stamp = stamp(base, mods)?; + if fs::read(out.join(STAMP)).is_ok_and(|s| s == stamp.as_bytes()) { + return Ok(out); + } build(base, mods, &out)?; + fs::write(out.join(STAMP), stamp)?; Ok(out) } +/// In a root built by [`resource_root`]: what it was built from. +const STAMP: &str = "horizon-mod-content.stamp"; + +/// What a content root is built from: this build of the game, the base's +/// manifest and the tables [`build`] rewrites, and every file of every mod +/// in order. Files count by size and modification time, as build tools do. +fn stamp(base: &Path, mods: &[ContentMod]) -> Result<String> { + use sha2::{Digest, Sha256}; + let meta = |path: &Path| -> Result<String> { + let m = fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?; + let modified = m + .modified()? + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default(); + Ok(format!( + "{} {} {}", + path.display(), + m.len(), + modified.as_nanos() + )) + }; + let mut parts = vec!["horizon mod content 1".to_owned()]; + parts.push(meta(&std::env::current_exe()?)?); + let base = std::path::absolute(base)?; + parts.push( + String::from_utf8_lossy(&fs::read(base.join("horizon-resources.json"))?).into_owned(), + ); + for name in JSON_TABLES.iter().chain(&NBT_TABLES).chain(&TAG_BUNDLES) { + if base.join(name).exists() { + parts.push(meta(&base.join(name))?); + } + } + for m in mods { + parts.push(m.id.clone()); + let source = m.content.source(); + if source.is_dir() { + for file in &m.content.files { + parts.push(meta(&source.join(file))?); + } + } else { + parts.push(meta(source)?); + } + } + let mut hasher = Sha256::new(); + for part in &parts { + hasher.update((part.len() as u64).to_le_bytes()); + hasher.update(part.as_bytes()); + } + Ok(format!("{:x}", hasher.finalize())) +} + #[cfg(test)] #[path = "mod_content_tests.rs"] mod tests; diff --git a/crates/horizon-client/src/mod_content_tests.rs b/crates/horizon-client/src/mod_content_tests.rs index 2a040b0fc..c80b45c3e 100644 --- a/crates/horizon-client/src/mod_content_tests.rs +++ b/crates/horizon-client/src/mod_content_tests.rs @@ -502,3 +502,162 @@ fn independent_reloads_read_changed_behaviour_json_and_report_invalid_files() { ); fs::remove_dir_all(&scratch).unwrap(); } + +/// A built root is kept for later starts, and built again when a mod's +/// files change. +#[test] +fn content_root_is_reused_until_a_mod_changes() { + let Some(base) = prepared() else { + return; + }; + let scratch = std::env::temp_dir().join(format!("horizon-mod-reuse-{}", std::process::id())); + let _ = fs::remove_dir_all(&scratch); + let m = ruby_mod(&scratch.join("ruby")); + let cache = scratch.join("cache"); + let root = resource_root(&base, std::slice::from_ref(&m), &cache).unwrap(); + // A rebuild starts from an empty folder: this file tells them apart. + let sentinel = root.join("sentinel"); + fs::write(&sentinel, b"").unwrap(); + assert_eq!( + resource_root(&base, std::slice::from_ref(&m), &cache).unwrap(), + root + ); + assert!(sentinel.exists(), "an unchanged mod rebuilt the root"); + let lang = scratch.join("ruby/assets/ruby/lang/en_us.json"); + fs::write(&lang, r#"{"block.ruby.ruby_block": "Ruby Block"}"#).unwrap(); + let file = fs::File::options().write(true).open(&lang).unwrap(); + file.set_modified(std::time::SystemTime::now() + std::time::Duration::from_secs(5)) + .unwrap(); + resource_root(&base, std::slice::from_ref(&m), &cache).unwrap(); + assert!(!sentinel.exists(), "a changed mod kept the old root"); + assert!( + fs::read_to_string(root.join("assets/ruby/lang/en_us.json")) + .unwrap() + .contains("Ruby Block") + ); + let _ = fs::remove_dir_all(&scratch); +} + +/// A structure mod's worldgen reaches the worldgen loader: its structure, +/// set, pool and templates join the bundles, and its biome tag keeps only +/// what the loader knows. +#[test] +fn content_root_carries_a_structure_mod() { + let Some(base) = prepared() else { + return; + }; + let scratch = std::env::temp_dir().join(format!("horizon-mod-worldgen-{}", std::process::id())); + let _ = fs::remove_dir_all(&scratch); + let dir = scratch.join("huts"); + let files = [ + ( + "horizon-mod.toml", + "id = \"huts\"\nname = \"Huts\"\nversion = \"1.0\"\napi = \"0.2\"\nside = \"both\"\ncapabilities = [\"registries\"]\n", + ), + ( + "data/huts/worldgen/structure/hut.json", + r##"{"type": "minecraft:jigsaw", "biomes": "#huts:has_hut", "step": "surface_structures", + "spawn_overrides": {}, "terrain_adaptation": "beard_thin", "start_pool": "huts:hut/start", + "size": 1, "start_height": {"absolute": 0}, "project_start_to_heightmap": "WORLD_SURFACE_WG", + "max_distance_from_center": 80}"##, + ), + ( + "data/huts/worldgen/template_pool/hut/start.json", + r#"{"fallback": "minecraft:empty", "elements": [{"weight": 1, "element": { + "element_type": "minecraft:single_pool_element", "location": "huts:hut", + "projection": "rigid", "processors": "minecraft:empty"}}]}"#, + ), + ( + "data/huts/worldgen/structure_set/huts.json", + r#"{"structures": [{"structure": "huts:hut", "weight": 1}], + "placement": {"type": "minecraft:random_spread", "salt": 7, "spacing": 4, "separation": 2}}"#, + ), + ( + "data/huts/tags/worldgen/biome/has_hut.json", + r##"{"values": ["#minecraft:is_overworld", "#c:is_plains", "othermod:glade", "minecraft:plains"]}"##, + ), + // Additions to vanilla's set and pool; a target nobody defines is skipped. + ( + "data/huts/worldgen/structure_set/added/villages.json", + r#"{"horizon:add_to": "minecraft:villages", + "structures": [{"structure": "huts:hut", "weight": 3}]}"#, + ), + ( + "data/huts/worldgen/template_pool/added/houses.json", + r#"{"horizon:add_to": ["othermod:houses", "minecraft:village/plains/houses"], + "elements": [{"weight": 2, "element": {"element_type": "minecraft:single_pool_element", + "location": "huts:hut", "projection": "rigid", "processors": "minecraft:empty"}}]}"#, + ), + ]; + for (name, text) in files { + let path = dir.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); + } + // The template: vanilla's smallest plains house, as the mod's own file. + let house = + base.join("worldgen/structure/minecraft/village/plains/houses/plains_small_house_1.nbt"); + fs::create_dir_all(dir.join("data/huts/structure")).unwrap(); + fs::copy(&house, dir.join("data/huts/structure/hut.nbt")).unwrap(); + let package = horizon_mods::Package::read(&dir).unwrap(); + let m = ContentMod { + id: "huts".into(), + content: Content::read(&dir, &package.manifest).unwrap(), + }; + let root = resource_root(&base, &[m], &scratch.join("cache")).unwrap(); + assert!(root.join("worldgen/structure/huts/hut.nbt").exists()); + let tags: BTreeMap<String, String> = + serde_json::from_slice(&fs::read(root.join("worldgen/biome_tags.json")).unwrap()).unwrap(); + let hut: serde_json::Value = serde_json::from_str(&tags["huts:has_hut"]).unwrap(); + assert_eq!( + hut["values"], + serde_json::json!(["#minecraft:is_overworld", "minecraft:plains"]) + ); + // The additions join vanilla's entries at the end and are no set or pool + // of their own. + let bundle = |name: &str, base: &Path| -> BTreeMap<String, String> { + serde_json::from_slice(&fs::read(base.join("worldgen").join(name)).unwrap()).unwrap() + }; + for (name, id, list, added) in [ + ( + "structure_sets.json", + "minecraft:villages", + "structures", + serde_json::json!({"structure": "huts:hut", "weight": 3}), + ), + ( + "template_pools.json", + "minecraft:village/plains/houses", + "elements", + serde_json::json!({"weight": 2, "element": {"element_type": "minecraft:single_pool_element", + "location": "huts:hut", "projection": "rigid", "processors": "minecraft:empty"}}), + ), + ] { + let (ours, vanilla) = (bundle(name, &root), bundle(name, &base)); + let entries = |text: &str| -> Vec<serde_json::Value> { + let v: serde_json::Value = serde_json::from_str(text).unwrap(); + v[list].as_array().unwrap().clone() + }; + let mut expected = entries(&vanilla[id]); + expected.push(added); + assert_eq!(entries(&ours[id]), expected, "{id}"); + assert!(!ours.keys().any(|k| k.starts_with("huts:added/")), "{name}"); + assert!(!ours.contains_key("othermod:houses")); + } + + let assets = Assets::load(&root).unwrap(); + let biomes = crate::biome::Biomes::load(&root).unwrap(); + let terrain = crate::vanillagen::VanillaTerrain::new( + &root.join("worldgen"), + assets.registry, + &biomes, + 1234, + ) + .unwrap(); + let (name, at) = terrain + .locate(&["huts:hut".to_owned()], [0, 64, 0], 16) + .expect("the mod's structure generates"); + assert_eq!(name, "huts:hut"); + assert!(at[0].abs() < 1024 && at[2].abs() < 1024, "{at:?}"); + let _ = fs::remove_dir_all(&scratch); +} diff --git a/crates/horizon-client/src/models.rs b/crates/horizon-client/src/models.rs index 110166f29..5979672e9 100644 --- a/crates/horizon-client/src/models.rs +++ b/crates/horizon-client/src/models.rs @@ -117,13 +117,11 @@ pub fn load_visibility( use horizon_world::{ block_render::{FaceVisibility, RenderDefinition, SkipRendering}, collision::CachedCollisionRegistry, - nbt::{self, Limits}, + registry::BlockTableFile, }; use std::{collections::BTreeMap, fs}; - let data = nbt::read_named(&fs::read(root.join("occlusion.nbt"))?, Limits::tables())? - .0 - .tag; - let occlusion = CachedCollisionRegistry::from_nbt(&data, registry)?; + let file = BlockTableFile::open(&root.join("occlusion.nbt"), registry)?; + let occlusion = CachedCollisionRegistry::from_table(file.table("occlusion")?)?; let raw: BTreeMap<String, Value> = serde_json::from_slice(&fs::read(root.join("render-definitions.json"))?)?; let definitions = raw diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 7dab3a5aa..293aa61a2 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -31,8 +31,7 @@ use horizon_world::{ movement_restitution::{self, RestitutionInput, RestitutionWorld}, movement_statistics::{self, MovementStat, MovementStatisticsWorld}, movement_support::{self, MovementLocation}, - nbt::{self, Limits}, - registry::BlockStateId, + registry::{BlockStateId, BlockTableFile}, world_movement::{self, MovementRequest}, worldgen::tags::TagDefinitions, }; @@ -57,17 +56,27 @@ pub struct MotionResources { pub fluids: FluidResources, } impl MotionResources { + /// [`Self::load_with_facts`] with the block facts decoded here. pub fn load(root: &Path, assets: &Assets) -> Result<Self> { + Self::load_with_facts( + root, + assets, + &crate::blocks::BlockFacts::load(root, assets.registry)?, + ) + } + /// The motion tables, with the block facts the game already decoded + /// (decoding `gameplay-facts.json` again costs a second or more and, with + /// a big modpack, hundreds of megabytes while it runs). + pub fn load_with_facts( + root: &Path, + assets: &Assets, + facts: &crate::blocks::BlockFacts, + ) -> Result<Self> { let attributes = Arc::new(Catalog::from_json(&serde_json::from_slice(&fs::read( root.join("attributes.json"), )?)?)?); - let data = nbt::read_named( - &fs::read(root.join("movement-properties.nbt"))?, - Limits::tables(), - )? - .0 - .tag; - let properties = MovementProperties::from_nbt(&data, assets.registry)?; + let file = BlockTableFile::open(&root.join("movement-properties.nbt"), assets.registry)?; + let properties = MovementProperties::from_table(file.table("movement")?)?; let bundle: BTreeMap<String, String> = serde_json::from_slice(&fs::read(root.join("block-tags.json"))?)?; let mut definitions = TagDefinitions::default(); @@ -91,7 +100,7 @@ impl MotionResources { Ok(Self { landing: crate::landing::load(root, &properties)?, health: crate::health::HealthResources::load(root)?, - fluids: FluidResources::load(root, assets)?, + fluids: FluidResources::new(assets, facts)?, attributes, blocks: properties.bind(&MovementTags { fences: tag("minecraft:fences")?, @@ -309,6 +318,7 @@ impl PlayerMotion { self.set_health(level.health, false)?; self.health.food.food = level.food; self.health.food.saturation = level.saturation; + self.flying = level.flying; } Ok(()) } @@ -639,7 +649,8 @@ impl MotionWorld<'_, '_, '_> { entities: self.entities, } } - pub(crate) fn no_player_collision(&mut self, bounds: Aabb) -> Result<bool> { + /// `Level.noCollision(player, bounds)`: blocks and the host's entity boxes. + pub fn no_player_collision(&mut self, bounds: Aabb) -> Result<bool> { let context = self.context(); Ok(world_movement::no_world_collision( &mut self.movement_collisions(), @@ -2048,9 +2059,10 @@ mod tests { return; } let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let binding = crate::collisions::load(&root, assets.registry).unwrap(); let resources = MotionResources::load(&root, &assets).unwrap(); - let mut scene = World::test_scene(&assets, 1).unwrap(); + let mut scene = World::test_scene(&assets, &render, 1).unwrap(); let entities = [Aabb::new( Vec3::new(10.0, 80.0, 10.0), Vec3::new(14.0, 84.0, 14.0), @@ -2118,10 +2130,11 @@ mod tests { return; } let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let binding = crate::collisions::load(&root, assets.registry).unwrap(); let resources = MotionResources::load(&root, &assets).unwrap(); let run = |name: &str, spectator: bool| { - let mut scene = World::test_scene(&assets, 2).unwrap(); + let mut scene = World::test_scene(&assets, &render, 2).unwrap(); let state = assets.registry.default_state(name).unwrap(); for x in 19..=23 { for y in 10..=17 { @@ -2357,10 +2370,11 @@ mod tests { return; } let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let binding = crate::collisions::load(&root, assets.registry).unwrap(); let resources = MotionResources::load(&root, &assets).unwrap(); for wet in [false, true] { - let mut scene = World::test_scene(&assets, 2).unwrap(); + let mut scene = World::test_scene(&assets, &render, 2).unwrap(); if wet { let water = assets.registry.default_state("minecraft:water").unwrap(); for x in 19..=21 { @@ -2403,9 +2417,10 @@ mod tests { return; } let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let binding = crate::collisions::load(&root, assets.registry).unwrap(); let resources = MotionResources::load(&root, &assets).unwrap(); - let mut scene = World::test_scene(&assets, 3).unwrap(); + let mut scene = World::test_scene(&assets, &render, 3).unwrap(); let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap(); let water = assets.registry.default_state("minecraft:water").unwrap(); for x in 19..=21 { @@ -2610,6 +2625,7 @@ mod tests { food: 11, saturation: 2.25, player_extra: Some(extra), + flying: true, ..Default::default() }; let mut pending = true; @@ -2617,6 +2633,7 @@ mod tests { .load_saved_state_once(&mut pending, &level) .unwrap(); assert_eq!((w.player.fire_ticks, w.player.air), (160, 8)); + assert!(w.player.flying); assert_eq!( ( w.player.health.health(), @@ -2628,6 +2645,7 @@ mod tests { let mut respawn = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap(); respawn.load_saved_state_once(&mut pending, &level).unwrap(); assert_eq!((respawn.fire_ticks, respawn.air), (-20, 300)); + assert!(!respawn.flying); assert_eq!( (respawn.health.health(), respawn.health.food.food), (20.0, 20) @@ -2654,9 +2672,10 @@ mod tests { return; } let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let binding = crate::collisions::load(&root, assets.registry).unwrap(); let resources = MotionResources::load(&root, &assets).unwrap(); - let mut scene = World::test_scene(&assets, 3).unwrap(); + let mut scene = World::test_scene(&assets, &render, 3).unwrap(); let water = assets.registry.default_state("minecraft:water").unwrap(); for y in 4..=6 { scene.set(20, y, 20, water).unwrap(); @@ -2726,10 +2745,11 @@ mod tests { return; } let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let binding = crate::collisions::load(&root, assets.registry).unwrap(); let resources = MotionResources::load(&root, &assets).unwrap(); for name in ["minecraft:lava", "minecraft:water"] { - let mut scene = World::test_scene(&assets, 3).unwrap(); + let mut scene = World::test_scene(&assets, &render, 3).unwrap(); let fluid = assets.registry.default_state(name).unwrap(); scene.set(20, 4, 20, fluid).unwrap(); let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap(); @@ -2777,9 +2797,10 @@ mod tests { return; } let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let binding = crate::collisions::load(&root, assets.registry).unwrap(); let resources = MotionResources::load(&root, &assets).unwrap(); - let mut scene = World::test_scene(&assets, 3).unwrap(); + let mut scene = World::test_scene(&assets, &render, 3).unwrap(); let water = assets.registry.default_state("minecraft:water").unwrap(); scene.set(20, 4, 20, water).unwrap(); scene.set(20, 5, 20, water).unwrap(); @@ -2846,10 +2867,11 @@ mod tests { return; } let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let binding = crate::collisions::load(&root, assets.registry).unwrap(); let resources = MotionResources::load(&root, &assets).unwrap(); for (water_level, lava_level, ground_jump) in [(0, 6, true), (6, 0, false)] { - let mut scene = World::test_scene(&assets, 3).unwrap(); + let mut scene = World::test_scene(&assets, &render, 3).unwrap(); for (name, level, x) in [ ("minecraft:water", water_level, 20), ("minecraft:lava", lava_level, 21), @@ -2894,7 +2916,8 @@ mod tests { return; } let assets = Assets::load(&root).unwrap(); - let mut scene = World::test_scene(&assets, 3).unwrap(); + let render = assets.reload(&root).unwrap(); + let mut scene = World::test_scene(&assets, &render, 3).unwrap(); let binding = crate::collisions::load(&root, assets.registry).unwrap(); let resources = MotionResources::load(&root, &assets).unwrap(); let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap(); diff --git a/crates/horizon-client/src/motion/fluids.rs b/crates/horizon-client/src/motion/fluids.rs index f85f755a9..89affeb64 100644 --- a/crates/horizon-client/src/motion/fluids.rs +++ b/crates/horizon-client/src/motion/fluids.rs @@ -33,8 +33,7 @@ pub struct FluidResources { pub shapes: Mutex<FluidShapeCache>, } impl FluidResources { - pub fn load(root: &Path, assets: &Assets) -> Result<Self> { - let facts = crate::blocks::BlockFacts::load(root, assets.registry)?; + pub fn new(assets: &Assets, facts: &crate::blocks::BlockFacts) -> Result<Self> { Ok(Self { states: FluidStateTable::new(assets.registry)?, sturdy: facts.states.iter().map(|s| s.sturdy_full).collect(), diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index f9ad5992a..74f1b0b6d 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -1,7 +1,8 @@ //! Multiplayer session: a network thread that connects to a server, logs in, //! runs the configuration phase and then forwards decoded play packets to the -//! game thread. Keep-alives and pings are answered on the network thread like -//! vanilla's connection handlers so a busy frame never times the client out. +//! game thread. Keep-alives are answered on the network thread; pings wait for +//! the game thread, like ClientCommonPacketListenerImpl.handlePing, so a pong +//! cannot overtake an earlier world update or teleport acknowledgement. //! Online-mode servers need the Microsoft account the launcher signed in //! (crate::auth): the login joins the server through the session service and //! encrypts the connection (ClientHandshakePacketListenerImpl.handleHello). @@ -382,8 +383,17 @@ fn run( uuid: profile.uuid, name: profile.name, }); + receive_play(&mut reader, shared_writer, lang, send) +} + +fn receive_play( + reader: &mut ConnReader, + shared_writer: &Mutex<Option<ConnWriter>>, + lang: &Language, + send: &Sender<Event>, +) -> Result<String, String> { loop { - let (id, payload) = reader.recv().map_err(e)?; + let (id, payload) = reader.recv().map_err(|e| e.to_string())?; let packet = match play::Clientbound::decode(id, &payload) { Ok(p) => p, Err(err) => { @@ -404,7 +414,6 @@ fn run( }; match packet { play::Clientbound::KeepAlive(k) => reply(play::Serverbound::KeepAlive(k)), - play::Clientbound::Ping(p) => reply(play::Serverbound::Pong(p)), play::Clientbound::BundleDelimiter(_) => {} play::Clientbound::ResourcePackPush(p) => { // Declined: Horizon has no server resource packs. @@ -415,7 +424,7 @@ fn run( } play::Clientbound::StartConfiguration(_) => { reply(play::Serverbound::ConfigurationAcknowledged(Empty)); - let registries = configure(&mut reader, shared_writer, lang, send)?; + let registries = configure(reader, shared_writer, lang, send)?; let _ = send.send(Event::Reconfigured(Arc::new(registries))); } play::Clientbound::Disconnect(d) => return Ok(plain(&d.reason, lang)), @@ -585,6 +594,50 @@ pub fn ping(address: &str, timeout: Duration) -> Result<(serde_json::Value, u128 mod tests { use super::*; + #[test] + fn pings_wait_behind_teleports_but_keepalives_do_not_wait_for_the_game() { + let (client, server) = horizon_protocol::connection::Pipe::pair(); + let (mut reader, writer) = Connection::local(client).split(); + let writer = Arc::new(Mutex::new(Some(writer))); + let (send, events) = channel(); + let thread_writer = writer.clone(); + let thread = std::thread::spawn(move || { + receive_play(&mut reader, &thread_writer, &Language::new(), &send) + }); + let mut server = Connection::local(server); + let teleport = play::Clientbound::PlayerPosition(play::PlayerPosition { + teleport: 42, + position: [10.0, 64.0, 10.0], + delta: [0.0; 3], + yaw: 90.0, + pitch: 0.0, + relatives: 0, + }); + server.send(&teleport.encode()).unwrap(); + server + .send(&play::Clientbound::Ping(cfg::Ping { id: 7 }).encode()) + .unwrap(); + // A reply to this proves the receive loop has passed the ping. The + // old implementation instead replies with Pong before this keepalive. + server + .send(&play::Clientbound::KeepAlive(cfg::KeepAlive { id: 9 }).encode()) + .unwrap(); + let (id, body) = server.recv().unwrap(); + assert_eq!( + play::Serverbound::decode(id, &body).unwrap(), + play::Serverbound::KeepAlive(cfg::KeepAlive { id: 9 }) + ); + let timeout = Duration::from_secs(5); + assert!( + matches!(events.recv_timeout(timeout).unwrap(), Event::Packet(p) if *p == teleport) + ); + assert!( + matches!(events.recv_timeout(timeout).unwrap(), Event::Packet(p) if *p == play::Clientbound::Ping(cfg::Ping { id: 7 })) + ); + writer.lock().unwrap().take().unwrap().shutdown(); + assert!(thread.join().unwrap().is_err()); + } + #[test] fn server_brand_payload_is_decoded_and_invalid_or_unrelated_payloads_are_ignored() { let (send, events) = channel(); diff --git a/crates/horizon-client/src/options_horizon.rs b/crates/horizon-client/src/options_horizon.rs index d3ecab639..b0a64c7e5 100644 --- a/crates/horizon-client/src/options_horizon.rs +++ b/crates/horizon-client/src/options_horizon.rs @@ -36,6 +36,8 @@ pub enum HRow { Extra(extras::Item), /// Installed mod `i` (`settings.mods.installed`) and its switch. Mod(usize), + /// Opens the directory where Horizon mods are installed. + OpenModFolder, } /// A sidebar section: name, description, rows. pub struct Section { @@ -192,12 +194,15 @@ pub const SECTIONS: &[Section] = &[ name: "Mods", blurb: "Mods made for Horizon, from the horizon-mods folder. Each runs in a sandbox and stays off until you turn it on; check what it may do first.", rows: |s| { + let mut rows = vec![HRow::OpenModFolder]; if s.mods.installed.is_empty() { - return vec![HRow::Header( + rows.push(HRow::Header( "No mods: put .hmod files in the horizon-mods folder", - )]; + )); + } else { + rows.extend((0..s.mods.installed.len()).map(HRow::Mod)); } - (0..s.mods.installed.len()).map(HRow::Mod).collect() + rows }, }, ]; @@ -207,8 +212,15 @@ const DONE: u64 = id("options.done", 0); const ROW: u64 = id("options.row", 0); const STYLE: u64 = id("options.style", 0); const LEVEL: u64 = id("options.level", 0); +const SEARCH: u64 = id("options.search", 0); const ROW_H: f32 = 12.0 + CONTROL + 12.0; const HEADER_H: f32 = 40.0; +pub(crate) fn searchable_section(section: usize) -> bool { + matches!( + SECTIONS.get(section).map(|s| s.name), + Some("Video" | "Controls") + ) +} /// Whether an option is an on/off switch, and its value. fn switch_value(opt: Opt, s: &Settings) -> Option<bool> { @@ -258,6 +270,7 @@ fn caption_value(opt: Opt, s: &Settings) -> (String, String) { enum Target { Nav(usize), Done, + Search, Row(usize), Slider(Item, f32), Style(usize), @@ -283,6 +296,22 @@ fn horizon_batch(framebuffer: [i32; 2]) -> HudBatch { HudBatch::new([framebuffer[0].max(1) as u32, framebuffer[1].max(1) as u32]) } impl OptionsUi { + fn horizon_rows(&self, s: &Settings, section: usize) -> Vec<HRow> { + let rows = (SECTIONS[section].rows)(s); + let query = self.settings_search.value.to_lowercase(); + if query.is_empty() || !searchable_section(section) { + return rows; + } + rows.into_iter() + .filter(|row| match row { + HRow::Opt(opt) => caption_value(*opt, s).0.to_lowercase().contains(&query), + HRow::Graphics(item, ..) => item.caption_value(s).0.to_lowercase().contains(&query), + HRow::Page(label, ..) => label.to_lowercase().contains(&query), + HRow::Level => true, + _ => false, + }) + .collect() + } /// Lay out (and draw, on a real frame) the Horizon options shell. /// Returns the sliders' tracks and the scroll area for pointer input. fn horizon_layout(&mut self, s: &Settings, ui: &mut Ui, backdrop: f32) -> HorizonLayout { @@ -321,8 +350,17 @@ impl OptionsUi { let sec = &SECTIONS[section]; let mut y = 36.0; y += ui.page_header(x, y, sec.name, sec.blurb) + 24.0; + if searchable_section(section) { + ui.text_field( + SEARCH, + [x + cw - 240.0, y, 240.0, CONTROL], + &self.settings_search.value, + self.settings_search.focused, + ); + y += CONTROL + 12.0; + } let top = y; - let rows = (sec.rows)(s); + let rows = self.horizon_rows(s, section); let content: f32 = rows .iter() .map(|r| { @@ -450,6 +488,18 @@ impl OptionsUi { ui.described_row(x, y, &installed.title, "", 0.0, cost, text, cw - 60.0); ui.switch(ROW + i as u64, control_x, y + ROW_H / 2.0, s.mods.is_on(m)); } + HRow::OpenModFolder => { + ui.row(x, y, "Mod folder", "", 0.0); + let label = "Open Folder"; + let bw = ui.button_width(label, false).max(96.0); + ui.button( + ROW + i as u64, + [control_x - bw, y + 12.0, bw, CONTROL], + label, + Button::Secondary, + true, + ); + } HRow::Extra(item) => { let cy = y + ROW_H / 2.0; let id = ROW + i as u64; @@ -569,6 +619,9 @@ impl OptionsUi { let Some(hit) = ui.hit((x, y)) else { return (None, scrollbar, cursor); }; + if hit == SEARCH { + return (Some(Target::Search), scrollbar, cursor); + } let section = self.section.min(SECTIONS.len() - 1); if (NAV..NAV + SECTIONS.len() as u64).contains(&hit) { return (Some(Target::Nav((hit - NAV) as usize)), scrollbar, cursor); @@ -593,7 +646,7 @@ impl OptionsUi { let Some(i) = hit.checked_sub(ROW).map(|i| i as usize) else { return (None, scrollbar, cursor); }; - let rows = (SECTIONS[section].rows)(s); + let rows = self.horizon_rows(s, section); let item = match rows.get(i) { Some(HRow::Opt(opt)) => Some(Item::Vanilla(*opt)), Some(HRow::Graphics(item, ..)) => Some(*item), @@ -670,6 +723,7 @@ impl OptionsUi { ); } let (target, scrollbar, cursor) = self.horizon_target(s, atlas, x, y, framebuffer); + self.settings_search.focused = false; // AbstractScrollArea.updateScrolling grabs anywhere in the scrollbar column. if !right && let Some(scrollbar) = scrollbar @@ -680,9 +734,16 @@ impl OptionsUi { } match target { Some(Target::Nav(i)) => { + if searchable_section(self.section) || searchable_section(i) { + self.settings_search.set_value(""); + } self.section = i; self.hscroll = 0.0; } + Some(Target::Search) => { + self.settings_search.focused = true; + self.settings_search.move_cursor_to_end(false); + } Some(Target::Done) => events.extend(self.back(s)), Some(Target::Style(i)) => { t::set_style(if i == 1 { @@ -706,7 +767,7 @@ impl OptionsUi { } Some(Target::Row(i)) => { let section = self.section.min(SECTIONS.len() - 1); - match (SECTIONS[section].rows)(s).get(i) { + match self.horizon_rows(s, section).get(i) { Some(HRow::Opt(opt)) => { opt.cycle(s, right, framebuffer); if *opt == Opt::Preset { @@ -730,6 +791,10 @@ impl OptionsUi { s.mods.toggle(*m); events.push(Event::Changed); } + Some(HRow::OpenModFolder) if !right => { + events.push(Event::ButtonClick); + events.push(Event::OpenModFolder); + } _ => {} } } @@ -908,4 +973,53 @@ mod tests { ui.click_horizon(&mut settings, &atlas, x, drag_y, framebuffer, true, false); assert_eq!(ui.hscroll, 0.0); } + + #[test] + fn mods_section_opens_folder_from_its_button() { + let atlas = atlas(); + let framebuffer = [2560, 1440]; + let mut options = section_ui("Mods"); + let mut settings = Settings::default(); + let mut batch = horizon_batch(framebuffer); + let mut ui = Ui::dry(&atlas, &mut batch, (0.0, 0.0)); + options.horizon_layout(&settings, &mut ui, 1.0); + let rect = ui + .hits + .iter() + .find(|hit| hit.id == ROW) + .expect("Mods section has an Open Folder button") + .rect; + let scale = ui.density / ui.batch.scale; + let cursor = ( + (rect[0] + rect[2]) * 0.5 * scale, + (rect[1] + rect[3]) * 0.5 * scale, + ); + drop(ui); + + assert_eq!( + options.click_horizon( + &mut settings, + &atlas, + cursor.0, + cursor.1, + framebuffer, + false, + false + ), + vec![Event::ButtonClick, Event::OpenModFolder] + ); + assert!( + options + .click_horizon( + &mut settings, + &atlas, + cursor.0, + cursor.1, + framebuffer, + false, + true + ) + .is_empty() + ); + } } diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index fc80530d9..8e1875f48 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -734,6 +734,7 @@ enum Act { /// Back to Horizon's own menus (Horizon only, see `list_rows`). HorizonMenus, ToggleMod(usize), + OpenModFolder, } enum WKind { Button { @@ -780,6 +781,7 @@ pub enum Event { /// The pack selection changed (reload resources). Packs(Vec<String>), OpenPackFolder, + OpenModFolder, } /// `SliderableValueSet.applyValueImmediately`: these apply 600 ms after /// the last change (`OptionInstanceSliderButton.delayedApplyAt`). @@ -824,6 +826,7 @@ pub struct OptionsUi { pub languages: Vec<LanguageInfo>, language_choice: Option<String>, language_search: ui::EditBox, + pub(crate) settings_search: ui::EditBox, /// Packs: the packs found and the selection the screen opens with. pub pack_infos: Vec<crate::pack_screen::PackInfo>, pub pack_selection: Vec<String>, @@ -842,6 +845,8 @@ impl Default for OptionsUi { fn default() -> Self { let mut search = ui::EditBox::new(0.0, 0.0, 200.0, 15.0); search.max_length = 32; + let mut settings_search = ui::EditBox::new(0.0, 0.0, 200.0, 15.0); + settings_search.focused = false; Self { stack: vec![Page::Main], scroll: 0.0, @@ -858,6 +863,7 @@ impl Default for OptionsUi { languages: Vec::new(), language_choice: None, language_search: search, + settings_search, pack_infos: Vec::new(), pack_selection: Vec::new(), pack_screen: None, @@ -919,6 +925,13 @@ fn pairs(opts: &[Opt]) -> Vec<Row> { .collect() } impl OptionsUi { + fn settings_search_active(&self) -> bool { + self.settings_search.focused + && (matches!(self.page(), Page::Video | Page::Controls | Page::KeyBinds) + || (crate::ui_theme::horizon() + && self.page() == Page::Main + && crate::options_horizon::searchable_section(self.section))) + } pub fn page(&self) -> Page { *self.stack.last().unwrap_or(&Page::Main) } @@ -946,6 +959,10 @@ impl OptionsUi { self.stack.push(page); self.scroll = 0.0; self.scrollbar_drag_y = None; + if matches!(page, Page::Video | Page::Controls | Page::KeyBinds) { + self.settings_search.set_value(""); + self.settings_search.focused = false; + } if page == Page::Language { self.language_choice = None; self.language_search.set_value(""); @@ -994,6 +1011,33 @@ impl OptionsUi { _ => 163.0, } } + fn filter_option_rows(&self, rows: Vec<Row>) -> Vec<Row> { + let query = self.settings_search.value.to_lowercase(); + if query.is_empty() { + return rows; + } + rows.into_iter() + .flat_map(|row| match row { + Row::Big(opt) if lang::get(opt.caption()).to_lowercase().contains(&query) => { + vec![Row::Big(opt)] + } + Row::Pair(a, b) => { + let matches = + |opt: Opt| lang::get(opt.caption()).to_lowercase().contains(&query); + pairs( + &[Some(a), b] + .into_iter() + .flatten() + .filter(|opt| matches(*opt)) + .collect::<Vec<_>>(), + ) + } + // Keep navigation available and omit section headers with no visible options. + Row::Buttons(a, b) => vec![Row::Buttons(a, b)], + _ => Vec::new(), + }) + .collect() + } fn list_rows(&self, s: &Settings) -> Vec<Row> { match self.page() { Page::Extras => crate::extras::rows() @@ -1081,7 +1125,7 @@ impl OptionsUi { Opt::AttackIndicator, Opt::ChunkFade, ])); - rows + self.filter_option_rows(rows) } Page::Sound => { let mut rows = vec![Row::Big(Opt::Volume(0))]; @@ -1123,7 +1167,7 @@ impl OptionsUi { ), None, )); - rows + self.filter_option_rows(rows) } Page::Controller => { let mut rows = vec![Row::Buttons( @@ -1228,6 +1272,10 @@ impl OptionsUi { let mut out = Vec::new(); let page = self.page(); let cx = (w / 2.0).floor(); + if matches!(page, Page::Video | Page::Controls | Page::KeyBinds) { + self.settings_search.x = cx - 100.0; + self.settings_search.y = 17.0; + } let done = |y: f32| button(cx - 100.0, y, 200.0, tr("gui.done"), Act::Done); // (list top, list bottom, content height) let (mut top, mut bottom, mut content) = (33.0, h - 33.0, 0.0); @@ -1277,9 +1325,10 @@ impl OptionsUi { bottom = 0.0; } Page::KeyBinds => { + top = 38.0; out.push(Widget { x: 0.0, - y: 12.0, + y: 4.0, w, h: 9.0, kind: WKind::Text { @@ -1291,6 +1340,10 @@ impl OptionsUi { }); let mut mappings: Vec<(&str, &str)> = MAPPINGS.iter().map(|(n, _, c)| (*n, *c)).collect(); + let query = self.settings_search.value.to_lowercase(); + mappings.retain(|(name, _)| { + query.is_empty() || lang::get(name).to_lowercase().contains(&query) + }); mappings.sort_by(|a, b| { let ca = CATEGORIES.iter().position(|c| *c == a.1).unwrap_or(99); let cb = CATEGORIES.iter().position(|c| *c == b.1).unwrap_or(99); @@ -1559,9 +1612,16 @@ impl OptionsUi { // Drawn by `pack_screen`. Page::Packs => {} _ => { + if matches!(page, Page::Video | Page::Controls) { + top = 38.0; + } out.push(Widget { x: 0.0, - y: 12.0, + y: if matches!(page, Page::Video | Page::Controls) { + 4.0 + } else { + 12.0 + }, w, h: 9.0, kind: WKind::Text { @@ -1626,7 +1686,18 @@ impl OptionsUi { } content = y + self.scroll - top + 2.0; out[list_start..].iter_mut().for_each(|w| w.list = true); - out.push(done(h - 27.0)); + if page == Page::Mods { + out.push(button( + cx - 154.0, + h - 27.0, + 150.0, + Text::literal("Open Mod Folder"), + Act::OpenModFolder, + )); + out.push(button(cx + 4.0, h - 27.0, 150.0, tr("gui.done"), Act::Done)); + } else { + out.push(done(h - 27.0)); + } } } // Layout may change the offset (language centering), or the list may @@ -1882,6 +1953,23 @@ impl OptionsUi { } self.language_search = search; } + if matches!(self.page(), Page::Video | Page::Controls | Page::KeyBinds) { + let mut search = self.settings_search.clone(); + search.draw(batch, atlas, None); + if search.value.is_empty() && !search.focused { + batch.text_styled( + atlas, + &Text::literal("Search settings...") + .with_color(text::GRAY) + .italic(), + search.text_x(), + search.text_y(), + u32::MAX, + true, + ); + } + self.settings_search = search; + } if let Some(lines) = tooltip { ui::tooltip(batch, atlas, &lines, cursor); } @@ -1965,6 +2053,16 @@ impl OptionsUi { } let (widgets, top, bottom, content) = self.layout(s, size.0, size.1); let mut events = Vec::new(); + if !drag && matches!(self.page(), Page::Video | Page::Controls | Page::KeyBinds) { + let search = &mut self.settings_search; + search.focused = ui::hovered((x, y), search.x, search.y, search.width, search.height); + if search.focused { + search.click(atlas, x, false, false); + self.scroll = 0.0; + events.push(Event::ButtonClick); + return events; + } + } if drag { if let Some(previous_y) = self.scrollbar_drag_y { if let Some((_, thumb)) = ui::scrollbar_thumb(top, bottom, content, self.scroll) { @@ -2078,6 +2176,7 @@ impl OptionsUi { s.mods.toggle(i); events.push(Event::Changed); } + Act::OpenModFolder => events.push(Event::OpenModFolder), Act::None => {} } } @@ -2239,6 +2338,9 @@ impl OptionsUi { if self.page() == Page::Language { self.language_search.insert_text(text); self.scroll = 0.0; + } else if self.settings_search_active() { + self.settings_search.insert_text(text); + self.scroll = 0.0; } } /// Ctrl+A/C/V/X in the language or pack search box; false when neither @@ -2264,6 +2366,12 @@ impl OptionsUi { } return true; } + if self.settings_search_active() { + if self.settings_search.shortcut(shortcut, clipboard) { + self.scroll = 0.0; + } + return true; + } false } fn bind_key(&mut self, s: &mut Settings, value: String) -> Vec<Event> { @@ -2347,6 +2455,16 @@ impl OptionsUi { } } self.scroll = 0.0; + } else if self.settings_search_active() { + if !self.settings_search.key(key, false, false) + && let Some(t) = text + { + let typed: String = t.chars().filter(|c| !c.is_control()).collect(); + if !typed.is_empty() { + self.settings_search.insert_text(&typed); + } + } + self.scroll = 0.0; } Vec::new() } @@ -2450,6 +2568,31 @@ mod tests { assert!(empty.iter().any(|w| { matches!(&w.kind, WKind::Text { text, .. } if text.plain().contains(".hmod")) })); + let open_folder = empty + .iter() + .find(|w| { + matches!( + &w.kind, + WKind::Button { + act: Act::OpenModFolder, + .. + } + ) + }) + .expect("Mods page has an Open Mod Folder button"); + assert_eq!( + ui.click( + &mut s, + &atlas, + open_folder.x + 1.0, + open_folder.y + 1.0, + size, + [480, 240], + false, + false, + ), + vec![Event::ButtonClick, Event::OpenModFolder] + ); for (id, dev) in [("normal", false), ("dev", true), ("", false)] { s.mods.installed.push(crate::mod_list::Installed { id: id.into(), diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index 57d9e60d7..938e8d72d 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -1264,12 +1264,21 @@ impl ParticleEngine { } self.create(options, p, v); } - /// `LevelEventHandler.singleBlockTeleportationParticles` (event 2015). - pub fn block_teleportation(&mut self, from: [i32; 3], data: i32, particle_level: u8) { + /// `LevelEventHandler.singleBlockTeleportationParticles` towards + /// `BlockUtil.unpackDifferenceInPosition(from, data, radius)`: the dragon + /// egg's event 2015 packs offsets within (16, 8, 16), a consumable's + /// teleport (2017) within (127, 127, 127). + pub fn block_teleportation( + &mut self, + from: [i32; 3], + data: i32, + radius: [i32; 3], + particle_level: u8, + ) { let to = [ - from[0].wrapping_add(((data >> 16) & 255) - 16), - from[1].wrapping_add(((data >> 8) & 255) - 8), - from[2].wrapping_add((data & 255) - 16), + from[0].wrapping_add(((data >> 16) & 255) - radius[0]), + from[1].wrapping_add(((data >> 8) & 255) - radius[1]), + from[2].wrapping_add((data & 255) - radius[2]), ] .map(f64::from); let from = from.map(f64::from); @@ -3798,7 +3807,7 @@ mod tests { let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new()); engine.seed_randoms(0, 0, 0); // Destination offset (-15, 7, 15); the unused top byte is ignored. - engine.block_teleportation([4, 12, -5], 0xff01_0f1fu32 as i32, 0); + engine.block_teleportation([4, 12, -5], 0xff01_0f1fu32 as i32, [16, 8, 16], 0); assert_eq!(engine.pending.len(), 128); assert!(engine.pending.iter().all(|p| p.ty == ParticleType::Portal)); let first = &engine.pending[0]; @@ -3818,6 +3827,25 @@ mod tests { assert!(engine.sounds.is_empty()); } + #[test] + fn consume_teleport_unpacks_offsets_within_127() { + let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new()); + engine.seed_randoms(0, 0, 0); + // TeleportRandomlyConsumeEffect: BlockUtil.clampedPackDifferenceInPosition + // of the move (-7, -3, 9) with radii 127, from (4, 12, -5) to (-3, 9, 4). + let data = (-7 + 127) << 16 | (-3 + 127) << 8 | (9 + 127); + engine.block_teleportation([4, 12, -5], data, [127, 127, 127], 0); + assert_eq!(engine.pending.len(), 128); + for p in &engine.pending { + let [x, y, z] = p.position; + assert!((-3.0..5.0).contains(&x), "{x}"); + assert!((8.5..12.5).contains(&y), "{y}"); + assert!((-5.0..5.0).contains(&z), "{z}"); + } + // The same draws as the egg's: only the unpacking differs. + assert_eq!(engine.level_random.state(), 99_413_408_083_437); + } + #[test] fn egg_teleport_options_roll_before_distance_rejection() { for (option, count, state) in [ @@ -3831,7 +3859,7 @@ mod tests { if distant { engine.camera = [1000.0; 3]; } - engine.block_teleportation([4, 12, -5], 0x010f1f, option); + engine.block_teleportation([4, 12, -5], 0x010f1f, [16, 8, 16], option); assert_eq!(engine.pending.len(), if distant { 0 } else { count }); assert_eq!(engine.level_random.state(), state); } diff --git a/crates/horizon-client/src/player_sync.rs b/crates/horizon-client/src/player_sync.rs new file mode 100644 index 000000000..96b09c708 --- /dev/null +++ b/crates/horizon-client/src/player_sync.rs @@ -0,0 +1,86 @@ +//! LocalPlayer.sendPosition and PositionMoveRotation.calculateAbsolute. +use horizon_core::geometry::Vec3; +use horizon_protocol::packets::play::{self, PlayerPosition, Serverbound as S, relative}; + +/// Only movement updates advance this baseline. A teleport acknowledgement is +/// separate and must not suppress the next tick's corrected position or look. +#[derive(Default)] +pub struct PositionSender { + position: [f64; 3], + rotation: (f32, f32), + on_ground: bool, + collision: bool, + reminder: u32, +} + +impl PositionSender { + pub fn update( + &mut self, + position: [f64; 3], + rotation: (f32, f32), + on_ground: bool, + collision: bool, + ) -> Option<S> { + self.reminder += 1; + let d: [f64; 3] = std::array::from_fn(|i| position[i] - self.position[i]); + let moved = + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] > 2.0e-4 * 2.0e-4 || self.reminder >= 20; + let rotated = rotation.0 - self.rotation.0 != 0.0 || rotation.1 - self.rotation.1 != 0.0; + let flags = u8::from(on_ground) | u8::from(collision) << 1; + let [x, y, z] = position; + let (yaw, pitch) = rotation; + let packet = if moved && rotated { + Some(S::MovePlayerPosRot(play::MovePlayerPosRot { + x, + y, + z, + yaw, + pitch, + flags, + })) + } else if moved { + Some(S::MovePlayerPos(play::MovePlayerPos { x, y, z, flags })) + } else if rotated { + Some(S::MovePlayerRot(play::MovePlayerRot { yaw, pitch, flags })) + } else if self.on_ground != on_ground || self.collision != collision { + Some(S::MovePlayerStatus(play::MovePlayerStatus { flags })) + } else { + None + }; + if moved { + self.position = position; + self.reminder = 0; + } + if rotated { + self.rotation = rotation; + } + self.on_ground = on_ground; + self.collision = collision; + packet + } +} + +/// Rotate the old velocity before adding the relative delta components. +/// Angles deliberately use Java's double toRadians followed by a float cast. +pub fn teleport_velocity( + mut velocity: Vec3, + old_rotation: (f32, f32), + new_rotation: (f32, f32), + packet: &PlayerPosition, +) -> Vec3 { + if packet.relatives & relative::ROTATE_DELTA != 0 { + let pitch = f64::from(old_rotation.1 - new_rotation.1).to_radians() as f32; + let yaw = f64::from(old_rotation.0 - new_rotation.0).to_radians() as f32; + velocity = velocity.rotate_x(pitch).rotate_y(yaw); + } + let old = [velocity.x, velocity.y, velocity.z]; + let flags = [relative::DELTA_X, relative::DELTA_Y, relative::DELTA_Z]; + let result: [f64; 3] = std::array::from_fn(|i| { + if packet.relatives & flags[i] != 0 { + old[i] + packet.delta[i] + } else { + packet.delta[i] + } + }); + Vec3::new(result[0], result[1], result[2]) +} diff --git a/crates/horizon-client/src/portal_sections.rs b/crates/horizon-client/src/portal_sections.rs new file mode 100644 index 000000000..f22cd2b83 --- /dev/null +++ b/crates/horizon-client/src/portal_sections.rs @@ -0,0 +1,123 @@ +//! Memoized nether-portal palette eligibility per resident chunk. +//! +//! `Game::find_entity_portals` asks the same sections every tick whether their +//! palette may hold a portal state. The answer only changes when a chunk's +//! blocks change, so it is kept per chunk until the weak handle stops matching. +use crate::{chunk::Chunk, fast_hash::FxHashMap}; +use std::sync::{Arc, Weak}; + +struct Cached { + chunk: Weak<Chunk>, + /// A bit per section, set when that section's palette may hold a portal. + sections: u32, +} + +/// Resident chunks are immutable behind `Arc`; edits use `Arc::make_mut`. +/// A weak reference detects both edits and replacement, without retaining block +/// data or forcing a deep copy on the next edit. It also prevents address reuse. +/// Clear this cache whenever the gameplay facts change (including resource reload). +#[derive(Default)] +pub struct PortalSections { + chunks: FxHashMap<(i32, i32), Cached>, +} + +impl PortalSections { + pub fn clear(&mut self) { + self.chunks.clear(); + } + pub fn remove(&mut self, key: &(i32, i32)) { + self.chunks.remove(key); + } + /// The sections of `chunk` whose palette may hold a portal, as a bitmask in + /// ascending section order (`MIN_Y` at bit 0). `portal` is only called while + /// (re)building an entry, so an unchanged chunk scans its palette once. + pub fn get( + &mut self, + key: (i32, i32), + chunk: &Arc<Chunk>, + mut portal: impl FnMut(u32) -> bool, + ) -> u32 { + const { + assert!(crate::chunk::SECTIONS <= u32::BITS as usize); + } + let cached = self.chunks.entry(key).or_insert_with(|| Cached { + chunk: Weak::new(), + sections: 0, + }); + if cached.chunk.as_ptr() != Arc::as_ptr(chunk) { + let mut mask = 0; + for (i, section) in chunk.sections.iter().enumerate() { + // Preserve maybe_has, including unused entries and global palettes. + if section.blocks.maybe_has(&mut portal) { + mask |= 1 << i; + } + } + cached.sections = mask; + cached.chunk = Arc::downgrade(chunk); + } + cached.sections + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::chunk::{MIN_Y, SECTIONS, Section}; + + #[test] + fn edits_replacements_compaction_and_reload() { + let mut cache = PortalSections::default(); + let mut chunk = Arc::new(Chunk::empty(0, 0)); + assert_eq!(cache.get((0, 0), &chunk, |id| id == 7), 0); + cache.get((0, 0), &chunk, |_| panic!("unchanged chunk rescanned")); + let worker = chunk.clone(); + Arc::make_mut(&mut chunk).set(0, MIN_Y, 0, 7); + assert_eq!(cache.get((0, 0), &chunk, |id| id == 7), 1); + assert_eq!(worker.get(0, MIN_Y, 0), 0); + // Even after the last portal block is removed, its unused palette entry counts. + Arc::make_mut(&mut chunk).set(0, MIN_Y, 0, 0); + assert_eq!(cache.get((0, 0), &chunk, |id| id == 7), 1); + Arc::make_mut(&mut Arc::make_mut(&mut chunk).sections[0]).compact(); + assert_eq!(cache.get((0, 0), &chunk, |id| id == 7), 0); + Arc::make_mut(&mut chunk).sections[SECTIONS - 1] = Arc::new(Section::default()); + cache.clear(); // resource reload, with changed facts for the same state IDs + assert_eq!( + cache.get((0, 0), &chunk, |id| id == 0), + (1 << SECTIONS) - 1, + "a fresh palette is rescanned for every section" + ); + cache.remove(&(0, 0)); + assert!(cache.chunks.is_empty()); + } + + #[test] + fn replacement_at_same_coordinates_and_early_snapshot() { + let mut cache = PortalSections::default(); + let mut chunk = Arc::new(Chunk::empty(-2, 3)); + let before = cache.get((-2, 3), &chunk, |id| id == 1); + Arc::make_mut(&mut chunk).set(0, MIN_Y + 16, 0, 1); + assert_eq!(before, 0); + assert_eq!(cache.get((-2, 3), &chunk, |id| id == 1), 1 << 1); + let weak = Arc::downgrade(&chunk); + drop(chunk); + assert!(weak.upgrade().is_none()); // cache does not retain unloaded block data + let replacement = Arc::new(Chunk::empty(-2, 3)); + assert_eq!(cache.get((-2, 3), &replacement, |id| id == 1), 0); + } + + #[test] + fn global_palette_covers_the_whole_id_range() { + 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 u32)); + } + let chunk = Arc::new(chunk); + let mut cache = PortalSections::default(); + // Global maybe_has considers the entire ID range, including absent states. + assert_eq!( + cache.get((0, 0), &chunk, |id| id == 40000), + (1 << 0) | (1 << 9) | (1 << (SECTIONS - 1)) + ); + } +} diff --git a/crates/horizon-client/src/projectiles.rs b/crates/horizon-client/src/projectiles.rs index bfd0e8a97..c2d4b4e3a 100644 --- a/crates/horizon-client/src/projectiles.rs +++ b/crates/horizon-client/src/projectiles.rs @@ -63,6 +63,8 @@ pub enum ProjectileKind { } #[derive(Clone, Debug, PartialEq)] pub struct Projectile { + /// The entity id a server tracks it by (0 until it is tracked). + pub id: u32, pub kind: ProjectileKind, pub owner: Option<Who>, pub position: Vec3, @@ -128,6 +130,7 @@ impl Projectile { pub fn new(kind: ProjectileKind, position: Vec3, owner: Option<Who>) -> Self { let kind_is_arrow = matches!(kind, ProjectileKind::Arrow { .. }); Self { + id: 0, kind, owner, position, diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 29038849f..c407a7967 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -31,7 +31,7 @@ use horizon_world::{ compression::Compression, heightmap::{Heightmap, HeightmapChunk, HeightmapType}, nbt::{self, Compound, JavaString, Limits, NamedTag, Tag}, - region::{ChunkRecord, RegionFile, RegionWriter}, + region::{ChunkRecord, RegionFile}, registry::{BlockRegistry, BlockStateId}, worldgen::terrain::TerrainBlockStates, }; @@ -1278,125 +1278,146 @@ pub fn load_light(tag: &Tag, chunk: &mut Chunk, sky_light: bool) { }; layers[si as usize] = (layer("SkyLight"), layer("BlockLight")); } - let sky_default = if sky_light { 15u8 } else { 0 }; - // Sky nibbles of the section above's bottom layer, going down. - let mut above: [u8; 256] = [sky_default; 256]; - for si in (0..SECTIONS).rev() { - let (sky, block) = layers[si]; - let mut data = Box::new([0u8; 4096]); - let nibble = |a: &[u8], i: usize| (a[i >> 1] >> ((i & 1) * 4)) & 15; - for (i, packed) in data.iter_mut().enumerate() { - let s = match sky { - Some(a) if sky_light => nibble(a, i), - _ => above[i & 255], - }; - let b = block.map_or(0, |a| nibble(a, i)); - *packed = s << 4 | b; - } - for (i, a) in above.iter_mut().enumerate() { - *a = data[i] >> 4; - } - let mut section = (*chunk.sections[si]).clone(); - section.light = Light::Full(data); - section.compact(); - chunk.sections[si] = Arc::new(section); - } - chunk.lit = true; - chunk.light_loaded = true; + let above = [if sky_light { 15 } else { 0 }; 256]; + crate::light::light_from_layers(chunk, &layers, above, sky_light); } type RegionCache = Mutex<HashMap<(i32, i32), Option<Arc<Mutex<RegionFile>>>>>; -/// Rewrite every region file in `folder` touched by `records`, keeping its -/// other chunks. `None` deletes a chunk. +/// The region file at `path` through the cache, which readers and the writer +/// share, so a read never sees a header older than the sectors it points to. +/// `create` makes a missing file (for a write); otherwise a missing file is +/// `None`, until a write creates it. +fn cached_region( + cache: &RegionCache, + key: (i32, i32), + path: &Path, + create: bool, +) -> Result<Option<Arc<Mutex<RegionFile>>>> { + let mut regions = cache.lock().map_err(|_| "region cache poisoned")?; + if let Some(Some(region)) = regions.get(&key) { + return Ok(Some(region.clone())); + } + if !create && regions.contains_key(&key) { + return Ok(None); + } + if create && let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + // A file this process can't write (a read-only world) is still read. + let region = match RegionFile::open_writable(path, create) { + Err(e) if !create && e.kind() == std::io::ErrorKind::PermissionDenied => { + RegionFile::open(path) + } + other => other, + }; + let region = match region { + Ok(r) => Some(Arc::new(Mutex::new(r))), + Err(_) if !create => None, + Err(e) => return Err(e.into()), + }; + regions.insert(key, region.clone()); + Ok(region) +} +/// Write `records` into the region files of `folder` in place, as vanilla's +/// `RegionFile.write` does: each chunk takes free sectors and the header +/// then points to it; the region's other chunks are not touched. `None` +/// clears a chunk. The chunks are encoded and compressed before their region +/// is locked for the writes (`compress_records`), and each region is flushed +/// to the disk once. fn write_region_records( root: &Path, cache: &RegionCache, folder: &str, - records: Vec<((i32, i32), Option<Arc<NamedTag>>)>, + records: &[((i32, i32), &Record)], ) -> Result<()> { - let mut by_region: BTreeMap<(i32, i32), Vec<((i32, i32), Option<Arc<NamedTag>>)>> = - BTreeMap::new(); - for (key, tag) in records { - by_region - .entry((key.0 >> 5, key.1 >> 5)) - .or_default() - .push((key, tag)); - } - if by_region.is_empty() { - return Ok(()); - } - let staging = root.join(folder).join(".staging"); - fs::create_dir_all(&staging)?; let timestamp = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_secs() as u32); + let compressed = compress_records(records, timestamp); + let mut by_region: BTreeMap<(i32, i32), Vec<(ChunkPos, Option<ChunkRecord>)>> = BTreeMap::new(); + for (&((x, z), _), record) in records.iter().zip(compressed) { + let record = record?; + by_region + .entry((x >> 5, z >> 5)) + .or_default() + .push((ChunkPos::new(x, z), record)); + } for ((rx, rz), list) in by_region { let path = region_path(root, folder, rx, rz); - let mut records: BTreeMap<(i32, i32), ChunkRecord> = BTreeMap::new(); - let only_deletes = list.iter().all(|(_, tag)| tag.is_none()); - if let Ok(mut existing) = RegionFile::open(&path) { - let positions: Vec<ChunkPos> = existing.chunks().map(|(p, _)| p).collect(); - if only_deletes - && !positions - .iter() - .any(|p| list.iter().any(|(k, _)| *k == (p.x, p.z))) - { - continue; - } - for p in positions { - if let Ok(Some(r)) = existing.read(p) { - records.insert((p.x, p.z), r); - } - } - } else if only_deletes { + // Clearing chunks of a region that doesn't exist changes nothing. + let create = list.iter().any(|(_, r)| r.is_some()); + let Some(region) = cached_region(cache, (rx, rz), &path, create)? else { continue; - } - // Deleting chunks the region doesn't hold changes nothing: leave - // the file alone (unloading empty entity chunks asks for that). + }; + let mut region = region.lock().map_err(|_| "region file poisoned")?; let mut changed = false; - for (key, tag) in list { - match tag { - Some(tag) => { + for (pos, record) in &list { + match record { + Some(record) => { + region.write(*pos, record)?; changed = true; - records.insert( - key, - ChunkRecord::from_nbt( - &tag, - Compression::Zlib, - timestamp, - Limits::default(), - )?, - ); - } - None => { - changed |= records.remove(&key).is_some(); } + None => changed |= region.clear(*pos, timestamp)?, } } - if !changed { - continue; + if changed { + region.sync()?; } - if records.is_empty() { - let _ = fs::remove_file(&path); - } else { - let temporary = staging.join(format!("r.{rx}.{rz}.mca")); - let _ = fs::remove_file(&temporary); - let mut writer = RegionWriter::create(&temporary)?; - for ((x, z), r) in &records { - writer.write(ChunkPos::new(*x, *z), r)?; - } - writer.finish()?; - fs::rename(&temporary, &path)?; - } - cache - .lock() - .map_err(|_| "region cache poisoned")? - .remove(&(rx, rz)); } - let _ = fs::remove_dir(&staging); Ok(()) } +/// Fewest chunks each helper of `compress_records` takes: below this a thread +/// costs more to start than it saves. +const CHUNKS_PER_HELPER: usize = 4; +/// Each record encoded and compressed (`None` for a deletion), in the order +/// given. Vanilla's IOWorker does this one chunk after another; here a batch +/// is shared out to scoped threads, which take the next chunk as they finish +/// one. Each chunk's bytes depend only on the chunk, and the writes stay in +/// order, so the files are the same as from one thread. At most half the +/// hardware threads help, leaving the rest to the game and its workers. +fn compress_records( + records: &[((i32, i32), &Record)], + timestamp: u32, +) -> Vec<std::io::Result<Option<ChunkRecord>>> { + let compress = |record: &Record| { + record + .tag() + .map(|tag| ChunkRecord::from_nbt(&tag, Compression::Zlib, timestamp, Limits::default())) + .transpose() + }; + let helpers = std::thread::available_parallelism() + .map_or(1, |n| n.get().div_ceil(2)) + .min(records.len() / CHUNKS_PER_HELPER); + if helpers <= 1 { + return records.iter().map(|(_, r)| compress(r)).collect(); + } + let next = std::sync::atomic::AtomicUsize::new(0); + let mut done: Vec<(usize, std::io::Result<Option<ChunkRecord>>)> = + std::thread::scope(|scope| { + let threads: Vec<_> = (0..helpers) + .map(|_| { + scope.spawn(|| { + let mut out = Vec::new(); + loop { + let i = next.fetch_add(1, Ordering::Relaxed); + let Some((_, record)) = records.get(i) else { + return out; + }; + out.push((i, compress(record))); + } + }) + }) + .collect(); + threads + .into_iter() + .flat_map(|t| t.join().unwrap_or_else(|e| std::panic::resume_unwind(e))) + .collect() + }); + done.sort_unstable_by_key(|(i, _)| *i); + done.into_iter().map(|(_, r)| r).collect() +} + fn region_path(root: &Path, folder: &str, rx: i32, rz: i32) -> PathBuf { root.join(format!("{folder}/r.{rx}.{rz}.mca")) } @@ -1436,7 +1457,7 @@ impl Record { type PendingWrites = Mutex<HashMap<(bool, i32, i32), (u64, Record)>>; type WriteBatch = (bool, Vec<((i32, i32), Record, u64)>); -/// The background thread that encodes chunks and rewrites region files, in +/// The background thread that encodes chunks and writes them into the region files, in /// submission order. struct Writer { send: mpsc::Sender<WriteBatch>, @@ -1498,17 +1519,8 @@ impl SaveDir { } else { &self.entity_regions }; - let region = { - let mut regions = cache.lock().ok()?; - regions - .entry(key) - .or_insert_with(|| { - RegionFile::open(self.region_path(folder, key.0, key.1)) - .ok() - .map(|r| Arc::new(Mutex::new(r))) - }) - .clone()? - }; + let path = self.region_path(folder, key.0, key.1); + let region = cached_region(cache, key, &path, false).ok()??; let record = region.lock().ok()?.read(ChunkPos::new(x, z)).ok()??; record.nbt(Limits::default()).ok() } @@ -1614,8 +1626,19 @@ impl SaveDir { } else { ("region", ®ions) }; - let records = batch.iter().map(|(k, r, _)| (*k, r.tag())).collect(); - if let Err(e) = write_region_records(&root, cache, folder, records) { + // IOWorker.pendingWrites: a chunk queued again since is + // written once, by its newest batch. + let newest = |k: &(i32, i32), seq: u64| { + pending.lock().map_or(true, |p| { + p.get(&(entities, k.0, k.1)).is_none_or(|p| p.0 <= seq) + }) + }; + let records: Vec<_> = batch + .iter() + .filter(|(k, _, seq)| newest(k, *seq)) + .map(|(k, r, _)| (*k, r)) + .collect(); + if let Err(e) = write_region_records(&root, cache, folder, &records) { log::warn!("Horizon: failed to write {folder} files: {e}"); } // Readers find the files (and a fresh region cache) from here on. @@ -1650,7 +1673,7 @@ impl SaveDir { }; } } - /// Rewrite every region touched by `chunks`, keeping their other chunks. + /// Write `chunks` into their region files and wait until they are on disk. pub fn save( &self, chunks: &[Arc<Chunk>], @@ -2146,6 +2169,8 @@ pub struct Level { pub on_ground: bool, pub food_exhaustion: f32, pub food_tick_timer: i32, + /// Abilities.flying: whether creative/spectator flight is active. + pub flying: bool, /// The player compound as loaded, for fields Horizon does not model /// (ender chest, effects, abilities, recipe book, attributes, ...). pub player_extra: Option<Tag>, @@ -2309,6 +2334,10 @@ impl Level { self.creative = mode == 1; self.game_mode = mode as i32; } + self.flying = p + .get("abilities") + .and_then(|a| number(a.get("flying"))) + .is_some_and(|v| v != 0); if let Some(d) = text(p.get("Dimension")) { self.dimension = d; } @@ -2440,7 +2469,9 @@ impl Level { } if spectator { put(&mut abilities, "flying", Tag::Byte(1)); - } else if !creative { + } else if creative { + put(&mut abilities, "flying", Tag::Byte(i8::from(self.flying))); + } else { put(&mut abilities, "flying", Tag::Byte(0)); } if let Tag::Compound(map) = &mut abilities { @@ -2925,6 +2956,43 @@ mod tests { assert_eq!(source.block_entities[0].0, (99, 0, 99)); } + #[test] + fn records_compressed_on_helpers_match_one_thread_in_order() { + use super::{Record, compress_records}; + let records: Vec<((i32, i32), Record)> = (0..53i32) + .map(|i| { + let record = if i % 7 == 3 { + Record::Delete + } else { + let payload: Vec<i64> = (0..i * 97 % 2000).map(|v| i64::from(v * i)).collect(); + Record::Tag(Arc::new(NamedTag { + name: "".into(), + tag: Tag::compound([ + ("xPos", Tag::Int(i)), + ("Data", Tag::LongArray(payload)), + ]), + })) + }; + ((i, -i), record) + }) + .collect(); + let refs: Vec<_> = records.iter().map(|(k, r)| (*k, r)).collect(); + let compressed = compress_records(&refs, 1234); + assert_eq!(compressed.len(), records.len()); + for ((_, record), got) in records.iter().zip(compressed) { + let want = record + .tag() + .map(|t| ChunkRecord::from_nbt(&t, Compression::Zlib, 1234, Limits::default())) + .transpose() + .unwrap(); + let got = got.unwrap(); + assert_eq!( + got.as_ref().map(|r| (&r.compressed, r.timestamp)), + want.as_ref().map(|r| (&r.compressed, r.timestamp)) + ); + } + } + #[test] fn older_worlds_are_upgraded_on_opening() { let dir = std::env::temp_dir().join(format!("horizon-dv-{}", std::process::id())); @@ -3153,6 +3221,7 @@ mod tests { world_spawn: Some([8, 64, 8]), spawn: Some([20.0, 70.0, 20.0]), difficulty_locked: true, + flying: true, ..Level::default() }; level.weather.raining = true; @@ -3164,6 +3233,7 @@ mod tests { assert_eq!(back.seed, -42); assert_eq!((back.time, back.day_time), (1234, 25000)); assert!(back.creative); + assert!(back.flying); assert_eq!(back.position, Some([1.5, 70.0, -3.25])); assert_eq!(back.rotation, [90.0, 10.0]); assert_eq!((back.health, back.food, back.saturation), (17.0, 15, 2.5)); @@ -3246,4 +3316,33 @@ mod tests { level.active_effects.clear(); assert!(level.player_tag().get("active_effects").is_none()); } + + #[test] + fn creative_flight_status_persists_in_save_and_resets_for_survival() { + let mut level = Level { + creative: true, + flying: true, + ..Level::default() + }; + let tag = level.player_tag(); + let flying_byte = tag + .get("abilities") + .and_then(|a| number(a.get("flying"))) + .unwrap_or(0); + assert_eq!(flying_byte, 1); + + let mut loaded = Level::default(); + loaded.read_player(&tag); + assert!(loaded.flying); + + // Survival mode resets flying ability to 0 in save. + level.creative = false; + level.game_mode = 0; + let tag_survival = level.player_tag(); + let flying_survival = tag_survival + .get("abilities") + .and_then(|a| number(a.get("flying"))) + .unwrap_or(0); + assert_eq!(flying_survival, 0); + } } diff --git a/crates/horizon-client/src/spans.rs b/crates/horizon-client/src/spans.rs index 9fd91b2df..5c37f2bfc 100644 --- a/crates/horizon-client/src/spans.rs +++ b/crates/horizon-client/src/spans.rs @@ -1,11 +1,12 @@ //! Named timings within a frame, for finding what makes a frame slow: //! `HORIZON_SPIKES=MS` prints the spans of every frame whose CPU time -//! exceeds MS milliseconds. Costs one clock read per span when enabled and -//! a relaxed load otherwise. +//! exceeds MS milliseconds, and of every server tick (dedicated or +//! integrated) longer than MS. Costs one clock read per span when enabled +//! and a relaxed load otherwise. use std::{ cell::RefCell, sync::atomic::{AtomicBool, Ordering}, - time::Instant, + time::{Duration, Instant}, }; static ENABLED: AtomicBool = AtomicBool::new(false); @@ -28,6 +29,18 @@ pub fn time<T>(name: &'static str, f: impl FnOnce() -> T) -> T { SPANS.with(|s| s.borrow_mut().push((name, ms))); out } +/// The CPU time this thread has used, where the platform tells it: a tick +/// with more wall time than CPU time waited (for a lock, or for a core on a +/// busy machine). +pub fn thread_cpu() -> Option<Duration> { + #[cfg(unix)] + { + let t = rustix::time::clock_gettime(rustix::time::ClockId::ThreadCPUTime); + Some(Duration::new(t.tv_sec as u64, t.tv_nsec as u32)) + } + #[cfg(not(unix))] + None +} /// The frame's spans, summed by name, slowest first; clears them. pub fn take() -> Vec<(&'static str, f32)> { let spans = SPANS.with(|s| std::mem::take(&mut *s.borrow_mut())); @@ -41,3 +54,29 @@ pub fn take() -> Vec<(&'static str, f32)> { sums.sort_by(|a, b| b.1.total_cmp(&a.1)); sums } + +#[cfg(test)] +mod tests { + /// The thread's CPU clock moves with work done on it, not with time + /// spent asleep. + #[cfg(unix)] + #[test] + fn thread_cpu_counts_work_not_sleep() { + let start = super::thread_cpu().unwrap(); + std::thread::sleep(std::time::Duration::from_millis(50)); + let slept = super::thread_cpu().unwrap() - start; + // Busy until the clock shows 10 ms of work (a loaded machine gives + // the thread less than its wall time). + let mut x = 0u64; + let busy = std::time::Instant::now(); + let worked = loop { + x = std::hint::black_box(x.wrapping_mul(31).wrapping_add(7)); + let worked = super::thread_cpu().unwrap() - start - slept; + if worked.as_millis() >= 10 || busy.elapsed().as_secs() >= 10 { + break worked; + } + }; + assert!(slept.as_millis() < 25, "{slept:?} while asleep"); + assert!(worked.as_millis() >= 10, "{worked:?} while busy"); + } +} diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 38fa33c7d..1a592e21b 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -5,7 +5,7 @@ use crate::fast_hash::{FxHashMap, FxHashSet}; use crate::{ chunk::{Chunk, SECTIONS}, - light::{LightTables, apply_lighting, apply_relighting, light_chunk}, + light::{LightChanges, LightTables, apply_lighting, apply_relighting, light_chunk}, mesher::{MeshTables, Mesher, Region, SectionMesh, borrow}, world::World, }; @@ -200,8 +200,10 @@ pub struct Streaming { /// Chunks come from a server (`insert_remote`/`forget`): nothing is /// generated and columns are only unloaded when the server says so. pub remote: bool, - /// More areas to keep loaded (centre chunk, radius), e.g. around guests - /// of a world open to the network. They are generated and kept but not meshed. + /// More areas to keep loaded (centre chunk, radius), e.g. around the + /// players of a server. Each is a square, like vanilla's ticket levels: + /// chunks finish out to `radius + 1` (Chebyshev) and generation reaches + /// past that as around the player. They are generated and kept but not meshed. pub extra: Vec<((i32, i32), i32)>, /// Mesh the sections for drawing (false on a server thread). pub mesh: bool, @@ -333,6 +335,7 @@ impl GenerationScan { } pub struct WorkerContext { pub assets: Arc<crate::assets::Assets>, + pub render: Arc<crate::assets::RenderAssets>, pub tables: Arc<MeshTables>, pub biomes: Arc<crate::biome::Biomes>, pub light: Arc<LightTables>, @@ -422,6 +425,7 @@ impl Streaming { cutout_leaves: settings.cutout_leaves, cull_leaves: settings.cull_leaves, assets: &context.assets, + render: &context.render, tables: &context.tables, biomes: &context.biomes, visibility, @@ -500,16 +504,38 @@ impl Streaming { } } } - /// A column received from a server: store it and relight it and its neighbours. + /// A column received from a server, with the light it sent + /// (`ClientPacketListener.handleLevelChunkWithLight`): nothing is + /// relit, and it and its neighbours remesh (`enableChunkLight`). pub fn insert_remote(&mut self, world: &mut World, chunk: Chunk) { let key = (chunk.x, chunk.z); - self.lit.remove(&key); self.lighting.remove(&key); + self.light_snapshots.remove(&key); world.chunks.insert(key, Arc::new(chunk)); + self.lit.insert(key); self.generated_total += 1; for dz in -1..=1 { for dx in -1..=1 { - world.dirty_light.insert((key.0 + dx, key.1 + dz)); + for sy in 0..SECTIONS as i32 { + world.dirty_sections.insert((key.0 + dx, sy, key.1 + dz)); + } + } + } + } + /// A server's light update for a resident column: the sections whose + /// light changed and their neighbours remesh + /// (`setSectionDirtyWithNeighbors`). + pub fn light_updated(world: &mut World, x: i32, z: i32, sections: &[usize]) { + for &sy in sections { + for dz in -1..=1 { + for dy in -1..=1 { + for dx in -1..=1 { + let s = sy as i32 + dy; + if (0..SECTIONS as i32).contains(&s) { + world.dirty_sections.insert((x + dx, s, z + dz)); + } + } + } } } } @@ -520,7 +546,7 @@ impl Streaming { self.lighting.remove(&(x, z)); self.meshing.retain(|k, _| (k.0, k.2) != (x, z)); self.waiting.retain(|k| (k.0, k.2) != (x, z)); - world.dirty_sections.retain(|k| (k.0, k.2) != (x, z)); + world.dirty_sections.take_column(x, z); world.chunks.remove(&(x, z)) } fn submit(&mut self, priority: i64, job: Job) { @@ -589,7 +615,7 @@ impl Streaming { } world .block_entities - .extend(std::mem::take(&mut chunk.block_entities)); + .load_chunk(std::mem::take(&mut chunk.block_entities)); world .block_names .extend(std::mem::take(&mut chunk.block_names)); @@ -724,12 +750,12 @@ impl Streaming { // only around the light that changed, as vanilla's light // updates dirty only their sections (#270). let first = self.lit.insert((x, z)); - let changed = if first { + let mut changed = LightChanges::default(); + if first { apply_lighting(chunk, sections); - Vec::new() } else { - apply_relighting(chunk, sections) - }; + apply_relighting(chunk, sections, &mut changed); + } chunk.lit = true; if first { for dz in -1..=1 { @@ -785,23 +811,22 @@ impl Streaming { let far: HashSet<(i32, i32)> = far.iter().copied().collect(); self.meshing.retain(|k, _| !far.contains(&(k.0, k.2))); self.waiting.retain(|k| !far.contains(&(k.0, k.2))); - world.dirty_sections.retain(|k| !far.contains(&(k.0, k.2))); + world + .dirty_sections + .retain_columns(|x, z| !far.contains(&(x, z))); } // Drop far proto chunks that are not checked out. - let areas: Vec<((i32, i32), i64)> = - std::iter::once((self.center, i64::from(self.radius + 4))) - .chain(self.extra.iter().map(|&(c, r)| (c, i64::from(r + 4)))) - .collect(); - let forced = &self.forced; + let (center, r4) = (self.center, i64::from(self.radius + 4)); + let ranges = self.ranges(); let far: Vec<(i32, i32)> = self .protos .iter() .filter(|&(&(x, z), p)| { p.is_some() - && !areas.iter().any(|&((cx, cz), r4)| { - i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2) <= r4 * r4 - }) - && !forced + && i64::from(x - center.0).pow(2) + i64::from(z - center.1).pow(2) > r4 * r4 + && !ranges.in_extra(x, z, 4) + && !ranges + .forced .iter() .any(|f| (x - f.0).abs() <= 3 && (z - f.1).abs() <= 3) }) @@ -1004,66 +1029,63 @@ impl Streaming { !back }); } - let dirty: Vec<_> = world.dirty_sections.iter().copied().collect(); - let mut columns: FxHashMap<(i32, i32), Option<Box<Region>>> = FxHashMap::default(); - let mut ready_columns: FxHashMap<(i32, i32), bool> = FxHashMap::default(); - for (x, sy, z) in dirty { + // Column by column: the checks below hold for all of a column's + // sections, and columns waiting for light cost one look per frame. + let columns: Vec<_> = world.dirty_sections.columns().collect(); + for ((x, z), sections) in columns { if !world.chunks.contains_key(&(x, z)) { - world.dirty_sections.remove(&(x, sy, z)); + world.dirty_sections.take_column(x, z); continue; } if !self.ranges().in_view(x, z) { - world.dirty_sections.remove(&(x, sy, z)); - self.waiting.insert((x, sy, z)); + world.dirty_sections.take_column(x, z); + for sy in section_indexes(sections) { + self.waiting.insert((x, sy, z)); + } continue; } - // Once per column: the 3x3 check would otherwise repeat for each - // of its sections every frame. A neighbour being lit dirties this - // column again when its light job finishes (new chunks relight - // their eight neighbours), so wait for it rather than mesh once - // per neighbour. Columns still in `dirty_light` here can't be lit - // yet (a neighbour of theirs is missing): waiting for them could - // last until the player comes back. - let (lit, lighting) = (&self.lit, &self.lighting); - let ready = *ready_columns.entry((x, z)).or_insert_with(|| { - (-1..=1).all(|dz| { - (-1..=1).all(|dx| { - let n = (x + dx, z + dz); - lit.contains(&n) && !lighting.contains_key(&n) - }) + // A neighbour being lit dirties this column again when its light + // job finishes (new chunks relight their eight neighbours), so + // wait for it rather than mesh once per neighbour. Columns still + // in `dirty_light` here can't be lit yet (a neighbour of theirs is + // missing): waiting for them could last until the player comes + // back. + let ready = (-1..=1).all(|dz| { + (-1..=1).all(|dx| { + let n = (x + dx, z + dz); + self.lit.contains(&n) && !self.lighting.contains_key(&n) }) }); if !ready { continue; } - let region = columns - .entry((x, z)) - .or_insert_with(|| Self::region(world, x, z)); - let Some(region) = region.clone() else { + let Some(region) = Self::region(world, x, z) else { continue; }; - world.dirty_sections.remove(&(x, sy, z)); - let first = self.meshed.insert((x, z)); - self.sequence += 1; - self.meshing.insert((x, sy, z), self.sequence); - self.submit( - self.distance(x, z) * 4 + if first { 2 } else { 0 }, - Job::Mesh( - x, - sy, - z, - region, - self.sequence, - MeshSettings { - nether: self.nether_shading, - zoom: self.biome_zoom, - blend_radius: self.biome_blend, - smooth_lighting: self.smooth_lighting, - cutout_leaves: self.cutout_leaves, - cull_leaves: self.cull_leaves, - }, - ), - ); + world.dirty_sections.take_column(x, z); + for sy in section_indexes(sections) { + let first = self.meshed.insert((x, z)); + self.sequence += 1; + self.meshing.insert((x, sy, z), self.sequence); + self.submit( + self.distance(x, z) * 4 + if first { 2 } else { 0 }, + Job::Mesh( + x, + sy, + z, + region.clone(), + self.sequence, + MeshSettings { + nether: self.nether_shading, + zoom: self.biome_zoom, + blend_radius: self.biome_blend, + smooth_lighting: self.smooth_lighting, + cutout_leaves: self.cutout_leaves, + cull_leaves: self.cull_leaves, + }, + ), + ); + } } (uploads, removed) } @@ -1104,12 +1126,14 @@ impl Streaming { if positions.is_empty() { return; } - let changed = crate::light::relight( + let mut changed = LightChanges::default(); + crate::light::relight( &mut world.chunks, &self.light_tables, self.sky_light, &positions, false, + &mut changed, ); Self::mark_light_changes(world, &changed); if !self.light_snapshots.is_empty() { @@ -1131,12 +1155,14 @@ impl Streaming { .map(|(_, p)| *p) .collect(); if !positions.is_empty() { - let changed = crate::light::relight( + let mut changed = LightChanges::default(); + crate::light::relight( &mut world.chunks, &self.light_tables, self.sky_light, &positions, true, + &mut changed, ); Self::mark_light_changes(world, &changed); } @@ -1148,26 +1174,15 @@ impl Streaming { } /// Sections whose meshes sample a changed light value (faces and corners /// read light from neighbouring blocks). - fn mark_light_changes(world: &mut World, changed: &[(i32, i32, i32)]) { - let mut last = None; - for &(x, y, z) in changed { - for dz in -1..=1 { - for dy in -1..=1 { - for dx in -1..=1 { - let s = ( - (y + dy - crate::chunk::MIN_Y) >> 4, - (x + dx) >> 4, - (z + dz) >> 4, - ); - if last == Some(s) || !(0..SECTIONS as i32).contains(&s.0) { - continue; - } - last = Some(s); - world.dirty_sections.insert((s.1, s.0, s.2)); - } - } + fn mark_light_changes(world: &mut World, changed: &LightChanges) { + if let Some(log) = &mut world.light_log { + for (x, sy, z) in changed.sections() { + *log.entry((x, z)).or_default() |= 1 << sy; } } + changed.dirty_sections(|section| { + world.dirty_sections.insert(section); + }); } fn ranges(&self) -> Ranges<'_> { Ranges { @@ -1277,21 +1292,21 @@ impl Ranges<'_> { /// circles, so a fixed margin alone misses the corners of those squares /// (render distance 2 never finished the chunks next to the player). fn near_finished(&self, x: i32, z: i32, reach: i32) -> bool { - let near = |c: (i32, i32), radius: i32| { - let gap = |d: i32| i64::from((d.abs() - reach).max(0)); - let (dx, dz) = (gap(x - c.0), gap(z - c.1)); - let r = i64::from(radius + 1); - dx * dx + dz * dz <= r * r - }; - near(self.center, self.radius) || self.extra.iter().any(|&(c, r)| near(c, r)) + let gap = |d: i32| i64::from((d.abs() - reach).max(0)); + let (dx, dz) = (gap(x - self.center.0), gap(z - self.center.1)); + let r = i64::from(self.radius + 1); + // The extra areas are squares: their finished square grown by `reach`. + dx * dx + dz * dz <= r * r || self.in_extra(x, z, 1 + reach) } fn in_range(&self, x: i32, z: i32, margin: i32) -> bool { - self.in_main_range(x, z, margin) - || self.extra.iter().any(|&(c, radius)| { - let r = i64::from(radius + margin); - let (dx, dz) = (i64::from(x - c.0), i64::from(z - c.1)); - dx * dx + dz * dz <= r * r - }) + self.in_main_range(x, z, margin) || self.in_extra(x, z, margin) + } + /// Within `margin` of an extra area's square (Chebyshev distance, as + /// vanilla's ticket levels spread). + fn in_extra(&self, x: i32, z: i32, margin: i32) -> bool { + self.extra + .iter() + .any(|&(c, radius)| (x - c.0).abs().max((z - c.1).abs()) <= radius + margin) } /// The columns meshed for drawing: those vanilla draws around the /// player (`in_view_distance`), and forced ones. @@ -1329,6 +1344,16 @@ impl Drop for Streaming { } } } +/// The section indexes set in a column's bits, lowest first. +fn section_indexes(mut bits: u32) -> impl Iterator<Item = i32> { + std::iter::from_fn(move || { + (bits != 0).then(|| { + let sy = bits.trailing_zeros() as i32; + bits &= bits - 1; + sy + }) + }) +} #[cfg(test)] mod tests { use super::*; @@ -1778,4 +1803,58 @@ mod tests { } } } + + /// A server player's area (`lan_update_streaming`: the server view + /// distance + 1) finishes vanilla's FULL square: PLAYER_LOADING tickets at + /// level 31 out to the view distance, FULL (33) two chunks past it. Every + /// chunk the player tracks has its 3x3 neighbourhood finished, so it can + /// be lit and sent, and generation reaches vanilla's FEATURES (34) and + /// TERRAIN (35) rings. + #[test] + fn server_player_areas_finish_vanillas_full_square() { + let forced = HashSet::new(); + for view in 2..=32 { + let extra = [((40, -9), view + 1)]; + let r = Ranges { + // The window's own area, far away. + center: (-400, 300), + radius: 2, + extra: &extra, + forced: &forced, + }; + let level = |x: i32, z: i32| 31 + ((x - 40).abs().max((z + 9).abs()) - view).max(0); + for x in 40 - view - 8..=40 + view + 8 { + for z in -9 - view - 8..=-9 + view + 8 { + assert_eq!( + r.in_range(x, z, 1), + level(x, z) <= 33, + "view {view}: ({x}, {z})" + ); + assert_eq!( + r.requested(x, z, true), + level(x, z) <= 35, + "view {view}: ({x}, {z})" + ); + assert_eq!( + r.unloaded(x, z, true), + level(x, z) > 35, + "view {view}: ({x}, {z})" + ); + // ChunkTrackingView.contains, at any view distance the player may ask for. + let tracked = |v: i64| { + let gap = |d: i32| i64::from(((d).abs() - 2).max(0)); + gap(x - 40).pow(2) + gap(z + 9).pow(2) < v * v + }; + if tracked(i64::from(view)) { + for (dx, dz) in (-1..=1).flat_map(|dx| (-1..=1).map(move |dz| (dx, dz))) { + assert!( + r.in_range(x + dx, z + dz, 1), + "view {view}: ({x}, {z}) tracked, not lit" + ); + } + } + } + } + } + } } diff --git a/crates/horizon-client/src/telemetry.rs b/crates/horizon-client/src/telemetry.rs index 9e83655fa..d0140f941 100644 --- a/crates/horizon-client/src/telemetry.rs +++ b/crates/horizon-client/src/telemetry.rs @@ -3,6 +3,7 @@ //! summary, in the outbox. It never sends anything itself: the launcher does, at its next start. //! Without the player's yes for that kind nothing is kept, and crash-reports/ stays local. use std::path::Path; +use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::{Mutex, OnceLock}; use std::time::Instant; @@ -18,6 +19,11 @@ const MIN_SECONDS: f32 = 60.0; const CRASH_DETAILS: [&str; 3] = ["Horizon Version", "Graphics Adapter", "Render Settings"]; static STARTED: OnceLock<Instant> = OnceLock::new(); +/// When the menu bundle became ready, so the time to the title screen measures +/// the menu and not the world bundle loaded behind it. +static UI_READY_MS: AtomicU32 = AtomicU32::new(u32::MAX); +static CORE_READY_MS: AtomicU32 = AtomicU32::new(u32::MAX); +static REST_READY_MS: AtomicU32 = AtomicU32::new(u32::MAX); /// The GPU's name, driver and backend, once the renderer has its adapter. static GPU: Mutex<Option<(String, String, String)>> = Mutex::new(None); @@ -26,6 +32,34 @@ pub fn mark_start() { STARTED.get_or_init(Instant::now); } +/// The menu bundle is ready: the title backdrop can draw. The first writer wins. +pub fn mark_ui_ready() { + if let Some(started) = STARTED.get() { + let ms = started.elapsed().as_millis() as u32; + let _ = UI_READY_MS.compare_exchange(u32::MAX, ms, Ordering::Relaxed, Ordering::Relaxed); + } +} + +pub fn mark_core_ready() { + mark_ready(&CORE_READY_MS); +} + +pub fn mark_rest_ready() { + mark_ready(&REST_READY_MS); +} + +fn mark_ready(mark: &AtomicU32) { + if let Some(started) = STARTED.get() { + let ms = started.elapsed().as_millis().min(u128::from(u32::MAX - 1)) as u32; + let _ = mark.compare_exchange(u32::MAX, ms, Ordering::Relaxed, Ordering::Relaxed); + } +} + +fn readiness_ms(mark: &AtomicU32) -> Option<u32> { + let ms = mark.load(Ordering::Relaxed); + (ms != u32::MAX).then_some(ms) +} + pub fn set_gpu(name: &str, driver: String, backend: String) { *GPU.lock().unwrap_or_else(|e| e.into_inner()) = Some((name.to_owned(), driver, backend)); } @@ -138,7 +172,12 @@ impl Session { pub fn title_shown(&mut self) { if !self.title_measured { self.title_measured = true; - self.to_title_ms = STARTED.get().map(|s| s.elapsed().as_millis() as u32); + let ui_ms = UI_READY_MS.load(Ordering::Relaxed); + self.to_title_ms = if ui_ms != u32::MAX { + Some(ui_ms) + } else { + STARTED.get().map(|s| s.elapsed().as_millis() as u32) + }; } } @@ -147,6 +186,11 @@ impl Session { self.opening.get_or_insert_with(Instant::now); } + /// An entry queued during startup was cancelled before opening a world. + pub fn cancel_world_opening(&mut self) { + self.opening = None; + } + /// A frame drawn while playing (not in menus or loading). pub fn frame(&mut self, ms: f32) { if let Some(opening) = self.opening.take() @@ -175,6 +219,8 @@ impl Session { peak_ram_mb: peak_ram_mb(), to_title_ms: self.to_title_ms, to_world_ms: self.to_world_ms, + to_core_ms: self.to_title_ms.and_then(|_| readiness_ms(&CORE_READY_MS)), + to_rest_ms: self.to_title_ms.and_then(|_| readiness_ms(&REST_READY_MS)), }) } @@ -377,6 +423,20 @@ mod tests { assert_eq!(pending[0].1.kind(), Kind::Crash); } + #[test] + fn cancelled_startup_entry_does_not_time_menu_browsing() { + let mut session = Session::default(); + session.world_opening(); + assert!(session.opening.is_some()); + session.cancel_world_opening(); + assert!(session.opening.is_none()); + session.frame(16.0); + assert!(session.to_world_ms.is_none()); + session.world_opening(); + session.frame(16.0); + assert!(session.to_world_ms.is_some()); + } + #[test] fn a_session_is_kept_only_with_consent_and_once_long_enough() { let home = home("session"); diff --git a/crates/horizon-client/src/terrain.wgsl b/crates/horizon-client/src/terrain.wgsl index 504d197aa..7d25cef2f 100644 --- a/crates/horizon-client/src/terrain.wgsl +++ b/crates/horizon-client/src/terrain.wgsl @@ -72,11 +72,16 @@ fn sample_lightmap(sky: f32, block: f32) -> vec4<f32> { return textureSampleLevel(lightmap, lightmap_sampler, clamp(uv / 256.0 + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0); } +// mesher.rs's TerrainVertex holds the UV in 32768 steps per unit: a power of +// two on an integer below 2^24, so it decodes exactly. +fn terrain_uv(packed: vec2<u32>) -> vec2<f32> { + return vec2<f32>(packed) * (1.0 / 32768.0); +} @vertex fn vs_terrain( - @location(0) position: vec3<f32>, @location(1) uv: vec2<f32>, + @location(0) position: vec3<f32>, @location(1) uv: vec2<u32>, @location(2) layer: u32, @location(3) color: vec4<f32>, @location(4) light: vec2<u32>, @location(5) origin: vec4<f32>) -> TerrainOut { - return terrain_vertex(position, uv, layer, color, light, origin.xyz); + return terrain_vertex(position, terrain_uv(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: @@ -85,11 +90,11 @@ fn sample_lightmap(sky: f32, block: f32) -> vec4<f32> { @group(1) @binding(1) var<storage, read> slot_origins: array<vec4<f32>>; @vertex fn vs_terrain_flat( @builtin(vertex_index) vertex: u32, - @location(0) position: vec3<f32>, @location(1) uv: vec2<f32>, + @location(0) position: vec3<f32>, @location(1) uv: vec2<u32>, @location(2) layer: u32, @location(3) color: vec4<f32>, @location(4) light: vec2<u32> ) -> TerrainOut { let origin = slot_origins[block_slots[vertex >> 8u]]; - return terrain_vertex(position, uv, layer, color, light, origin.xyz); + return terrain_vertex(position, terrain_uv(uv), layer, color, light, origin.xyz); } fn terrain_vertex(position: vec3<f32>, uv: vec2<f32>, layer: u32, color: vec4<f32>, light: vec2<u32>, origin: vec3<f32>) -> TerrainOut { diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client/src/text.rs index e0b144714..3874efd17 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client/src/text.rs @@ -267,6 +267,24 @@ impl Text { _ => c, } } + /// Style fields the spans don't model (an entity hover, an insertion), + /// set on the component sent to vanilla only. + pub fn with_component_fields(mut self, fields: Vec<(String, Value)>) -> Self { + let mut c = self.component(); + if let Value::Object(o) = &mut c { + for (k, v) in fields { + o.entry(k).or_insert(v); + } + } + self.source = Some(c.into()); + self + } + /// The same spans, sent to vanilla as `component` (a shape the spans' + /// own JSON would not take, such as a styled root with siblings). + pub fn with_component(mut self, component: Value) -> Self { + self.source = Some(component.into()); + self + } pub fn with_color(self, color: u32) -> Self { self.with_style(&Style::color(color)) } diff --git a/crates/horizon-client/src/tick_chunk_membership.rs b/crates/horizon-client/src/tick_chunk_membership.rs index 42785f289..a7e934443 100644 --- a/crates/horizon-client/src/tick_chunk_membership.rs +++ b/crates/horizon-client/src/tick_chunk_membership.rs @@ -10,6 +10,9 @@ pub struct TickChunkMembership { revision: Option<u64>, added: Vec<Key>, removed: Vec<Key>, + /// Loaded chunks with saved ticks that have not started ticking yet + /// (`LevelChunkTicks.pendingTicks`, unpacked by `startTickingChunk`). + waiting: HashSet<Key>, } impl TickChunkMembership { @@ -20,6 +23,7 @@ impl TickChunkMembership { self.revision = None; self.added.clear(); self.removed.clear(); + self.waiting.clear(); } /// Returns false in O(1) when resident membership is unchanged. On change, @@ -36,6 +40,7 @@ impl TickChunkMembership { true } else { self.removed.push(*key); + self.waiting.remove(key); false } }); @@ -62,6 +67,28 @@ impl TickChunkMembership { pub fn removed(&self) -> &[Key] { &self.removed } + + /// `key` was registered with saved ticks to unpack once it ticks. + pub fn wait(&mut self, key: Key) { + self.waiting.insert(key); + } + + /// The waiting chunks that `ticking` says now tick, no longer waiting. + pub fn start_ticking(&mut self, mut ticking: impl FnMut(Key) -> bool) -> Vec<Key> { + if self.waiting.is_empty() { + return Vec::new(); + } + let started: Vec<Key> = self + .waiting + .iter() + .copied() + .filter(|&k| ticking(k)) + .collect(); + for key in &started { + self.waiting.remove(key); + } + started + } } #[cfg(test)] @@ -124,6 +151,24 @@ mod tests { compare(&mut cache, &mut old, &map); } + #[test] + fn waiting_chunks_start_ticking_once_and_unloaded_ones_stop_waiting() { + let mut map = ChunkMap::default(); + let mut cache = TickChunkMembership::default(); + for key in [(0, 0), (1, 0), (2, 0)] { + map.insert(key, Arc::new(Chunk::empty(key.0, key.1))); + cache.wait(key); + } + cache.synchronize(&map); + assert_eq!(cache.start_ticking(|k| k == (0, 0)), vec![(0, 0)]); + assert!(cache.start_ticking(|k| k == (0, 0)).is_empty()); + map.remove(&(1, 0)); + cache.synchronize(&map); + let mut started = cache.start_ticking(|_| true); + started.sort_unstable(); + assert_eq!(started, vec![(2, 0)]); + } + #[test] fn scheduler_keeps_saved_ticks_on_stable_membership_and_removes_unloaded_chunks() { use horizon_core::{ diff --git a/crates/horizon-client/src/ticket_levels.rs b/crates/horizon-client/src/ticket_levels.rs new file mode 100644 index 000000000..216815de1 --- /dev/null +++ b/crates/horizon-client/src/ticket_levels.rs @@ -0,0 +1,232 @@ +//! Which chunks tick, from the chunk tickets of `DistanceManager`. +//! +//! Every player holds two kinds of ticket: +//! - `PLAYER_LOADING` at level 31 (`ENTITY_TICKING`) on every chunk within +//! the server's view distance (Chebyshev), from `PlayerTicketTracker`; +//! - `PLAYER_SIMULATION` at level `31 - simulationDistance` on its own chunk. +//! +//! A `/forceload`ed chunk holds a `FORCED` ticket at level 31 of both kinds. +//! Levels rise by one per chunk away from a ticket (`ChunkTracker`) and each +//! chunk takes the lowest. The loading level gives the chunk's +//! `FullChunkStatus` (`ChunkLevel.fullStatus`: 31 entity ticking, 32 block +//! ticking, 33 full) and the simulation level gives what +//! `inEntityTickingRange` (31 or less) and `inBlockTickingRange` (32 or less) +//! answer. Vanilla needs both: +//! - entities tick where both levels are entity ticking (`ServerLevel.tick`, +//! and `EntityTickList` holds only the entities of entity-ticking chunks); +//! - random ticks run in the simulation tracker's entity-ticking chunks that +//! have a ticking chunk (`ChunkMap.forEachBlockTickingChunk`); +//! - scheduled ticks, block events and block entities run where both are +//! block ticking (`isPositionTickingWithEntitiesLoaded`, +//! `shouldTickBlocksAt`, `LevelChunk.isTicking`). +//! +//! Whoever the players are (the local player, LAN guests, a dedicated +//! server's players), they count the same. +use crate::fast_hash::FxHashMap; +use std::sync::Arc; + +/// `ChunkLevel`'s levels. +pub const ENTITY_TICKING: u8 = 31; +pub const BLOCK_TICKING: u8 = 32; +/// What a chunk with no ticket near it has (`FULL` and above count as none). +const NONE: (u8, u8) = (BLOCK_TICKING + 1, BLOCK_TICKING + 1); + +/// The tickets of one level: where its players are, its forced chunks, and +/// the server's view and simulation distances. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Sources { + pub players: Vec<(i32, i32)>, + pub forced: Vec<(i32, i32)>, + pub view_distance: i32, + pub simulation_distance: i32, +} + +/// Each chunk's (loading, simulation) level, for the chunks where either is +/// block ticking or lower; `None` ticks everywhere (a game with no server and +/// no player: the headless fixtures). +#[derive(Clone, Default)] +pub struct Levels(Option<Arc<FxHashMap<(i32, i32), (u8, u8)>>>); + +impl Levels { + /// Chunk coordinates. + fn get(&self, x: i32, z: i32) -> Option<(u8, u8)> { + let map = self.0.as_ref()?; + Some(map.get(&(x, z)).copied().unwrap_or(NONE)) + } + /// `DistanceManager.inEntityTickingRange`, in an entity-ticking chunk: + /// where entities tick. + pub fn entity_ticking(&self, x: i32, z: i32) -> bool { + self.get(x, z) + .is_none_or(|(l, s)| l <= ENTITY_TICKING && s <= ENTITY_TICKING) + } + /// `inBlockTickingRange` in a block-ticking chunk: where scheduled ticks, + /// block events and block entities run. + pub fn block_ticking(&self, x: i32, z: i32) -> bool { + self.get(x, z) + .is_none_or(|(l, s)| l <= BLOCK_TICKING && s <= BLOCK_TICKING) + } + /// `inEntityTickingRange` in a block-ticking chunk: where random ticks run. + pub fn random_ticking(&self, x: i32, z: i32) -> bool { + self.get(x, z) + .is_none_or(|(l, s)| l <= BLOCK_TICKING && s <= ENTITY_TICKING) + } + /// `ChunkHolder.getFullStatus` is block ticking or more: the chunk's + /// ticking future can complete (its saved ticks unpack then). + pub fn loaded_ticking(&self, x: i32, z: i32) -> bool { + self.get(x, z).is_none_or(|(l, _)| l <= BLOCK_TICKING) + } + /// The same as [`Self::entity_ticking`] at a block position. + pub fn entity_ticking_at(&self, x: i32, z: i32) -> bool { + self.entity_ticking(x >> 4, z >> 4) + } + /// The same as [`Self::block_ticking`] at a block position. + pub fn block_ticking_at(&self, x: i32, z: i32) -> bool { + self.block_ticking(x >> 4, z >> 4) + } +} + +/// The levels, rebuilt only when their sources change (a player crossing +/// into another chunk, a distance or a forced chunk changing). +#[derive(Default)] +pub struct ChunkTickets { + sources: Option<Sources>, + levels: Levels, +} + +impl ChunkTickets { + /// `None`: tick everywhere. + pub fn update(&mut self, mut sources: Option<Sources>) { + if let Some(s) = sources.as_mut() { + s.players.sort_unstable(); + s.players.dedup(); + s.forced.sort_unstable(); + } + if sources == self.sources { + return; + } + self.levels = Levels(sources.as_ref().map(|s| Arc::new(compute(s)))); + self.sources = sources; + } + pub fn levels(&self) -> Levels { + self.levels.clone() + } +} + +fn compute(s: &Sources) -> FxHashMap<(i32, i32), (u8, u8)> { + let view = s.view_distance.clamp(0, 32); + let simulation = s.simulation_distance.clamp(0, 32); + let mut levels: FxHashMap<(i32, i32), (u8, u8)> = FxHashMap::default(); + let mut lower = |key, loading: i32, sim: i32| { + let e = levels.entry(key).or_insert(NONE); + e.0 = e.0.min(loading.min(i32::from(NONE.0)) as u8); + e.1 = e.1.min(sim.min(i32::from(NONE.1)) as u8); + }; + // PLAYER_LOADING within the view distance, PLAYER_SIMULATION at the + // player's chunk (`getPlayerTicketLevel`: never below 0). + let player_sim = (i32::from(ENTITY_TICKING) - simulation).max(0); + let reach = (view + 1).max(i32::from(BLOCK_TICKING) - player_sim); + for &(px, pz) in &s.players { + for dz in -reach..=reach { + for dx in -reach..=reach { + let d = dx.abs().max(dz.abs()); + lower( + (px + dx, pz + dz), + i32::from(ENTITY_TICKING) + (d - view).max(0), + player_sim + d, + ); + } + } + } + for &(fx, fz) in &s.forced { + for dz in -1i32..=1 { + for dx in -1i32..=1 { + let level = i32::from(ENTITY_TICKING) + dx.abs().max(dz.abs()); + lower((fx + dx, fz + dz), level, level); + } + } + } + levels.retain(|_, l| *l != NONE); + levels +} + +#[cfg(test)] +mod tests { + use super::*; + + fn levels(players: &[(i32, i32)], forced: &[(i32, i32)], view: i32, sim: i32) -> Levels { + let mut t = ChunkTickets::default(); + t.update(Some(Sources { + players: players.to_vec(), + forced: forced.to_vec(), + view_distance: view, + simulation_distance: sim, + })); + t.levels() + } + + #[test] + fn simulation_distance_inside_the_view() { + // view 8, simulation 4: entities and random ticks out to 4 chunks, + // scheduled ticks out to 5. + let l = levels(&[(0, 0)], &[], 8, 4); + assert!(l.entity_ticking(4, -4) && !l.entity_ticking(5, 0)); + assert!(l.random_ticking(-4, 4) && !l.random_ticking(0, 5)); + assert!(l.block_ticking(5, 5) && !l.block_ticking(6, 0)); + assert!(l.loaded_ticking(9, 9) && !l.loaded_ticking(10, 0)); + } + + #[test] + fn view_distance_inside_the_simulation() { + // view 4, simulation 10: what isn't loaded at entity ticking (beyond + // the view distance) runs no entities, and block ticks stop where the + // chunk is only full (beyond the view distance + 1). + let l = levels(&[(0, 0)], &[], 4, 10); + assert!(l.entity_ticking(4, 0) && !l.entity_ticking(5, 0)); + assert!(l.random_ticking(5, 0) && !l.random_ticking(6, 0)); + assert!(l.block_ticking(5, 5) && !l.block_ticking(6, 0)); + } + + #[test] + fn every_player_and_forced_chunk() { + let l = levels(&[(0, 0), (40, 0)], &[(-100, 7)], 4, 4); + assert!(l.entity_ticking(44, 0) && l.entity_ticking(0, -4)); + assert!(!l.entity_ticking(20, 0)); + // A forced chunk entity ticks, its neighbours only block tick. + assert!(l.entity_ticking(-100, 7) && !l.entity_ticking(-101, 7)); + assert!(l.block_ticking(-101, 8) && !l.block_ticking(-102, 7)); + assert!(!l.random_ticking(-101, 7)); + assert!(l.entity_ticking_at(-1600, 112) && !l.block_ticking_at(-1617, 112)); + } + + #[test] + fn no_tickets_tick_nothing_and_no_sources_everything() { + let none = levels(&[], &[], 10, 10); + assert!(!none.block_ticking(0, 0) && !none.entity_ticking(0, 0)); + let everywhere = ChunkTickets::default().levels(); + assert!(everywhere.random_ticking(1000, -1000)); + } + + #[test] + fn rebuilt_only_when_sources_change() { + let mut t = ChunkTickets::default(); + let s = |players: Vec<(i32, i32)>| { + Some(Sources { + players, + forced: Vec::new(), + view_distance: 2, + simulation_distance: 2, + }) + }; + t.update(s(vec![(0, 0), (5, 5)])); + let first = t.levels(); + t.update(s(vec![(5, 5), (0, 0)])); + assert!(Arc::ptr_eq( + first.0.as_ref().unwrap(), + t.levels().0.as_ref().unwrap() + )); + t.update(s(vec![(1, 0), (5, 5)])); + assert!(t.levels().entity_ticking(3, 0) && !first.entity_ticking(3, 0)); + t.update(None); + assert!(t.levels().0.is_none()); + } +} diff --git a/crates/horizon-client/src/ui_theme.rs b/crates/horizon-client/src/ui_theme.rs index 2cb3b5315..7f99e9830 100644 --- a/crates/horizon-client/src/ui_theme.rs +++ b/crates/horizon-client/src/ui_theme.rs @@ -1042,6 +1042,49 @@ impl<'a> Ui<'a> { self.opacity = saved; hover } + /// A search field styled like the launcher's rounded text inputs. + pub fn text_field(&mut self, id: u64, rect: [f32; 4], value: &str, focused: bool) { + let [x, y, w, h] = rect; + self.record_label(value, rect, true, crate::widgets::Kind::Button); + let hover = self.interact(id, x, y, w, h, true); + self.rounded( + x, + y, + w, + h, + 8.0, + if focused { color::HOVER } else { color::RAISED }, + ); + self.rounded( + x, + y, + w, + h, + 8.0, + color::with_alpha(color::HOVER, hover * 0.5), + ); + let display = if value.is_empty() { + "Search settings".to_owned() + } else if focused { + format!("{value}|") + } else { + value.to_owned() + }; + let display = self.fit(Face::Regular, BODY, &display, w - 24.0); + self.text_line( + Face::Regular, + BODY, + h, + x + 12.0, + y, + if value.is_empty() { + color::FAINT + } else { + color::TEXT + }, + &display, + ); + } /// The width the launcher's button gives a label (padding 16, or 24 large). pub fn button_width(&self, label: &str, large: bool) -> f32 { let (size, pad) = if large { (LARGE, 24.0) } else { (BODY, 16.0) }; diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index 657817bb9..6c94ea67d 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -56,6 +56,19 @@ impl VanillaTerrain { biomes: &Biomes, seed: i64, dimension: &str, + ) -> crate::Result<Self> { + Self::for_world(dir, registry, biomes, seed, dimension, true) + } + /// A dimension of a world whose `generate_structures` is `structures` + /// (`ChunkGenerator.createStructures` and `findNearestMapStructure` do + /// nothing without). + pub fn for_world( + dir: &Path, + registry: &'static BlockRegistry, + biomes: &Biomes, + seed: i64, + dimension: &str, + structures: bool, ) -> crate::Result<Self> { let data: Arc<GeneratorData> = shared_data(dir, registry)?; let biome_map = data @@ -64,7 +77,7 @@ impl VanillaTerrain { .map(|name| biomes.id(name)) .collect(); let generator = - OverworldGenerator::for_dimension(data, seed, "minecraft:normal", dimension)?; + OverworldGenerator::for_world(data, seed, "minecraft:normal", dimension, structures)?; let unsupported = generator.unsupported_features(); if !unsupported.is_empty() { log::warn!( diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index 05b89234c..af7c1671b 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -8,6 +8,46 @@ use std::{ sync::Arc, }; +/// Sections (x, section index, z) waiting to be remeshed, kept by column +/// (a bit per section index), so the mesh scheduler looks at each column once +/// rather than at every section of it. +#[derive(Clone, Debug, Default)] +pub struct DirtySections { + columns: crate::fast_hash::FxHashMap<(i32, i32), u32>, +} +const _: () = assert!(SECTIONS <= 32); +impl DirtySections { + pub fn insert(&mut self, (x, sy, z): (i32, i32, i32)) { + debug_assert!((0..SECTIONS as i32).contains(&sy)); + *self.columns.entry((x, z)).or_default() |= 1 << sy; + } + pub fn contains(&self, &(x, sy, z): &(i32, i32, i32)) -> bool { + (0..SECTIONS as i32).contains(&sy) + && self.columns.get(&(x, z)).is_some_and(|m| m & 1 << sy != 0) + } + /// The dirty section indexes of column (x, z), as bits, removed. + pub fn take_column(&mut self, x: i32, z: i32) -> u32 { + self.columns.remove(&(x, z)).unwrap_or(0) + } + /// Keep the columns `keep` accepts. + pub fn retain_columns(&mut self, mut keep: impl FnMut(i32, i32) -> bool) { + self.columns.retain(|&(x, z), _| keep(x, z)); + } + /// The columns holding dirty sections, with their section bits. + pub fn columns(&self) -> impl Iterator<Item = ((i32, i32), u32)> + '_ { + self.columns.iter().map(|(&c, &m)| (c, m)) + } + pub fn clear(&mut self) { + self.columns.clear(); + } + pub fn is_empty(&self) -> bool { + self.columns.is_empty() + } + /// How many sections are dirty. + pub fn len(&self) -> usize { + self.columns.values().map(|m| m.count_ones() as usize).sum() + } +} pub struct World { pub fast_lava: bool, pub chunks: crate::chunk_map::ChunkMap, @@ -16,7 +56,7 @@ pub struct World { pub health_rules: crate::health::HealthRules, pub air: BlockStateId, /// Sections whose geometry changed and need remeshing. - pub dirty_sections: crate::fast_hash::FxHashSet<(i32, i32, i32)>, + pub dirty_sections: DirtySections, /// Chunks whose light must be recomputed. pub dirty_light: crate::fast_hash::FxHashSet<(i32, i32)>, /// Edits on lit chunks (position, old state, new state), relit @@ -26,7 +66,8 @@ pub struct World { pub loaded_entities: Vec<((i32, i32), Vec<horizon_world::nbt::Tag>)>, /// Chunks changed since the last save. pub modified: HashSet<(i32, i32)>, - pub block_entities: HashMap<(i32, i32, i32), crate::containers::BlockEntity>, + /// Block entities, and the order they tick in. + pub block_entities: crate::block_entities::BlockEntities, /// Each chest's `ContainerOpenersCounter`: opener count and largest /// interaction range. pub chest_openers: HashMap<(i32, i32, i32), (i32, f64)>, @@ -46,6 +87,10 @@ pub struct World { /// Every block position written since the log was last drained, kept /// only while the world is open to the network (see `lan`). pub block_log: Option<Vec<(i32, i32, i32)>>, + /// The sections whose light changed since the log was last drained, as + /// a bit per section of each column, kept while `block_log` is + /// (`ChunkHolder.sectionLightChanged`). + pub light_log: Option<crate::fast_hash::FxHashMap<(i32, i32), u32>>, /// The villager POIs of each section (`PoiManager`'s sections). pub pois: crate::poi_sections::PoiSections<crate::mobs::villager_brain::Poi>, } @@ -122,7 +167,7 @@ impl World { light_edits: Vec::new(), loaded_entities: Vec::new(), modified: HashSet::new(), - block_entities: HashMap::new(), + block_entities: Default::default(), chest_openers: HashMap::new(), block_names: HashMap::new(), watched: Vec::new(), @@ -132,12 +177,17 @@ impl World { day_time: 1000, weather: Weather::default(), block_log: None, + light_log: None, pois: Default::default(), } } /// A controlled blockstate scene for the native scene probes: material /// layers, a stepped pyramid and the model gallery. Not generated terrain. - pub fn test_scene(assets: &crate::assets::Assets, radius: i32) -> crate::Result<Self> { + pub fn test_scene( + assets: &crate::assets::Assets, + render: &crate::assets::RenderAssets, + radius: i32, + ) -> crate::Result<Self> { let air = assets .registry .default_state("minecraft:air") @@ -182,7 +232,7 @@ impl World { } } } - for (position, state) in &assets.model_placements { + for (position, state) in &render.model_placements { world.set(position.x, position.y, position.z, *state)?; } world.revision = 0; @@ -200,6 +250,8 @@ impl World { } let previous = Arc::make_mut(chunk).set(x & 15, y, z & 15, state.0); if previous != state.0 { + self.block_entities + .state_changed((x, y, z), 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)); @@ -235,11 +287,28 @@ impl World { } Ok(()) } + /// `getHeight(Heightmap.Types.WORLD_SURFACE, x, z)`: one above the highest + /// block that isn't `air`, or `MIN_Y` (also where the chunk isn't loaded). + pub fn world_surface(&self, x: i32, z: i32, air: impl Fn(BlockStateId) -> bool) -> i32 { + self.chunks.get(&(x >> 4, z >> 4)).map_or(MIN_Y, |chunk| { + chunk.world_surface(x, z, |v| air(BlockStateId(v))) + }) + } pub fn block(&self, x: i32, y: i32, z: i32) -> BlockStateId { self.chunks .get(&(x >> 4, z >> 4)) .map_or(self.air, |chunk| chunk.block(x & 15, y, z & 15)) } + /// The block entities to tick this tick, in order (`BlockEntities::tickers`). + pub fn block_entity_tickers(&mut self) -> Vec<(crate::block_entities::Pos, u32)> { + let (chunks, air) = (&self.chunks, self.air); + self.block_entities.tickers(|(x, y, z)| { + chunks + .get(&(x >> 4, z >> 4)) + .map_or(air, |chunk| chunk.block(x & 15, y, z & 15)) + .0 + }) + } pub fn light(&self, x: i32, y: i32, z: i32) -> u8 { self.chunks .get(&(x >> 4, z >> 4)) diff --git a/crates/horizon-client/tests/generation_saves.rs b/crates/horizon-client/tests/generation_saves.rs index 26da11efe..ce91a1096 100644 --- a/crates/horizon-client/tests/generation_saves.rs +++ b/crates/horizon-client/tests/generation_saves.rs @@ -170,13 +170,15 @@ fn chunks_left_behind_keep_their_decoration() { return; }; let assets = Arc::new(Assets::load(&root).unwrap()); + let render = Arc::new(assets.reload(&root).unwrap()); let facts = BlockFacts::load(&root, assets.registry).unwrap(); let visibility = models::load_visibility(&root, assets.registry).unwrap(); let context = Arc::new(WorkerContext { - tables: Arc::new(MeshTables::new(&assets, &facts, visibility).unwrap()), + tables: Arc::new(MeshTables::new(&assets, &render, &facts, visibility).unwrap()), light: Arc::new(LightTables::load(&root, assets.registry, &facts).unwrap()), biomes: Arc::new(Biomes::load(&root).unwrap()), assets, + render: render.clone(), }); let generator = Arc::new(Recorder::default()); let mut session = Session::new(generator.clone(), context.clone()); diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index 4d6cd4e86..18af20343 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -181,6 +181,8 @@ impl Server { sprinting: false, equipment: Default::default(), health: 20.0, + attributes: Vec::new(), + living_flags: 0, }; let mut ctx = TickCtx { world: &mut self.world, @@ -422,16 +424,40 @@ fn guests_see_each_other_and_the_world_entities() { data: 0, meta: Vec::new(), equipment: Vec::new(), + attributes: Vec::new(), + precise: false, }; let first = thread::spawn(move || { let mut bot = connect(port, "Alex", false)?; + bot.c + .reader + .set_read_timeout(Some(Duration::from_millis(200))) + .unwrap(); let mut zombies = 0; let mut players = 0; let mut moves = 0; + let mut at: Option<[f64; 3]> = None; + let mut reminder = Instant::now(); let deadline = Instant::now() + Duration::from_secs(20); while Instant::now() < deadline && !(zombies > 0 && players > 0 && moves > 0) { - match bot.recv_play()? { + // A vanilla client sends its position at least every 20 ticks even + // when standing still (LocalPlayer's positionReminder), and the + // server checks which entities it sees again on each one. + if let Some([x, y, z]) = at + && reminder.elapsed() >= Duration::from_secs(1) + { + bot.send(S::MovePlayerPos(play::MovePlayerPos { x, y, z, flags: 1 })); + reminder = Instant::now(); + } + let Ok((id, payload)) = bot.c.recv() else { + continue; + }; + let Ok(packet) = C::decode(id, &payload) else { + continue; + }; + match packet { C::PlayerPosition(p) => { + at = Some(p.position); bot.send(S::AcceptTeleportation(play::AcceptTeleportation { id: p.teleport, x: p.position[0], diff --git a/crates/horizon-client/tests/streaming_meshes.rs b/crates/horizon-client/tests/streaming_meshes.rs index 6804d197e..3aa30a330 100644 --- a/crates/horizon-client/tests/streaming_meshes.rs +++ b/crates/horizon-client/tests/streaming_meshes.rs @@ -55,13 +55,15 @@ fn columns_loaded_past_the_render_distance_mesh_when_they_come_in_range() { return; }; let assets = Arc::new(Assets::load(&root).unwrap()); + let render = Arc::new(assets.reload(&root).unwrap()); let facts = BlockFacts::load(&root, assets.registry).unwrap(); let visibility = models::load_visibility(&root, assets.registry).unwrap(); let context = Arc::new(WorkerContext { - tables: Arc::new(MeshTables::new(&assets, &facts, visibility).unwrap()), + tables: Arc::new(MeshTables::new(&assets, &render, &facts, visibility).unwrap()), light: Arc::new(LightTables::load(&root, assets.registry, &facts).unwrap()), biomes: Arc::new(Biomes::load(&root).unwrap()), assets, + render: render.clone(), }); let mut streaming = Streaming::new(Arc::new(Saved), context, 3); streaming.radius = 4; @@ -135,13 +137,15 @@ fn relit_columns_keep_every_mesh_current() { return; }; let assets = Arc::new(Assets::load(&root).unwrap()); + let render = Arc::new(assets.reload(&root).unwrap()); let facts = BlockFacts::load(&root, assets.registry).unwrap(); let visibility = models::load_visibility(&root, assets.registry).unwrap(); let context = Arc::new(WorkerContext { - tables: Arc::new(MeshTables::new(&assets, &facts, visibility).unwrap()), + tables: Arc::new(MeshTables::new(&assets, &render, &facts, visibility).unwrap()), light: Arc::new(LightTables::load(&root, assets.registry, &facts).unwrap()), biomes: Arc::new(Biomes::load(&root).unwrap()), assets: assets.clone(), + render: render.clone(), }); let state = |name: &str| assets.registry.default_state(name).unwrap().0; let (stone, glowstone, torch) = ( @@ -149,8 +153,9 @@ fn relit_columns_keep_every_mesh_current() { state("minecraft:glowstone"), state("minecraft:torch"), ); - // Columns from a server, one of them never sent: its neighbours stay - // unlit, next to lit columns within the render distance. + // Columns from a server, one of them not sent yet. They keep the light + // the server sent (#824, as vanilla's `enableChunkLight`), so its + // neighbours are lit too. let mut streaming = Streaming::new(Arc::new(Saved), context.clone(), 3); streaming.radius = 4; streaming.remote = true; @@ -176,7 +181,7 @@ fn relit_columns_keep_every_mesh_current() { } }; settle(&mut streaming, &mut world); - assert!(!streaming.is_lit(1, 0) && streaming.is_lit(0, 0)); + assert!(streaming.is_lit(1, 0) && streaming.is_lit(0, 0)); // Open the roof and put torches in the cave on a ring two blocks inside // the unlit (1, 0): its lit neighbours are relit, and their meshes change // only through light (no edit is next to them). @@ -210,6 +215,7 @@ fn relit_columns_keep_every_mesh_current() { cutout_leaves: true, cull_leaves: false, assets: &context.assets, + render: &context.render, tables: &context.tables, biomes: &context.biomes, visibility: context.tables.visibility.clone(), diff --git a/crates/horizon-core/src/biome.rs b/crates/horizon-core/src/biome.rs index 4f8c9ff54..96baeda4b 100644 --- a/crates/horizon-core/src/biome.rs +++ b/crates/horizon-core/src/biome.rs @@ -22,20 +22,86 @@ impl BiomeZoom { } /// Choose the closest of eight jittered quart corners, preserving vanilla's /// corner order, strict tie comparison and signed coordinate wrapping. + /// + /// Each corner re-derives its distance from a fresh six-step mix driven by + /// the quart coordinate. The first two steps depend only on the X and Y + /// offsets, so those shared prefixes are mixed once (two X states, then four + /// XY states) instead of eight times, and the six-step tail is evaluated for + /// all eight corners. Since `next(m, salt + offset) == next(m, salt) + + /// offset`, each coordinate is folded into its step with one addition. pub fn quart_at_block(self, block: BlockPos) -> [i32; 3] { let shifted = [block.x, block.y, block.z].map(|v| v.wrapping_sub(2)); let base = shifted.map(|v| v >> 2); let fractions = shifted.map(|v| f64::from(v & 3) / 4.); + let coordinate = base.map(i64::from); + let seed = self.seed; + const A: i64 = 6364136223846793005; + const B: i64 = 1442695040888963407; + let g = |m: i64| m.wrapping_mul(m.wrapping_mul(A).wrapping_add(B)); + let root = g(seed); + let m0: [i64; 2] = + std::array::from_fn(|x: usize| root.wrapping_add(coordinate[0].wrapping_add(x as i64))); + let m1: [[i64; 2]; 2] = std::array::from_fn(|x: usize| { + std::array::from_fn(|y: usize| { + g(m0[x]).wrapping_add(coordinate[1].wrapping_add(y as i64)) + }) + }); + let m2: [[[i64; 2]; 2]; 2] = std::array::from_fn(|x: usize| { + std::array::from_fn(|y: usize| { + std::array::from_fn(|z: usize| { + g(m1[x][y]).wrapping_add(coordinate[2].wrapping_add(z as i64)) + }) + }) + }); + let m3: [[[i64; 2]; 2]; 2] = std::array::from_fn(|x: usize| { + std::array::from_fn(|y: usize| { + std::array::from_fn(|z: usize| { + g(m2[x][y][z]).wrapping_add(coordinate[0].wrapping_add(x as i64)) + }) + }) + }); + let m4: [[[i64; 2]; 2]; 2] = std::array::from_fn(|x: usize| { + std::array::from_fn(|y: usize| { + std::array::from_fn(|z: usize| { + g(m3[x][y][z]).wrapping_add(coordinate[1].wrapping_add(y as i64)) + }) + }) + }); + let m5: [[[i64; 2]; 2]; 2] = std::array::from_fn(|x: usize| { + std::array::from_fn(|y: usize| { + std::array::from_fn(|z: usize| { + g(m4[x][y][z]).wrapping_add(coordinate[2].wrapping_add(z as i64)) + }) + }) + }); + let m6: [[[i64; 2]; 2]; 2] = std::array::from_fn(|x: usize| { + std::array::from_fn(|y: usize| { + std::array::from_fn(|z: usize| g(m5[x][y][z]).wrapping_add(seed)) + }) + }); + let m7: [[[i64; 2]; 2]; 2] = std::array::from_fn(|x: usize| { + std::array::from_fn(|y: usize| { + std::array::from_fn(|z: usize| g(m6[x][y][z]).wrapping_add(seed)) + }) + }); let mut selected = base; let mut best = f64::INFINITY; - for corner in 0..8 { - let offsets = [(corner >> 2) & 1, (corner >> 1) & 1, corner & 1]; - let quart = std::array::from_fn(|i| base[i].wrapping_add(offsets[i])); - let delta = std::array::from_fn(|i| fractions[i] - f64::from(offsets[i])); - let distance = fiddled_distance(self.seed, quart, delta); - if best > distance { - best = distance; - selected = quart; + for x in 0..2 { + for y in 0..2 { + for z in 0..2 { + let dx = fractions[0] - x as f64 + fiddle(m5[x][y][z]); + let dy = fractions[1] - y as f64 + fiddle(m6[x][y][z]); + let dz = fractions[2] - z as f64 + fiddle(m7[x][y][z]); + let distance = dz * dz + dy * dy + dx * dx; + if best > distance { + best = distance; + selected = [ + base[0].wrapping_add(x as i32), + base[1].wrapping_add(y as i32), + base[2].wrapping_add(z as i32), + ]; + } + } } } selected @@ -50,25 +116,112 @@ pub fn noise_quart_at_block(block: BlockPos) -> [i32; 3] { pub fn noise_quart_at_position(position: [f64; 3]) -> [i32; 3] { position.map(|v| (v.floor() as i32) >> 2) } -fn next(seed: i64, salt: i64) -> i64 { - seed.wrapping_mul( - seed.wrapping_mul(6364136223846793005) - .wrapping_add(1442695040888963407), - ) - .wrapping_add(salt) -} fn fiddle(seed: i64) -> f64 { (((seed >> 24) & 1023) as f64 / 1024. - 0.5) * 0.9 } -fn fiddled_distance(seed: i64, quart: [i32; 3], delta: [f64; 3]) -> f64 { - let mut mixed = seed; - for coordinate in quart.into_iter().cycle().take(6) { - mixed = next(mixed, i64::from(coordinate)); + +#[cfg(test)] +mod tests { + use super::*; + + /// The straightforward per-corner formulation, kept as the parity oracle + /// for the prefix-shared implementation. + fn reference(seed: i64, block: BlockPos) -> [i32; 3] { + let shifted = [block.x, block.y, block.z].map(|v| v.wrapping_sub(2)); + let base = shifted.map(|v| v >> 2); + let fractions = shifted.map(|v| f64::from(v & 3) / 4.); + let mut selected = base; + let mut best = f64::INFINITY; + for corner in 0..8 { + let offsets = [(corner >> 2) & 1, (corner >> 1) & 1, corner & 1]; + let quart: [i32; 3] = std::array::from_fn(|i| base[i].wrapping_add(offsets[i])); + let delta: [f64; 3] = std::array::from_fn(|i| fractions[i] - f64::from(offsets[i])); + let mut mixed = seed; + for coordinate in quart.into_iter().cycle().take(6) { + mixed = mixed + .wrapping_mul( + mixed + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407), + ) + .wrapping_add(i64::from(coordinate)); + } + let x = delta[0] + fiddle(mixed); + mixed = mixed + .wrapping_mul( + mixed + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407), + ) + .wrapping_add(seed); + let y = delta[1] + fiddle(mixed); + mixed = mixed + .wrapping_mul( + mixed + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407), + ) + .wrapping_add(seed); + let z = delta[2] + fiddle(mixed); + let distance = z * z + y * y + x * x; + if best > distance { + best = distance; + selected = quart; + } + } + selected + } + + #[test] + fn quart_at_block_matches_reference() { + let seeds = [ + 0i64, + 1, + -1, + i64::MIN, + i64::MAX, + 0x0123_4567_89ab_cdef, + -0x0123_4567_89ab_cdef, + ]; + let extremes = [ + i32::MIN, + i32::MIN + 1, + -1, + 0, + 1, + 2, + 3, + 4, + -2, + i32::MAX - 1, + i32::MAX, + ]; + for &seed in &seeds { + let zoom = BiomeZoom::new(seed); + for x in -34..34 { + for y in -34..34 { + for z in -34..34 { + let block = BlockPos::new(x, y, z); + assert_eq!( + zoom.quart_at_block(block), + reference(seed, block), + "seed {seed} at {x} {y} {z}" + ); + } + } + } + for &x in &extremes { + for &y in &extremes { + for &z in &extremes { + let block = BlockPos::new(x, y, z); + assert_eq!( + zoom.quart_at_block(block), + reference(seed, block), + "seed {seed} at {x} {y} {z}" + ); + } + } + } + } } - let x = delta[0] + fiddle(mixed); - mixed = next(mixed, seed); - let y = delta[1] + fiddle(mixed); - mixed = next(mixed, seed); - let z = delta[2] + fiddle(mixed); - z * z + y * y + x * x } diff --git a/crates/horizon-core/src/paletted.rs b/crates/horizon-core/src/paletted.rs index f162404f5..3d56bb987 100644 --- a/crates/horizon-core/src/paletted.rs +++ b/crates/horizon-core/src/paletted.rs @@ -151,33 +151,85 @@ fn write(words: &mut [u64], bits: u8, i: usize, value: u32) { let (word, shift) = locate(bits, i); words[word] = (words[word] & !(mask(bits) << shift)) | (u64::from(value) << shift); } +/// Values below this are looked up in a table indexed by value once a +/// palette outgrows the scan: every block state and biome id of 26.3. +const DENSE_VALUES: u32 = 1 << 16; +thread_local! { + /// `palette_ids`' table: 1 + the id of each value seen, 0 for the others. + /// Only the entries of the palette being built are set, and they are + /// cleared again before it returns. + static DENSE_IDS: std::cell::RefCell<Vec<u32>> = const { std::cell::RefCell::new(Vec::new()) }; +} /// The distinct `values` in first-occurrence order and each value's index in -/// them. Up to 16 distinct values a scan finds them faster than hashing. +/// them. A run of one value (most of a section) is matched once, a scan finds +/// up to 16 distinct values faster than any lookup, and past that a table +/// indexed by value finds them without hashing. fn palette_ids(values: &[u32]) -> (Vec<u32>, Vec<u32>) { let mut palette: Vec<u32> = Vec::new(); - let mut small = true; - let mut lookup: std::collections::HashMap<u32, u32> = std::collections::HashMap::new(); let mut ids = Vec::with_capacity(values.len()); - for &value in values { - let id = if small { - match palette.iter().position(|&v| v == value) { + let mut last: Option<(u32, u32)> = None; + let mut rest = values; + while let Some((&value, tail)) = rest.split_first() { + let id = match last { + Some((v, id)) if v == value => id, + _ if palette.len() > 16 => break, + _ => match palette.iter().position(|&v| v == value) { Some(id) => id as u32, None => { palette.push(value); - if palette.len() > 16 { - small = false; - lookup.extend(palette.iter().enumerate().map(|(i, &v)| (v, i as u32))); - } palette.len() as u32 - 1 } + }, + }; + last = Some((value, id)); + ids.push(id); + rest = tail; + } + if rest.is_empty() { + return (palette, ids); + } + if palette.iter().chain(rest).all(|&v| v < DENSE_VALUES) { + DENSE_IDS.with(|table| { + let mut table = table.borrow_mut(); + for (id, &v) in palette.iter().enumerate() { + let v = v as usize; + if table.len() <= v { + table.resize(v + 1, 0); + } + table[v] = id as u32 + 1; } - } else { - *lookup.entry(value).or_insert_with(|| { + for &value in rest { + let v = value as usize; + if table.len() <= v { + table.resize(v + 1, 0); + } + let id = match table[v] { + 0 => { + palette.push(value); + table[v] = palette.len() as u32; + palette.len() as u32 - 1 + } + slot => slot - 1, + }; + ids.push(id); + } + for &v in &palette { + table[v as usize] = 0; + } + }); + } else { + let mut lookup: std::collections::HashMap<u32, u32> = palette + .iter() + .enumerate() + .map(|(i, &v)| (v, i as u32)) + .collect(); + for &value in rest { + let id = *lookup.entry(value).or_insert_with(|| { palette.push(value); palette.len() as u32 - 1 - }) - }; - ids.push(id); + }); + ids.push(id); + } } (palette, ids) } @@ -391,17 +443,24 @@ impl PalettedContainer { assert_eq!(out.len(), self.strategy.entries()); match &self.palette { Palette::Single(value) => out.fill(*value), - palette => { + Palette::List(list) => { let bits = usize::from(self.bits); let per = 64 / bits; let m = mask(self.bits); for (chunk, &word) in out.chunks_mut(per).zip(&self.words) { for (slot, cell) in chunk.iter_mut().enumerate() { - let id = ((word >> (slot * bits)) & m) as u32; - *cell = match palette { - Palette::List(list) => list[id as usize], - _ => id, - }; + let id = ((word >> (slot * bits)) & m) as usize; + *cell = list[id]; + } + } + } + Palette::Global => { + let bits = usize::from(self.bits); + let per = 64 / bits; + let m = mask(self.bits); + for (chunk, &word) in out.chunks_mut(per).zip(&self.words) { + for (slot, cell) in chunk.iter_mut().enumerate() { + *cell = ((word >> (slot * bits)) & m) as u32; } } } @@ -412,17 +471,24 @@ impl PalettedContainer { debug_assert_eq!(self.strategy.entries(), 4096); match &self.palette { Palette::Single(value) => out.fill(*value as u16), - palette => { + Palette::List(list) => { let bits = usize::from(self.bits); let per = 64 / bits; let m = mask(self.bits); for (chunk, &word) in out.chunks_mut(per).zip(&self.words) { for (slot, cell) in chunk.iter_mut().enumerate() { let id = ((word >> (slot * bits)) & m) as usize; - *cell = match palette { - Palette::List(list) => list[id] as u16, - _ => id as u16, - }; + *cell = list[id] as u16; + } + } + } + Palette::Global => { + let bits = usize::from(self.bits); + let per = 64 / bits; + let m = mask(self.bits); + for (chunk, &word) in out.chunks_mut(per).zip(&self.words) { + for (slot, cell) in chunk.iter_mut().enumerate() { + *cell = ((word >> (slot * bits)) & m) as u16; } } } @@ -738,4 +804,211 @@ mod tests { } } } + + /// The pre-optimization `unpack`, kept to compare against in the benchmark. + fn baseline_unpack(c: &PalettedContainer, out: &mut [u32]) { + match &c.palette { + Palette::Single(value) => out.fill(*value), + palette => { + let bits = usize::from(c.bits); + let per = 64 / bits; + let m = mask(c.bits); + for (chunk, &word) in out.chunks_mut(per).zip(&c.words) { + for (slot, cell) in chunk.iter_mut().enumerate() { + let id = ((word >> (slot * bits)) & m) as u32; + *cell = match palette { + Palette::List(list) => list[id as usize], + _ => id, + }; + } + } + } + } + } + + /// `unpack` against the pre-optimization implementation, for a list palette + /// and the global palette. The result is checked before timing; 25 measured + /// rounds alternate order and report the median and best microsecond-per-call. + #[test] + #[ignore = "microbenchmark; run with --ignored --nocapture"] + fn benchmark_unpack() { + use std::{hint::black_box, time::Instant}; + let values: Vec<u32> = (0..4096).map(|i| (i % 12) as u32).collect(); + let list = PalettedContainer::from_values(BLOCKS, &values); + let global = PalettedContainer::from_values( + BLOCKS, + &(0..4096).map(|i| (i * 3) as u32).collect::<Vec<_>>(), + ); + for (name, container) in [("list", &list), ("global", &global)] { + let mut expected = vec![0u32; 4096]; + baseline_unpack(container, &mut expected); + let mut out = vec![0u32; 4096]; + container.unpack(&mut out); + assert_eq!(expected, out, "unpack {name} differs"); + let mut times = [Vec::new(), Vec::new()]; + for round in 0..25 { + for optimized in [round % 2 == 0, round % 2 != 0] { + let started = Instant::now(); + for _ in 0..2000 { + if optimized { + container.unpack(black_box(&mut out)); + } else { + baseline_unpack(black_box(container), black_box(&mut out)); + } + } + if round > 0 { + times[usize::from(optimized)] + .push(started.elapsed().as_secs_f64() * 1e6 / 2000.0); + } + } + } + for values in &mut times { + values.sort_by(f64::total_cmp); + } + let median = |v: &[f64]| v[v.len() / 2]; + println!( + "unpack {name} median: baseline {:.3} us optimized {:.3} us speedup {:.3}x", + median(×[0]), + median(×[1]), + median(×[0]) / median(×[1]) + ); + println!( + "unpack {name} best: baseline {:.3} us optimized {:.3} us speedup {:.3}x", + times[0][0], + times[1][0], + times[0][0] / times[1][0] + ); + } + } + + /// The pre-optimization `palette_ids` (scan, then a SipHash map), kept to + /// compare against. + fn baseline_palette_ids(values: &[u32]) -> (Vec<u32>, Vec<u32>) { + let mut palette: Vec<u32> = Vec::new(); + let mut small = true; + let mut lookup: std::collections::HashMap<u32, u32> = std::collections::HashMap::new(); + let mut ids = Vec::with_capacity(values.len()); + for &value in values { + let id = if small { + match palette.iter().position(|&v| v == value) { + Some(id) => id as u32, + None => { + palette.push(value); + if palette.len() > 16 { + small = false; + lookup.extend(palette.iter().enumerate().map(|(i, &v)| (v, i as u32))); + } + palette.len() as u32 - 1 + } + } + } else { + *lookup.entry(value).or_insert_with(|| { + palette.push(value); + palette.len() as u32 - 1 + }) + }; + ids.push(id); + } + (palette, ids) + } + /// Sections like the ones saved: stone, ores and caves under dirt, grass + /// and air; a mixed surface (plants, leaves, logs) in short runs; a + /// global palette; ids past the table; and biomes. + fn palette_cases() -> Vec<(&'static str, Vec<u32>)> { + let mut state = 0x9E37_79B9_7F4A_7C15u64; + let mut terrain = Vec::with_capacity(4096); + for i in 0..4096u32 { + let y = i >> 8; + let r = rng(&mut state); + terrain.push(match y { + 0..=8 if r % 40 == 0 => 2000 + (r >> 8) as u32 % 6, + 0..=8 if r % 13 == 0 => 0, + 0..=8 => 1, + 9..=10 => 10, + 11 => 9, + _ => 0, + }); + } + let mut surface = Vec::with_capacity(4096); + while surface.len() < 4096 { + let r = rng(&mut state); + let run = 1 + (r % 8) as usize; + let v = 100 + ((r >> 8) % 24) as u32 * 37; + surface.extend(std::iter::repeat_n(v, run.min(4096 - surface.len()))); + } + let global: Vec<u32> = (0..4096) + .map(|_| (rng(&mut state) % 600) as u32 * 41) + .collect(); + let large: Vec<u32> = (0..4096) + .map(|i| { + if i % 3 == 0 { + 70_000 + (rng(&mut state) % 40) as u32 + } else { + i as u32 % 20 + } + }) + .collect(); + let biomes: Vec<u32> = (0..64).map(|i| [3, 3, 3, 7, 7, 12][i % 6]).collect(); + vec![ + ("terrain", terrain), + ("surface", surface), + ("global", global), + ("large ids", large), + ("biomes", biomes), + ("single", vec![5; 4096]), + ("seventeen", (0..4096).map(|i| (i % 17) as u32).collect()), + ] + } + #[test] + fn palette_ids_match_first_occurrence_order() { + for (name, values) in palette_cases() { + assert_eq!( + palette_ids(&values), + baseline_palette_ids(&values), + "{name}" + ); + // The table is left clean for the next section. + assert_eq!( + palette_ids(&values), + baseline_palette_ids(&values), + "{name} again" + ); + } + DENSE_IDS.with(|t| assert!(t.borrow().iter().all(|&slot| slot == 0))); + } + /// `palette_ids` against the pre-optimization implementation over the + /// cases above. 25 measured rounds alternate order and report the median + /// microseconds per call. + #[test] + #[ignore = "microbenchmark; run with --ignored --nocapture"] + fn benchmark_palette_ids() { + use std::{hint::black_box, time::Instant}; + for (name, values) in palette_cases() { + let mut times = [Vec::new(), Vec::new()]; + for round in 0..25 { + for optimized in [round % 2 == 0, round % 2 != 0] { + let started = Instant::now(); + for _ in 0..500 { + if optimized { + black_box(palette_ids(black_box(&values))); + } else { + black_box(baseline_palette_ids(black_box(&values))); + } + } + if round > 0 { + times[usize::from(optimized)] + .push(started.elapsed().as_secs_f64() * 1e6 / 500.0); + } + } + } + for t in &mut times { + t.sort_by(f64::total_cmp); + } + let (base, new) = (times[0][times[0].len() / 2], times[1][times[1].len() / 2]); + println!( + "palette_ids {name}: baseline {base:.2} us, new {new:.2} us, {:.2}x", + base / new + ); + } + } } diff --git a/crates/horizon-core/src/storage.rs b/crates/horizon-core/src/storage.rs index 61f8c505f..6b8a8ec38 100644 --- a/crates/horizon-core/src/storage.rs +++ b/crates/horizon-core/src/storage.rs @@ -88,6 +88,28 @@ impl PackedStorage { Ok(((self.words[word] >> shift) & self.mask) as u32) } + /// Reads `index` without a bounds check. Callers use this once they hold a + /// slice length or a section index they have already validated. + /// `index` must be less than `len`. + pub fn read(&self, index: usize) -> u32 { + debug_assert!(index < self.len); + let word = index / self.per_word; + let shift = (index % self.per_word) * usize::from(self.bits); + ((self.words[word] >> shift) & self.mask) as u32 + } + + /// Writes `value` at `index` without revalidating either. `index` must be + /// less than `len` and `value` must fit `bits`, which holds for a section + /// palette index from the same container. Returns the previous value. + pub fn write(&mut self, index: usize, value: u32) -> u32 { + debug_assert!(index < self.len && u64::from(value) <= self.mask); + let word = index / self.per_word; + let shift = (index % self.per_word) * usize::from(self.bits); + let old = ((self.words[word] >> shift) & self.mask) as u32; + self.words[word] = (self.words[word] & !(self.mask << shift)) | (u64::from(value) << shift); + old + } + /// Validation fails before mutation. Writes accept nonnegative Java ints; /// imported 32-bit words may still decode to any u32 bit pattern. pub fn set(&mut self, index: usize, value: u32) -> Result<u32, StorageError> { diff --git a/crates/horizon-mods/src/content.rs b/crates/horizon-mods/src/content.rs index 40b641759..9afe95d0a 100644 --- a/crates/horizon-mods/src/content.rs +++ b/crates/horizon-mods/src/content.rs @@ -192,6 +192,13 @@ impl Content { Ok(content) } + /// Where the files are read from: the mod's folder or its `.hmod`. + pub fn source(&self) -> &Path { + match &self.source { + Source::Dir(path) | Source::Zip(path) => path, + } + } + /// No files: a mod with code only. pub fn is_empty(&self) -> bool { self.files.is_empty() diff --git a/crates/horizon-port-pack/src/carry.rs b/crates/horizon-port-pack/src/carry.rs index dfe4d3dbc..2f4af104c 100644 --- a/crates/horizon-port-pack/src/carry.rs +++ b/crates/horizon-port-pack/src/carry.rs @@ -25,6 +25,9 @@ pub struct Report { pub unreadable: BTreeMap<String, String>, pub recipes_upgraded: usize, pub loot_tables_upgraded: usize, + /// Blocks whose jar has no loot table but drop themselves in the oracle: + /// the mod registers that table in code, and carry-over writes it. + pub loot_tables_added: usize, /// Worldgen and structure files (`data/<id>/worldgen/`, `structure/`). pub worldgen: usize, /// Recipes left as they were: custom types, NeoForge conditions. @@ -44,6 +47,11 @@ pub struct Report { pub items_unknown: BTreeMap<String, String>, /// Convention (`c:`) tags the recipes use, filled in from the oracle. pub convention_tags: usize, + /// Structure, placement and pool element types rewritten as vanilla's, + /// and those left as they are. + pub worldgen_types: crate::worldgen::Upgrade, + /// The loader's convention biome tags the structures name, carried. + pub convention_biome_tags: usize, } /// Vanilla blocks by their sorted property names. @@ -197,6 +205,29 @@ pub fn upgrade_recipe(recipe: &mut Value) -> bool { true } +/// Block and item ids vanilla renamed after 1.21.1, as its datafixers +/// rename them in worlds (DataVersion 4541: the chain became the iron chain +/// when copper chains came in). A data file naming the old id fails to load +/// in 26.3: a recipe, a loot entry, a processor's block match. +const RENAMED_IDS: [(&str, &str); 1] = [("minecraft:chain", "minecraft:iron_chain")]; + +/// Every string of a data file that is a renamed id ([`RENAMED_IDS`]) set to +/// the new one, in place; whether any was. +pub fn renamed_ids(v: &mut Value) -> bool { + match v { + Value::String(s) => match RENAMED_IDS.iter().find(|(old, _)| s == old) { + Some((_, new)) => { + *s = (*new).to_owned(); + true + } + None => false, + }, + Value::Array(a) => a.iter_mut().fold(false, |c, x| renamed_ids(x) | c), + Value::Object(o) => o.values_mut().fold(false, |c, x| renamed_ids(x) | c), + _ => false, + } +} + /// A 1.21.1 loot table in 26.3's shape, in place: `conditions` lists become /// one `condition` (`all_of` for several), `functions` become `modifier`, /// and conditions and functions name their kind in `type`. A tool match on @@ -323,13 +354,17 @@ fn unreadable(name: &str, bytes: &mut Vec<u8>) -> Option<String> { /// Carries `jar` over into `out/carry/`. With the oracle's `facts`, blocks /// and items are the ones the mod registers, with the templates and numbers -/// the facts give; `allowed` says which vanilla blocks the game has. +/// the facts give; `allowed` says which vanilla blocks the game has; +/// `loaded` which mods are ported along, for the conditions of the mod's +/// worldgen modifiers. pub fn carry( jar: &Path, info: &JarInfo, out: &Path, facts: Option<&Facts>, allowed: &dyn Fn(&str) -> bool, + loaded: &dyn Fn(&str) -> bool, + conventions: &BTreeMap<String, Value>, ) -> Result<Report, String> { let id = &info.mod_id; if id.is_empty() @@ -351,6 +386,11 @@ pub fn carry( let mut blockstates: BTreeMap<String, Value> = BTreeMap::new(); let mut item_models = BTreeSet::new(); let mut convention = BTreeSet::new(); + let mut block_loot = BTreeSet::new(); + let mut biome_conventions = BTreeSet::new(); + let set_tags = crate::worldgen::structure_set_tags(&mut zip); + let piece_counts = crate::worldgen::piece_counts(&mut zip); + let processor_data = crate::processors::ProcessorData::read(&mut zip); for i in 0..zip.len() { let mut entry = zip.by_index(i).map_err(|e| e.to_string())?; let name = entry.name().to_owned(); @@ -393,17 +433,103 @@ pub fn carry( { if let Ok(mut recipe) = serde_json::from_slice::<Value>(&bytes) { tags_used(&recipe, &mut convention); - if upgrade_recipe(&mut recipe) { + let renamed = renamed_ids(&mut recipe); + let upgraded = upgrade_recipe(&mut recipe); + if upgraded { report.recipes_upgraded += 1; - bytes = serde_json::to_vec_pretty(&recipe).unwrap_or(bytes); } else { report.recipes_kept.push(file.to_owned()); } + if upgraded || renamed { + bytes = serde_json::to_vec_pretty(&recipe).unwrap_or(bytes); + } + } + } else if let Some(kind) = rel + .strip_prefix("worldgen/") + .and_then(|r| r.split_once('/')) + .map(|(kind, _)| kind) + .filter(|_| name.starts_with("data/") && name.ends_with(".json")) + { + if let Ok(mut v) = serde_json::from_slice::<Value>(&bytes) { + if kind == "structure" { + crate::worldgen::convention_tags(&v["biomes"], &mut biome_conventions); + } + let types = &mut report.worldgen_types; + let carried = crate::processors::carry( + kind, + &mut v, + &processor_data, + &mut types.processors_carried, + ) | crate::processors::rule_tests( + kind, + &mut v, + &mut types.rule_tests_carried, + ); + let mut changed = + crate::worldgen::upgrade(kind, &mut v, types, &set_tags) || carried; + if kind == "structure" { + let path = rel.trim_start_matches("worldgen/structure/"); + let structure = format!("{id}:{}", path.trim_end_matches(".json")); + changed |= crate::worldgen::disables(&structure, &mut v); + changed |= + crate::worldgen::add_piece_counts(&structure, &mut v, &piece_counts); + } + if changed { + bytes = serde_json::to_vec_pretty(&v).unwrap_or(bytes); + } + } + } else if let Some(path) = rel + .strip_prefix("lithostitched/worldgen_modifier/") + .filter(|_| name.starts_with("data/") && name.ends_with(".json")) + { + // Additions to other sets and pools, as files the game merges. + let modifier = serde_json::from_slice::<Value>(&bytes).ok(); + let types = &mut report.worldgen_types; + if let Some((kind, mut added)) = + modifier.and_then(|v| crate::worldgen::modifier(&v, loaded, types)) + { + crate::processors::carry( + kind, + &mut added, + &processor_data, + &mut types.processors_carried, + ); + crate::processors::rule_tests(kind, &mut added, &mut types.rule_tests_carried); + crate::worldgen::upgrade(kind, &mut added, types, &set_tags); + let to = format!( + "data/{id}/worldgen/{kind}/{}/{path}", + crate::worldgen::ADDED + ); + write( + &inside.join(to), + &serde_json::to_vec_pretty(&added).unwrap_or_default(), + )?; + } + } else if rel.starts_with("trial_spawner/") + && name.starts_with("data/") + && name.ends_with(".json") + { + // Trial spawner configs (Moog's arenas): their mobs' NBT. + if let Ok(mut config) = serde_json::from_slice::<Value>(&bytes) + && crate::processors::upgrade_trial_spawner(&mut config) + { + bytes = serde_json::to_vec_pretty(&config).unwrap_or(bytes); + } + } else if rel.starts_with("tags/worldgen/biome/") && name.starts_with("data/") { + if let Ok(v) = serde_json::from_slice::<Value>(&bytes) { + crate::worldgen::convention_tags(&v, &mut biome_conventions); } } else if rel.starts_with("loot_table/") && name.starts_with("data/") { + if let Some(b) = rel + .strip_prefix("loot_table/blocks/") + .and_then(|b| b.strip_suffix(".json")) + { + block_loot.insert(b.to_owned()); + } if let Ok(mut table) = serde_json::from_slice::<Value>(&bytes) { let before = table.clone(); upgrade_loot(&mut table); + renamed_ids(&mut table); if table != before { report.loot_tables_upgraded += 1; bytes = serde_json::to_vec_pretty(&table).unwrap_or(bytes); @@ -425,6 +551,35 @@ pub fn carry( } write(&dest, &bytes)?; } + // Entries the mod adds to other structure sets in Java code, for the + // structures it has. + for (file, set, entries) in crate::worldgen::code_set_entries(id) { + let entries: Vec<Value> = entries + .into_iter() + .filter(|(s, _)| { + s.split_once(':').is_some_and(|(ns, path)| { + inside + .join(format!("data/{ns}/worldgen/structure/{path}.json")) + .exists() + }) + }) + .map(|(structure, weight)| json!({"structure": structure, "weight": weight})) + .collect(); + if entries.is_empty() { + continue; + } + let added = &mut report.worldgen_types.added_to; + *added.entry(set.to_owned()).or_default() += entries.len(); + let to = format!( + "data/{id}/worldgen/structure_set/{}/{file}.json", + crate::worldgen::ADDED + ); + let v = json!({"horizon:add_to": set, "structures": entries}); + write( + &inside.join(to), + &serde_json::to_vec_pretty(&v).unwrap_or_default(), + )?; + } // 1.21.4 moved item models behind `items/<name>.json` definitions. for m in &item_models { let def = inside.join(format!("assets/{id}/items/{m}.json")); @@ -435,6 +590,18 @@ pub fn carry( report.item_definitions_added += 1; } } + // The loader's convention biome tags the structures and their tags name + // (NeoForge's `c:is_plains`...): the game has no loader, so they come along. + for tag in crate::worldgen::with_included(&biome_conventions, conventions) { + let file = inside.join(format!("data/c/tags/worldgen/biome/{tag}.json")); + if !file.exists() { + write( + &file, + &serde_json::to_vec_pretty(&conventions[&tag]).unwrap_or_default(), + )?; + report.convention_biome_tags += 1; + } + } let decl = inside.join(format!("data/{id}/horizon")); let write_decl = |kind: &str, name: &str, v: &Value| { let text = serde_json::to_vec_pretty(v).unwrap_or_default(); @@ -470,6 +637,34 @@ pub fn carry( .push(format!("its item is {}", block.item)); } else { declared.insert(full.clone()); + let drop = (!block_loot.contains(b)) + .then(|| block.drops_itself(full)) + .flatten(); + if let Some(drop) = drop { + let mut entry = json!({"type": "minecraft:item", "name": full}); + if let crate::oracle::SelfDrop::When(property, value) = drop { + entry["condition"] = json!({ + "type": "minecraft:match_block", + "blocks": full, + "state": {property: value} + }); + } + let table = json!({ + "type": "minecraft:block", + "pools": [{ + "condition": {"type": "minecraft:survives_explosion"}, + "entries": [entry], + "rolls": 1 + }], + "random_sequence": format!("{id}:blocks/{b}") + }); + let file = inside.join(format!("data/{id}/loot_table/blocks/{b}.json")); + write( + &file, + &serde_json::to_vec_pretty(&table).unwrap_or_default(), + )?; + report.loot_tables_added += 1; + } } write_decl("block", b, &v)?; report.blocks.insert(b.to_owned(), choice.template); @@ -657,6 +852,27 @@ mod tests { assert_eq!(new, glass); } + #[test] + fn renames_ids_vanilla_renamed() { + let mut recipe = json!({"type": "minecraft:crafting_shaped", "pattern": ["c"], + "key": {"c": {"item": "minecraft:chain"}}, "result": {"id": "m:sign", "count": 1}}); + assert!(renamed_ids(&mut recipe)); + assert_eq!(recipe["key"]["c"]["item"], "minecraft:iron_chain"); + let mut rule = json!({"input_predicate": {"predicate_type": "minecraft:block_match", + "block": "minecraft:chain"}, "output_state": {"id": "minecraft:chain", + "properties": {"axis": "y"}}}); + assert!(renamed_ids(&mut rule)); + assert_eq!(rule["input_predicate"]["block"], "minecraft:iron_chain"); + assert_eq!(rule["output_state"]["id"], "minecraft:iron_chain"); + // Only whole ids: other blocks and mods' own chains stay. + let mut other = json!([ + "minecraft:chain_command_block", + "m:chain", + "minecraft:iron_chain" + ]); + assert!(!renamed_ids(&mut other)); + } + #[test] fn templates_from_blockstate_properties() { let door = @@ -755,6 +971,14 @@ mod tests { r#"{"values": ["gem:gem_block"]}"#, ), ("data/c/tags/item/gems.json", r#"{"values": ["gem:gem"]}"#), + ( + "data/gem/lithostitched/worldgen_modifier/houses.json", + r#"{"type": "lithostitched:add_template_pool_elements", + "template_pools": "minecraft:village/plains/houses", + "elements": [{"weight": 2, "element": {"element_type": "minecraft:single_pool_element", + "location": "gem:hut", "projection": "rigid", + "processors": {"processors": [{"processor_type": "lithostitched:block_swap"}]}}}]}"#, + ), // What the game would refuse: vanilla skips these files alone. ("assets/gem/lang/ry_UA.json", r#"{"item.gem.gem": "Gem"}"#), ("data/gem/tags/item/empty.json", ""), @@ -781,8 +1005,17 @@ mod tests { ); assert_eq!(info.census.classes, 1); let out = dir.join("work/mods/gem"); - let report = carry(&jar, &info, &out, None, &|_| true).unwrap(); - assert_eq!(report.copied, 13); + let report = carry( + &jar, + &info, + &out, + None, + &|_| true, + &|_| true, + &BTreeMap::new(), + ) + .unwrap(); + assert_eq!(report.copied, 14); let unreadable: Vec<&str> = report.unreadable.keys().map(String::as_str).collect(); assert_eq!( unreadable, @@ -815,6 +1048,25 @@ mod tests { ) .unwrap(); assert_eq!(recipe["key"]["#"], "gem:gem"); + // A lithostitched pool addition, as a file the game merges, upgraded + // as the mod's own pools are. + let added: Value = serde_json::from_slice( + &fs::read(carried.join("data/gem/worldgen/template_pool/horizon_added/houses.json")) + .unwrap(), + ) + .unwrap(); + assert_eq!( + added["horizon:add_to"], + json!(["minecraft:village/plains/houses"]) + ); + assert_eq!( + added["elements"][0]["element"]["processors"], + json!({"processors": []}) + ); + assert_eq!( + report.worldgen_types.added_to["minecraft:village/plains/houses"], + 1 + ); // Horizon's own reader accepts it: blocks and items declared, files fenced. let package = horizon_mods::Package::read(&carried).unwrap(); diff --git a/crates/horizon-port-pack/src/fetch.rs b/crates/horizon-port-pack/src/fetch.rs index 011e99e1f..f8f7b2dc7 100644 --- a/crates/horizon-port-pack/src/fetch.rs +++ b/crates/horizon-port-pack/src/fetch.rs @@ -139,6 +139,28 @@ pub fn fetch( } fetched.files.push(o); } + // The loader's own data (its convention tags), from its own repository. + if let Some((dest, url)) = crate::worldgen::loader_jar(work, &pack.loader, &pack.loader_version) + .filter(|(dest, _)| !dest.exists()) + { + let sha1 = ureq::get(&format!("{url}.sha1")) + .set("User-Agent", modrinth::AGENT) + .call() + .ok() + .and_then(|r| r.into_string().ok()) + .map(|s| s.trim().to_owned()); + let made = dest.parent().map(fs::create_dir_all); + match made + .unwrap_or(Ok(())) + .map_err(|e| e.to_string()) + .and_then(|()| download(&url, sha1.as_deref(), &dest)) + { + Ok(()) => log(format!("loader: {}", dest.display())), + Err(e) => log(format!( + "loader: {e} (structures keep only vanilla biome tags)" + )), + } + } write_json(&work.join("fetch.json"), &fetched)?; log(format!( "jars: {} downloaded, {} copied, {} already here, {} need a CurseForge key, {} not found, {} failed", diff --git a/crates/horizon-port-pack/src/lib.rs b/crates/horizon-port-pack/src/lib.rs index ecd61956c..08f9b273f 100644 --- a/crates/horizon-port-pack/src/lib.rs +++ b/crates/horizon-port-pack/src/lib.rs @@ -14,4 +14,6 @@ pub mod jar; pub mod modrinth; pub mod oracle; pub mod pipeline; +pub mod processors; pub mod report; +pub mod worldgen; diff --git a/crates/horizon-port-pack/src/oracle.rs b/crates/horizon-port-pack/src/oracle.rs index 1fa9a717c..7e04aa9ef 100644 --- a/crates/horizon-port-pack/src/oracle.rs +++ b/crates/horizon-port-pack/src/oracle.rs @@ -60,6 +60,10 @@ pub struct State { pub sound: Value, pub outline: Value, pub collision: Value, + /// What breaking the state drops, per tool (`hand`, `diamond_pickaxe`, + /// `shears`, `silk_touch_pickaxe`...): item id → count. + #[serde(default)] + pub drops: BTreeMap<String, BTreeMap<String, u32>>, } #[derive(Debug, Deserialize)] @@ -76,6 +80,23 @@ pub struct Item { const VANILLA_PACKAGE: &str = "net.minecraft."; /// A state key with its properties sorted, so keys compare across blocks. +/// Which states of a block drop the block itself. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SelfDrop { + /// Every state: `dropSelf`. + Always, + /// Only the states where this property has this value. + When(String, String), +} + +/// A state key's `property=value` pairs. +fn pairs(key: &str) -> BTreeSet<(String, String)> { + key.split(',') + .filter_map(|p| p.split_once('=')) + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect() +} + pub fn state_key(key: &str) -> String { let mut parts: Vec<&str> = key.split(',').filter(|p| !p.is_empty()).collect(); parts.sort_unstable(); @@ -96,6 +117,45 @@ impl Block { .first() .is_some_and(|c| !c.starts_with(VANILLA_PACKAGE)) } + /// Every state drops one `item` (the block's own) with every tool, except + /// where the state needs a tool and gets none: vanilla's `dropSelf`. Or + /// only the states where one property has one value do, and the others + /// drop nothing with any tool: a door's lower half (`createDoorTable`). + /// Mods often register these tables in code, so their jar has no file. + pub fn drops_itself(&self, item: &str) -> Option<SelfDrop> { + let one = BTreeMap::from([(item.to_owned(), 1)]); + let (mut dropping, mut nothing) = (Vec::new(), Vec::new()); + for (key, state) in &self.states { + if state.drops.is_empty() { + continue; + } + let mut drops = false; + let mut short = false; + for got in state.drops.values() { + if *got == one { + drops = true; + } else if got.is_empty() { + short = true; + } else { + return None; + } + } + match (drops, short) { + (true, true) if !state.requires_tool => return None, + (true, _) => dropping.push(pairs(key)), + (false, _) => nothing.push(pairs(key)), + } + } + let (first, rest) = dropping.split_first()?; + if nothing.is_empty() { + return Some(SelfDrop::Always); + } + first + .iter() + .filter(|pair| rest.iter().all(|s| s.contains(*pair))) + .find(|pair| nothing.iter().all(|s| !s.contains(*pair))) + .map(|(p, v)| SelfDrop::When(p.clone(), v.clone())) + } fn default_state(&self) -> Option<&State> { self.states .get(&self.default) @@ -373,6 +433,65 @@ mod tests { assert_eq!(tile.differences[0], "sounds: no vanilla block has them"); } + #[test] + fn drops_itself_is_vanillas_drop_self() { + let cube = json!([[0, 0, 0, 1, 1, 1]]); + let with = |requires_tool: bool, drops: Value| { + let mut s = state(1.5, "stone", cube.clone()); + s["requires_tool"] = json!(requires_tool); + s["drops"] = drops; + let b: Block = serde_json::from_value(block(&[], json!({}), json!({"": s}))).unwrap(); + b.drops_itself("m:tile") + }; + let me = json!({"m:tile": 1}); + let always = Some(SelfDrop::Always); + assert_eq!(with(false, json!({"hand": me, "shears": me})), always); + // A state that needs a tool drops nothing by hand, as dropSelf does. + assert_eq!( + with(true, json!({"hand": {}, "diamond_pickaxe": me})), + always + ); + assert_eq!( + with(false, json!({"hand": {}, "diamond_pickaxe": me})), + None + ); + // Two of itself (a double slab), or something else, is not dropSelf. + assert_eq!(with(false, json!({"hand": {"m:tile": 2}})), None); + assert_eq!(with(false, json!({"hand": {"m:other": 1}})), None); + assert_eq!(with(false, json!({})), None); + } + + #[test] + fn a_door_drops_from_its_lower_half() { + let cube = json!([[0, 0, 0, 1, 1, 1]]); + let me = json!({"hand": {"m:door": 1}, "shears": {"m:door": 1}}); + let none = json!({"hand": {}, "shears": {}}); + let door = |upper: &Value| { + let mut states = serde_json::Map::new(); + for (key, drops) in [ + ("half=lower,open=false", &me), + ("half=lower,open=true", &me), + ("half=upper,open=false", upper), + ("half=upper,open=true", upper), + ] { + let mut s = state(3.0, "wood", cube.clone()); + s["drops"] = drops.clone(); + states.insert(key.to_owned(), s); + } + let props = json!({"half": ["upper", "lower"], "open": ["true", "false"]}); + let b: Block = + serde_json::from_value(block(&[], props, Value::Object(states))).unwrap(); + b.drops_itself("m:door") + }; + assert_eq!( + door(&none), + Some(SelfDrop::When("half".to_owned(), "lower".to_owned())) + ); + assert_eq!(door(&me), Some(SelfDrop::Always)); + // Something else from the upper half: not a door table. + assert_eq!(door(&json!({"hand": {"m:other": 1}})), None); + } + #[test] fn state_keys_sort() { assert_eq!( diff --git a/crates/horizon-port-pack/src/pipeline.rs b/crates/horizon-port-pack/src/pipeline.rs index 80a88ee18..7152dc921 100644 --- a/crates/horizon-port-pack/src/pipeline.rs +++ b/crates/horizon-port-pack/src/pipeline.rs @@ -119,13 +119,28 @@ pub fn carry( .ok() }); let allowed = |b: &str| vanilla.as_ref().is_none_or(|v| v.contains(b)); - let mut done = 0; - for r in &records { - let chosen = if only.is_empty() { + let conventions = crate::worldgen::loader_biome_tags(work); + let chosen = |r: &inventory::Record| { + if only.is_empty() { r.class == "content" } else { only.contains(&r.key) - }; + } + }; + // The mods ported along (carried now or before), for the conditions of + // the mods' worldgen modifiers. + let ported: BTreeSet<&str> = records + .iter() + .filter(|r| { + r.jar.is_some() && (chosen(r) || work.join("mods").join(&r.key).join("carry").is_dir()) + }) + .filter_map(|r| Some(r.info.as_ref()?.mod_id.as_str())) + .chain(["minecraft"]) + .collect(); + let loaded = |m: &str| ported.contains(m); + let mut done = 0; + for r in &records { + let chosen = chosen(r); let (Some(jar), Some(info)) = (&r.jar, &r.info) else { if chosen && !only.is_empty() { log(format!( @@ -154,16 +169,19 @@ pub fn carry( &work.join("mods").join(&r.key), facts.as_ref().filter(seen), &allowed, + &loaded, + &conventions, ) { Ok(report) => { done += 1; log(format!( - "{}: {} files, {} recipes upgraded ({} kept), {} loot tables upgraded, {} item definitions added, {} blocks ({} left out, {} with differences), {} items ({} left out), {} convention tags, {} outside", + "{}: {} files, {} recipes upgraded ({} kept), {} loot tables upgraded ({} added), {} item definitions added, {} blocks ({} left out, {} with differences), {} items ({} left out), {} convention tags, {} outside", r.key, report.copied, report.recipes_upgraded, report.recipes_kept.len(), report.loot_tables_upgraded, + report.loot_tables_added, report.item_definitions_added, report.blocks.len(), report.blocks_unknown.len(), diff --git a/crates/horizon-port-pack/src/processors.rs b/crates/horizon-port-pack/src/processors.rs new file mode 100644 index 000000000..33cde2f99 --- /dev/null +++ b/crates/horizon-port-pack/src/processors.rs @@ -0,0 +1,1019 @@ +//! Structure processors the structure libraries write in Java, carried over +//! as data the game runs: the ones that give spawners their mob. +//! +//! - Moog's Structure Lib's and Repurposed Structures' spawner randomizing +//! processors pick a mob from a weighted list for each spawner. They become +//! `horizon:spawner_mobs` (`horizon_world::worldgen::structure::processor`), +//! with Repurposed's `rs_spawners` list written in. +//! - YUNG's Better Dungeons and Better Desert Temples turn a spawner or a +//! placeholder block into a spawner of a fixed mob. That is vanilla's `rule` +//! processor with an `append_static` block entity. +//! - Moog's vanilla loot swap only acts when its mod's "replace vanilla" +//! preset is on; one that ships off is a no-op and is taken out. +//! +//! What is not here is taken out of its list later and counted +//! (`worldgen::upgrade`). The entity NBT is written in 26.3's shape (an +//! `equipment` map, not 1.21.1's `HandItems` and `ArmorItems`). +use serde_json::{Value, json}; +use std::{ + collections::{BTreeMap, BTreeSet}, + io::{Read, Seek}, +}; + +/// What the processors read from the mod's own data files. +#[derive(Debug, Default)] +pub struct ProcessorData { + /// Repurposed Structures' `rs_spawners/<path>.json` by id: each mob and + /// its weight, without the weight-0 entries its loader removes. + pub spawners: BTreeMap<String, Vec<(String, f64)>>, + /// Moog's "replace vanilla" presets that are on by default: + /// `(mod id, vanilla_key)`. + pub replace_vanilla: BTreeSet<(String, String)>, +} + +impl ProcessorData { + pub fn read<R: Read + Seek>(zip: &mut zip::ZipArchive<R>) -> Self { + let mut out = Self::default(); + for i in 0..zip.len() { + let Ok(mut entry) = zip.by_index(i) else { + continue; + }; + let name = entry.name().to_owned(); + let Some((ns, rest)) = name + .strip_prefix("data/") + .and_then(|r| r.strip_suffix(".json")) + .and_then(|r| r.split_once('/')) + else { + continue; + }; + let spawners = rest.strip_prefix("rs_spawners/"); + if spawners.is_none() && rest != "moogs_structures/replace_vanilla" { + continue; + } + let mut text = String::new(); + let Ok(v) = entry + .read_to_string(&mut text) + .map_err(|_| ()) + .and_then(|_| serde_json::from_str::<Value>(&text).map_err(|_| ())) + else { + continue; + }; + if let Some(path) = spawners { + let mobs = v["mobs"] + .as_array() + .into_iter() + .flatten() + .filter_map(|m| Some((m["name"].as_str()?.to_owned(), m["weight"].as_f64()?))) + .filter(|(_, w)| *w != 0.) + .collect(); + out.spawners.insert(format!("{ns}:{path}"), mobs); + continue; + } + for preset in v["presets"].as_array().into_iter().flatten() { + if preset["default_enabled"].as_bool() != Some(true) { + continue; + } + for r in preset["replacements"].as_array().into_iter().flatten() { + if let Some(key) = r["vanilla_key"].as_str() { + out.replace_vanilla.insert((ns.to_owned(), key.to_owned())); + } + } + } + } + out + } +} + +/// Calls `f` on each processor list in a worldgen file: a `processor_list` +/// file, and the inline lists of a template pool's elements (list elements +/// included). Whether any call changed something. +pub fn each_list(kind: &str, v: &mut Value, f: &mut dyn FnMut(&mut Value) -> bool) -> bool { + match kind { + "processor_list" => f(v), + "template_pool" => { + let mut changed = false; + for e in v["elements"].as_array_mut().into_iter().flatten() { + let element = &mut e["element"]; + if let Some(list) = element.get_mut("elements").and_then(Value::as_array_mut) { + for inner in list { + if let Some(p) = inner.get_mut("processors") { + changed |= f(p); + } + } + } else if let Some(p) = element.get_mut("processors") { + changed |= f(p); + } + } + changed + } + _ => false, + } +} + +/// The processors of a list: `{"processors": [...]}` or a bare list (an id +/// names another file and is left alone). +pub fn processors(list: &mut Value) -> Option<&mut Vec<Value>> { + match list { + Value::Array(a) => Some(a), + Value::Object(o) => o.get_mut("processors").and_then(Value::as_array_mut), + _ => None, + } +} + +/// Rewrites the processors of a worldgen file that have a data form; each is +/// counted by type in `carried`. Whether anything changed. +pub fn carry( + kind: &str, + v: &mut Value, + data: &ProcessorData, + carried: &mut BTreeMap<String, usize>, +) -> bool { + each_list(kind, v, &mut |list| { + let Some(list) = processors(list) else { + return false; + }; + let mut changed = false; + let mut out = Vec::with_capacity(list.len()); + for p in list.drain(..) { + let kind = p["processor_type"].as_str().unwrap_or_default().to_owned(); + match as_data(&kind, &p, data) { + Some(replacement) => { + *carried.entry(kind).or_default() += 1; + out.extend(replacement); + changed = true; + } + None => out.push(p), + } + } + *list = out; + changed + }) +} + +/// Repurposed Structures' rule tests and the game's types that run them +/// (`horizon_world::worldgen`'s `rule_test` and `structure::processor`). +const RULE_TESTS: [(&str, &str); 3] = [ + ( + "repurposed_structures:matter_phase_rule_test", + "horizon:matter_phase", + ), + ( + "repurposed_structures:piece_origin_axis_aligned_linear_pos_rule_test", + "horizon:piece_origin_axis_aligned_linear_pos", + ), + ( + "repurposed_structures:y_value_pos_rule_test", + "horizon:y_value", + ), +]; + +/// Renames the rule tests written in Java that the game runs under its own +/// type ([`RULE_TESTS`]) in a worldgen file's processor lists; each is +/// counted by type in `carried`. Their fields are the mod's. Whether +/// anything changed. Without this the game, like vanilla, refuses the list +/// and every pool naming it: Repurposed's mineshafts and Nether monument. +pub fn rule_tests(kind: &str, v: &mut Value, carried: &mut BTreeMap<String, usize>) -> bool { + fn rename(v: &mut Value, carried: &mut BTreeMap<String, usize>) -> bool { + match v { + Value::Object(o) => { + let mut changed = false; + if let Some(Value::String(t)) = o.get_mut("predicate_type") + && let Some((old, new)) = RULE_TESTS.iter().find(|(old, _)| t == old) + { + *carried.entry((*old).to_owned()).or_default() += 1; + *t = (*new).to_owned(); + changed = true; + } + o.values_mut().fold(changed, |c, x| rename(x, carried) | c) + } + Value::Array(a) => a.iter_mut().fold(false, |c, x| rename(x, carried) | c), + _ => false, + } + } + each_list(kind, v, &mut |list| rename(list, carried)) +} + +/// The data form of a Java processor: the processors to put in its place +/// (none for a no-op), or `None` when it has none. +fn as_data(kind: &str, p: &Value, data: &ProcessorData) -> Option<Vec<Value>> { + let (ns, _) = kind.split_once(':')?; + Some(match kind { + "moogs_structures:spawner_randomizing_processor" => { + let mobs = p["weighted_entities"] + .as_array()? + .iter() + .map(|e| { + // The entry's NBT, then its id over it. + let mut entity = match &e["nbt"] { + Value::Object(o) => o.clone(), + _ => serde_json::Map::new(), + }; + entity.insert("id".into(), e["entity"].as_str()?.into()); + Some(json!({"entity": entity, "weight": e["weight"].as_f64()?})) + }) + .collect::<Option<Vec<_>>>()?; + vec![spawner_mobs(p, mobs, None)] + } + "repurposed_structures:spawner_randomizing_processor" => { + // A list the mod does not ship falls back to a vanilla dungeon + // mob in the mod; left out here. + let list = data + .spawners + .get(p["rs_spawner_resourcelocation"].as_str()?)?; + let mobs = list + .iter() + .map(|(id, weight)| json!({"entity": {"id": id}, "weight": weight})) + .collect(); + vec![spawner_mobs(p, mobs, repurposed_light(p)?)] + } + "moogs_structures:vanilla_loot_swap_processor" => { + let key = ( + p["modid"].as_str()?.to_owned(), + p["vanilla_key"].as_str()?.to_owned(), + ); + if data.replace_vanilla.contains(&key) { + return None; + } + Vec::new() + } + "moogs_structures:trial_spawner_randomizing_processor" => { + // The configs by id: 26.3 reads them from `trial_spawner/`, the + // folder Moog's loads them from. + let mut nbt = json!({"normal_config": p["normal_config"].as_str()?}); + if let Some(ominous) = p["ominous_config"].as_str() { + nbt["ominous_config"] = ominous.into(); + } + // The state the template was saved with goes. + let saved = [ + "server_data", + "shared_data", + "spawn_data", + "cooldown_end_at_tick", + "next_mob_spawns_at", + ]; + vec![same_state_rule(&TRIAL_SPAWNER_STATES, &saved, |_| { + nbt.clone() + })] + } + "moogs_structures:vault_randomizing_processor" => { + let normal = p["loot_table"].as_str()?; + let config = |ominous: bool| { + let (table, key) = match ominous { + true => ( + p["ominous_loot_table"].as_str().unwrap_or(normal), + p["ominous_key_item"] + .as_str() + .unwrap_or("minecraft:ominous_trial_key"), + ), + false => ( + normal, + p["key_item"].as_str().unwrap_or("minecraft:trial_key"), + ), + }; + // Merged into the vault's config, as the mod puts both in. + json!({"config": {"loot_table": table, "key_item": {"id": key, "count": 1}}}) + }; + vec![same_state_rule( + &VAULT_STATES, + &["server_data", "shared_data"], + |s| config(s.get("ominous") == Some(&"true")), + )] + } + _ if ns == "betterdeserttemples" + && let Some(processor) = desert_temple(kind) => + { + vec![processor] + } + "lithostitched:block_swap" => { + // The same map; the game's swap keeps the properties both have. + p["blocks"].as_object()?; + vec![json!({"processor_type": "horizon:block_swap", "blocks": p["blocks"]})] + } + "betterdungeons:small_dungeon_chest_processor" => { + // Its config's defaults: one chest at least, two at most, a + // fifth of the others kept until then; ChestBlock covers both. + vec![json!({"processor_type": "horizon:count_cap", + "blocks": ["minecraft:chest", "minecraft:trapped_chest"], + "min": 1, "max": 2, "chance": 0.2f32 as f64, + "replacement": block("minecraft:cave_air")})] + } + _ if ns == "betterdungeons" || ns == "betterdeserttemples" => vec![yung_spawner(kind, p)?], + _ => return None, + }) +} + +/// A block's states, as (block, [(property, values)]). +type States = ( + &'static str, + &'static [(&'static str, &'static [&'static str])], +); +const TRIAL_SPAWNER_STATES: States = ( + "minecraft:trial_spawner", + &[ + ( + "trial_spawner_state", + &[ + "inactive", + "waiting_for_players", + "active", + "waiting_for_reward_ejection", + "ejecting_reward", + "cooldown", + ], + ), + ("ominous", &["false", "true"]), + ], +); +const VAULT_STATES: States = ( + "minecraft:vault", + &[ + ("facing", &["north", "south", "west", "east"]), + ( + "vault_state", + &["inactive", "active", "unlocking", "ejecting"], + ), + ("ominous", &["false", "true"]), + ], +); + +/// Moog's trial spawner and vault processors keep the block, take keys out +/// of its block entity and set others. As vanilla's `rule`: one rule per +/// state of the block, matching it and writing it back, with the game's +/// `horizon:edit` modifier taking out `remove` and merging `nbt(state)` in. +fn same_state_rule( + states: &States, + remove: &[&str], + nbt: impl Fn(&BTreeMap<&str, &str>) -> Value, +) -> Value { + let (block, properties) = states; + let mut all = vec![BTreeMap::new()]; + for (key, values) in properties.iter() { + all = all + .into_iter() + .flat_map(|s| { + values.iter().map(move |v| { + let mut s = s.clone(); + s.insert(*key, *v); + s + }) + }) + .collect(); + } + let rules: Vec<Value> = all + .iter() + .map(|s| { + let state = json!({"id": block, "properties": s}); + json!({ + "input_predicate": {"predicate_type": "minecraft:blockstate_match", "block_state": state}, + "location_predicate": {"predicate_type": "minecraft:always_true"}, + "output_state": state, + "block_entity_modifier": {"type": "horizon:edit", "remove": remove, "data": nbt(s)}, + }) + }) + .collect(); + json!({"processor_type": "minecraft:rule", "rules": rules}) +} + +/// An entity's NBT in 26.3's shape, in place: 1.21.1's `ArmorItems` (feet +/// to head), `HandItems` (main hand, off hand) and their drop chances become +/// `equipment` and `drop_chances` by slot; empty items and the default drop +/// chance (0.085) are left out, as 26.3 saves them. Whether it changed. +pub fn upgrade_entity(entity: &mut Value) -> bool { + let Some(o) = entity.as_object_mut() else { + return false; + }; + const ARMOR: [&str; 4] = ["feet", "legs", "chest", "head"]; + const HANDS: [&str; 2] = ["mainhand", "offhand"]; + let mut changed = false; + for (items, chances, slots) in [ + ("ArmorItems", "ArmorDropChances", &ARMOR[..]), + ("HandItems", "HandDropChances", &HANDS[..]), + ] { + if let Some(Value::Array(list)) = o.remove(items) { + changed = true; + for (slot, item) in slots.iter().zip(list) { + if item.get("id").is_some() { + let equipment = o.entry("equipment").or_insert_with(|| json!({})); + equipment[*slot] = item; + } + } + } + if let Some(Value::Array(list)) = o.remove(chances) { + changed = true; + for (slot, chance) in slots.iter().zip(list) { + if chance.as_f64().is_some_and(|c| (c - 0.085).abs() > 1e-6) { + let drop = o.entry("drop_chances").or_insert_with(|| json!({})); + drop[*slot] = chance; + } + } + } + } + changed +} + +/// A 1.21.1 trial spawner config (`trial_spawner/`) in 26.3's shape, in +/// place: its mobs' NBT ([`upgrade_entity`]). Whether it changed. +pub fn upgrade_trial_spawner(config: &mut Value) -> bool { + let mut changed = false; + for p in config["spawn_potentials"] + .as_array_mut() + .into_iter() + .flatten() + { + changed |= upgrade_entity(&mut p["data"]["entity"]); + } + changed +} + +/// A block state as 26.3 writes it. +fn block(id: &str) -> Value { + json!({"id": id}) +} + +/// Better Desert Temples' placeholder blocks (glass, concrete and wool in +/// the templates) as the mod's processors turn them: the fixed ones as +/// vanilla's `rule`, the random ones as the game's `horizon:pick`, with the +/// mod's bounds on one `nextFloat` (YUNG's BlockStateRandomizer adds its +/// chances up in floats). The ones that read or change the world around +/// (pillars, Diorite's waterlogging) stay dropped. +fn desert_temple(kind: &str) -> Option<Value> { + let swap = |from: &str, to: &str| { + json!({"processor_type": "minecraft:rule", "rules": [{ + "input_predicate": {"predicate_type": "minecraft:block_match", "block": from}, + "location_predicate": {"predicate_type": "minecraft:always_true"}, + "output_state": block(to)}]}) + }; + let pick = |from: &str, picks: Vec<Value>, default: Value| json!({"processor_type": "horizon:pick", "block": from, "picks": picks, "default": default}); + // YUNG's BlockStateRandomizer: an entry wins below the sum of the + // chances so far, summed as floats. + let randomizer = |entries: &[(f32, &str)]| { + let mut bottom = 0f32; + entries + .iter() + .map(|(chance, id)| { + bottom += chance; + json!({"below": bottom as f64, "state": block(id)}) + }) + .collect::<Vec<_>>() + }; + let at = |below: f32, id: &str| json!({"below": below as f64, "state": block(id)}); + // Sandstone stairs, upside down, facing Plane.HORIZONTAL.getRandomDirection. + let stairs = || { + let states: Vec<Value> = ["north", "east", "south", "west"] + .iter() + .map(|facing| { + json!({"id": "minecraft:sandstone_stairs", "properties": { + "facing": facing, "half": "top", "shape": "straight", "waterlogged": "false"}}) + }) + .collect(); + json!({"states": states}) + }; + Some(match kind.strip_prefix("betterdeserttemples:")? { + "blue_concrete_processor" => swap("minecraft:blue_concrete", "minecraft:blue_terracotta"), + "yellow_concrete_processor" => { + swap("minecraft:yellow_concrete", "minecraft:yellow_terracotta") + } + "red_wool_processor" => swap("minecraft:red_wool", "minecraft:tnt"), + "white_stained_glass_processor" => pick( + "minecraft:white_stained_glass", + randomizer(&[(0.4, "minecraft:cobweb")]), + json!({"state": block("minecraft:air")}), + ), + "polished_diorite_processor" => pick( + "minecraft:polished_diorite", + randomizer(&[(0.6, "minecraft:cut_sandstone")]), + json!({"state": block("minecraft:sandstone")}), + ), + "orange_stained_glass_processor" => { + let mut sus = at(0.01, "minecraft:suspicious_sand"); + sus["nbt"] = json!({"LootTable": "minecraft:archaeology/desert_pyramid"}); + let mut stairs = stairs(); + stairs["below"] = (0.45f32 as f64).into(); + pick( + "minecraft:orange_stained_glass", + vec![ + sus, + at(0.1, "minecraft:sand"), + at(0.2, "minecraft:sandstone"), + stairs, + ], + json!({"state": block("minecraft:cut_sandstone")}), + ) + } + "red_stained_glass_processor" => pick( + "minecraft:red_stained_glass", + vec![at(0.3, "minecraft:sand"), at(0.75, "minecraft:sandstone")], + stairs(), + ), + "pot_processor" => { + // Four sherds, one float each; the pot back to its default state. + let values: Vec<Value> = [ + (0.05f32, "archer"), + (0.1, "miner"), + (0.15, "prize"), + (0.2, "skull"), + ] + .iter() + .map(|(below, sherd)| { + json!({"below": *below as f64, "value": format!("minecraft:{sherd}_pottery_sherd")}) + }) + .collect(); + pick( + "minecraft:decorated_pot", + Vec::new(), + json!({"state": block("minecraft:decorated_pot"), "lists": [{ + "key": "sherds", "count": 4, "values": values, "default": "minecraft:brick"}]}), + ) + } + _ => return None, + }) +} + +/// [`as_data`]'s `horizon:spawner_mobs` for the mods' spawner randomizing +/// processors, whose fields have the same names and defaults. +fn spawner_mobs(p: &Value, mobs: Vec<Value>, rules: Option<Value>) -> Value { + let mut out = json!({"processor_type": "horizon:spawner_mobs", "mobs": mobs}); + for key in [ + "delay", + "min_spawn_delay", + "max_spawn_delay", + "spawn_count", + "max_nearby_entities", + "required_player_range", + "spawn_range", + ] { + if let Some(n) = p.get(key).filter(|n| n.is_i64()) { + out[key] = n.clone(); + } + } + if let Some(r) = rules { + out["custom_spawn_rules"] = r; + } + if let Some(b) = p.get("spawner_replacement_block") { + out["replacement"] = b.clone(); + } + out +} + +/// Repurposed Structures' `custom_spawn_rules` from its light level ranges: +/// `Some(None)` without either, `None` when one does not read. The sky +/// light's upper bound is written as `max_exclusive`, as the mod does. +fn repurposed_light(p: &Value) -> Option<Option<Value>> { + let range = |key: &str| -> Option<Option<(i64, i64)>> { + match p.get(key) { + None => Some(None), + Some(Value::Number(n)) => n.as_i64().map(|n| Some((n, n))), + Some(v) => Some(Some(( + v["min_inclusive"].as_i64()?, + v["max_inclusive"].as_i64()?, + ))), + } + }; + let (block, sky) = ( + range("valid_block_light_level")?, + range("valid_sky_light_level")?, + ); + if block.is_none() && sky.is_none() { + return Some(None); + } + let mut rules = json!({}); + if let Some((min, max)) = block { + rules["block_light_limit"] = json!({"min_inclusive": min, "max_inclusive": max}); + } + if let Some((min, max)) = sky { + rules["sky_light_limit"] = json!({"min_inclusive": min, "max_exclusive": max}); + } + Some(Some(rules)) +} + +/// An item as 26.3 saves it. +fn item(id: &str) -> Value { + json!({"id": format!("minecraft:{id}"), "count": 1}) +} + +/// YUNG's processors that make a spawner of a fixed mob (YUNG's API's +/// `MobSpawnerData`), as vanilla's `rule`: every `input` block becomes a +/// spawner with that NBT. +fn yung_spawner(kind: &str, p: &Value) -> Option<Value> { + const SPAWNER: &str = "minecraft:spawner"; + // (input block, mob, fields other than the defaults, whether the mob is + // also the only potential, its equipment) + let (input, mob, fields, potential, equipment): (_, _, &[(&str, i64)], _, _) = match kind { + "betterdungeons:mob_spawner_processor" => { + (SPAWNER, p["spawner_mob"].as_str()?, &[], true, None) + } + "betterdungeons:zombie_mob_spawner_processor" => ( + SPAWNER, + "minecraft:zombie", + &[("MaxNearbyEntities", 8)], + true, + None, + ), + "betterdungeons:skeleton_mob_spawner_processor" => ( + SPAWNER, + "minecraft:skeleton", + &[ + ("RequiredPlayerRange", 18), + ("MaxNearbyEntities", 8), + ("MaxSpawnDelay", 650), + ], + true, + None, + ), + "betterdungeons:small_nether_dungeon_mob_spawner_processor" => { + let mob = p["spawner_mob"].as_str()?; + // Wither skeletons get netherite armor that never drops and a + // stone sword (with the mod's default config, they and blazes + // keep their loot). + let armor = (mob == "minecraft:wither_skeleton").then(|| { + json!({ + "equipment": { + "feet": item("netherite_boots"), + "legs": item("netherite_leggings"), + "chest": item("netherite_chestplate"), + "head": item("netherite_helmet"), + "mainhand": item("stone_sword"), + }, + "drop_chances": {"feet": 0.0, "legs": 0.0, "chest": 0.0, "head": 0.0}, + }) + }); + (SPAWNER, mob, &[], true, armor) + } + "betterdungeons:zombie_tombstone_spawner_processor" => ( + "minecraft:black_stained_glass", + "minecraft:skeleton", + &[], + false, + Some(json!({"equipment": {"mainhand": item("iron_sword")}})), + ), + "betterdeserttemples:gravel_processor" => ( + "minecraft:gravel", + "minecraft:husk", + &[("MaxNearbyEntities", 8), ("RequiredPlayerRange", 24)], + false, + None, + ), + // An empty hand list in 1.21.1: the skeletons spawn without a bow, + // since a spawn entry with more than its id is not finalized. + "betterdeserttemples:bone_block_processor" => ( + "minecraft:bone_block", + "minecraft:skeleton", + &[("RequiredPlayerRange", 32)], + false, + Some(json!({"equipment": {}})), + ), + "betterdeserttemples:infested_cracked_stone_bricks_processor" => ( + "minecraft:infested_cracked_stone_bricks", + "minecraft:silverfish", + &[("RequiredPlayerRange", 24)], + false, + None, + ), + // 1.21.1 ignores the items' old `Count` and `tag` (the shield's + // pattern, the boots' dye): plain items. + "betterdeserttemples:yellow_wool_processor" => ( + "minecraft:yellow_wool", + "minecraft:husk", + &[("MaxNearbyEntities", 8), ("RequiredPlayerRange", 24)], + false, + Some(json!({"equipment": { + "mainhand": item("golden_sword"), + "offhand": item("shield"), + "feet": item("leather_boots"), + "legs": item("leather_leggings"), + "chest": item("golden_chestplate"), + "head": item("chainmail_helmet"), + }})), + ), + _ => return None, + }; + let mut entity = json!({"id": mob}); + if let Some(Value::Object(extra)) = equipment { + entity.as_object_mut()?.extend(extra); + } + let potentials = match potential { + true => json!([{"data": {"entity": entity.clone()}, "weight": 1}]), + false => json!([]), + }; + let mut nbt = json!({ + "Delay": 20, "MinSpawnDelay": 200, "MaxSpawnDelay": 800, "SpawnCount": 4, + "MaxNearbyEntities": 6, "RequiredPlayerRange": 16, "SpawnRange": 4, + "SpawnData": {"entity": entity}, + "SpawnPotentials": potentials, + }); + for (key, value) in fields { + nbt[*key] = (*value).into(); + } + Some(json!({ + "processor_type": "minecraft:rule", + "rules": [{ + "input_predicate": {"predicate_type": "minecraft:block_match", "block": input}, + "location_predicate": {"predicate_type": "minecraft:always_true"}, + "output_state": {"Name": SPAWNER}, + "block_entity_modifier": {"type": "minecraft:append_static", "data": nbt}, + }], + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn data() -> ProcessorData { + let mut d = ProcessorData::default(); + d.spawners.insert( + "repurposed_structures:dungeons/badlands".into(), + vec![ + ("minecraft:husk".into(), 10.), + ("minecraft:cave_spider".into(), 3.), + ], + ); + d.replace_vanilla.insert(("mvs".into(), "village".into())); + d + } + + #[test] + fn spawner_processors_become_data() { + let mut list = json!({"processors": [ + {"processor_type": "moogs_structures:spawner_randomizing_processor", + "weighted_entities": [{"entity": "minecraft:blaze", "weight": 2, "nbt": {"Health": 5}}], + "spawn_count": 2, "spawner_replacement_block": {"Name": "minecraft:stone"}}, + {"processor_type": "repurposed_structures:spawner_randomizing_processor", + "rs_spawner_resourcelocation": "repurposed_structures:dungeons/badlands", + "valid_block_light_level": {"min_inclusive": 0, "max_inclusive": 7}}, + {"processor_type": "repurposed_structures:spawner_randomizing_processor", + "rs_spawner_resourcelocation": "repurposed_structures:missing"}, + {"processor_type": "minecraft:gravity", "heightmap": "WORLD_SURFACE_WG", "offset": 0}, + {"processor_type": "moogs_structures:vanilla_loot_swap_processor", + "modid": "mns", "vanilla_key": "fortress", "loot_table_mapping": {}}, + {"processor_type": "moogs_structures:vanilla_loot_swap_processor", + "modid": "mvs", "vanilla_key": "village", "loot_table_mapping": {}}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data(), &mut carried)); + let p = list["processors"].as_array().unwrap(); + assert_eq!(p.len(), 5, "{p:#?}"); + assert_eq!( + p[0], + json!({"processor_type": "horizon:spawner_mobs", + "mobs": [{"entity": {"Health": 5, "id": "minecraft:blaze"}, "weight": 2.0}], + "spawn_count": 2, "replacement": {"Name": "minecraft:stone"}}) + ); + assert_eq!( + p[1], + json!({"processor_type": "horizon:spawner_mobs", + "mobs": [{"entity": {"id": "minecraft:husk"}, "weight": 10.0}, + {"entity": {"id": "minecraft:cave_spider"}, "weight": 3.0}], + "custom_spawn_rules": {"block_light_limit": {"min_inclusive": 0, "max_inclusive": 7}}}) + ); + // Unknown list, vanilla processor, and a swap whose preset is on: kept + // (the Java ones are dropped later); the swap that is off is gone. + assert_eq!( + p[2]["rs_spawner_resourcelocation"], + "repurposed_structures:missing" + ); + assert_eq!(p[3]["processor_type"], "minecraft:gravity"); + assert_eq!(p[4]["modid"], "mvs"); + assert_eq!( + carried, + BTreeMap::from([ + ("moogs_structures:spawner_randomizing_processor".into(), 1), + ("moogs_structures:vanilla_loot_swap_processor".into(), 1), + ( + "repurposed_structures:spawner_randomizing_processor".into(), + 1 + ), + ]) + ); + } + + #[test] + fn yungs_spawners_become_rules() { + let mut pool = json!({"elements": [{"element": {"processors": {"processors": [ + {"processor_type": "betterdungeons:skeleton_mob_spawner_processor"}, + {"processor_type": "betterdeserttemples:bone_block_processor"}, + {"processor_type": "betterdungeons:small_nether_dungeon_mob_spawner_processor", + "spawner_mob": "minecraft:wither_skeleton"}, + {"processor_type": "betterdungeons:candle_processor"}]}}}]}); + let mut carried = BTreeMap::new(); + assert!(carry("template_pool", &mut pool, &data(), &mut carried)); + let p = &pool["elements"][0]["element"]["processors"]["processors"]; + let rule = |i: usize| &p[i]["rules"][0]; + assert_eq!(rule(0)["input_predicate"]["block"], "minecraft:spawner"); + assert_eq!( + rule(0)["output_state"], + json!({"Name": "minecraft:spawner"}) + ); + let nbt = &rule(0)["block_entity_modifier"]["data"]; + assert_eq!( + ( + nbt["RequiredPlayerRange"].clone(), + nbt["MaxNearbyEntities"].clone() + ), + (json!(18), json!(8)) + ); + assert_eq!(nbt["MaxSpawnDelay"], 650); + assert_eq!( + nbt["SpawnPotentials"], + json!([{"data": {"entity": {"id": "minecraft:skeleton"}}, "weight": 1}]) + ); + // Bone blocks become bowless skeleton spawners with no potentials. + let bone = &rule(1)["block_entity_modifier"]["data"]; + assert_eq!(rule(1)["input_predicate"]["block"], "minecraft:bone_block"); + assert_eq!( + bone["SpawnData"], + json!({"entity": {"id": "minecraft:skeleton", "equipment": {}}}) + ); + assert_eq!(bone["SpawnPotentials"], json!([])); + let wither = &rule(2)["block_entity_modifier"]["data"]["SpawnData"]["entity"]; + assert_eq!( + wither["equipment"]["head"]["id"], + "minecraft:netherite_helmet" + ); + assert_eq!(wither["drop_chances"]["feet"], 0.0); + assert_eq!(p[3]["processor_type"], "betterdungeons:candle_processor"); + assert_eq!(carried.values().sum::<usize>(), 3); + } + + #[test] + fn trial_spawners_and_vaults_drop_their_saved_state() { + let mut list = json!({"processors": [ + {"processor_type": "moogs_structures:trial_spawner_randomizing_processor", + "normal_config": "mns:arena/normal", "ominous_config": "mns:arena/ominous"}, + {"processor_type": "moogs_structures:vault_randomizing_processor", + "loot_table": "mns:vaults/main", "ominous_loot_table": "mns:vaults/ominous"}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data(), &mut carried)); + let p = list["processors"].as_array().unwrap(); + let rules = |i: usize| p[i]["rules"].as_array().unwrap().clone(); + // Every state of the block: 6 x 2 trial spawners, 4 x 4 x 2 vaults. + assert_eq!((rules(0).len(), rules(1).len()), (12, 32)); + let spawner = &rules(0)[0]; + assert_eq!( + spawner["input_predicate"]["block_state"], + spawner["output_state"] + ); + assert_eq!( + spawner["block_entity_modifier"], + json!({"type": "horizon:edit", + "remove": ["server_data", "shared_data", "spawn_data", + "cooldown_end_at_tick", "next_mob_spawns_at"], + "data": {"normal_config": "mns:arena/normal", + "ominous_config": "mns:arena/ominous"}}) + ); + for rule in rules(1) { + let ominous = rule["output_state"]["properties"]["ominous"] == "true"; + let (table, key) = match ominous { + true => ("mns:vaults/ominous", "minecraft:ominous_trial_key"), + false => ("mns:vaults/main", "minecraft:trial_key"), + }; + assert_eq!( + rule["block_entity_modifier"], + json!({"type": "horizon:edit", "remove": ["server_data", "shared_data"], + "data": {"config": {"loot_table": table, + "key_item": {"id": key, "count": 1}}}}) + ); + } + assert_eq!(carried.len(), 2); + } + + #[test] + fn trial_spawner_mobs_take_26_3s_equipment() { + let mut config = json!({"spawn_potentials": [{"weight": 1, "data": {"entity": { + "id": "minecraft:skeleton", + "ArmorItems": [{}, {}, {}, {"id": "minecraft:iron_helmet", "count": 1}], + "ArmorDropChances": [0.085, 0.085, 0.085, 0.0], + "HandItems": [{"id": "minecraft:bow", "count": 1}, {}], + "HandDropChances": [0.085, 0.085]}}}]}); + assert!(upgrade_trial_spawner(&mut config)); + assert_eq!( + config["spawn_potentials"][0]["data"]["entity"], + json!({"id": "minecraft:skeleton", + "equipment": {"head": {"id": "minecraft:iron_helmet", "count": 1}, + "mainhand": {"id": "minecraft:bow", "count": 1}}, + "drop_chances": {"head": 0.0}}) + ); + assert!(!upgrade_trial_spawner(&mut config)); + } + + #[test] + fn desert_temple_placeholders_become_rules_and_picks() { + let mut list = json!({"processors": [ + {"processor_type": "betterdeserttemples:red_wool_processor"}, + {"processor_type": "betterdeserttemples:white_stained_glass_processor"}, + {"processor_type": "betterdeserttemples:orange_stained_glass_processor"}, + {"processor_type": "betterdeserttemples:pot_processor"}, + {"processor_type": "betterdeserttemples:quartz_pillar_processor"}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data(), &mut carried)); + let p = list["processors"].as_array().unwrap(); + assert_eq!( + p[0]["rules"][0]["output_state"], + json!({"id": "minecraft:tnt"}) + ); + assert_eq!(p[1]["processor_type"], "horizon:pick"); + assert_eq!(p[1]["picks"][0]["below"], 0.4f32 as f64); + assert_eq!(p[1]["default"]["state"]["id"], "minecraft:air"); + let glass = &p[2]["picks"]; + assert_eq!(glass[0]["state"]["id"], "minecraft:suspicious_sand"); + assert_eq!( + glass[0]["nbt"]["LootTable"], + "minecraft:archaeology/desert_pyramid" + ); + assert_eq!(glass[3]["states"].as_array().unwrap().len(), 4); + assert_eq!(glass[3]["below"], 0.45f32 as f64); + assert_eq!(p[3]["default"]["lists"][0]["count"], 4); + // The pillar reads the world below: still Java, still dropped later. + assert_eq!( + p[4]["processor_type"], + "betterdeserttemples:quartz_pillar_processor" + ); + assert_eq!(carried.values().sum::<usize>(), 4); + } + + #[test] + fn small_dungeon_chests_are_capped() { + let mut list = json!({"processors": [ + {"processor_type": "betterdungeons:small_dungeon_chest_processor"}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data(), &mut carried)); + let cap = &list["processors"][0]; + assert_eq!(cap["processor_type"], "horizon:count_cap"); + assert_eq!( + (cap["min"].as_u64(), cap["max"].as_u64()), + (Some(1), Some(2)) + ); + assert_eq!(cap["replacement"], json!({"id": "minecraft:cave_air"})); + } + + #[test] + fn lithostitched_block_swaps_become_the_games() { + let mut list = json!({"processors": [ + {"processor_type": "lithostitched:block_swap", + "blocks": {"minecraft:cobblestone": "minecraft:mossy_cobblestone"}}, + {"processor_type": "lithostitched:block_swap", "blocks": []}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data(), &mut carried)); + let p = list["processors"].as_array().unwrap(); + assert_eq!( + p[0], + json!({"processor_type": "horizon:block_swap", + "blocks": {"minecraft:cobblestone": "minecraft:mossy_cobblestone"}}) + ); + // A map that is not one stays Java (dropped later). + assert_eq!(p[1]["processor_type"], "lithostitched:block_swap"); + } + + #[test] + fn repurposed_rule_tests_become_the_games() { + let rule = |input: Value, position: Value| { + json!({"input_predicate": input, "location_predicate": {"predicate_type": + "repurposed_structures:matter_phase_rule_test", "phase_to_test_for": "AIR"}, + "position_predicate": position, "output_state": {"id": "minecraft:lava"}}) + }; + let mut pool = json!({"elements": [{"weight": 1, "element": { + "element_type": "minecraft:single_pool_element", "processors": {"processors": [ + {"processor_type": "minecraft:rule", "rules": [rule( + json!({"predicate_type": "minecraft:always_true"}), + json!({"predicate_type": "repurposed_structures:y_value_pos_rule_test", + "min_y_value": 0, "max_y_value": 31}))]}, + {"processor_type": "minecraft:capped", "limit": 2, "delegate": { + "processor_type": "minecraft:rule", "rules": [rule( + json!({"predicate_type": "minecraft:block_match", "block": "minecraft:rail"}), + json!({"predicate_type": + "repurposed_structures:piece_origin_axis_aligned_linear_pos_rule_test", + "axis": "y", "min_dist": 0, "max_dist": 1}))]}}]}}}]}); + let mut carried = BTreeMap::new(); + assert!(rule_tests("template_pool", &mut pool, &mut carried)); + let list = &pool["elements"][0]["element"]["processors"]["processors"]; + let first = &list[0]["rules"][0]; + assert_eq!( + first["location_predicate"]["predicate_type"], + "horizon:matter_phase" + ); + assert_eq!(first["location_predicate"]["phase_to_test_for"], "AIR"); + assert_eq!( + first["position_predicate"]["predicate_type"], + "horizon:y_value" + ); + assert_eq!(first["position_predicate"]["max_y_value"], 31); + let delegated = &list[1]["delegate"]["rules"][0]; + assert_eq!( + delegated["position_predicate"]["predicate_type"], + "horizon:piece_origin_axis_aligned_linear_pos" + ); + assert_eq!( + delegated["input_predicate"]["predicate_type"], + "minecraft:block_match" + ); + assert_eq!(carried.values().sum::<usize>(), 4); + assert_eq!(carried["repurposed_structures:matter_phase_rule_test"], 2); + // A file holding none is left as it is. + assert!(!rule_tests("template_pool", &mut pool, &mut carried)); + assert!(!rule_tests( + "structure", + &mut json!({"predicate_type": + "repurposed_structures:y_value_pos_rule_test"}), + &mut carried + )); + } +} diff --git a/crates/horizon-port-pack/src/worldgen.rs b/crates/horizon-port-pack/src/worldgen.rs new file mode 100644 index 000000000..a6adc2000 --- /dev/null +++ b/crates/horizon-port-pack/src/worldgen.rs @@ -0,0 +1,1568 @@ +//! Structure mods' worldgen, carried over: block and fluid states in 26.3's +//! shape, the structure, placement and pool element types of the common +//! structure libraries rewritten as vanilla's, and the loader's convention +//! biome tags (`c:`) the structures name. +//! +//! The libraries' types add rules on top of vanilla's. The start and +//! placement rules of Repurposed Structures' and Moog's jigsaws (no start in +//! liquid, biomes and terrain height in a radius, a minimum distance from +//! the world origin, sets to keep away from) are written under `horizon:` +//! keys the game reads (`horizon_world::worldgen::structure::start_checks`), +//! so those structures start where the mod would. Rules that change how the +//! pieces are laid out (piece caps, burying, clipping) are lost and counted +//! by name. Each rewrite is counted in the carry report, and every type left +//! as it is is listed, so the coverage report can say what generates and how +//! closely. +use serde_json::Value; +use std::{ + collections::{BTreeMap, BTreeSet}, + io::Read, + path::{Path, PathBuf}, +}; + +/// Structure types that are vanilla's jigsaw with extra start rules. +const JIGSAWS: [&str; 3] = [ + "lithostitched:jigsaw", + "moogs_structures:moogs_structures_generic_jigsaw_structure", + "repurposed_structures:generic_jigsaw_structure", +]; +/// The Nether variants of the piece-limited jigsaws: laid out the same, +/// then moved onto land. +const NETHER_JIGSAWS: [&str; 2] = [ + "moogs_structures:moogs_structures_generic_nether_jigsaw_structure", + "repurposed_structures:generic_nether_jigsaw_structure", +]; +/// Repurposed Structures' generic jigsaws with a start check of their own: the +/// `repurposed` key of `horizon:start_checks` names it. +const REPURPOSED_CHECKED: [(&str, &str); 3] = [ + ("repurposed_structures:city_nether_structure", "city_nether"), + ( + "repurposed_structures:shipwreck_nether_structure", + "shipwreck_nether", + ), + ("repurposed_structures:stronghold_end", "stronghold_end"), +]; +/// Repurposed Structures' mineshaft: its generic jigsaw laid out under the +/// terrain (`"layout": "mineshaft"` in `horizon:piece_limited`). +const REPURPOSED_MINESHAFT: &str = "repurposed_structures:generic_mineshaft"; +/// Layout rules the piece-limited assembler keeps (`horizon:piece_limited`). +const PIECE_LIMITED_RULES: [&str; 4] = [ + "y_allowance", + "burying_type", + "use_bounding_box_hack", + "pools_that_ignore_boundaries", +]; +/// Placements that are vanilla's random spread with extra rules. +const SPREADS: [&str; 2] = [ + "moogs_structures:advanced_random_spread", + "repurposed_structures:advanced_random_spread", +]; +/// YUNG's placements: vanilla's random spread with an enhanced exclusion +/// zone (several sets), plus, for the temples, no start near an ocean or a +/// river, and for strongholds, starts only in odd rings around the origin. +const YUNG_SPREADS: [&str; 4] = [ + "yungsapi:enhanced_random_spread", + "betterdeserttemples:desert_temple", + "betterjungletemples:jungle_temple", + "betterstrongholds:stronghold", +]; +/// YUNG's structures and the vanilla structure type each one's mod turns +/// off (its DisableVanilla*Mixin, on by default in each mod's config). +const YUNG_REPLACES: [(&str, &str); 7] = [ + ( + "betterdeserttemples:desert_temple", + "minecraft:desert_pyramid", + ), + ( + "betterjungletemples:jungle_temple", + "minecraft:jungle_temple", + ), + ("betterwitchhuts:witch_hut", "minecraft:swamp_hut"), + ( + "betteroceanmonuments:ocean_monument", + "minecraft:ocean_monument", + ), + ("betterstrongholds:stronghold", "minecraft:stronghold"), + ("betterfortresses:fortress", "minecraft:fortress"), + ("bettermineshafts:mineshaft_", "minecraft:mineshaft"), +]; +/// Moog's Structure Lib spreads its structures 1.65 times as far apart as +/// its files say (AdvancedRandomSpread's constructor). +const MOOGS_SPACING: f64 = 1.65; +/// The jigsaws' start rules and the `horizon:start_checks` key each maps to. +const START_RULES: [(&str, &str); 3] = [ + ("valid_biome_radius_check", "biome_radius"), + ("terrain_height_radius_check", "terrain_radius"), + ("allowed_terrain_height_range", "terrain_range"), +]; +/// The jigsaws' rules on laying out pieces, which vanilla's jigsaw has no +/// place for. +const LAYOUT_RULES: [&str; 5] = [ + "y_allowance", + "burying_type", + "use_bounding_box_hack", + "pools_that_ignore_boundaries", + "enhanced_terrain_adaptation", +]; +/// Fields of older versions the mods' codecs no longer read: their own +/// structures ignore them, and so does carry. Repurposed's jungle fortress +/// and End stronghold still write `vertical_distance_from_start_piece`. +const DEAD_FIELDS: [&str; 1] = ["vertical_distance_from_start_piece"]; +/// Pool elements that are vanilla's with extra fields: (mod type, vanilla type). +const ELEMENTS: [(&str, &str); 3] = [ + ( + "moogs_structures:versioned_single_pool_element", + "minecraft:single_pool_element", + ), + ( + "repurposed_structures:legacy_ocean_bottom_single_pool_element", + "minecraft:legacy_single_pool_element", + ), + ("empty_pool_element", "minecraft:empty_pool_element"), +]; + +/// What carry-over did to a mod's worldgen files. +#[derive(Debug, Default, serde::Serialize)] +pub struct Upgrade { + /// Files rewritten to vanilla types. + pub mapped: usize, + /// Files whose block and fluid states were written in 26.3's shape. + pub block_states: usize, + /// Types left as they are (Horizon skips what it cannot run), by type. + pub unsupported: BTreeMap<String, usize>, + /// Rules of mapped types the game does not run, by field. + pub rules_lost: BTreeMap<String, usize>, + /// Processors written in Java, taken out of their lists, by type. + pub processors_dropped: BTreeMap<String, usize>, + /// Processors written in Java carried as data the game runs + /// ([`crate::processors`]), by type. + pub processors_carried: BTreeMap<String, usize>, + /// Rule tests written in Java carried as the game's own + /// ([`crate::processors::rule_tests`]), by type. + pub rule_tests_carried: BTreeMap<String, usize>, + /// Entries added to other structure sets and template pools + /// (`horizon:add_to`), by the set or pool they join. + pub added_to: BTreeMap<String, usize>, + /// Lithostitched worldgen modifiers not carried: by type, `conditions` + /// when they need a mod that is not ported along, `target` when they + /// name their sets or pools by a tag. + pub modifiers_left: BTreeMap<String, usize>, +} + +/// Where a mod's additions to other sets and pools go in its carry: +/// `data/<id>/worldgen/<kind>/horizon_added/<name>.json`. +pub const ADDED: &str = "horizon_added"; + +/// A lithostitched worldgen modifier +/// (`data/<ns>/lithostitched/worldgen_modifier/`) that adds to structure +/// sets or template pools, as a file the game merges into them (the key +/// `horizon:add_to`, `horizon_client::mod_content`): (kind, file). The +/// modifier's conditions are checked against `loaded`, the mods ported +/// along: a compat addition for a mod that is not would place that mod's +/// blocks, which the game does not have. Other modifier types are left out. +/// Both are counted in `report`. +pub fn modifier( + v: &Value, + loaded: &dyn Fn(&str) -> bool, + report: &mut Upgrade, +) -> Option<(&'static str, Value)> { + let t = v["type"].as_str().unwrap_or_default(); + let mut left = |why: &str| *report.modifiers_left.entry(why.to_owned()).or_default() += 1; + let (kind, targets, from, to) = match t { + "lithostitched:add_structure_set_entries" => { + ("structure_set", "structure_sets", "entries", "structures") + } + "lithostitched:add_template_pool_elements" => { + ("template_pool", "template_pools", "elements", "elements") + } + _ => { + left(t); + return None; + } + }; + if !conditions_hold(v, loaded) { + left("conditions"); + return None; + } + let targets: Option<Vec<&str>> = match &v[targets] { + Value::String(s) => Some(vec![s.as_str()]), + Value::Array(a) => a.iter().map(Value::as_str).collect(), + _ => None, + }; + let Some(targets) = targets.filter(|t| !t.is_empty() && t.iter().all(|t| !t.starts_with('#'))) + else { + left("target"); + return None; + }; + let entries = v[from].as_array().cloned().unwrap_or_default(); + for target in &targets { + *report.added_to.entry((*target).to_owned()).or_default() += entries.len(); + } + Some(( + kind, + serde_json::json!({"horizon:add_to": targets, to: entries}), + )) +} + +/// Whether a modifier's load conditions hold: lithostitched's `predicate`, +/// and the loader's conditions (NeoForge's, else Fabric's). A condition +/// type not known here does not hold. +fn conditions_hold(v: &Value, loaded: &dyn Fn(&str) -> bool) -> bool { + let all = |list: &Value, test: &dyn Fn(&Value) -> bool| { + list.as_array().is_some_and(|a| a.iter().all(test)) + }; + fn predicate(p: &Value, loaded: &dyn Fn(&str) -> bool) -> bool { + let test = |q: &Value| predicate(q, loaded); + let list = &p["predicates"]; + match p["type"] + .as_str() + .map(|t| t.trim_start_matches("lithostitched:")) + { + Some("true") => true, + Some("mod_loaded") => p["mod_id"].as_str().is_some_and(loaded), + Some("not") => !predicate(&p["predicate"], loaded), + Some("all_of") => list.as_array().is_some_and(|a| a.iter().all(test)), + Some("any_of") => list.as_array().is_some_and(|a| a.iter().any(test)), + _ => false, + } + } + fn neoforge(c: &Value, loaded: &dyn Fn(&str) -> bool) -> bool { + let test = |q: &Value| neoforge(q, loaded); + match c["type"].as_str() { + Some("neoforge:true") => true, + Some("neoforge:mod_loaded") => c["modid"].as_str().is_some_and(loaded), + Some("neoforge:not") => !neoforge(&c["value"], loaded), + Some("neoforge:and") => c["values"].as_array().is_some_and(|a| a.iter().all(test)), + Some("neoforge:or") => c["values"].as_array().is_some_and(|a| a.iter().any(test)), + _ => false, + } + } + fn fabric(c: &Value, loaded: &dyn Fn(&str) -> bool) -> bool { + let test = |q: &Value| fabric(q, loaded); + let mods = || { + c["values"] + .as_array() + .into_iter() + .flatten() + .map(Value::as_str) + }; + match c["condition"].as_str() { + Some("fabric:true") => true, + Some("fabric:all_mods_loaded") => mods().all(|m| m.is_some_and(loaded)), + Some("fabric:any_mods_loaded") => mods().any(|m| m.is_some_and(loaded)), + Some("fabric:not") => !fabric(&c["value"], loaded), + Some("fabric:and") => c["values"].as_array().is_some_and(|a| a.iter().all(test)), + Some("fabric:or") => c["values"].as_array().is_some_and(|a| a.iter().any(test)), + _ => false, + } + } + let litho = v.get("predicate").is_none_or(|p| predicate(p, loaded)); + let loader = match ( + v.get("neoforge:conditions"), + v.get("fabric:load_conditions"), + ) { + (Some(c), _) => all(c, &|c| neoforge(c, loaded)), + // One condition or a list of them. + (None, Some(c)) if c.is_array() => all(c, &|c| fabric(c, loaded)), + (None, Some(c)) => fabric(c, loaded), + (None, None) => true, + }; + litho && loader +} + +/// ChoiceTheorem's Overhauled Village's villages and outposts, which it adds +/// to vanilla's `villages` and `pillager_outposts` sets in Java code +/// (`CTOV.registerstructure`, through lithostitched), with its default +/// config: every village type in three sizes, weighted 10, 4 and 1, and +/// every outpost weighted 1. Vanilla's own entries stay (weight 1 each). +const CTOV_VILLAGES: [&str; 21] = [ + "beach", + "christmas", + "desert", + "desert_oasis", + "dark_forest", + "jungle", + "jungle_tree", + "mesa", + "mesa_fortified", + "mountain", + "mountain_alpine", + "mushroom", + "plains", + "plains_fortified", + "savanna", + "savanna_na", + "snowy_igloo", + "swamp", + "swamp_fortified", + "taiga", + "taiga_fortified", +]; +const CTOV_OUTPOSTS: [&str; 11] = [ + "beach", + "dark_forest", + "desert", + "jungle", + "badlands", + "mountain", + "plains", + "savanna", + "snowy", + "swamp", + "taiga", +]; + +/// The entries a mod adds to other structure sets in Java code, as its +/// default config has them: (file name, set, `[(structure, weight)]`). +/// Lithostitched appends them in the order of a hash map of every modifier +/// in the pack, which carry cannot know; they are written in the order the +/// mod registers them. Each set picks by weight, so how often each starts +/// is the same. +pub fn code_set_entries(mod_id: &str) -> Vec<(&'static str, &'static str, Vec<(String, u32)>)> { + match mod_id { + "ctov" => { + let outposts = CTOV_OUTPOSTS + .iter() + .map(|v| (format!("ctov:pillager_outpost_{v}"), 1)) + .collect(); + let villages = [("small", 10), ("medium", 4), ("large", 1)] + .into_iter() + .flat_map(|(size, weight)| { + CTOV_VILLAGES + .iter() + .map(move |v| (format!("ctov:{size}/village_{v}"), weight)) + }) + .collect(); + vec![ + ("pillager_outposts", "minecraft:pillager_outposts", outposts), + ("villages", "minecraft:villages", villages), + ] + } + _ => Vec::new(), + } +} + +/// Rewrites one `data/<ns>/worldgen/<kind>/...` file in place; whether it +/// changed. +/// `set_tags` are the mod's structure set tags, expanded +/// ([`structure_set_tags`]). +pub fn upgrade( + kind: &str, + v: &mut Value, + report: &mut Upgrade, + set_tags: &BTreeMap<String, Vec<String>>, +) -> bool { + let states = block_states(v); + report.block_states += usize::from(states); + let renamed = crate::carry::renamed_ids(v); + let dropped = crate::processors::each_list(kind, v, &mut |list| { + drop_java_processors(list, &mut report.processors_dropped) + }); + upgrade_types(kind, v, report, set_tags) || states || dropped || renamed +} + +/// Takes the processors written in Java (any type outside `minecraft:` and +/// the game's own `horizon:`) out of a processor list: `{"processors": +/// [...]}`, a bare list, or an id (left as it is). The ones with a data form +/// were rewritten before ([`crate::processors::carry`]). The game, like vanilla, refuses a list holding a type it +/// does not know, and with it every pool that names the list, so without +/// this the structure does not generate at all. Without them it generates +/// undecorated: no pillars under it, spawners left as the template has +/// them, blocks not swapped. Whether anything was taken out. +fn drop_java_processors(list: &mut Value, dropped: &mut BTreeMap<String, usize>) -> bool { + let Some(processors) = crate::processors::processors(list) else { + return false; + }; + let before = processors.len(); + processors.retain(|p| { + let t = p["processor_type"].as_str().unwrap_or_default(); + let java = !t.starts_with("minecraft:") && !t.starts_with("horizon:"); + if java { + *dropped.entry(t.to_owned()).or_default() += 1; + } + !java + }); + processors.len() != before +} + +/// 1.21.1 writes a block or fluid state as `{"Name": ..., "Properties": +/// {...}}`; 26.3's codec reads `{"id": ..., "properties": {...}}` and +/// refuses the old shape, which fails the processor list, feature or pool +/// holding it. Whether anything changed. +fn block_states(v: &mut Value) -> bool { + match v { + Value::Object(o) => { + let state = o.get("Name").is_some_and(Value::is_string) + && o.keys().all(|k| k == "Name" || k == "Properties"); + if state { + if let Some(name) = o.remove("Name") { + o.insert("id".into(), name); + } + if let Some(properties) = o.remove("Properties") { + o.insert("properties".into(), properties); + } + return true; + } + o.values_mut() + .fold(false, |changed, x| block_states(x) | changed) + } + Value::Array(a) => a + .iter_mut() + .fold(false, |changed, x| block_states(x) | changed), + _ => false, + } +} + +/// The library types of one file rewritten as vanilla's; whether it changed. +fn upgrade_types( + kind: &str, + v: &mut Value, + report: &mut Upgrade, + set_tags: &BTreeMap<String, Vec<String>>, +) -> bool { + let lost = &mut report.rules_lost; + let mut unsupported = |t: &str| *report.unsupported.entry(t.to_owned()).or_default() += 1; + let changed = match kind { + "structure" => match v["type"].as_str() { + // Better Dungeons' small Nether dungeon is YUNG's jigsaw behind a + // config switch that ships on. + Some("yungsapi:yung_jigsaw" | "betterdungeons:small_nether_dungeon") => { + yung_structure(v, lost); + true + } + Some(t) + if JIGSAWS.contains(&t) + || NETHER_JIGSAWS.contains(&t) + || t == REPURPOSED_MINESHAFT + || REPURPOSED_CHECKED.iter().any(|(r, _)| *r == t) => + { + let mineshaft = t == REPURPOSED_MINESHAFT; + let check = REPURPOSED_CHECKED.iter().find(|(r, _)| *r == t); + let check = check.map(|(_, c)| *c); + let library = match t.split_once(':').map(|(ns, _)| ns) { + Some("moogs_structures") => Some("moogs"), + Some("repurposed_structures") => Some("repurposed"), + _ => None, + }; + let liquid = if library == Some("moogs") { + "top" + } else { + "lowest" + }; + let mut limited = library.map(|l| piece_limited(v, l)); + if let Some(limited) = limited.as_mut().filter(|_| mineshaft) { + limited["layout"] = "mineshaft".into(); + } + start_checks(v, liquid, lost, limited.is_some()); + if let Some(check) = check { + if !v["horizon:start_checks"].is_object() { + v["horizon:start_checks"] = Value::Object(Default::default()); + } + v["horizon:start_checks"]["repurposed"] = check.into(); + } + if let Some(limited) = limited { + v["horizon:piece_limited"] = limited; + } + v["type"] = "minecraft:jigsaw".into(); + true + } + Some(t) if !t.starts_with("minecraft:") => { + unsupported(t); + false + } + _ => false, + }, + "structure_set" => match v["placement"]["type"].as_str() { + Some(t) if SPREADS.contains(&t) => { + let moogs = t.starts_with("moogs_structures:"); + let p = &mut v["placement"]; + if moogs { + moogs_spacing(p, lost); + } + placement_rules(p, set_tags, lost); + p["type"] = "minecraft:random_spread".into(); + true + } + Some(t) if YUNG_SPREADS.contains(&t) => { + let t = t.to_owned(); + yung_placement(&t, &mut v["placement"], set_tags, lost); + true + } + Some(t) if !t.starts_with("minecraft:") => { + unsupported(t); + false + } + _ => false, + }, + "template_pool" => { + let mut changed = false; + let mut elements: Vec<&mut Value> = Vec::new(); + for e in v["elements"].as_array_mut().into_iter().flatten() { + let element = &mut e["element"]; + // A list element holds elements of its own. + if element.get("elements").is_some_and(Value::is_array) { + elements.extend(element["elements"].as_array_mut().into_iter().flatten()); + } else { + elements.push(element); + } + } + for element in elements { + let Some(t) = element["element_type"].as_str() else { + continue; + }; + if let Some((_, to)) = ELEMENTS.iter().find(|(from, _)| *from == t) { + element["element_type"] = (*to).into(); + changed = true; + } else if t == "yungsapi:yung_single_element" { + yung_element(element, lost); + changed = true; + } else if !t.starts_with("minecraft:") { + unsupported(t); + } + } + changed + } + _ => false, + }; + report.mapped += usize::from(changed); + changed +} + +/// YUNG's API's jigsaw as vanilla's, laid out by its own assembler in the +/// game (`horizon:yungsapi`, `horizon_world::worldgen::structure::yung`): +/// the heights pieces stay within move under the key. Its terrain +/// adaptation and a start offset in the chunk are lost. +fn yung_structure(v: &mut Value, lost: &mut BTreeMap<String, usize>) { + let Some(o) = v.as_object_mut() else { + return; + }; + o.insert("type".into(), "minecraft:jigsaw".into()); + let mut rules = serde_json::Map::new(); + for key in ["min_y", "max_y"] { + if let Some(y) = o.remove(key) { + rules.insert(key.into(), y); + } + } + let none = |a: &Value| a["type"] == "yungsapi:none"; + if o.remove("enhanced_terrain_adaptation") + .is_some_and(|a| !none(&a)) + { + *lost + .entry("enhanced_terrain_adaptation".into()) + .or_default() += 1; + } + for key in ["x_offset_in_chunk", "z_offset_in_chunk"] { + if o.remove(key).is_some_and(|n| n != 0) { + *lost.entry(key.into()).or_default() += 1; + } + } + o.insert("horizon:yungsapi".into(), rules.into()); +} + +/// YUNG's single pool element as vanilla's, its rules under +/// `horizon:yungsapi`: name and `max_count`, depth range, priority, +/// `ignore_bounds` and its condition. Its terrain adaptation, dead-end pool +/// and modifiers are lost. +fn yung_element(element: &mut Value, lost: &mut BTreeMap<String, usize>) { + let Some(o) = element.as_object_mut() else { + return; + }; + o.insert( + "element_type".into(), + "minecraft:single_pool_element".into(), + ); + let mut rules = serde_json::Map::new(); + for (from, to) in [ + ("name", "name"), + ("max_count", "max_count"), + ("min_required_depth", "min_depth"), + ("max_possible_depth", "max_depth"), + ("is_priority", "priority"), + ("ignore_bounds", "ignore_bounds"), + ] { + if let Some(x) = o.remove(from) { + rules.insert(to.into(), x); + } + } + if let Some(c) = o.remove("condition") { + rules.insert("condition".into(), yung_condition(&c, lost)); + } + for key in ["enhanced_terrain_adaptation", "deadend_pool", "modifiers"] { + let empty = + |x: &Value| x.as_array().is_some_and(Vec::is_empty) || x["type"] == "yungsapi:none"; + if o.remove(key).is_some_and(|x| !empty(&x)) { + *lost.entry(format!("yungsapi {key}")).or_default() += 1; + } + } + o.insert("horizon:yungsapi".into(), rules.into()); +} + +/// One of YUNG's structure conditions in the game's terms. `mod_loaded` +/// holds for Minecraft alone: a mod that needs code is not ported, and the +/// pieces it guards would place its blocks. A condition the game does not +/// have does not hold, and is counted. +fn yung_condition(c: &Value, lost: &mut BTreeMap<String, usize>) -> Value { + let t = c["type"].as_str().unwrap_or_default(); + let list = |lost: &mut BTreeMap<String, usize>| -> Value { + let all = c["conditions"].as_array().into_iter().flatten(); + all.map(|x| yung_condition(x, lost)) + .collect::<Vec<_>>() + .into() + }; + let opt = |k: &str| c.get(k).cloned().unwrap_or(Value::Null); + match t.trim_start_matches("yungsapi:") { + "always_true" => serde_json::json!({"type": "true"}), + "not" => { + serde_json::json!({"type": "not", "condition": yung_condition(&c["condition"], lost)}) + } + "all_of" => serde_json::json!({"type": "all_of", "conditions": list(lost)}), + "any_of" => serde_json::json!({"type": "any_of", "conditions": list(lost)}), + "depth" => serde_json::json!({"type": "depth", + "min_depth": opt("min_required_depth"), "max_depth": opt("max_possible_depth")}), + "altitude" => serde_json::json!({"type": "altitude", + "bottom": opt("bottom_cutoff_y"), "top": opt("top_cutoff_y")}), + "random_chance" => serde_json::json!({"type": "random_chance", "chance": opt("chance")}), + "rotation" => serde_json::json!({"type": "rotation", "rotations": opt("rotations")}), + "piece_in_horizontal_direction" => { + // "yungsapi:all" (or no list) matches any piece. + let pieces: Vec<Value> = c["pieces"].as_array().cloned().unwrap_or_default(); + let any = pieces.is_empty() || pieces.iter().any(|p| p == "yungsapi:all"); + serde_json::json!({"type": "piece_in_horizontal_direction", + "pieces": if any { Vec::new() } else { pieces }, + "range": opt("range"), "rotation": opt("rotation")}) + } + "mod_loaded" if c["modid"] == "minecraft" => serde_json::json!({"type": "true"}), + "mod_loaded" => serde_json::json!({"type": "false"}), + _ => { + *lost.entry(format!("yungsapi condition {t}")).or_default() += 1; + serde_json::json!({"type": "false"}) + } + } +} + +/// Moves a Repurposed Structures or Moog's jigsaw's start rules under +/// `horizon:start_checks`, and counts the layout rules it loses. `liquid` is +/// the block its no-start-in-liquid rule reads. +fn start_checks(v: &mut Value, liquid: &str, lost: &mut BTreeMap<String, usize>, limited: bool) { + let Some(o) = v.as_object_mut() else { + return; + }; + let mut checks = serde_json::Map::new(); + for (from, to) in START_RULES { + if let Some(n) = o.remove(from) { + checks.insert(to.into(), n); + } + } + if o.remove("cannot_spawn_in_liquid").and_then(|b| b.as_bool()) == Some(true) { + checks.insert("liquid".into(), liquid.into()); + } + // y_allowance bounds the terrain heights checked; it also clips pieces, + // which is lost. + for (from, to) in [("min_y_allowed", "min_y"), ("max_y_allowed", "max_y")] { + if let Some(n) = o.get("y_allowance").and_then(|y| y.get(from)) { + checks.insert(to.into(), n.clone()); + } + } + for field in DEAD_FIELDS { + o.remove(field); + } + for rule in LAYOUT_RULES { + let kept = limited && PIECE_LIMITED_RULES.contains(&rule); + if o.remove(rule).is_some_and(|r| r != Value::Bool(false)) && !kept { + *lost.entry(rule.into()).or_default() += 1; + } + } + if !checks.is_empty() { + o.insert("horizon:start_checks".into(), checks.into()); + } +} + +/// A Repurposed Structures or Moog's jigsaw's layout rules for the game's +/// piece-limited assembler: y_allowance, burying, the pools whose fallbacks +/// ignore the bounds, liquid, and the Nether variants' land search. The +/// bounding box hack is vanilla's expansion hack. The pieces' counts are +/// added from the mod's count files ([`piece_counts`]). +fn piece_limited(v: &mut Value, library: &str) -> Value { + let mut out = serde_json::Map::new(); + out.insert("library".into(), library.into()); + let lower = |x: &Value| x.as_str().map(str::to_ascii_lowercase); + for (from, to) in [("min_y_allowed", "min_y"), ("max_y_allowed", "max_y")] { + if let Some(n) = v.get("y_allowance").and_then(|y| y.get(from)) { + out.insert(to.into(), n.clone()); + } + } + if let Some(b) = v.get("burying_type").and_then(lower) { + out.insert("burying".into(), b.into()); + } + if v["cannot_spawn_in_liquid"].as_bool() == Some(true) { + out.insert("no_liquid".into(), true.into()); + } + if let Some(pools) = v + .get("pools_that_ignore_boundaries") + .filter(|p| p.is_array()) + { + out.insert("ignore_bounds_pools".into(), pools.clone()); + } + if v["use_bounding_box_hack"].as_bool() == Some(true) { + v["use_expansion_hack"] = true.into(); + } + if let Some(o) = v.as_object_mut() { + if let Some(search) = o.remove("land_search_direction") { + out.insert("land_search".into(), lower(&search).into()); + } + if let Some(ledge) = o.remove("ledge_offset_y") { + out.insert("ledge_offset_y".into(), ledge); + } + } + out.into() +} + +/// The pieces' spawn counts of the structures a mod ships, by structure id: +/// Repurposed Structures' `rs_pieces_spawn_counts` (each file names its +/// `target_structure`) and Moog's `msl_pieces_spawn_counts` (the file's id), +/// in the game's `horizon:piece_limited` shape. +pub fn piece_counts<R: Read + std::io::Seek>( + zip: &mut zip::ZipArchive<R>, +) -> BTreeMap<String, Value> { + let mut out = BTreeMap::new(); + for i in 0..zip.len() { + let Ok(mut entry) = zip.by_index(i) else { + continue; + }; + let name = entry.name().to_owned(); + let Some((ns, rest)) = name + .strip_prefix("data/") + .and_then(|r| r.strip_suffix(".json")) + .and_then(|r| r.split_once('/')) + else { + continue; + }; + let (rs, path) = if let Some(p) = rest.strip_prefix("rs_pieces_spawn_counts/") { + (true, p) + } else if let Some(p) = rest.strip_prefix("msl_pieces_spawn_counts/") { + (false, p) + } else { + continue; + }; + let mut text = String::new(); + let Ok(v) = entry + .read_to_string(&mut text) + .map_err(|_| ()) + .and_then(|_| serde_json::from_str::<Value>(&text).map_err(|_| ())) + else { + continue; + }; + let id = match v["target_structure"].as_str() { + Some(target) if rs => target.to_owned(), + _ if rs => continue, + _ => format!("{ns}:{path}"), + }; + let pieces: Vec<Value> = v["pieces_spawn_counts"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| { + let mut e = serde_json::Map::new(); + e.insert("name".into(), p["nbt_piece_name"].as_str()?.into()); + for (from, to) in [ + ("always_spawn_this_many", "required"), + ("never_spawn_more_than_this_many", "max"), + ("minimum_distance_from_center_piece", "min_depth"), + ] { + if let Some(n) = p.get(from).filter(|n| n.is_number()) { + e.insert(to.into(), n.clone()); + } + } + Some(Value::Object(e)) + }) + .collect(); + out.insert(id, pieces.into()); + } + out +} + +/// Adds a structure's piece counts to its `horizon:piece_limited` key. +pub fn add_piece_counts(id: &str, v: &mut Value, counts: &BTreeMap<String, Value>) -> bool { + match (counts.get(id), v.get_mut("horizon:piece_limited")) { + (Some(pieces), Some(limited)) => { + limited["pieces"] = pieces.clone(); + true + } + _ => false, + } +} + +/// AdvancedRandomSpread's spacing and separation, as Moog's computes them +/// with its default config: 1.65 times the file's, rounded, the separation +/// below the spacing. `when_replacing` (other numbers while a preset +/// replaces a vanilla structure) is lost. +fn moogs_spacing(p: &mut Value, lost: &mut BTreeMap<String, usize>) { + let scaled = |k: &str| (p[k].as_f64().unwrap_or(0.) * MOOGS_SPACING).round() as i64; + let spacing = scaled("spacing").max(1); + let separation = scaled("separation").min(spacing - 1); + p["spacing"] = spacing.into(); + p["separation"] = separation.into(); + if let Some(o) = p.as_object_mut() { + if o.remove("when_replacing").is_some() { + *lost.entry("when_replacing".into()).or_default() += 1; + } + } +} + +/// An advanced random spread's minimum distance from the world origin and +/// its super exclusion zone (sets named by a tag) under `horizon:` keys. +fn placement_rules( + p: &mut Value, + set_tags: &BTreeMap<String, Vec<String>>, + lost: &mut BTreeMap<String, usize>, +) { + let Some(o) = p.as_object_mut() else { + return; + }; + if let Some(d) = o.remove("min_distance_from_world_origin") { + o.insert("horizon:min_distance_from_world_origin".into(), d); + } + let zone = ["super_exclusion_zone", "enhanced_exclusion_zone"] + .into_iter() + .find_map(|k| Some((k, o.remove(k)?))); + if let Some((key, zone)) = zone { + let sets: Vec<String> = match &zone["other_set"] { + Value::String(s) => match s.strip_prefix('#') { + Some(tag) => set_tags.get(tag).cloned().unwrap_or_default(), + None => vec![s.clone()], + }, + Value::Array(a) => a + .iter() + .filter_map(|s| Some(s.as_str()?.to_owned())) + .collect(), + _ => Vec::new(), + }; + if sets.is_empty() { + *lost.entry(key.into()).or_default() += 1; + } else { + o.insert( + "horizon:exclusion_zone".into(), + serde_json::json!({"other_sets": sets, "chunk_count": zone["chunk_count"]}), + ); + } + } +} + +/// One of YUNG's placements as vanilla's random spread with `horizon:` keys: +/// the enhanced exclusion zone as `horizon:exclusion_zone`; the temples' +/// ocean and river search (findBiomeHorizontal around the chunk's middle +/// block at y 120, 48 blocks, every 2 quarts) as `horizon:avoid_biomes`; the +/// strongholds' rings as `horizon:ring_sections`. +fn yung_placement( + t: &str, + p: &mut Value, + set_tags: &BTreeMap<String, Vec<String>>, + lost: &mut BTreeMap<String, usize>, +) { + placement_rules(p, set_tags, lost); + p["type"] = "minecraft:random_spread".into(); + let Some(o) = p.as_object_mut() else { + return; + }; + match t { + "betterdeserttemples:desert_temple" | "betterjungletemples:jungle_temple" => { + o.insert( + "horizon:avoid_biomes".into(), + serde_json::json!({"biomes": ["#minecraft:is_river", "#minecraft:is_ocean"], + "radius": 48, "step": 2, "y": 120}), + ); + } + "betterstrongholds:stronghold" => { + let mut rings = serde_json::Map::new(); + for (from, to) in [ + ("chunk_distance_to_first_ring", "distance_to_first_ring"), + ("ring_chunk_thickness", "thickness"), + ("max_ring_section", "max_section"), + ] { + if let Some(n) = o.remove(from) { + rings.insert(to.into(), n); + } + } + o.insert("horizon:ring_sections".into(), rings.into()); + } + _ => {} + } +} + +/// Marks a YUNG's structure that the game can start (its type is vanilla's +/// after the upgrade) with the vanilla type its mod turns off, under +/// `horizon:disables`. One the game cannot start leaves the vanilla +/// structure in place, so the world keeps one of the two. +pub fn disables(id: &str, v: &mut Value) -> bool { + let Some((_, vanilla)) = YUNG_REPLACES.iter().find(|(s, _)| id.starts_with(s)) else { + return false; + }; + if !v["type"] + .as_str() + .is_some_and(|t| t.starts_with("minecraft:")) + { + return false; + } + v["horizon:disables"] = serde_json::json!([vanilla]); + true +} + +/// The mod's structure set tags (`data/<ns>/tags/worldgen/structure_set/`), +/// by tag id, with the tags they include expanded. Optional entries +/// (`{"id": ..., "required": false}`) count as their id. +pub fn structure_set_tags<R: Read + std::io::Seek>( + zip: &mut zip::ZipArchive<R>, +) -> BTreeMap<String, Vec<String>> { + let mut raw: BTreeMap<String, Vec<String>> = BTreeMap::new(); + for i in 0..zip.len() { + let Ok(mut entry) = zip.by_index(i) else { + continue; + }; + let Some(id) = entry + .name() + .strip_prefix("data/") + .and_then(|r| r.split_once("/tags/worldgen/structure_set/")) + .and_then(|(ns, path)| Some(format!("{ns}:{}", path.strip_suffix(".json")?))) + else { + continue; + }; + let mut text = String::new(); + let Ok(v) = entry.read_to_string(&mut text).map_err(drop).and_then(|_| { + serde_json::from_str::<Value>(text.trim_start_matches('\u{feff}')).map_err(drop) + }) else { + continue; + }; + let values = v["values"].as_array().into_iter().flatten(); + raw.insert( + id, + values + .filter_map(|e| e.as_str().or_else(|| e["id"].as_str()).map(str::to_owned)) + .collect(), + ); + } + let expand = |tag: &str| { + let (mut out, mut seen, mut todo) = (Vec::new(), BTreeSet::new(), vec![tag.to_owned()]); + while let Some(t) = todo.pop() { + if !seen.insert(t.clone()) { + continue; + } + for e in raw.get(&t).into_iter().flatten() { + match e.strip_prefix('#') { + Some(inner) => todo.push(inner.to_owned()), + None if !out.contains(e) => out.push(e.clone()), + None => {} + } + } + } + out + }; + raw.keys().map(|t| (t.clone(), expand(t))).collect() +} + +/// The `#c:` biome tags `v` names. +pub fn convention_tags(v: &Value, out: &mut BTreeSet<String>) { + match v { + Value::String(s) => { + if let Some(tag) = s.strip_prefix("#c:") { + out.insert(tag.to_owned()); + } + } + Value::Array(a) => a.iter().for_each(|x| convention_tags(x, out)), + Value::Object(o) => o.values().for_each(|x| convention_tags(x, out)), + _ => {} + } +} + +/// The loader's own convention biome tags (`data/c/tags/worldgen/biome/`), +/// by path, read from the loader jar `fetch` keeps in `<work>/loader/`. +pub fn loader_biome_tags(work: &Path) -> BTreeMap<String, Value> { + let mut out = BTreeMap::new(); + let Ok(dir) = std::fs::read_dir(work.join("loader")) else { + return out; + }; + for jar in dir.flatten().map(|e| e.path()) { + let Some(mut zip) = std::fs::File::open(&jar) + .ok() + .and_then(|f| zip::ZipArchive::new(f).ok()) + else { + continue; + }; + for i in 0..zip.len() { + let Ok(mut entry) = zip.by_index(i) else { + continue; + }; + let Some(path) = entry + .name() + .strip_prefix("data/c/tags/worldgen/biome/") + .and_then(|p| p.strip_suffix(".json")) + .map(str::to_owned) + else { + continue; + }; + let mut text = String::new(); + if entry.read_to_string(&mut text).is_ok() { + if let Ok(v) = serde_json::from_str(&text) { + out.insert(path, v); + } + } + } + } + out +} + +/// `tags` and the convention tags they include, in `conventions`. +pub fn with_included( + tags: &BTreeSet<String>, + conventions: &BTreeMap<String, Value>, +) -> BTreeSet<String> { + let mut all = BTreeSet::new(); + let mut todo: Vec<String> = tags.iter().cloned().collect(); + while let Some(tag) = todo.pop() { + if !conventions.contains_key(&tag) || !all.insert(tag.clone()) { + continue; + } + let mut more = BTreeSet::new(); + convention_tags(&conventions[&tag], &mut more); + todo.extend(more); + } + all +} + +/// Where `fetch` keeps the pack's loader jar, and where it comes from: +/// NeoForge's own Maven repository. Only NeoForge packs need it today. +pub fn loader_jar(work: &Path, loader: &str, version: &str) -> Option<(PathBuf, String)> { + (loader == "neoforge" && !version.is_empty()).then(|| { + ( + work.join("loader").join(format!("neoforge-{version}-universal.jar")), + format!( + "https://maven.neoforged.net/releases/net/neoforged/neoforge/{version}/neoforge-{version}-universal.jar" + ), + ) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + const NO_TAGS: BTreeMap<String, Vec<String>> = BTreeMap::new(); + + #[test] + fn maps_library_types_to_vanillas() { + let mut report = Upgrade::default(); + let mut s = json!({"type": "lithostitched:jigsaw", "start_pool": "a:b"}); + assert!(upgrade("structure", &mut s, &mut report, &NO_TAGS)); + assert_eq!(s["type"], "minecraft:jigsaw"); + let mut formation = json!({"type": "formations:simple"}); + assert!(!upgrade("structure", &mut formation, &mut report, &NO_TAGS)); + let mut set = json!({"placement": {"type": "moogs_structures:advanced_random_spread", + "spacing": 10, "separation": 5, "min_distance_from_world_origin": 250}}); + assert!(upgrade("structure_set", &mut set, &mut report, &NO_TAGS)); + assert_eq!(set["placement"]["type"], "minecraft:random_spread"); + // Moog's spreads 1.65 times as far as its file says. + assert_eq!(set["placement"]["spacing"], 17); + assert_eq!(set["placement"]["separation"], 8); + assert_eq!( + set["placement"]["horizon:min_distance_from_world_origin"], + 250 + ); + assert!( + set["placement"] + .get("min_distance_from_world_origin") + .is_none() + ); + let mut pool = json!({"elements": [ + {"weight": 1, "element": {"element_type": "moogs_structures:versioned_single_pool_element", "location": "m:x"}}, + {"weight": 1, "element": {"element_type": "minecraft:list_pool_element", "elements": [ + {"element_type": "empty_pool_element"}]}}, + {"weight": 1, "element": {"element_type": "somelib:element"}} + ]}); + assert!(upgrade("template_pool", &mut pool, &mut report, &NO_TAGS)); + assert_eq!( + pool["elements"][0]["element"]["element_type"], + "minecraft:single_pool_element" + ); + assert_eq!( + pool["elements"][1]["element"]["elements"][0]["element_type"], + "minecraft:empty_pool_element" + ); + assert_eq!(report.mapped, 3); + assert_eq!(report.block_states, 0); + assert_eq!( + report.unsupported, + BTreeMap::from([ + ("formations:simple".into(), 1), + ("somelib:element".into(), 1), + ]) + ); + } + + #[test] + fn keeps_the_jigsaws_start_rules() { + let mut report = Upgrade::default(); + let mut moogs = json!({"type": "moogs_structures:moogs_structures_generic_jigsaw_structure", + "cannot_spawn_in_liquid": true, "terrain_height_radius_check": 2, + "allowed_terrain_height_range": 12, "valid_biome_radius_check": 1, + "y_allowance": {"min_y_allowed": 60}, "burying_type": "lowest_corner", + "use_bounding_box_hack": false, "size": 7}); + assert!(upgrade("structure", &mut moogs, &mut report, &NO_TAGS)); + assert_eq!( + moogs["horizon:start_checks"], + json!({"liquid": "top", "terrain_radius": 2, "terrain_range": 12, + "biome_radius": 1, "min_y": 60}) + ); + for gone in [ + "cannot_spawn_in_liquid", + "y_allowance", + "burying_type", + "use_bounding_box_hack", + ] { + assert!(moogs.get(gone).is_none(), "{gone}"); + } + assert_eq!(moogs["size"], 7); + // Repurposed Structures reads the block above the bottom. Its jungle + // fortress's vertical distance is a field its code no longer reads. + let mut rs = json!({"type": "repurposed_structures:generic_jigsaw_structure", + "cannot_spawn_in_liquid": true, "vertical_distance_from_start_piece": 35}); + assert!(upgrade("structure", &mut rs, &mut report, &NO_TAGS)); + assert_eq!(rs["horizon:start_checks"], json!({"liquid": "lowest"})); + assert!(rs.get("vertical_distance_from_start_piece").is_none()); + // Repurposed's own checks: the Nether city, Nether shipwrecks, the End stronghold. + for (t, check) in [ + ("city_nether_structure", "city_nether"), + ("shipwreck_nether_structure", "shipwreck_nether"), + ("stronghold_end", "stronghold_end"), + ] { + let mut rs = json!({"type": format!("repurposed_structures:{t}"), + "cannot_spawn_in_liquid": false, "size": 7}); + assert!(upgrade("structure", &mut rs, &mut report, &NO_TAGS)); + assert_eq!(rs["type"], "minecraft:jigsaw"); + assert_eq!(rs["horizon:start_checks"], json!({"repurposed": check})); + assert_eq!(rs["horizon:piece_limited"]["library"], "repurposed"); + } + assert!(report.unsupported.is_empty()); + // Nothing to check: no key. + let mut plain = json!({"type": "lithostitched:jigsaw", "cannot_spawn_in_liquid": false}); + assert!(upgrade("structure", &mut plain, &mut report, &NO_TAGS)); + assert!(plain.get("horizon:start_checks").is_none()); + // The layout rules go to the piece-limited assembler. + assert!(report.rules_lost.is_empty()); + assert_eq!( + moogs["horizon:piece_limited"], + json!({"library": "moogs", "min_y": 60, "burying": "lowest_corner", + "no_liquid": true}) + ); + } + + #[test] + fn super_exclusion_zones_name_their_sets() { + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default(); + for (name, text) in [ + ( + "data/rs/tags/worldgen/structure_set/avoid.json", + r##"{"values": ["minecraft:villages", "#rs:more", {"id": "x:y", "required": false}]}"##, + ), + ( + "data/rs/tags/worldgen/structure_set/more.json", + r##"{"values": ["minecraft:villages", "rs:cities", "#rs:avoid"]}"##, + ), + ] { + zip.start_file(name, opts).unwrap(); + std::io::Write::write_all(&mut zip, text.as_bytes()).unwrap(); + } + let mut zip = zip::ZipArchive::new(zip.finish().unwrap()).unwrap(); + let tags = structure_set_tags(&mut zip); + assert_eq!(tags["rs:avoid"], ["minecraft:villages", "x:y", "rs:cities"]); + let mut report = Upgrade::default(); + let mut set = json!({"placement": {"type": "repurposed_structures:advanced_random_spread", + "spacing": 30, "separation": 10, + "super_exclusion_zone": {"chunk_count": 4, "other_set": "#rs:avoid"}}}); + assert!(upgrade("structure_set", &mut set, &mut report, &tags)); + assert_eq!(set["placement"]["spacing"], 30); + assert_eq!( + set["placement"]["horizon:exclusion_zone"], + json!({"other_sets": ["minecraft:villages", "x:y", "rs:cities"], "chunk_count": 4}) + ); + let mut unknown = json!({"placement": {"type": "repurposed_structures:advanced_random_spread", + "spacing": 30, "separation": 10, + "super_exclusion_zone": {"chunk_count": 4, "other_set": "#rs:none"}}}); + assert!(upgrade("structure_set", &mut unknown, &mut report, &tags)); + assert_eq!(report.rules_lost["super_exclusion_zone"], 1); + } + + #[test] + fn yungs_jigsaws_keep_their_rules() { + let mut report = Upgrade::default(); + let mut s = json!({"type": "yungsapi:yung_jigsaw", "start_pool": "y:start", "size": 20, + "max_y": 60, "x_offset_in_chunk": 0, "max_distance_from_center": 80, + "enhanced_terrain_adaptation": {"type": "yungsapi:custom", "kernel_size": 24}}); + assert!(upgrade("structure", &mut s, &mut report, &NO_TAGS)); + assert_eq!(s["type"], "minecraft:jigsaw"); + assert_eq!(s["horizon:yungsapi"], json!({"max_y": 60})); + for gone in ["max_y", "x_offset_in_chunk", "enhanced_terrain_adaptation"] { + assert!(s.get(gone).is_none(), "{gone}"); + } + // Better Dungeons' small Nether dungeon is the same jigsaw. + let mut nether = json!({"type": "betterdungeons:small_nether_dungeon", + "start_pool": "betterdungeons:small_nether_dungeon", "size": 10, + "start_jigsaw_name": "betterdungeons:small_nether_dungeon_anchor", + "max_distance_from_center": 80, "liquid_settings": "ignore_waterlogging"}); + assert!(upgrade("structure", &mut nether, &mut report, &NO_TAGS)); + assert_eq!(nether["type"], "minecraft:jigsaw"); + assert_eq!(nether["horizon:yungsapi"], json!({})); + assert_eq!( + nether["start_jigsaw_name"], + "betterdungeons:small_nether_dungeon_anchor" + ); + assert!(report.unsupported.is_empty()); + let mut pool = json!({"elements": [{"weight": 3, "element": { + "element_type": "yungsapi:yung_single_element", "location": "y:room", + "processors": "minecraft:empty", "projection": "rigid", + "name": "room", "max_count": 2, "min_required_depth": 1, "is_priority": true, + "ignore_bounds": false, "deadend_pool": "y:end", + "condition": {"type": "yungsapi:all_of", "conditions": [ + {"type": "yungsapi:piece_in_horizontal_direction", "pieces": ["yungsapi:all"], + "range": 5, "rotation": "none"}, + {"type": "yungsapi:not", "condition": {"type": "yungsapi:mod_loaded", "modid": "create"}}, + {"type": "yungsapi:biome", "biomes": []}]}}}]}); + assert!(upgrade("template_pool", &mut pool, &mut report, &NO_TAGS)); + let e = &pool["elements"][0]["element"]; + assert_eq!(e["element_type"], "minecraft:single_pool_element"); + assert_eq!(e["location"], "y:room"); + assert_eq!( + e["horizon:yungsapi"], + json!({"name": "room", "max_count": 2, "min_depth": 1, "priority": true, + "ignore_bounds": false, "condition": {"type": "all_of", "conditions": [ + {"type": "piece_in_horizontal_direction", "pieces": [], "range": 5, "rotation": "none"}, + {"type": "not", "condition": {"type": "false"}}, + {"type": "false"}]}}) + ); + assert!(e.get("deadend_pool").is_none()); + assert_eq!( + report.rules_lost, + BTreeMap::from([ + ("enhanced_terrain_adaptation".into(), 1), + ("yungsapi condition yungsapi:biome".into(), 1), + ("yungsapi deadend_pool".into(), 1), + ]) + ); + assert!(report.unsupported.is_empty()); + } + + #[test] + fn drops_processors_written_in_java() { + let mut report = Upgrade::default(); + let mut list = json!({"processors": [ + {"processor_type": "repurposed_structures:bottom_pillar_processor"}, + {"processor_type": "minecraft:gravity", "heightmap": "WORLD_SURFACE_WG", "offset": -1}, + {"processor_type": "moogs_structures:spawner_randomizing_processor"}]}); + assert!(upgrade("processor_list", &mut list, &mut report, &NO_TAGS)); + assert_eq!( + list["processors"], + json!([{"processor_type": "minecraft:gravity", + "heightmap": "WORLD_SURFACE_WG", "offset": -1}]) + ); + let mut pool = json!({"elements": [ + {"weight": 1, "element": {"element_type": "minecraft:single_pool_element", + "processors": {"processors": [{"processor_type": "lithostitched:block_swap"}]}}}, + {"weight": 1, "element": {"element_type": "minecraft:list_pool_element", "elements": [ + {"element_type": "minecraft:single_pool_element", "processors": "x:named"}]}}]}); + assert!(upgrade("template_pool", &mut pool, &mut report, &NO_TAGS)); + assert_eq!( + pool["elements"][0]["element"]["processors"], + json!({"processors": []}) + ); + assert_eq!( + pool["elements"][1]["element"]["elements"][0]["processors"], + "x:named" + ); + let mut vanilla = json!({"processors": [{"processor_type": "minecraft:nop"}]}); + assert!(!upgrade( + "processor_list", + &mut vanilla, + &mut report, + &NO_TAGS + )); + assert_eq!( + report.processors_dropped, + BTreeMap::from([ + ("lithostitched:block_swap".into(), 1), + ("moogs_structures:spawner_randomizing_processor".into(), 1), + ("repurposed_structures:bottom_pillar_processor".into(), 1), + ]) + ); + } + + #[test] + fn yungs_placements_keep_their_rules() { + let tags = BTreeMap::from([( + "bf:avoid".to_owned(), + vec!["minecraft:nether_complexes".to_owned()], + )]); + let mut report = Upgrade::default(); + let mut fortress = json!({"placement": {"type": "yungsapi:enhanced_random_spread", + "salt": 1, "spacing": 30, "separation": 20, + "enhanced_exclusion_zone": {"other_set": "#bf:avoid", "chunk_count": 10}}}); + assert!(upgrade("structure_set", &mut fortress, &mut report, &tags)); + assert_eq!( + fortress["placement"], + json!({"type": "minecraft:random_spread", "salt": 1, "spacing": 30, "separation": 20, + "horizon:exclusion_zone": {"other_sets": ["minecraft:nether_complexes"], "chunk_count": 10}}) + ); + let mut temple = json!({"placement": {"type": "betterdeserttemples:desert_temple", + "salt": 2, "spacing": 30, "separation": 20, + "exclusion_zone": {"other_set": "minecraft:villages", "chunk_count": 6}}}); + assert!(upgrade("structure_set", &mut temple, &mut report, &tags)); + assert_eq!(temple["placement"]["type"], "minecraft:random_spread"); + assert_eq!(temple["placement"]["exclusion_zone"]["chunk_count"], 6); + assert_eq!( + temple["placement"]["horizon:avoid_biomes"], + json!({"biomes": ["#minecraft:is_river", "#minecraft:is_ocean"], + "radius": 48, "step": 2, "y": 120}) + ); + let mut stronghold = json!({"placement": {"type": "betterstrongholds:stronghold", + "salt": 3, "spacing": 85, "separation": 50, + "chunk_distance_to_first_ring": 80, "ring_chunk_thickness": 96}}); + assert!(upgrade( + "structure_set", + &mut stronghold, + &mut report, + &tags + )); + assert_eq!( + stronghold["placement"], + json!({"type": "minecraft:random_spread", "salt": 3, "spacing": 85, "separation": 50, + "horizon:ring_sections": {"distance_to_first_ring": 80, "thickness": 96}}) + ); + assert_eq!(report.mapped, 3); + assert!(report.unsupported.is_empty()); + // The vanilla counterpart is turned off only for a structure the game starts. + let mut ported = json!({"type": "minecraft:jigsaw"}); + assert!(disables("betterstrongholds:stronghold", &mut ported)); + assert_eq!(ported["horizon:disables"], json!(["minecraft:stronghold"])); + let mut java = json!({"type": "bettermineshafts:mineshaft"}); + assert!(!disables("bettermineshafts:mineshaft_oak", &mut java)); + let mut circle = json!({"type": "minecraft:jigsaw"}); + assert!(!disables("betterwitchhuts:witch_circle", &mut circle)); + } + + #[test] + fn piece_limited_jigsaws_keep_their_layout() { + let mut report = Upgrade::default(); + let mut nether = json!({"type": "repurposed_structures:generic_nether_jigsaw_structure", + "start_pool": "rs:x", "size": 8, "y_allowance": {"min_y_allowed": 40, "max_y_allowed": 90}, + "cannot_spawn_in_liquid": true, "pools_that_ignore_boundaries": ["rs:roof"], + "use_bounding_box_hack": true, "land_search_direction": "HIGHEST_LAND", + "ledge_offset_y": 2}); + assert!(upgrade("structure", &mut nether, &mut report, &NO_TAGS)); + assert_eq!(nether["type"], "minecraft:jigsaw"); + assert_eq!( + nether["horizon:piece_limited"], + json!({"library": "repurposed", "min_y": 40, "max_y": 90, "no_liquid": true, + "ignore_bounds_pools": ["rs:roof"], "land_search": "highest_land", + "ledge_offset_y": 2}) + ); + assert_eq!(nether["use_expansion_hack"], true); + for gone in [ + "y_allowance", + "use_bounding_box_hack", + "land_search_direction", + "ledge_offset_y", + ] { + assert!(nether.get(gone).is_none(), "{gone}"); + } + let mut moogs = json!({"type": "moogs_structures:moogs_structures_generic_jigsaw_structure", + "burying_type": "AVERAGE_LAND"}); + assert!(upgrade("structure", &mut moogs, &mut report, &NO_TAGS)); + assert_eq!( + moogs["horizon:piece_limited"], + json!({"library": "moogs", "burying": "average_land"}) + ); + // Repurposed's mineshaft is laid out under the terrain. + let mut mineshaft = json!({"type": "repurposed_structures:generic_mineshaft", + "start_pool": "rs:mineshafts/birch/start_pool", "size": 9, + "liquid_settings": "ignore_waterlogging"}); + assert!(upgrade("structure", &mut mineshaft, &mut report, &NO_TAGS)); + assert_eq!(mineshaft["type"], "minecraft:jigsaw"); + assert_eq!( + mineshaft["horizon:piece_limited"], + json!({"library": "repurposed", "layout": "mineshaft"}) + ); + assert_eq!(mineshaft["liquid_settings"], "ignore_waterlogging"); + // Lithostitched's jigsaw is vanilla's: no key. + let mut litho = json!({"type": "lithostitched:jigsaw"}); + assert!(upgrade("structure", &mut litho, &mut report, &NO_TAGS)); + assert!(litho.get("horizon:piece_limited").is_none()); + assert!(report.rules_lost.is_empty(), "{:?}", report.rules_lost); + assert!(report.unsupported.is_empty()); + + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default(); + for (name, text) in [ + ( + "data/rs/rs_pieces_spawn_counts/city.json", + r#"{"target_structure": "rs:city_nether", "pieces_spawn_counts": [ + {"nbt_piece_name": "rs:city/center", "always_spawn_this_many": 1, + "never_spawn_more_than_this_many": 1, "minimum_distance_from_center_piece": 3}]}"#, + ), + ( + "data/mvs/msl_pieces_spawn_counts/tower.json", + r#"{"pieces_spawn_counts": [{"nbt_piece_name": "mvs:top", "never_spawn_more_than_this_many": 2}]}"#, + ), + ] { + zip.start_file(name, opts).unwrap(); + std::io::Write::write_all(&mut zip, text.as_bytes()).unwrap(); + } + let mut zip = zip::ZipArchive::new(zip.finish().unwrap()).unwrap(); + let counts = piece_counts(&mut zip); + assert_eq!( + counts["rs:city_nether"], + json!([{"name": "rs:city/center", "required": 1, "max": 1, "min_depth": 3}]) + ); + assert_eq!(counts["mvs:tower"], json!([{"name": "mvs:top", "max": 2}])); + assert!(add_piece_counts("rs:city_nether", &mut nether, &counts)); + assert_eq!(nether["horizon:piece_limited"]["pieces"][0]["required"], 1); + assert!(!add_piece_counts("rs:other", &mut nether, &counts)); + } + + #[test] + fn writes_block_states_in_26_3_shape() { + let mut report = Upgrade::default(); + let mut list = json!({"processors": [{"processor_type": "minecraft:rule", "rules": [{ + "input_predicate": {"predicate_type": "minecraft:always_true"}, + "output_state": {"Name": "minecraft:oak_stairs", "Properties": {"facing": "east"}}}]}]}); + assert!(upgrade("processor_list", &mut list, &mut report, &NO_TAGS)); + assert_eq!( + list["processors"][0]["rules"][0]["output_state"], + json!({"id": "minecraft:oak_stairs", "properties": {"facing": "east"}}) + ); + let mut spring = json!({"type": "minecraft:spring_feature", "config": { + "state": {"Name": "minecraft:water"}, "valid_blocks": ["minecraft:stone"]}}); + assert!(upgrade( + "configured_feature", + &mut spring, + &mut report, + &NO_TAGS + )); + assert_eq!(spring["config"]["state"], json!({"id": "minecraft:water"})); + // An object with other keys is not a state; a 26.3 state is left as it is. + let mut other = json!({"Name": "x", "weight": 1, "state": {"id": "minecraft:stone"}}); + assert!(!upgrade( + "configured_feature", + &mut other, + &mut report, + &NO_TAGS + )); + assert_eq!(report.block_states, 2); + assert_eq!(report.mapped, 0); + } + + #[test] + fn modifiers_add_to_sets_and_pools() { + let mut report = Upgrade::default(); + let only_fd = |m: &str| m == "farmersdelight"; + let set = json!({"type": "lithostitched:add_structure_set_entries", + "structure_sets": "minecraft:villages", + "entries": [{"structure": "x:village", "weight": 4}]}); + let (kind, added) = modifier(&set, &only_fd, &mut report).unwrap(); + assert_eq!(kind, "structure_set"); + assert_eq!( + added, + json!({"horizon:add_to": ["minecraft:villages"], + "structures": [{"structure": "x:village", "weight": 4}]}) + ); + // A compat addition holds only when its mod is ported along. + let pool = |modid: &str| { + json!({"type": "lithostitched:add_template_pool_elements", + "neoforge:conditions": [{"type": "neoforge:mod_loaded", "modid": modid}], + "fabric:load_conditions": {"condition": "fabric:all_mods_loaded", "values": ["other"]}, + "template_pools": ["x:houses", "y:houses"], + "elements": [{"weight": 5, "element": {"element_type": "minecraft:single_pool_element", + "location": "x:fd_farm", "projection": "rigid", "processors": "minecraft:empty"}}]}) + }; + let (kind, added) = modifier(&pool("farmersdelight"), &only_fd, &mut report).unwrap(); + assert_eq!(kind, "template_pool"); + assert_eq!(added["horizon:add_to"], json!(["x:houses", "y:houses"])); + assert_eq!(added["elements"][0]["weight"], 5); + assert!(modifier(&pool("create"), &only_fd, &mut report).is_none()); + // Fabric's conditions when there are no NeoForge ones; lithostitched's own. + let fabric = json!({"type": "lithostitched:add_structure_set_entries", + "fabric:load_conditions": [{"condition": "fabric:not", + "value": {"condition": "fabric:any_mods_loaded", "values": ["create"]}}], + "predicate": {"type": "lithostitched:all_of", "predicates": [ + {"type": "lithostitched:mod_loaded", "mod_id": "farmersdelight"}, + {"type": "lithostitched:true"}]}, + "structure_sets": "minecraft:villages", "entries": []}); + assert!(modifier(&fabric, &only_fd, &mut report).is_some()); + let tagged = json!({"type": "lithostitched:add_structure_set_entries", + "structure_sets": "#x:sets", "entries": []}); + assert!(modifier(&tagged, &only_fd, &mut report).is_none()); + let features = json!({"type": "lithostitched:add_features"}); + assert!(modifier(&features, &only_fd, &mut report).is_none()); + assert_eq!( + report.added_to, + BTreeMap::from([ + ("minecraft:villages".into(), 1), + ("x:houses".into(), 1), + ("y:houses".into(), 1), + ]) + ); + assert_eq!( + report.modifiers_left, + BTreeMap::from([ + ("conditions".into(), 1), + ("lithostitched:add_features".into(), 1), + ("target".into(), 1), + ]) + ); + } + + #[test] + fn ctov_joins_vanillas_villages_and_outposts() { + let sets = code_set_entries("ctov"); + let (file, set, outposts) = &sets[0]; + assert_eq!( + (*file, *set), + ("pillager_outposts", "minecraft:pillager_outposts") + ); + assert_eq!(outposts.len(), 11); + assert!(outposts.iter().all(|(_, w)| *w == 1)); + let (_, set, villages) = &sets[1]; + assert_eq!(*set, "minecraft:villages"); + assert_eq!(villages.len(), 63); + assert_eq!(villages[0], ("ctov:small/village_beach".into(), 10)); + assert_eq!(villages[21], ("ctov:medium/village_beach".into(), 4)); + assert_eq!( + villages[62], + ("ctov:large/village_taiga_fortified".into(), 1) + ); + assert!(code_set_entries("mvs").is_empty()); + } + + #[test] + fn convention_tags_include_theirs() { + let conventions = BTreeMap::from([ + ( + "is_hot".to_owned(), + json!({"values": ["#c:is_desert", "#minecraft:is_badlands"]}), + ), + ( + "is_desert".to_owned(), + json!({"values": ["minecraft:desert"]}), + ), + ("is_cold".to_owned(), json!({"values": []})), + ]); + let mut used = BTreeSet::new(); + convention_tags( + &json!({"biomes": ["#c:is_hot", "#c:unknown", "#minecraft:x"]}), + &mut used, + ); + assert_eq!(used, BTreeSet::from(["is_hot".into(), "unknown".into()])); + assert_eq!( + with_included(&used, &conventions), + BTreeSet::from(["is_hot".into(), "is_desert".into()]) + ); + } +} diff --git a/crates/horizon-prepare/src/artifacts.rs b/crates/horizon-prepare/src/artifacts.rs index c9b1947ed..80b3bcf05 100644 --- a/crates/horizon-prepare/src/artifacts.rs +++ b/crates/horizon-prepare/src/artifacts.rs @@ -11,9 +11,10 @@ use std::fs; use std::path::{Component, Path, PathBuf}; const LAUNCHER_HINT: &str = - "Horizon does not download the game: install Minecraft Java Edition with the official \ -launcher, play {version} once, then rerun. If the launcher uses another game directory, \ -pass --minecraft-dir or set HORIZON_MINECRAFT_DIR."; + "Horizon does not download the game: play {version} once in the launcher you play \ +Minecraft Java Edition with (the official launcher, Prism Launcher, MultiMC...) so it downloads \ +the game's files, then rerun. If that launcher keeps them in another folder, pass \ +--minecraft-dir or set HORIZON_MINECRAFT_DIR."; const SERVER_HINT: &str = "Horizon does not download the game: download the {version} server jar yourself (minecraft.net/download/server \ while {version} is the current release, otherwise the downloads.server.url in your launcher's \ versions/{version}/{version}.json), then pass --server-jar PATH or set HORIZON_SERVER_JAR."; @@ -337,8 +338,9 @@ fn native_library_matches(library: &Value, names: &[&str]) -> bool { true } -/// The client libraries the official launcher installs on this OS and architecture. -fn client_library_artifacts(manifest: &Value) -> Result<Vec<&Value>, String> { +/// The client libraries the official launcher installs on this OS and architecture: each +/// library's Maven name and its download. +fn client_library_artifacts(manifest: &Value) -> Result<Vec<(&str, &Value)>, String> { let libraries = manifest .get("libraries") .and_then(Value::as_array) @@ -353,7 +355,8 @@ fn client_library_artifacts(manifest: &Value) -> Result<Vec<&Value>, String> { continue; }; if library_allowed(library)? && native_library_matches(library, &names) { - artifacts.push(artifact); + let name = library.get("name").and_then(Value::as_str).unwrap_or(""); + artifacts.push((name, artifact)); } } Ok(artifacts) @@ -374,6 +377,35 @@ pub(crate) fn safe_relative(path: &str) -> Option<PathBuf> { Some(parts.iter().collect()) } +/// A launcher's copy of the library `name`, whose path in the version JSON is `relative`, under +/// its game folder `minecraft`: at that path, else where Prism Launcher keeps it (#849). Prism's +/// metadata moves a native jar's classifier into its artifact name +/// (`com.mojang:jtracy:1.14.38:natives-windows` is its `com.mojang:jtracy-natives-windows:1.14.38`) +/// and Prism keeps libraries at their name's path, so the same jar, with the same sha1, is in +/// `com/mojang/jtracy-natives-windows/1.14.38/jtracy-natives-windows-1.14.38.jar`. The path the +/// version JSON gives is returned when neither exists, for the error to name. +pub fn launcher_library(minecraft: &Path, name: &str, relative: &Path) -> PathBuf { + let libraries = minecraft.join("libraries"); + let official = libraries.join(relative); + if official.is_file() { + return official; + } + if let [group, artifact, version, classifier] = name.split(':').collect::<Vec<_>>()[..] { + let artifact = format!("{artifact}-{classifier}"); + let path = format!( + "{}/{artifact}/{version}/{artifact}-{version}.jar", + group.replace('.', "/") + ); + if let Some(prism) = safe_relative(&path) + .map(|p| libraries.join(p)) + .filter(|p| p.is_file()) + { + return prism; + } + } + official +} + fn artifact_fields(artifact: &Value) -> Result<(&str, &str), String> { let path = artifact.get("path").and_then(Value::as_str); let sha1 = artifact.get("sha1").and_then(Value::as_str); @@ -502,11 +534,11 @@ pub fn import( let server = import_server(lock, server_jar)?; let (server, server_libraries) = unpack_server(server, &lock.directory, id)?; let mut client_libraries = Vec::new(); - for artifact in client_library_artifacts(&manifest)? { + for (name, artifact) in client_library_artifacts(&manifest)? { let (path, sha1) = artifact_fields(artifact)?; let relative = safe_relative(path).ok_or("Unsafe library path")?; client_libraries.push(import_copy( - &minecraft.join("libraries").join(&relative), + &launcher_library(&minecraft, name, &relative), &lock.directory.join("libraries/client").join(&relative), sha1, "sha1", @@ -744,7 +776,7 @@ pub fn verify(lock: &Lock) -> Result<Artifacts, String> { /// `client_libraries`); the client-side exporters compile against them. pub fn client_libraries(lock: &Lock, manifest: &Value) -> Result<Vec<PathBuf>, String> { let mut libraries = Vec::new(); - for artifact in client_library_artifacts(manifest)? { + for (_, artifact) in client_library_artifacts(manifest)? { let (path, sha1) = artifact_fields(artifact)?; let relative = safe_relative(path).ok_or("Unsafe client library path")?; let library = lock.directory.join("libraries/client").join(&relative); @@ -992,6 +1024,43 @@ mod tests { ); } + /// A native jar is found where the official launcher keeps it, else under the name Prism + /// Launcher's metadata gives it (#849); a plain library only at the version JSON's path. + #[test] + fn libraries_are_found_where_prism_launcher_keeps_them() { + let fixture = Imports::new(); + let minecraft = &fixture.directory; + let official = Path::new("com/mojang/jtracy/1.14.38/jtracy-1.14.38-natives-windows.jar"); + let name = "com.mojang:jtracy:1.14.38:natives-windows"; + let prism = minecraft.join( + "libraries/com/mojang/jtracy-natives-windows/1.14.38/jtracy-natives-windows-1.14.38.jar", + ); + assert_eq!( + launcher_library(minecraft, name, official), + minecraft.join("libraries").join(official) + ); + fs::create_dir_all(prism.parent().unwrap()).unwrap(); + fs::write(&prism, b"natives").unwrap(); + assert_eq!(launcher_library(minecraft, name, official), prism); + let mojang = minecraft.join("libraries").join(official); + fs::create_dir_all(mojang.parent().unwrap()).unwrap(); + fs::write(&mojang, b"natives").unwrap(); + assert_eq!(launcher_library(minecraft, name, official), mojang); + let plain = Path::new("com/mojang/jtracy/1.14.38/jtracy-1.14.38.jar"); + assert_eq!( + launcher_library(minecraft, "com.mojang:jtracy:1.14.38", plain), + minecraft.join("libraries").join(plain) + ); + for unsafe_name in ["a:..:1:x", "a:b\\c:1:x"] { + let path = launcher_library(minecraft, unsafe_name, plain); + assert_eq!( + path, + minecraft.join("libraries").join(plain), + "{unsafe_name}" + ); + } + } + #[test] fn natives_follow_the_architecture() { let names = ["a:b:1:natives-macos", "a:b:1:natives-macos-arm64"]; diff --git a/crates/horizon-prepare/src/sounds.rs b/crates/horizon-prepare/src/sounds.rs index b18ed3426..f6ff0b714 100644 --- a/crates/horizon-prepare/src/sounds.rs +++ b/crates/horizon-prepare/src/sounds.rs @@ -53,7 +53,7 @@ fn launcher_object(assets: &Path, checksum: &str) -> Result<PathBuf, String> { let path = object_path(assets, checksum)?; if !path.is_file() { return Err(format!( - "Missing asset object {}. Play the pinned version once in the official launcher.", + "Missing asset object {}. Play the pinned version once in your launcher.", path.display() )); } diff --git a/crates/horizon-protocol/Cargo.toml b/crates/horizon-protocol/Cargo.toml index fad282080..66a0af162 100644 --- a/crates/horizon-protocol/Cargo.toml +++ b/crates/horizon-protocol/Cargo.toml @@ -8,11 +8,13 @@ description = "Horizon's Minecraft Java Edition 26.3 network protocol (version 7 [dependencies] horizon-world = { path = "../horizon-world" } -flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] } +flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] } serde_json = "1.0.151" # The shared secret and RSA padding (OS randomness) and the server hash. getrandom = "0.3" sha1 = "0.10" +# Secure chat: SHA256withRSA message signatures. +sha2 = "0.10" [lints] workspace = true diff --git a/crates/horizon-protocol/src/buf.rs b/crates/horizon-protocol/src/buf.rs index e761aec3f..349ec74cf 100644 --- a/crates/horizon-protocol/src/buf.rs +++ b/crates/horizon-protocol/src/buf.rs @@ -311,6 +311,16 @@ impl Codec<Vec<u8>> for Bytes { w.byte_array(v) } } +/// ByteBufCodecs.byteArray(N): VarInt-prefixed bytes, at most N. +pub struct BytesN<const N: usize>; +impl<const N: usize> Codec<Vec<u8>> for BytesN<N> { + fn read(r: &mut Reader) -> Result<Vec<u8>> { + r.byte_array(N) + } + fn write(v: &Vec<u8>, w: &mut Writer) { + w.byte_array(v) + } +} /// Everything left in the packet (custom payloads). pub struct Rest; impl Codec<Vec<u8>> for Rest { diff --git a/crates/horizon-protocol/src/chunk.rs b/crates/horizon-protocol/src/chunk.rs index 32d7f98b6..165627d90 100644 --- a/crates/horizon-protocol/src/chunk.rs +++ b/crates/horizon-protocol/src/chunk.rs @@ -57,6 +57,19 @@ pub fn storage_len(bits: u8, entries: usize) -> usize { } } +/// SimpleBitStorage's longs for `values` at `bits` each, a long at a time. +fn pack<T>(values: &[T], bits: u8, id: impl Fn(&T) -> u64) -> Vec<i64> { + let per = 64 / bits as usize; + values + .chunks(per) + .map(|word| { + word.iter() + .enumerate() + .fold(0u64, |w, (k, v)| w | id(v) << (k * bits as usize)) as i64 + }) + .collect() +} + /// One PalettedContainer as sent. #[derive(Clone, Debug, PartialEq)] pub struct Paletted { @@ -160,12 +173,11 @@ impl Paletted { data: Vec::new(), }; } - let mut data = vec![0i64; storage_len(bits, values.len())]; - let per = 64 / bits as usize; - for (i, (&v, &id)) in values.iter().zip(&ids).enumerate() { - let id = if has_palette { u64::from(id) } else { v as u64 }; - data[i / per] |= (id << ((i % per) * bits as usize)) as i64; - } + let data = if has_palette { + pack(&ids, bits, |&id| u64::from(id)) + } else { + pack(values, bits, |&v| v as u64) + }; Self { bits, palette: if has_palette { palette } else { Vec::new() }, diff --git a/crates/horizon-protocol/src/lib.rs b/crates/horizon-protocol/src/lib.rs index e49031b77..1d0f081f7 100644 --- a/crates/horizon-protocol/src/lib.rs +++ b/crates/horizon-protocol/src/lib.rs @@ -13,6 +13,7 @@ pub mod item; pub mod packets; pub mod registry; pub mod rsa; +pub mod secure_chat; pub mod servers; pub mod text; diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 95ce869a4..95a68d1ef 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -2,9 +2,9 @@ use crate::{ Error, Result, buf::{ - Bool, Byte, ChunkPos, Codec, Double, Float, Ident, Int, List, Long, LpVec3, Nbt, Opt, - OptVarInt, Pos, Reader, SectionPos, Short, Str, StrN, UByte, Uuid, VarInt, VarLong, Vec3d, - Writer, + Bool, Byte, BytesN, ChunkPos, Codec, Double, Float, Ident, Int, List, Long, LpVec3, Nbt, + Opt, OptVarInt, Pos, Reader, SectionPos, Short, Str, StrN, UByte, Uuid, VarInt, VarLong, + Vec3d, Writer, }, chunk::{ChunkData, LightData}, entity_data::{EntityData, Value}, @@ -244,6 +244,18 @@ packet!(EntityPositionSync { id: i32 => VarInt, path: PositionPath => PositionPa packet!(ForgetLevelChunk { pos: [i32; 2] => ChunkPos }); packet!(GameEvent { event: u8 => UByte, param: f32 => Float }); packet!(HurtAnimation { id: i32 => VarInt, yaw: f32 => Float }); +packet!( + /// ClientboundDamageEventPacket: the hurt entity, the damage type's + /// registry id, the causing and the direct entity (none: -1 on the wire's + /// id + 1) and the source's position. + DamageEvent { + id: i32 => VarInt, + source_type: i32 => VarInt, + cause: Option<i32> => OptVarInt, + direct: Option<i32> => OptVarInt, + position: Option<[f64; 3]> => Opt<Vec3d>, + } +); packet!(LevelChunkWithLight { x: i32 => Int, z: i32 => Int, chunk: ChunkData => ChunkData, light: LightData => LightData }); packet!(LevelEvent { kind: i32 => Int, pos: [i32; 3] => Pos, data: i32 => Int, global: bool => Bool }); packet!(LightUpdate { x: i32 => VarInt, z: i32 => VarInt, light: LightData => LightData }); @@ -567,6 +579,10 @@ packet!(PlayerPosition { pitch: f32 => Float, relatives: i32 => Int, }); +packet!( + /// ClientboundProjectilePowerPacket: an AbstractHurtingProjectile's accelerationPower. + ProjectilePower { id: i32 => VarInt, power: f64 => Double } +); packet!(PlayerRotation { yaw: f32 => Float, relative_yaw: bool => Bool, pitch: f32 => Float, relative_pitch: bool => Bool }); packet!(RemoveEntities { ids: Vec<i32> => List<VarInt> }); packet!(Respawn { spawn: SpawnInfo => SpawnInfo, keep: i8 => Byte }); @@ -590,6 +606,10 @@ packet!(SetCursorItem { item: Option<Stack> => Slot }); packet!(SetDefaultSpawnPosition { pos: GlobalPos => GlobalPos, yaw: f32 => Float, pitch: f32 => Float }); packet!(SetEntityData { id: i32 => VarInt, values: Vec<(u8, i32, Value)> => EntityData }); packet!(SetEntityMotion { id: i32 => VarInt, velocity: [f64; 3] => LpVec3 }); +packet!( + /// ClientboundSetPassengersPacket: a vehicle and every entity riding it. + SetPassengers { vehicle: i32 => VarInt, passengers: Vec<i32> => List<VarInt> } +); /// ClientboundSetEquipmentPacket: (EquipmentSlot ordinal, stack) pairs. pub struct Equipment; impl Codec<Vec<(u8, Option<Stack>)>> for Equipment { @@ -873,6 +893,24 @@ packet!( UpdateMobEffect { id: i32 => VarInt, effect: i32 => VarInt, amplifier: i32 => VarInt, duration: i32 => VarInt, flags: i8 => Byte } ); packet!(RemoveMobEffect { id: i32 => VarInt, effect: i32 => VarInt }); +packet!( + /// AttributeModifier.STREAM_CODEC: id, amount and operation (0 add_value, + /// 1 add_multiplied_base, 2 add_multiplied_total). + AttributeModifier { id: String => Ident, amount: f64 => Double, operation: i32 => VarInt } +); +packet!( + /// ClientboundUpdateAttributesPacket.AttributeSnapshot: the attribute's + /// registry id, its base value and every modifier. + AttributeSnapshot { + attribute: i32 => VarInt, + base: f64 => Double, + modifiers: Vec<AttributeModifier> => List<AttributeModifier>, + } +); +packet!( + /// ClientboundUpdateAttributesPacket: an entity's synced attribute instances. + UpdateAttributes { id: i32 => VarInt, values: Vec<AttributeSnapshot> => List<AttributeSnapshot> } +); packet!( /// ClientboundSwingAnimationPacket: hand (0 main, 1 off) and the swing /// type (0 none, 1 whack, 2 stab) with its duration in ticks. @@ -1380,6 +1418,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { GameEvent(GameEvent) = GAME_EVENT, GameRuleValues(GameRuleValues) = GAME_RULE_VALUES, HurtAnimation(HurtAnimation) = HURT_ANIMATION, + DamageEvent(DamageEvent) = DAMAGE_EVENT, KeepAlive(KeepAlive) = KEEP_ALIVE, InitializeBorder(InitializeBorder) = INITIALIZE_BORDER, LevelChunkWithLight(LevelChunkWithLight) = LEVEL_CHUNK_WITH_LIGHT, @@ -1426,6 +1465,8 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { SetHealth(SetHealth) = SET_HEALTH, SetHeldSlot(SetHeldSlot) = SET_HELD_SLOT, SetObjective(SetObjective) = SET_OBJECTIVE, + SetPassengers(SetPassengers) = SET_PASSENGERS, + ProjectilePower(ProjectilePower) = PROJECTILE_POWER, SetPlayerInventory(SetPlayerInventory) = SET_PLAYER_INVENTORY, SetPlayerTeam(SetPlayerTeam) = SET_PLAYER_TEAM, SetScore(SetScore) = SET_SCORE, @@ -1445,6 +1486,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { TickingState(TickingState) = TICKING_STATE, TickingStep(TickingStep) = TICKING_STEP, UpdateAdvancements(UpdateAdvancements) = UPDATE_ADVANCEMENTS, + UpdateAttributes(UpdateAttributes) = UPDATE_ATTRIBUTES, UpdateMobEffect(UpdateMobEffect) = UPDATE_MOB_EFFECT, UpdateTags(UpdateTags) = UPDATE_TAGS, TrackedWaypoint(TrackedWaypoint) = WAYPOINT, @@ -1594,6 +1636,42 @@ packet!(Chat { last_seen: LastSeenUpdate => LastSeenUpdate, }); packet!(ChatCommand { command: String => Str }); +packet!(ChatAck { offset: i32 => VarInt }); +/// ArgumentSignatures: each signed argument's name (at most 16 chars) and +/// signature, at most 8. +pub struct ArgumentSignatures; +impl Codec<Vec<(String, Vec<u8>)>> for ArgumentSignatures { + fn read(r: &mut Reader) -> Result<Vec<(String, Vec<u8>)>> { + let n = r.count(8)?; + (0..n) + .map(|_| Ok((r.string(16)?, r.bytes(256)?.to_vec()))) + .collect() + } + fn write(v: &Vec<(String, Vec<u8>)>, w: &mut Writer) { + w.varint(v.len() as i32); + for (name, signature) in v { + w.string(name); + w.bytes(signature); + } + } +} +packet!(ChatCommandSigned { + command: String => Str, + timestamp: i64 => Long, + salt: i64 => Long, + arguments: Vec<(String, Vec<u8>)> => ArgumentSignatures, + last_seen: LastSeenUpdate => LastSeenUpdate, +}); +packet!( + /// RemoteChatSession.Data: the session id, then ProfilePublicKey.Data + /// (expiry in epoch milliseconds, X.509 key, the services' signature). + ChatSessionUpdate { + session: u128 => Uuid, + expires_at: i64 => Long, + key: Vec<u8> => BytesN<512>, + key_signature: Vec<u8> => BytesN<4096>, + } +); packet!(ChangeDifficultyRequest { difficulty: i32 => VarInt }); packet!(LockDifficulty { locked: bool => Bool }); packet!(SetGameRule { entries: Vec<GameRuleEntry> => List<GameRuleEntry> }); @@ -1687,7 +1765,10 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { Attack(Attack) = ATTACK, ChangeGameMode(ChangeGameMode) = CHANGE_GAME_MODE, Chat(Chat) = CHAT, + ChatAck(ChatAck) = CHAT_ACK, ChatCommand(ChatCommand) = CHAT_COMMAND, + ChatCommandSigned(ChatCommandSigned) = CHAT_COMMAND_SIGNED, + ChatSessionUpdate(ChatSessionUpdate) = CHAT_SESSION_UPDATE, PlaceRecipe(super::recipes::PlaceRecipe) = PLACE_RECIPE, ChunkBatchReceived(ChunkBatchReceived) = CHUNK_BATCH_RECEIVED, ClientCommand(ClientCommand) = CLIENT_COMMAND, @@ -2052,10 +2133,34 @@ mod tests { id: 2, velocity: [0.0; 3], }), + Clientbound::SetPassengers(SetPassengers { + vehicle: 2, + passengers: vec![3, 300], + }), + Clientbound::ProjectilePower(ProjectilePower { id: 4, power: 0.1 }), Clientbound::SetEquipment(SetEquipment { id: 2, slots: vec![(0, None), (5, Some(Stack::new(1, 1)))], }), + Clientbound::UpdateAttributes(UpdateAttributes { + id: 2, + values: vec![AttributeSnapshot { + attribute: 26, + base: 0.23, + modifiers: vec![AttributeModifier { + id: "minecraft:baby".into(), + amount: 0.5, + operation: 1, + }], + }], + }), + Clientbound::DamageEvent(DamageEvent { + id: 7, + source_type: 31, + cause: Some(0), + direct: None, + position: Some([1.5, -2.0, 3.25]), + }), Clientbound::SetHealth(SetHealth { health: 17.5, food: 18, @@ -2169,6 +2274,24 @@ mod tests { Serverbound::ChatCommand(ChatCommand { command: "time set day".into(), }), + Serverbound::ChatAck(ChatAck { offset: 3 }), + Serverbound::ChatCommandSigned(ChatCommandSigned { + command: "say hi".into(), + timestamp: 1_700_000_000_000, + salt: -5, + arguments: vec![("message".into(), vec![9; 256])], + last_seen: LastSeenUpdate { + offset: 1, + acknowledged: [1, 0, 8], + checksum: -3, + }, + }), + Serverbound::ChatSessionUpdate(ChatSessionUpdate { + session: 0x1234, + expires_at: 1_800_000_000_000, + key: vec![0x30; 294], + key_signature: vec![7; 512], + }), Serverbound::ChunkBatchReceived(ChunkBatchReceived { chunks_per_tick: 9.5, }), @@ -2275,4 +2398,31 @@ mod tests { ); assert_eq!(p.encode()[1..], [1, 2, 3]); } + + #[test] + fn update_attributes_encode_like_vanilla() { + let p = Clientbound::UpdateAttributes(UpdateAttributes { + id: 5, + values: vec![AttributeSnapshot { + attribute: 1, + base: 0.0, + modifiers: vec![AttributeModifier { + id: "minecraft:armor.helmet".into(), + amount: 3.0, + operation: 0, + }], + }], + }); + let body = p.encode(); + // The packet id (134) is a two-byte VarInt. + let mut expected = vec![134, 1, 5, 1, 1]; + expected.extend(0.0f64.to_be_bytes()); + expected.extend([1, 22]); + expected.extend(b"minecraft:armor.helmet"); + expected.extend(3.0f64.to_be_bytes()); + expected.push(0); + assert_eq!(body, expected); + assert_eq!(crate::ids::play::clientbound::UPDATE_ATTRIBUTES, 134); + assert_eq!(Clientbound::decode(134, &body[2..]).unwrap(), p); + } } diff --git a/crates/horizon-protocol/src/rsa.rs b/crates/horizon-protocol/src/rsa.rs index fe31e425e..d34489fb4 100644 --- a/crates/horizon-protocol/src/rsa.rs +++ b/crates/horizon-protocol/src/rsa.rs @@ -3,8 +3,10 @@ //! and challenge (Crypt.encryptUsingKey, Java's "RSA" cipher = //! RSA/ECB/PKCS1Padding), and on the server's side the key pair it makes at //! startup (Crypt.generateKeyPair: 1024 bits) and the decryption -//! (Crypt.decryptUsingKey). Modular exponentiation uses Montgomery -//! multiplication on 32-bit limbs; RSA moduli are always odd. +//! (Crypt.decryptUsingKey); and the PKCS#1 v1.5 signature checks of secure +//! chat (SHA256withRSA for messages, SHA1withRSA for the services' profile +//! key signatures). Modular exponentiation uses Montgomery multiplication on +//! 32-bit limbs; RSA moduli are always odd. use crate::{Error, Result}; /// A non-negative integer, little-endian 32-bit limbs. @@ -291,6 +293,63 @@ impl RsaPublicKey { } } +/// The digest a PKCS#1 v1.5 signature covers: Java's `SHA1withRSA` and +/// `SHA256withRSA`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SignatureHash { + Sha1, + Sha256, +} + +impl SignatureHash { + /// The DER DigestInfo before the digest (RFC 8017 9.2, note 1). + fn prefix(self) -> &'static [u8] { + match self { + Self::Sha1 => &[ + 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, + 0x14, + ], + Self::Sha256 => &[ + 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, + 0x01, 0x05, 0x00, 0x04, 0x20, + ], + } + } + fn digest(self, message: &[u8]) -> Vec<u8> { + use sha1::Digest; + match self { + Self::Sha1 => sha1::Sha1::digest(message).to_vec(), + Self::Sha256 => sha2::Sha256::digest(message).to_vec(), + } + } +} + +impl RsaPublicKey { + /// `Signature.verify` for RSASSA-PKCS1-v1_5 (RFC 8017 8.2.2): the + /// signature is exactly the modulus' length and below it, and opens to + /// `00 01 FF.. 00 DigestInfo`. Anything else is a failed check, as + /// SignatureValidator reports Java's exceptions. + pub fn verify(&self, hash: SignatureHash, message: &[u8], signature: &[u8]) -> bool { + let k = self.size(); + // Equal lengths compare as big-endian numbers. + if signature.len() != k || signature >= self.modulus.as_slice() { + return false; + } + let (prefix, digest) = (hash.prefix(), hash.digest(message)); + let t = prefix.len() + digest.len(); + if k < t + 11 { + return false; + } + let mut expected = vec![0xff; k]; + expected[0] = 0; + expected[1] = 1; + expected[k - t - 1] = 0; + expected[k - t..k - digest.len()].copy_from_slice(prefix); + expected[k - digest.len()..].copy_from_slice(&digest); + self.apply(signature, &self.exponent) == expected + } +} + /// Small odd primes for sieving prime candidates. const SMALL_PRIMES: [u32; 53] = [ 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, @@ -604,5 +663,34 @@ pub(crate) mod tests { assert!(block.ends_with(&hex( "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" ))); + let signature = hex(TEST_SIG_HELLO); + assert!(key.verify(SignatureHash::Sha256, b"hello", &signature)); + assert!(!key.verify(SignatureHash::Sha256, b"hellO", &signature)); + assert!(!key.verify(SignatureHash::Sha1, b"hello", &signature)); + let mut flipped = signature.clone(); + flipped[40] ^= 1; + assert!(!key.verify(SignatureHash::Sha256, b"hello", &flipped)); + assert!(!key.verify(SignatureHash::Sha256, b"hello", &signature[1..])); + assert!(!key.verify(SignatureHash::Sha256, b"hello", &key.modulus)); + } + + /// Signatures made here with the private exponent (EMSA-PKCS1-v1_5 by + /// hand) check out for both digests. + #[test] + fn verifies_both_digests() { + let key = RsaPublicKey::from_der(&hex(TEST_SPKI)).unwrap(); + for hash in [SignatureHash::Sha1, SignatureHash::Sha256] { + let (prefix, digest) = (hash.prefix(), hash.digest(b"payload")); + let mut block = vec![0xff; 128]; + block[0] = 0; + block[1] = 1; + let t = prefix.len() + digest.len(); + block[127 - t] = 0; + block[128 - t..128 - digest.len()].copy_from_slice(prefix); + block[128 - digest.len()..].copy_from_slice(&digest); + let signature = key.apply(&block, &hex(TEST_D)); + assert!(key.verify(hash, b"payload", &signature)); + assert!(!key.verify(hash, b"payloaD", &signature)); + } } } diff --git a/crates/horizon-protocol/src/secure_chat.rs b/crates/horizon-protocol/src/secure_chat.rs new file mode 100644 index 000000000..534c132f6 --- /dev/null +++ b/crates/horizon-protocol/src/secure_chat.rs @@ -0,0 +1,491 @@ +//! Secure chat as vanilla 26.3's server keeps it: a player's profile key, +//! validated against the services' keys (ProfilePublicKey, +//! RemoteChatSession), the message chain each player signs +//! (SignedMessageChain), what a signature covers (PlayerChatMessage, +//! SignedMessageLink, SignedMessageBody), the window of messages a client +//! acknowledges (LastSeenMessagesValidator) and the cache a connection packs +//! signatures against (MessageSignatureCache). +use crate::rsa::{RsaPublicKey, SignatureHash}; +use std::collections::{HashSet, VecDeque}; + +/// MessageSignature.BYTES. +pub const SIGNATURE_BYTES: usize = 256; +/// A message signature (MessageSignature). +pub type Signature = [u8; SIGNATURE_BYTES]; +/// LastSeenMessages.LAST_SEEN_MESSAGES_MAX_LENGTH: the window a client acknowledges. +pub const LAST_SEEN: usize = 20; +/// PlayerChatMessage.MESSAGE_EXPIRES_AFTER_SERVER, in milliseconds. +pub const EXPIRES_AFTER_SERVER: i64 = 5 * 60 * 1000; + +/// A signature from its packet bytes (always 256 on the wire). +pub fn signature(bytes: &[u8]) -> Option<Signature> { + bytes.try_into().ok() +} + +/// ProfilePublicKey.Data: the player's chat key (X.509 DER), when it +/// expires (epoch milliseconds), and the services' signature over both. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ProfileKey { + pub expires_at: i64, + pub key: Vec<u8>, + pub signature: Vec<u8>, +} + +impl ProfileKey { + /// Data.signedPayload: the profile id, the expiry and the key. + fn signed_payload(&self, profile: u128) -> Vec<u8> { + let mut out = Vec::with_capacity(24 + self.key.len()); + out.extend_from_slice(&profile.to_be_bytes()); + out.extend_from_slice(&self.expires_at.to_be_bytes()); + out.extend_from_slice(&self.key); + out + } + /// Data.validateSignature with the services' profile-key keys + /// (SignatureValidator.from(keySet, PROFILE_KEY): any of them, SHA1withRSA). + pub fn signed_by(&self, services: &[RsaPublicKey], profile: u128) -> bool { + let payload = self.signed_payload(profile); + services + .iter() + .any(|k| k.verify(SignatureHash::Sha1, &payload, &self.signature)) + } + /// Data.hasExpired. + pub fn has_expired(&self, now: i64) -> bool { + self.expires_at < now + } +} + +/// A validated RemoteChatSession: its id and the player's profile key. +#[derive(Clone, Debug)] +pub struct ChatSession { + pub id: u128, + pub profile_key: ProfileKey, + key: RsaPublicKey, +} + +impl ChatSession { + /// RemoteChatSession.Data.validate (ProfilePublicKey.createValidated); + /// the error is the disconnect message's translation key. + pub fn validate( + id: u128, + profile_key: ProfileKey, + services: &[RsaPublicKey], + profile: u128, + ) -> Result<Self, &'static str> { + const INVALID: &str = "multiplayer.disconnect.invalid_public_key_signature"; + let key = RsaPublicKey::from_der(&profile_key.key).map_err(|_| INVALID)?; + if !profile_key.signed_by(services, profile) { + return Err(INVALID); + } + Ok(Self { + id, + profile_key, + key, + }) + } + /// RemoteChatSession.Data, as ClientboundPlayerInfoUpdatePacket's + /// INITIALIZE_CHAT carries it. + pub fn data(&self) -> (u128, i64, Vec<u8>, Vec<u8>) { + let k = &self.profile_key; + (self.id, k.expires_at, k.key.clone(), k.signature.clone()) + } +} + +/// SignedMessageBody: what a player signed besides the chain link. +#[derive(Clone, Copy, Debug)] +pub struct Body<'a> { + pub content: &'a str, + /// Epoch milliseconds. + pub timestamp: i64, + pub salt: i64, + pub last_seen: &'a [Signature], +} + +/// PlayerChatMessage.updateSignature: the version, the link (sender, +/// session, index) and the body (salt, time in seconds, content, last seen). +pub fn signed_payload(sender: u128, session: u128, index: i32, body: &Body) -> Vec<u8> { + let content = body.content.as_bytes(); + let mut out = Vec::with_capacity(64 + content.len() + body.last_seen.len() * SIGNATURE_BYTES); + out.extend_from_slice(&1i32.to_be_bytes()); + out.extend_from_slice(&sender.to_be_bytes()); + out.extend_from_slice(&session.to_be_bytes()); + out.extend_from_slice(&index.to_be_bytes()); + out.extend_from_slice(&body.salt.to_be_bytes()); + out.extend_from_slice(&body.timestamp.div_euclid(1000).to_be_bytes()); + out.extend_from_slice(&(content.len() as i32).to_be_bytes()); + out.extend_from_slice(content); + out.extend_from_slice(&(body.last_seen.len() as i32).to_be_bytes()); + for s in body.last_seen { + out.extend_from_slice(s); + } + out +} + +/// SignedMessageChain.DecodeException's messages, and the signed command +/// mismatch (ServerGamePacketListenerImpl.INVALID_COMMAND_SIGNATURE). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DecodeError { + MissingProfileKey, + ChainBroken, + ExpiredProfileKey, + InvalidSignature, + OutOfOrderChat, + InvalidCommandSignature, +} + +impl DecodeError { + pub fn key(self) -> &'static str { + match self { + Self::MissingProfileKey => "chat.disabled.missingProfileKey", + Self::ChainBroken => "chat.disabled.chain_broken", + Self::ExpiredProfileKey => "chat.disabled.expiredProfileKey", + Self::InvalidSignature => "chat.disabled.invalid_signature", + Self::OutOfOrderChat => "chat.disabled.out_of_order_chat", + Self::InvalidCommandSignature => "chat.disabled.invalid_command_signature", + } + } +} + +/// A message the chain let through: unsigned (PlayerChatMessage.unsigned) +/// or signed at a link of the sender's chain. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Unpacked { + Unsigned, + Signed { index: i32, signature: Signature }, +} + +/// A player's SignedMessageChain.Decoder: unsigned until the player sends a +/// chat session, then keyed to it. +#[derive(Clone, Debug, Default)] +pub struct Chain { + session: Option<ChatSession>, + /// The next link's index; None once the chain is broken. + next: Option<i32>, + /// The last message's time (lastTimeStamp, from Instant.EPOCH). + last_timestamp: i64, +} + +impl Chain { + /// RemoteChatSession.createMessageDecoder: a new chain from link 0. + pub fn keyed(session: ChatSession) -> Self { + Self { + session: Some(session), + next: Some(0), + last_timestamp: 0, + } + } + pub fn session(&self) -> Option<&ChatSession> { + self.session.as_ref() + } + /// Decoder.unpack for `sender`'s message. Without a session the message + /// is unsigned unless the server enforces secure chat; with one it must + /// be the next link, in order, signed by the player's key. + pub fn unpack( + &mut self, + sender: u128, + signature: Option<&Signature>, + body: &Body, + enforce: bool, + now: i64, + ) -> Result<Unpacked, DecodeError> { + let Some(session) = &self.session else { + return if enforce { + Err(DecodeError::MissingProfileKey) + } else { + Ok(Unpacked::Unsigned) + }; + }; + let signature = signature.ok_or(DecodeError::MissingProfileKey)?; + if session.profile_key.has_expired(now) { + return Err(DecodeError::ExpiredProfileKey); + } + let index = self.next.ok_or(DecodeError::ChainBroken)?; + if body.timestamp < self.last_timestamp { + self.next = None; + return Err(DecodeError::OutOfOrderChat); + } + self.last_timestamp = body.timestamp; + let payload = signed_payload(sender, session.id, index, body); + if !session + .key + .verify(SignatureHash::Sha256, &payload, signature) + { + self.next = None; + return Err(DecodeError::InvalidSignature); + } + self.next = index.checked_add(1); + Ok(Unpacked::Signed { + index, + signature: *signature, + }) + } + /// Decoder.setChainBroken (nothing for the unsigned decoder). + pub fn set_broken(&mut self) { + if self.session.is_some() { + self.next = None; + } + } +} + +/// Arrays.hashCode(byte[]). +fn java_hash(bytes: &[u8]) -> i32 { + bytes.iter().fold(1i32, |h, &b| { + h.wrapping_mul(31).wrapping_add(i32::from(b as i8)) + }) +} + +/// LastSeenMessages.computeChecksum: never 0, which means "not checked". +pub fn checksum(entries: &[Signature]) -> i8 { + let c = entries + .iter() + .fold(1i32, |c, e| c.wrapping_mul(31).wrapping_add(java_hash(e))); + match c as i8 { + 0 => 1, + b => b, + } +} + +/// LastSeenMessagesValidator: the messages sent to a player that its next +/// acknowledgement may name, each pending until it does. +#[derive(Clone, Debug)] +pub struct LastSeenValidator { + tracked: VecDeque<Option<(Signature, bool)>>, + last_pending: Option<Signature>, +} + +impl Default for LastSeenValidator { + fn default() -> Self { + Self { + tracked: std::iter::repeat_n(None, LAST_SEEN).collect(), + last_pending: None, + } + } +} + +impl LastSeenValidator { + pub fn add_pending(&mut self, signature: &Signature) { + if self.last_pending.as_ref() != Some(signature) { + self.tracked.push_back(Some((*signature, true))); + self.last_pending = Some(*signature); + } + } + pub fn tracked_count(&self) -> usize { + self.tracked.len() + } + /// applyOffset: drop the `offset` oldest messages. + pub fn apply_offset(&mut self, offset: i32) -> Result<(), String> { + let max = self.tracked.len() as i64 - LAST_SEEN as i64; + if offset >= 0 && i64::from(offset) <= max { + self.tracked.drain(..offset as usize); + Ok(()) + } else { + Err(format!( + "Advanced last seen window by {offset} messages, but expected at most {max}" + )) + } + } + /// applyUpdate: the offset, then the acknowledged messages of the + /// window (a 20-bit set, little-endian bytes), checked against the + /// client's checksum unless it sent 0. + pub fn apply_update( + &mut self, + offset: i32, + acknowledged: [u8; 3], + checksum: i8, + ) -> Result<Vec<Signature>, String> { + self.apply_offset(offset)?; + let bit = |i: usize| acknowledged[i / 8] >> (i % 8) & 1 != 0; + let length = (0..24).rev().find(|&i| bit(i)).map_or(0, |i| i + 1); + if length > LAST_SEEN { + return Err(format!( + "Last seen update contained {length} messages, but maximum window size is {LAST_SEEN}" + )); + } + let mut seen = Vec::with_capacity(LAST_SEEN); + for i in 0..LAST_SEEN { + let entry = self.tracked[i]; + if bit(i) { + let Some((s, _)) = entry else { + return Err(format!( + "Last seen update acknowledged unknown or previously ignored message at index {i}" + )); + }; + self.tracked[i] = Some((s, false)); + seen.push(s); + } else { + if let Some((_, false)) = entry { + return Err(format!( + "Last seen update ignored previously acknowledged message at index {i}" + )); + } + self.tracked[i] = None; + } + } + if checksum != 0 && checksum != self::checksum(&seen) { + return Err( + "Checksum mismatch on last seen update: the client and server must have desynced" + .to_owned(), + ); + } + Ok(seen) + } +} + +/// MessageSignatureCache: the 128 signatures a connection's client also +/// holds, so a packed signature can name one by index. +#[derive(Clone, Debug)] +pub struct SignatureCache { + entries: Vec<Option<Signature>>, +} + +impl Default for SignatureCache { + fn default() -> Self { + Self { + entries: vec![None; 128], + } + } +} + +impl SignatureCache { + /// MessageSignature.pack: the cache index, or the full signature. + pub fn pack(&self, signature: &Signature) -> (i32, Option<Vec<u8>>) { + match self + .entries + .iter() + .position(|e| e.as_ref() == Some(signature)) + { + Some(i) => (i as i32, None), + None => (-1, Some(signature.to_vec())), + } + } + /// push(body, signature): the message's last seen and its signature go + /// to the front, most recent first; what they displace moves back. + pub fn push(&mut self, last_seen: &[Signature], signature: Option<&Signature>) { + let mut queue: VecDeque<Signature> = last_seen.iter().chain(signature).copied().collect(); + let new: HashSet<Signature> = queue.iter().copied().collect(); + for slot in &mut self.entries { + let Some(next) = queue.pop_back() else { break }; + if let Some(old) = slot.replace(next) + && !new.contains(&old) + { + queue.push_front(old); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sig(b: u8) -> Signature { + [b; SIGNATURE_BYTES] + } + + #[test] + fn payload_layout_matches_update_signature() { + let body = Body { + content: "hé", + timestamp: 1_700_000_123_456, + salt: -2, + last_seen: &[sig(7)], + }; + let p = signed_payload(1, 2, 3, &body); + assert_eq!(&p[..4], &[0, 0, 0, 1]); + assert_eq!(&p[4..20], &1u128.to_be_bytes()); + assert_eq!(&p[20..36], &2u128.to_be_bytes()); + assert_eq!(&p[36..40], &3i32.to_be_bytes()); + assert_eq!(&p[40..48], &(-2i64).to_be_bytes()); + assert_eq!(&p[48..56], &1_700_000_123i64.to_be_bytes()); + assert_eq!(&p[56..60], &3i32.to_be_bytes()); + assert_eq!(&p[60..63], "hé".as_bytes()); + assert_eq!(&p[63..67], &1i32.to_be_bytes()); + assert_eq!(p.len(), 67 + 256); + // Instant.getEpochSecond floors. + let before = Body { + timestamp: -1, + ..body + }; + assert_eq!( + &signed_payload(1, 2, 3, &before)[48..56], + &(-1i64).to_be_bytes() + ); + } + + #[test] + fn unsigned_chain_follows_enforcement() { + let mut chain = Chain::default(); + let body = Body { + content: "hi", + timestamp: 5, + salt: 0, + last_seen: &[], + }; + assert_eq!( + chain.unpack(1, None, &body, false, 0), + Ok(Unpacked::Unsigned) + ); + assert_eq!( + chain.unpack(1, Some(&sig(1)), &body, false, 0), + Ok(Unpacked::Unsigned) + ); + assert_eq!( + chain.unpack(1, None, &body, true, 0), + Err(DecodeError::MissingProfileKey) + ); + } + + #[test] + fn checksums_follow_java_hash_codes() { + // Arrays.hashCode(new byte[]{-1}) = 31 + (-1) = 30. + assert_eq!(java_hash(&[0xff]), 30); + assert_eq!(checksum(&[]), 1); + let one = [sig(0)]; + let expected = 31i32.wrapping_add(java_hash(&sig(0))) as i8; + assert_eq!(checksum(&one), if expected == 0 { 1 } else { expected }); + } + + #[test] + fn last_seen_window() { + let mut v = LastSeenValidator::default(); + assert_eq!(v.tracked_count(), 20); + v.add_pending(&sig(1)); + v.add_pending(&sig(1)); + v.add_pending(&sig(2)); + assert_eq!(v.tracked_count(), 22); + assert!(v.apply_offset(3).is_err()); + // Slide by two: the two messages are the window's last entries. + let mut ack = [0u8; 3]; + ack[18 / 8] |= 1 << (18 % 8); + ack[19 / 8] |= 1 << (19 % 8); + let seen = v.apply_update(2, ack, checksum(&[sig(1), sig(2)])).unwrap(); + assert_eq!(seen, vec![sig(1), sig(2)]); + // Once acknowledged, a message can't be ignored. + assert!(v.apply_update(0, [0; 3], 0).is_err()); + let mut v = LastSeenValidator::default(); + v.add_pending(&sig(1)); + assert!(v.apply_update(1, [0, 0, 0x10], 0).is_err(), "bit 20"); + let mut v = LastSeenValidator::default(); + assert!(v.apply_update(0, [1, 0, 0], 0).is_err(), "unknown"); + let mut v = LastSeenValidator::default(); + v.add_pending(&sig(1)); + let mut ack = [0u8; 3]; + ack[2] |= 1 << 3; + assert!(v.apply_update(1, ack, 99).is_err(), "checksum"); + } + + #[test] + fn cache_moves_recent_signatures_first() { + let mut c = SignatureCache::default(); + assert_eq!(c.pack(&sig(1)), (-1, Some(sig(1).to_vec()))); + c.push(&[], Some(&sig(1))); + assert_eq!(c.pack(&sig(1)), (0, None)); + c.push(&[sig(1)], Some(&sig(2))); + assert_eq!(c.pack(&sig(2)), (0, None)); + assert_eq!(c.pack(&sig(1)), (1, None)); + c.push(&[], Some(&sig(3))); + assert_eq!( + [c.pack(&sig(3)).0, c.pack(&sig(2)).0, c.pack(&sig(1)).0], + [0, 1, 2] + ); + } +} diff --git a/crates/horizon-server-files/Cargo.toml b/crates/horizon-server-files/Cargo.toml index 184dadc90..2643fc726 100644 --- a/crates/horizon-server-files/Cargo.toml +++ b/crates/horizon-server-files/Cargo.toml @@ -12,6 +12,8 @@ horizon-protocol = { path = "../horizon-protocol" } horizon-world = { path = "../horizon-world" } log = "0.4" # Online mode: finding accounts by name (the services' profiles endpoint). +# Secure chat: the services' public keys arrive base64-encoded. +base64 = "0.22" ureq = { version = "2", default-features = false, features = ["tls"] } [lints] diff --git a/crates/horizon-server-files/src/profiles.rs b/crates/horizon-server-files/src/profiles.rs index a093fbfb1..3e16e2a41 100644 --- a/crates/horizon-server-files/src/profiles.rs +++ b/crates/horizon-server-files/src/profiles.rs @@ -6,6 +6,7 @@ use crate::{ json::{self, Json}, user_lists::NameAndId, }; +use horizon_protocol::rsa::RsaPublicKey; use std::time::Duration; /// Mojang's services discovery document. @@ -51,6 +52,57 @@ pub fn find_by_name(discovery: &str, name: &str) -> Option<NameAndId> { found(&agent.get(&url).call().ok()?.into_string().ok()?, name) } +/// MinecraftServicesKeyInfo.get: the services' public keys from the +/// discovery document's `authentication` / `getPublicKeys` endpoint. The +/// profile-key keys (`playerCertificateKeys`, ServicesKeyType.PROFILE_KEY) +/// sign the players' chat keys; secure chat checks them. The error is the +/// line vanilla logs, after which it has no keys. +pub fn fetch_profile_key_keys(discovery: &str) -> Result<Vec<RsaPublicKey>, &'static str> { + const FAILED: &str = "Failed to request Minecraft Services public key"; + let agent = ureq::AgentBuilder::new() + .timeout(Duration::from_secs(15)) + .user_agent(concat!("Horizon/", env!("CARGO_PKG_VERSION"))) + .build(); + let get = |url: &str| agent.get(url).call().ok()?.into_string().ok(); + let doc = get(discovery) + .and_then(|d| json::parse(&d, true).ok()) + .ok_or(FAILED)?; + let url = endpoint(&doc, "authentication", "getPublicKeys").ok_or(FAILED)?; + profile_key_keys(&get(&url).ok_or(FAILED)?) +} + +/// The key set answer: `{"profilePropertyKeys": [...], "playerCertificateKeys": +/// [...]}`, each `{"publicKey": base64 X.509}`. One bad key makes the whole +/// answer malformed (parseList throws). +pub fn profile_key_keys(answer: &str) -> Result<Vec<RsaPublicKey>, &'static str> { + use base64::Engine; + const MALFORMED: &str = "Received malformed Minecraft Services public key data"; + let doc = json::parse(answer, true).map_err(|_| MALFORMED)?; + let list = |name: &str| -> Result<Vec<RsaPublicKey>, &'static str> { + let Some(entries) = doc.get(name) else { + return Ok(Vec::new()); + }; + let Json::Array(entries) = entries else { + return Err(MALFORMED); + }; + entries + .iter() + .map(|e| { + let text = e + .get("publicKey") + .and_then(Json::as_string) + .ok_or(MALFORMED)?; + let der = base64::engine::general_purpose::STANDARD + .decode(text) + .map_err(|_| MALFORMED)?; + RsaPublicKey::from_der(&der).map_err(|_| MALFORMED) + }) + .collect() + }; + list("profilePropertyKeys")?; + list("playerCertificateKeys") +} + /// MinecraftServicesDiscoveryService.getUrl(service, endpoint). fn endpoint(doc: &Json, service: &str, name: &str) -> Option<String> { doc.get("discovery")? @@ -97,4 +149,20 @@ mod tests { assert_eq!(found("{}", "Notch"), None); assert_eq!(found("", "Notch"), None); } + + #[test] + fn services_key_sets() { + // The 1024-bit test key of horizon-protocol's RSA tests, base64. + let key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrAmB0+SRQqPcm84lbsRF2yo8GXzEAzUFDusT302dO3P+VtBoFJdI2WlScEG7GaFiBs5IXdCD9Mf9cFE/xG6JDEedRzSxrXRgXtq9mhqQ8ldYSQ2EwBeaUW2CTzZUiPOxeiFaCbanS7hsyM2KsHOvqs2WcvEUxmptUDdqBakeY/wIDAQAB"; + let answer = format!( + r#"{{"profilePropertyKeys":[{{"publicKey":"{key}"}}],"playerCertificateKeys":[{{"publicKey":"{key}"}},{{"publicKey":"{key}"}}]}}"# + ); + let keys = profile_key_keys(&answer).unwrap(); + assert_eq!(keys.len(), 2); + assert_eq!(keys[0].size(), 128); + assert_eq!(profile_key_keys("{}").unwrap().len(), 0); + let bad = r#"{"profilePropertyKeys":[{"publicKey":"AAAA"}],"playerCertificateKeys":[]}"#; + assert!(profile_key_keys(bad).is_err()); + assert!(profile_key_keys("not json").is_err()); + } } diff --git a/crates/horizon-server/Cargo.toml b/crates/horizon-server/Cargo.toml index c3800b80c..2432cd481 100644 --- a/crates/horizon-server/Cargo.toml +++ b/crates/horizon-server/Cargo.toml @@ -10,6 +10,8 @@ description = "Host a Horizon server: server.toml, the CLI and the supervisor th horizon-server-files = { path = "../horizon-server-files" } # The game process's RAM and CPU (the same probes the benchmark reports use). horizon-bench = { path = "../horizon-bench" } +# The log's local times, as the game prints them. +chrono = { version = "0.4.42", default-features = false, features = ["clock", "std"] } serde = { version = "1", features = ["derive"] } serde_json = "1" toml = "1.1" diff --git a/crates/horizon-server/src/engine.rs b/crates/horizon-server/src/engine.rs index c0043e1d3..aa83693cb 100644 --- a/crates/horizon-server/src/engine.rs +++ b/crates/horizon-server/src/engine.rs @@ -11,7 +11,9 @@ use std::{ time::Duration, }; -/// The game's program names, most specific first: a headless engine once there is one, else the game. +/// The game's program names, most specific first: the server build (the game without sound or +/// controllers, so it needs neither ALSA nor udev on Linux; `horizon-server-linux-x86_64.tar.gz` holds it), +/// else the full game. const PROGRAMS: [&str; 2] = ["horizon-engine", "horizon-client"]; fn exe(name: &str) -> String { @@ -49,6 +51,55 @@ pub fn program(config: &Config, dir: &Path) -> Result<PathBuf, String> { }) } +/// Checks that the game program starts at all: `--help` loads no game files, so it fails only when the +/// system can't load the program, as on a Linux without the ALSA and udev libraries the full game links +/// (the server build doesn't). The reason, with what to install. +pub fn check_starts(program: &Path) -> Result<(), String> { + let output = Command::new(program) + .arg("--help") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .output() + .map_err(|e| format!("the game ({}) can't start: {e}", program.display()))?; + if output.status.success() { + return Ok(()); + } + let stderr = String::from_utf8_lossy(&output.stderr); + Err(start_failure(program, output.status.code(), &stderr)) +} + +/// What to tell the owner when the game program exits at once. +fn start_failure(program: &Path, code: Option<i32>, stderr: &str) -> String { + let reason = stderr + .lines() + .find(|l| !l.trim().is_empty()) + .unwrap_or("") + .trim(); + let mut text = format!( + "the game ({}) can't start{}{}", + program.display(), + code.map_or(String::new(), |c| format!(" (exit status {c})")), + if reason.is_empty() { + String::new() + } else { + format!(": {reason}") + } + ); + if reason.contains("error while loading shared libraries") + && (reason.contains("libasound") || reason.contains("libudev")) + { + text.push_str( + "\nThe full game needs ALSA's and udev's libraries (libasound.so.2, libudev.so.1). Install the \ + server build, which needs neither (packaging/server/install.sh picks it on Linux), or the \ + libraries:\n Debian, Ubuntu: sudo apt install libasound2 libudev1 (Ubuntu 24.04 and later: \ + libasound2t64)\n Fedora, RHEL: sudo dnf install alsa-lib systemd-libs\n Arch: sudo pacman -S \ + alsa-lib systemd-libs\n NixOS: enable programs.nix-ld with alsa-lib and udev in its libraries", + ); + } + text +} + /// Where the prepared game files may be, in the order they are tried. pub fn resource_candidates(config: &Config, dir: &Path, program: Option<&Path>) -> Vec<PathBuf> { if !config.engine.resources.is_empty() { @@ -65,12 +116,13 @@ pub fn resource_candidates(config: &Config, dir: &Path, program: Option<&Path>) out } -/// The prepared game files: a folder holding the asset index `horizon-prepare` writes. +/// The prepared game files: a folder holding the manifest every `horizon-prepare` run writes +/// (`asset-index.json` comes only with the optional sounds, which a server doesn't need). pub fn resources(config: &Config, dir: &Path, program: Option<&Path>) -> Result<PathBuf, String> { let candidates = resource_candidates(config, dir, program); candidates .iter() - .find(|d| d.join("asset-index.json").is_file()) + .find(|d| d.join("horizon-resources.json").is_file()) .cloned() .ok_or_else(|| { let tried: Vec<String> = candidates @@ -179,4 +231,73 @@ mod tests { [PathBuf::from("/data/res")] ); } + + #[test] + fn resources_prepared_without_sounds_are_found() { + let root = std::env::temp_dir().join(format!("horizon-server-res-{}", std::process::id())); + let prepared = root.join(".local/horizon-client/26.3"); + std::fs::create_dir_all(&prepared).unwrap(); + let program = root.join("horizon-client"); + let config = Config::default(); + let server = root.join("server"); + assert!(resources(&config, &server, Some(&program)).is_err()); + // What `horizon-prepare` writes on every run; no asset index without `horizon-prepare sounds`. + std::fs::write(prepared.join("horizon-resources.json"), "{}").unwrap(); + assert_eq!(resources(&config, &server, Some(&program)), Ok(prepared)); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn a_missing_library_says_what_to_install() { + let program = Path::new("/opt/horizon/horizon-client"); + let text = start_failure( + program, + Some(127), + "/opt/horizon/horizon-client: error while loading shared libraries: libasound.so.2: cannot open \ + shared object file: No such file or directory\n", + ); + assert!(text.starts_with( + "the game (/opt/horizon/horizon-client) can't start (exit status 127): /opt/horizon/horizon-client: \ + error while loading shared libraries: libasound.so.2" + )); + assert!(text.contains("sudo apt install libasound2 libudev1")); + // Another library: no ALSA advice (the server build, horizon-engine, links neither). + let engine = start_failure( + Path::new("/opt/horizon/horizon-engine"), + Some(127), + "/opt/horizon/horizon-engine: error while loading shared libraries: libgcc_s.so.1: cannot open \ + shared object file: No such file or directory\n", + ); + assert!(!engine.contains("libasound"), "{engine}"); + let other = start_failure(program, Some(1), "something else\n"); + assert_eq!( + other, + "the game (/opt/horizon/horizon-client) can't start (exit status 1): something else" + ); + } + + #[cfg(unix)] + #[test] + fn the_check_runs_the_program() { + use std::os::unix::fs::PermissionsExt; + let root = + std::env::temp_dir().join(format!("horizon-server-check-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let script = |name: &str, body: &str| { + let path = root.join(name); + std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + path + }; + assert_eq!(check_starts(&script("starts", "exit 0")), Ok(())); + let fails = script("fails", "echo 'no luck' >&2; exit 3"); + assert_eq!( + check_starts(&fails), + Err(format!( + "the game ({}) can't start (exit status 3): no luck", + fails.display() + )) + ); + std::fs::remove_dir_all(&root).unwrap(); + } } diff --git a/crates/horizon-server/src/init.rs b/crates/horizon-server/src/init.rs index 757b6def8..bd595cddb 100644 --- a/crates/horizon-server/src/init.rs +++ b/crates/horizon-server/src/init.rs @@ -205,6 +205,9 @@ pub fn run(dir: &Path, answers: Answers) -> Result<(), String> { match engine::program(&cfg, dir) { Ok(program) => { println!("Game: {}", program.display()); + if let Err(e) = engine::check_starts(&program) { + println!("Warning: {e}"); + } match engine::resources(&cfg, dir, Some(&program)) { Ok(resources) => println!("Game files: {}", resources.display()), Err(e) => println!("{e}"), diff --git a/crates/horizon-server/src/service.rs b/crates/horizon-server/src/service.rs index 2cafa0e3d..6e6d59f23 100644 --- a/crates/horizon-server/src/service.rs +++ b/crates/horizon-server/src/service.rs @@ -32,7 +32,8 @@ pub fn name(dir: &Path) -> String { } /// The program the service runs: the `horizon-server` on the PATH (the installer's launcher, which keeps -/// running the current version after an update), else this program. +/// running the current version after an update), else this program, through the installer's `current` +/// link when it runs from an installed release. fn program() -> Result<PathBuf, String> { let on_path = std::env::var_os("PATH") .map(|p| std::env::split_paths(&p).collect::<Vec<_>>()) @@ -42,10 +43,30 @@ fn program() -> Result<PathBuf, String> { .find(|p| p.is_file()); match on_path { Some(path) => Ok(path), - None => std::env::current_exe().map_err(|e| e.to_string()), + None => std::env::current_exe() + .map(|exe| through_current(&exe)) + .map_err(|e| e.to_string()), } } +/// `<dir>/releases/<tag>/horizon-server` as `<dir>/current/horizon-server` while `current` points at that +/// release (install.sh and install.ps1's layout), so an update applies at the next restart. Linux reports +/// the running program with links resolved, so the release's own path is what this program sees there. +fn through_current(exe: &Path) -> PathBuf { + let current = (|| { + let release = exe.parent()?; + let releases = release.parent()?; + if releases.file_name()? != "releases" { + return None; + } + let current = releases.parent()?.join("current"); + let name = exe.file_name()?; + let same = std::fs::canonicalize(¤t).ok()? == std::fs::canonicalize(release).ok()?; + same.then(|| current.join(name)) + })(); + current.unwrap_or_else(|| exe.to_path_buf()) +} + /// A systemd unit: a user unit, or with `user` a system unit running as that user. pub fn systemd_unit(program: &Path, dir: &Path, user: Option<&str>) -> String { let (run_as, wanted_by) = match user { @@ -374,4 +395,22 @@ mod tests { assert!(plist.contains("<string>/srv/R&D</string>")); assert!(plist.contains("<string>/srv/R&D/logs/supervisor.log</string>")); } + + #[cfg(unix)] + #[test] + fn an_installed_release_runs_through_current() { + let root = + std::env::temp_dir().join(format!("horizon-service-current-{}", std::process::id())); + let release = root.join("releases/v1"); + std::fs::create_dir_all(&release).unwrap(); + let exe = release.join("horizon-server"); + std::fs::write(&exe, "").unwrap(); + // Not the release in use (or no installer layout): this program as it is. + assert_eq!(through_current(&exe), exe); + std::os::unix::fs::symlink(&release, root.join("current")).unwrap(); + assert_eq!(through_current(&exe), root.join("current/horizon-server")); + let other = root.join("bin/horizon-server"); + assert_eq!(through_current(&other), other); + std::fs::remove_dir_all(&root).unwrap(); + } } diff --git a/crates/horizon-server/src/supervisor.rs b/crates/horizon-server/src/supervisor.rs index ad056a77c..b26ac67cb 100644 --- a/crates/horizon-server/src/supervisor.rs +++ b/crates/horizon-server/src/supervisor.rs @@ -8,7 +8,6 @@ use crate::{ config::Config, engine, signals, }; -use horizon_server_files::java_properties::now_millis; use serde_json::json; use std::{ fs::File, @@ -29,15 +28,12 @@ const MAX_BACKOFF: Duration = Duration::from_secs(300); /// How long `stop` may take before the game is killed. const STOP_TIMEOUT: Duration = Duration::from_secs(120); -/// A line from the supervisor, in the game's log format (`[HH:mm:ss] [thread/LEVEL]: message`, UTC), on -/// stdout and in the log the API serves. +/// A line from the supervisor, in the game's log format (`[HH:mm:ss] [thread/LEVEL]: message`, local time +/// as the game's own lines), on stdout and in the log the API serves. fn note(shared: &Shared, level: &str, message: &str) { - let secs = now_millis().div_euclid(1000).rem_euclid(86_400); let line = format!( - "[{:02}:{:02}:{:02}] [Supervisor/{level}]: {message}", - secs / 3600, - secs / 60 % 60, - secs % 60 + "[{}] [Supervisor/{level}]: {message}", + chrono::Local::now().format("%H:%M:%S") ); println!("{line}"); shared.log.lock().unwrap().push(line); @@ -76,6 +72,8 @@ pub fn run(dir: &Path) -> Result<(), String> { let config = Config::load(dir)?; let program = engine::program(&config, dir)?; let resources = engine::resources(&config, dir, Some(&program))?; + // A game the system can't load would only crash again at every restart: say why at once. + engine::check_starts(&program)?; let _lock = lock(dir)?; let shared = Shared::new(dir); let _endpoint = api::start(shared.clone())?; diff --git a/crates/horizon-telemetry/src/payload.rs b/crates/horizon-telemetry/src/payload.rs index 1429a7116..2ed0ba88d 100644 --- a/crates/horizon-telemetry/src/payload.rs +++ b/crates/horizon-telemetry/src/payload.rs @@ -179,6 +179,10 @@ pub struct Perf { /// From start to the title screen. #[serde(skip_serializing_if = "Option::is_none")] pub to_title_ms: Option<u32>, + #[serde(skip_serializing_if = "Option::is_none")] + pub to_core_ms: Option<u32>, + #[serde(skip_serializing_if = "Option::is_none")] + pub to_rest_ms: Option<u32>, /// From choosing a world to playing in it, the first time this session. #[serde(skip_serializing_if = "Option::is_none")] pub to_world_ms: Option<u32>, diff --git a/crates/horizon-world/Cargo.toml b/crates/horizon-world/Cargo.toml index 737edd289..3a8621243 100644 --- a/crates/horizon-world/Cargo.toml +++ b/crates/horizon-world/Cargo.toml @@ -13,7 +13,7 @@ serde = { version = "1", features = ["derive"] } sha2 = "0.10" postcard = { version = "=1.1.3", default-features = false, features = ["alloc"] } horizon-core = { path = "../horizon-core" } -flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] } +flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] } lz4_flex = { version = "0.14", default-features = false, features = ["std", "safe-encode", "safe-decode", "checked-decode"] } xxhash-rust = { version = "0.8.19", features = ["xxh32"] } diff --git a/crates/horizon-world/src/attributes/entity.rs b/crates/horizon-world/src/attributes/entity.rs index 1bdf94aaf..b7ffd3925 100644 --- a/crates/horizon-world/src/attributes/entity.rs +++ b/crates/horizon-world/src/attributes/entity.rs @@ -11,6 +11,11 @@ impl AttributeId { pub(super) fn index(self) -> usize { self.0 } + /// The attribute's id in the `minecraft:attribute` registry: the catalog + /// export lists `BuiltInRegistries.ATTRIBUTE` in order. + pub fn registry_id(self) -> i32 { + self.0 as i32 + } } #[derive(Debug)] pub struct RegisteredAttribute { @@ -100,6 +105,10 @@ impl Catalog { defaults, }) } + /// The entity type's supplier base of an attribute, if the type has it. + pub fn default_base(&self, entity: &str, id: AttributeId) -> Option<f64> { + self.defaults.get(entity).and_then(|b| b[id.0]) + } pub fn id(&self, name: &str) -> Option<AttributeId> { self.ids.get(name).copied() } diff --git a/crates/horizon-world/src/block_properties.rs b/crates/horizon-world/src/block_properties.rs index 2a463b9e3..98e06f7cb 100644 --- a/crates/horizon-world/src/block_properties.rs +++ b/crates/horizon-world/src/block_properties.rs @@ -2,11 +2,10 @@ //! collision shapes. Replacement with an item/fluid context is separate behavior. use crate::{ DATA_VERSION, - chunk::BlockState, collision::CachedCollisionRegistry, compression::invalid, nbt::Tag, - registry::{BlockRegistry, BlockStateId}, + registry::{BlockRegistry, BlockStateId, BlockTable}, }; use horizon_core::geometry::{Direction, ShapeError, ShapeOp, VoxelShape}; use std::{ @@ -80,15 +79,18 @@ impl BlockProperty { #[derive(Clone, Debug)] pub struct BoundBlockProperty { states: Arc<[u8]>, - property: BlockProperty, + mask: u8, } impl BoundBlockProperty { pub fn contains(&self, id: BlockStateId) -> bool { self.states .get(id.0 as usize) - .is_some_and(|flags| flags & self.property.mask() != 0) + .is_some_and(|flags| flags & self.mask != 0) } } +/// The per-state flag of the block definition's `canOcclude`, past the +/// [`BlockProperty`] bits. +const CAN_OCCLUDE: u8 = 16; /// Immutable FULL face-occlusion results, independent of support/collision. #[derive(Clone, Debug)] @@ -112,21 +114,25 @@ pub struct BlockPropertiesRegistry<'r> { } impl<'r> BlockPropertiesRegistry<'r> { pub fn from_nbt(tag: &Tag, collisions: &CachedCollisionRegistry<'r>) -> io::Result<Self> { + Self::from_table( + BlockTable::check(tag, collisions.registry(), "block property")?, + collisions, + ) + } + pub fn from_table( + table: BlockTable<'_, '_>, + collisions: &CachedCollisionRegistry<'r>, + ) -> io::Result<Self> { let registry = collisions.registry(); + if !std::ptr::eq(table.registry(), registry) { + return Err(invalid( + "block properties and collisions use other registries", + )); + } + let tag = table.tag(); if tag.get("DataVersion") != Some(&Tag::Int(DATA_VERSION)) { return Err(invalid("block properties DataVersion mismatch")); } - let Some(Tag::List(states)) = tag.get("states") else { - return Err(invalid("missing block property state identities")); - }; - if states.len() != registry.len() { - return Err(invalid("block property registry size mismatch")); - } - for (id, state) in states.iter().enumerate() { - if registry.state(BlockStateId(id as u32)) != Some(&BlockState::from_nbt(state)?) { - return Err(invalid("block property state identities differ")); - } - } let Some(Tag::Compound(blocks)) = tag.get("blocks") else { return Err(invalid("missing block definition properties")); }; @@ -150,10 +156,8 @@ impl<'r> BlockPropertiesRegistry<'r> { }, ); } - let occlusion = CachedCollisionRegistry::from_nbt( - tag.get("occlusion") - .ok_or_else(|| invalid("missing block occlusion shapes"))?, - registry, + let occlusion = CachedCollisionRegistry::from_table( + table.nested("occlusion", "block occlusion shapes")?, )?; let mut result = Vec::with_capacity(registry.len()); let mut faces = Vec::with_capacity(registry.len()); @@ -194,7 +198,12 @@ impl<'r> BlockPropertiesRegistry<'r> { .ok_or_else(|| invalid("missing block occlusion shape"))?, ) .map_err(|error| invalid(error.to_string()))?, - ) << 3), + ) << 3) + | if properties.can_occlude { + CAN_OCCLUDE + } else { + 0 + }, ); } Ok(Self { @@ -224,7 +233,14 @@ impl<'r> BlockPropertiesRegistry<'r> { pub fn bind(&self, property: BlockProperty) -> BoundBlockProperty { BoundBlockProperty { states: Arc::clone(&self.states), - property, + mask: property.mask(), + } + } + /// The states whose block definition can occlude (BlockState.canOcclude). + pub fn bind_can_occlude(&self) -> BoundBlockProperty { + BoundBlockProperty { + states: Arc::clone(&self.states), + mask: CAN_OCCLUDE, } } } diff --git a/crates/horizon-world/src/block_support.rs b/crates/horizon-world/src/block_support.rs index 2c7a9aecc..295999d18 100644 --- a/crates/horizon-world/src/block_support.rs +++ b/crates/horizon-world/src/block_support.rs @@ -61,7 +61,7 @@ use crate::{ collision::CachedCollisionRegistry, compression::invalid, nbt::Tag, - registry::{BlockRegistry, BlockStateId}, + registry::{BlockRegistry, BlockStateId, BlockTable}, }; use std::{collections::HashMap, io}; /// Cached branch of BlockState.isFaceSturdy. Dynamic support-shape selection @@ -72,10 +72,14 @@ pub struct CachedBlockSupportRegistry<'r> { } impl<'r> CachedBlockSupportRegistry<'r> { pub fn from_nbt(tag: &Tag, registry: &'r BlockRegistry) -> io::Result<Self> { - if tag.get("Kind") != Some(&Tag::String("block_support".into())) { + Self::from_table(BlockTable::check(tag, registry, "support")?) + } + pub fn from_table(table: BlockTable<'_, 'r>) -> io::Result<Self> { + if table.get("Kind") != Some(&Tag::String("block_support".into())) { return Err(invalid("wrong cached support data kind")); } - let shapes = CachedCollisionRegistry::from_nbt(tag, registry)?; + let registry = table.registry(); + let shapes = CachedCollisionRegistry::from_table(table)?; let mut cache = HashMap::new(); let mut states = Vec::with_capacity(registry.len()); for id in 0..registry.len() { @@ -163,7 +167,11 @@ impl<E: std::fmt::Display> std::fmt::Display for SupportQueryError<E> { impl<E: std::error::Error + 'static> std::error::Error for SupportQueryError<E> {} impl<'r> BlockSupportRegistry<'r> { pub fn from_nbt(tag: &Tag, registry: &'r BlockRegistry) -> io::Result<Self> { - let cached = CachedBlockSupportRegistry::from_nbt(tag, registry)?; + Self::from_table(BlockTable::check(tag, registry, "support")?) + } + pub fn from_table(table: BlockTable<'_, 'r>) -> io::Result<Self> { + let registry = table.registry(); + let cached = CachedBlockSupportRegistry::from_table(table)?; let mut dynamic = HashMap::new(); for id in 0..registry.len() { let id = BlockStateId(id as u32); diff --git a/crates/horizon-world/src/chunk.rs b/crates/horizon-world/src/chunk.rs index f4341c92f..fdbefe259 100644 --- a/crates/horizon-world/src/chunk.rs +++ b/crates/horizon-world/src/chunk.rs @@ -442,54 +442,58 @@ impl<'r> BlockSection<'r> { if index >= 4096 { return Err(invalid("section index out of bounds")); } - let id = self.storage.as_ref().map_or(0, |s| s.get(index).unwrap()); + let id = self.storage.as_ref().map_or(0, |s| s.read(index)); Ok(self.palette[id as usize]) } pub fn set(&mut self, index: usize, state: BlockStateId) -> io::Result<BlockStateId> { - let old = self.get(index)?; + if index >= 4096 { + return Err(invalid("section index out of bounds")); + } if state.0 as usize >= self.registry.len() { return Err(invalid("state ID outside registry")); } + // The slot at `index` is the old state's id, so no palette lookup is + // needed for it; only the new state has to be resolved. + let old_id = self.storage.as_ref().map_or(0, |s| s.read(index)); + let old = self.palette[old_id as usize]; if old == state { return Ok(old); } - let old_id = self.local_ids[&old]; - if self.counts[old_id as usize] == 1 && !self.local_ids.contains_key(&state) { - // Replacing the last occurrence can reuse its slot without repacking. - self.palette[old_id as usize] = state; - self.local_ids.remove(&old); - self.local_ids.insert(state, old_id); - return Ok(old); - } - let id = if let Some(id) = self.local_ids.get(&state) { - *id - } else if let Some(id) = self.free.pop() { - self.palette[id as usize] = state; - self.local_ids.insert(state, id); - id - } else { - let id = self.palette.len() as u32; - let next_bits = bits_for_palette(self.palette.len() + 1, 4); - if next_bits != self.bits() { - let mut storage = - PackedStorage::new(next_bits, 4096).map_err(|e| invalid(e.to_string()))?; - if let Some(old) = &self.storage { - for i in 0..4096 { - storage.set(i, old.get(i).unwrap()).unwrap(); - } - } - self.storage = Some(storage); + let id = match self.local_ids.get(&state) { + Some(&id) => id, + None if self.counts[old_id as usize] == 1 => { + // Replacing the last occurrence can reuse its slot without repacking. + self.palette[old_id as usize] = state; + self.local_ids.remove(&old); + self.local_ids.insert(state, old_id); + return Ok(old); + } + None => { + if let Some(id) = self.free.pop() { + self.palette[id as usize] = state; + self.local_ids.insert(state, id); + id + } else { + let id = self.palette.len() as u32; + let next_bits = bits_for_palette(self.palette.len() + 1, 4); + if next_bits != self.bits() { + let mut storage = PackedStorage::new(next_bits, 4096) + .map_err(|e| invalid(e.to_string()))?; + if let Some(old) = &self.storage { + for i in 0..4096 { + storage.write(i, old.read(i)); + } + } + self.storage = Some(storage); + } + self.palette.push(state); + self.counts.push(0); + self.local_ids.insert(state, id); + id + } } - self.palette.push(state); - self.counts.push(0); - self.local_ids.insert(state, id); - id }; - self.storage - .as_mut() - .unwrap() - .set(index, id) - .map_err(|e| invalid(e.to_string()))?; + self.storage.as_mut().unwrap().write(index, id); self.counts[old_id as usize] -= 1; self.counts[id as usize] += 1; if self.counts[old_id as usize] == 0 { @@ -585,4 +589,271 @@ mod tests { map.insert(key("data"), Tag::LongArray(vec![-1; 256])); assert!(PalettedContainer::from_nbt(&tag, 4096, 4).is_err()); } + + /// The pre-optimization `get`, kept to compare against in the benchmark. + fn baseline_get(section: &BlockSection<'_>, index: usize) -> io::Result<BlockStateId> { + if index >= 4096 { + return Err(invalid("section index out of bounds")); + } + let id = section + .storage + .as_ref() + .map_or(0, |s| s.get(index).unwrap()); + Ok(section.palette[id as usize]) + } + /// The pre-optimization `set`, kept to compare against in the benchmark. + fn baseline_set( + section: &mut BlockSection<'_>, + index: usize, + state: BlockStateId, + ) -> io::Result<BlockStateId> { + let old = baseline_get(section, index)?; + if state.0 as usize >= section.registry.len() { + return Err(invalid("state ID outside registry")); + } + if old == state { + return Ok(old); + } + let old_id = section.local_ids[&old]; + if section.counts[old_id as usize] == 1 && !section.local_ids.contains_key(&state) { + section.palette[old_id as usize] = state; + section.local_ids.remove(&old); + section.local_ids.insert(state, old_id); + return Ok(old); + } + let id = if let Some(id) = section.local_ids.get(&state) { + *id + } else if let Some(id) = section.free.pop() { + section.palette[id as usize] = state; + section.local_ids.insert(state, id); + id + } else { + let id = section.palette.len() as u32; + let next_bits = bits_for_palette(section.palette.len() + 1, 4); + if next_bits != section.bits() { + let mut storage = + PackedStorage::new(next_bits, 4096).map_err(|e| invalid(e.to_string()))?; + if let Some(old) = §ion.storage { + for i in 0..4096 { + storage.set(i, old.get(i).unwrap()).unwrap(); + } + } + section.storage = Some(storage); + } + section.palette.push(state); + section.counts.push(0); + section.local_ids.insert(state, id); + id + }; + section + .storage + .as_mut() + .unwrap() + .set(index, id) + .map_err(|e| invalid(e.to_string()))?; + section.counts[old_id as usize] -= 1; + section.counts[id as usize] += 1; + if section.counts[old_id as usize] == 0 { + section.local_ids.remove(&old); + section.free.push(old_id); + } + if section.counts[id as usize] == 4096 { + section.palette = vec![state]; + section.local_ids = local_ids(state); + section.counts = vec![4096]; + section.free.clear(); + section.storage = None; + } + Ok(old) + } + + fn benchmark_registry(states: usize) -> BlockRegistry { + let list: Vec<Tag> = (0..states) + .map(|i| { + Tag::compound([("id", Tag::String(format!("minecraft:b{i}").as_str().into()))]) + }) + .collect(); + let defaults: BTreeMap<_, _> = (0..states) + .map(|i| { + ( + JavaString::from(format!("minecraft:b{i}").as_str()), + Tag::Int(i as i32), + ) + }) + .collect(); + let tag = Tag::compound([ + ("DataVersion", Tag::Int(crate::DATA_VERSION)), + ("states", Tag::List(list)), + ("defaults", Tag::Compound(defaults)), + ]); + BlockRegistry::from_nbt(&tag).unwrap() + } + + /// The optimized `set`/`get` must agree with the pre-optimization ones on + /// every field, across growth, collapse and reclaimed palette slots. + #[test] + fn set_matches_baseline_under_random_edits() { + let registry = benchmark_registry(64); + for &(distinct, seed) in &[(1u64, 1u64), (2, 2), (16, 3), (17, 4), (24, 5), (64, 6)] { + let mut base = BlockSection::uniform(BlockStateId(0), ®istry).unwrap(); + let mut fast = BlockSection::uniform(BlockStateId(0), ®istry).unwrap(); + let mut rng = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1; + let mut next = || { + rng ^= rng << 13; + rng ^= rng >> 7; + rng ^= rng << 17; + rng + }; + for step in 0..50_000u32 { + if step % 5_000 == 4_999 { + let value = (next() % distinct) as u32; + for index in 0..4096 { + assert_eq!( + baseline_set(&mut base, index, BlockStateId(value)).unwrap(), + fast.set(index, BlockStateId(value)).unwrap() + ); + } + } else { + let index = (next() % 4096) as usize; + let value = (next() % distinct) as u32; + assert_eq!( + baseline_set(&mut base, index, BlockStateId(value)).unwrap(), + fast.set(index, BlockStateId(value)).unwrap() + ); + } + assert_eq!(base.bits(), fast.bits()); + } + assert_eq!(base.palette, fast.palette); + assert_eq!(base.counts, fast.counts); + assert_eq!(base.free, fast.free); + assert_eq!(base.local_ids, fast.local_ids); + for index in 0..4096 { + assert_eq!( + baseline_get(&base, index).unwrap(), + fast.get(index).unwrap(), + "distinct {distinct} index {index}" + ); + } + assert_eq!(base.to_nbt().unwrap(), fast.to_nbt().unwrap()); + } + } + + /// `set` and `get` against the pre-optimization implementations, on the same + /// edit stream. The result is checked before timing; 51 measured rounds + /// alternate order and report the median and best nanosecond-per-operation. + #[test] + #[ignore = "microbenchmark; run with --ignored --nocapture"] + fn benchmark_section_get_set() { + use std::{hint::black_box, time::Instant}; + const OPS: usize = 50_000; + const ROUNDS: u32 = 51; + let registry = benchmark_registry(32); + let mut rng = 0x1234_5678_9abc_def1u64; + let mut next = || { + rng ^= rng << 13; + rng ^= rng >> 7; + rng ^= rng << 17; + rng + }; + let ops: Vec<(usize, u32)> = (0..OPS) + .map(|_| ((next() % 4096) as usize, (next() % 24) as u32)) + .collect(); + let make = || BlockSection::uniform(BlockStateId(0), ®istry).unwrap(); + + let mut base = make(); + let mut fast = make(); + for &(index, value) in &ops { + assert_eq!( + baseline_set(&mut base, index, BlockStateId(value)).unwrap(), + fast.set(index, BlockStateId(value)).unwrap() + ); + } + assert_eq!(base.bits(), fast.bits()); + assert_eq!(base.palette, fast.palette); + assert_eq!(base.counts, fast.counts); + assert_eq!(base.free, fast.free); + assert_eq!(base.to_nbt().unwrap(), fast.to_nbt().unwrap()); + for i in 0..4096 { + assert_eq!(baseline_get(&base, i).unwrap(), fast.get(i).unwrap()); + } + + let mut times = [Vec::new(), Vec::new()]; + for round in 0..ROUNDS { + for optimized in [round % 2 == 0, round % 2 != 0] { + let mut section = make(); + let started = Instant::now(); + for &(index, value) in &ops { + if optimized { + section + .set(black_box(index), black_box(BlockStateId(value))) + .unwrap(); + } else { + baseline_set( + &mut section, + black_box(index), + black_box(BlockStateId(value)), + ) + .unwrap(); + } + } + black_box(§ion); + if round > 0 { + times[usize::from(optimized)] + .push(started.elapsed().as_secs_f64() * 1e9 / OPS as f64); + } + } + } + for values in &mut times { + values.sort_by(f64::total_cmp); + } + let median = |v: &[f64]| v[v.len() / 2]; + println!( + "section set median: baseline {:.3} ns/op optimized {:.3} ns/op speedup {:.3}x", + median(×[0]), + median(×[1]), + median(×[0]) / median(×[1]) + ); + println!( + "section set best: baseline {:.3} ns/op optimized {:.3} ns/op speedup {:.3}x", + times[0][0], + times[1][0], + times[0][0] / times[1][0] + ); + + let mut get_times = [Vec::new(), Vec::new()]; + for round in 0..ROUNDS { + for optimized in [round % 2 == 0, round % 2 != 0] { + let started = Instant::now(); + let mut acc = 0u32; + for &(index, _) in &ops { + let state = if optimized { + fast.get(black_box(index)).unwrap() + } else { + baseline_get(&base, black_box(index)).unwrap() + }; + acc ^= state.0; + } + black_box(acc); + if round > 0 { + get_times[usize::from(optimized)] + .push(started.elapsed().as_secs_f64() * 1e9 / OPS as f64); + } + } + } + for values in &mut get_times { + values.sort_by(f64::total_cmp); + } + println!( + "section get median: baseline {:.3} ns/op optimized {:.3} ns/op speedup {:.3}x", + median(&get_times[0]), + median(&get_times[1]), + median(&get_times[0]) / median(&get_times[1]) + ); + println!( + "section get best: baseline {:.3} ns/op optimized {:.3} ns/op speedup {:.3}x", + get_times[0][0], + get_times[1][0], + get_times[0][0] / get_times[1][0] + ); + } } diff --git a/crates/horizon-world/src/collision.rs b/crates/horizon-world/src/collision.rs index 694264a5e..3d3311646 100644 --- a/crates/horizon-world/src/collision.rs +++ b/crates/horizon-world/src/collision.rs @@ -5,10 +5,10 @@ //! This module covers the cached branch only; uncached states remain explicit. use crate::{ DATA_VERSION, - chunk::{BlockSection, BlockState}, + chunk::BlockSection, compression::invalid, nbt::Tag, - registry::{BlockRegistry, BlockStateId}, + registry::{BlockRegistry, BlockStateId, BlockTable}, }; use horizon_core::geometry::{Axis, VoxelShape}; use std::{collections::HashMap, io}; @@ -35,20 +35,13 @@ impl<'r> CachedCollisionRegistry<'r> { self.registry } pub fn from_nbt(tag: &Tag, registry: &'r BlockRegistry) -> io::Result<Self> { + Self::from_table(BlockTable::check(tag, registry, "collision")?) + } + pub fn from_table(table: BlockTable<'_, 'r>) -> io::Result<Self> { + let (tag, registry) = (table.tag(), table.registry()); if tag.get("DataVersion") != Some(&Tag::Int(DATA_VERSION)) { return Err(invalid("collision DataVersion mismatch")); } - let Some(Tag::List(states)) = tag.get("states") else { - return Err(invalid("missing collision state identities")); - }; - if states.len() != registry.len() { - return Err(invalid("collision registry size mismatch")); - } - for (id, state) in states.iter().enumerate() { - if registry.state(BlockStateId(id as u32)) != Some(&BlockState::from_nbt(state)?) { - return Err(invalid("collision state identities differ")); - } - } let Some(Tag::List(entries)) = tag.get("shapes") else { return Err(invalid("missing collision shapes")); }; diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs index 280f21582..e0ef0dca1 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -8,8 +8,7 @@ use crate::{ collision::CachedCollisionRegistry, compression::invalid, fluid::{FluidBlockBindings, FluidKind, FluidState}, - nbt::{self, Limits}, - registry::{BlockRegistry, BlockStateId}, + registry::{BlockRegistry, BlockStateId, BlockTableFile}, worldgen::tags::TagDefinitions, }; use horizon_core::geometry::{Aabb, Direction, ShapeOp, Vec3, VoxelShape}; @@ -614,45 +613,9 @@ fn set_type(value: &Value, cache: &mut HashMap<String, Arc<str>>) -> Option<SetT } /// Build the block-state registry from the resources' `facts.json` (the -/// same source the native client uses). +/// same source the native client uses), streamed. pub fn load_registry(root: &Path) -> io::Result<BlockRegistry> { - use crate::{DATA_VERSION, nbt::Tag}; - fn tag(value: &Value) -> io::Result<Tag> { - Ok(match value { - Value::String(value) => Tag::String(value.as_str().into()), - Value::Number(value) => Tag::Int( - value - .as_i64() - .and_then(|v| i32::try_from(v).ok()) - .ok_or_else(|| fail("invalid registry number"))?, - ), - Value::Array(values) => Tag::List(values.iter().map(tag).collect::<io::Result<_>>()?), - Value::Object(values) => Tag::Compound( - values - .iter() - .map(|(name, value)| Ok((name.as_str().into(), tag(value)?))) - .collect::<io::Result<_>>()?, - ), - _ => return Err(fail("unsupported registry value")), - }) - } - let facts = read_json(&root.join("facts.json"))?; - let states = facts["states"] - .as_array() - .ok_or_else(|| fail("missing registry state facts"))?; - BlockRegistry::from_nbt(&Tag::compound([ - ("DataVersion", Tag::Int(DATA_VERSION)), - ( - "states", - Tag::List( - states - .iter() - .map(|state| tag(&state[4])) - .collect::<io::Result<_>>()?, - ), - ), - ("defaults", tag(&facts["defaults"])?), - ])) + BlockRegistry::from_facts_json(File::open(root.join("facts.json"))?) } pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result<Behaviours> { @@ -787,14 +750,8 @@ fn build_with_gameplay<G: GameplayStateSource>( }; // Collision shapes. - let collision_tag = nbt::read_named( - &fs::read(root.join("cached-collision.nbt"))?, - Limits::tables(), - ) - .map_err(|e| invalid(e.to_string()))? - .0 - .tag; - let cached = CachedCollisionRegistry::from_nbt(&collision_tag, registry)?; + let collision_file = BlockTableFile::open(&root.join("cached-collision.nbt"), registry)?; + let cached = CachedCollisionRegistry::from_table(collision_file.table("collision")?)?; let mut shapes: Vec<VoxelShape> = Vec::new(); let mut shape_ids = Vec::with_capacity(table.state_count()); for id in 0..table.state_count() { diff --git a/crates/horizon-world/src/movement_properties.rs b/crates/horizon-world/src/movement_properties.rs index 84cafae1e..9e1dc6236 100644 --- a/crates/horizon-world/src/movement_properties.rs +++ b/crates/horizon-world/src/movement_properties.rs @@ -1,11 +1,10 @@ //! Registry-bound block movement coefficients, identities and reloadable tags. use crate::{ DATA_VERSION, - chunk::BlockState, compression::invalid, movement_support::MovementBlockWorld, nbt::Tag, - registry::{BlockRegistry, BlockStateId}, + registry::{BlockRegistry, BlockStateId, BlockTable}, }; use horizon_core::position::BlockPos; use std::{ @@ -55,20 +54,13 @@ impl<'r> MovementProperties<'r> { } pub fn from_nbt(tag: &Tag, registry: &'r BlockRegistry) -> io::Result<Self> { + Self::from_table(BlockTable::check(tag, registry, "movement")?) + } + pub fn from_table(table: BlockTable<'_, 'r>) -> io::Result<Self> { + let (tag, registry) = (table.tag(), table.registry()); if tag.get("DataVersion") != Some(&Tag::Int(DATA_VERSION)) { return Err(invalid("movement properties DataVersion mismatch")); } - let Some(Tag::List(states)) = tag.get("states") else { - return Err(invalid("missing movement state identities")); - }; - if states.len() != registry.len() { - return Err(invalid("movement registry size mismatch")); - } - for (id, state) in states.iter().enumerate() { - if registry.state(BlockStateId(id as u32)) != Some(&BlockState::from_nbt(state)?) { - return Err(invalid("movement state identities differ")); - } - } let Some(Tag::Compound(blocks)) = tag.get("blocks") else { return Err(invalid("missing movement definitions")); }; diff --git a/crates/horizon-world/src/nbt.rs b/crates/horizon-world/src/nbt.rs index 414767795..a8bed543a 100644 --- a/crates/horizon-world/src/nbt.rs +++ b/crates/horizon-world/src/nbt.rs @@ -110,6 +110,19 @@ impl Limits { max_depth: 512, } } + + /// Structure templates (`structure/*.nbt`): vanilla reads them with + /// `NbtAccounter.unlimitedHeap()` (TemplateSource.readStructure), and + /// mods ship templates past the default node cap (YUNG's Better Ocean + /// Monuments' start piece, 115x64x126 blocks, holds millions of tags). + /// The byte cap stays as the only guard on the decompressed file. + pub fn templates() -> Self { + Self { + max_bytes: 1 << 28, + max_nodes: usize::MAX, + max_depth: 512, + } + } } #[derive(Clone, Debug, PartialEq, Eq)] @@ -124,13 +137,20 @@ impl std::fmt::Display for Error { } impl std::error::Error for Error {} -struct Reader<'a> { +/// Hands a streamed list's elements to the caller one at a time (see +/// [`read_named_streaming`]). +type Visit<'s> = &'s mut dyn FnMut(&mut ListElements<'_, '_, '_>) -> Result<(), Error>; + +struct Reader<'a, 's> { bytes: &'a [u8], offset: usize, limits: Limits, nodes: usize, + /// Lists with this key in the root compound or in a compound directly + /// under it are streamed to the visitor instead of kept. + stream: Option<(&'s str, Visit<'s>)>, } -impl<'a> Reader<'a> { +impl<'a> Reader<'a, '_> { fn error(&self, reason: &'static str) -> Error { Error { offset: self.offset, @@ -266,7 +286,11 @@ impl<'a> Reader<'a> { break; } let name = self.string()?; - let value = self.payload(id, depth + 1)?; + let value = if id == 9 && depth <= 1 && self.streams(&name) { + self.stream_list(depth + 1)? + } else { + self.payload(id, depth + 1)? + }; map.insert(name, value); // Java maps retain the last duplicate key. } Tag::Compound(map) @@ -290,6 +314,82 @@ impl<'a> Reader<'a> { _ => return Err(self.error("unknown tag type")), }) } + fn streams(&self, name: &JavaString) -> bool { + self.stream + .as_ref() + .is_some_and(|(key, _)| name.0.iter().copied().eq(key.encode_utf16())) + } + /// A list's payload handed to the visitor element by element; the tree + /// keeps it empty. Elements the visitor leaves are read and dropped. + fn stream_list(&mut self, depth: usize) -> Result<Tag, Error> { + if self.nodes >= self.limits.max_nodes { + return Err(self.error("node limit exceeded")); + } + self.nodes += 1; + if depth >= self.limits.max_depth { + return Err(self.error("depth limit exceeded")); + } + let element_id = self.byte()?; + let len = self.count(0)?; + if len > 0 && (element_id == 0 || element_id > 12) { + return Err(self.error("invalid list element type")); + } + if len > self.bytes.len().saturating_sub(self.offset) { + return Err(self.error("truncated list")); + } + let (key, visit) = self.stream.take().expect("streams() checked the visitor"); + let mut elements = ListElements { + reader: self, + element_id, + depth: depth + 1, + len, + left: len, + }; + let rest = visit(&mut elements).and_then(|()| { + while elements.next_element()?.is_some() {} + Ok(()) + }); + self.stream = Some((key, visit)); + rest.map(|()| Tag::List(Vec::new())) + } +} + +/// The elements of a list [`read_named_streaming`] streams, read one at a +/// time. +pub struct ListElements<'r, 'a, 's> { + reader: &'r mut Reader<'a, 's>, + element_id: u8, + depth: usize, + len: usize, + left: usize, +} +impl ListElements<'_, '_, '_> { + /// The list's length, as its header gives it. + pub fn len(&self) -> usize { + self.len + } + pub fn is_empty(&self) -> bool { + self.len == 0 + } + /// The next element, unwrapped as [`read_named`] unwraps mixed-list + /// elements; `None` past the last. + pub fn next_element(&mut self) -> Result<Option<Tag>, Error> { + if self.left == 0 { + return Ok(None); + } + self.left -= 1; + let mut value = self.reader.payload(self.element_id, self.depth)?; + if let Tag::Compound(map) = &mut value { + if map.len() == 1 && map.contains_key(&JavaString::default()) { + value = map.remove(&JavaString::default()).unwrap(); + } + } + Ok(Some(value)) + } + /// An error at the current position in the input. + pub fn error(&self, reason: &'static str) -> Error { + self.reader.error(reason) + } } /// Read a file root (type, modified-UTF name, payload), returning bytes consumed. @@ -299,6 +399,35 @@ pub fn read_named(bytes: &[u8], limits: Limits) -> Result<(NamedTag, usize), Err offset: 0, limits, nodes: 0, + stream: None, + }; + let id = reader.byte()?; + let name = if id == 0 { + JavaString::default() + } else { + reader.string()? + }; + let tag = reader.payload(id, 0)?; + Ok((NamedTag { name, tag }, reader.offset)) +} + +/// [`read_named`], except that lists keyed `key` in the root compound or in +/// a compound directly under it are not kept: `visit` reads each one's +/// elements as they come, and the tree holds it as an empty list. Per-state +/// tables check hundreds of thousands of state identities this way without +/// holding them as a tree (crate::registry::BlockTableFile). +pub fn read_named_streaming( + bytes: &[u8], + limits: Limits, + key: &str, + visit: &mut dyn FnMut(&mut ListElements<'_, '_, '_>) -> Result<(), Error>, +) -> Result<(NamedTag, usize), Error> { + let mut reader = Reader { + bytes, + offset: 0, + limits, + nodes: 0, + stream: Some((key, visit)), }; let id = reader.byte()?; let name = if id == 0 { @@ -317,6 +446,7 @@ pub fn read_network(bytes: &[u8], limits: Limits) -> Result<(Tag, usize), Error> offset: 0, limits, nodes: 0, + stream: None, }; let id = reader.byte()?; let tag = reader.payload(id, 0)?; @@ -659,6 +789,50 @@ impl Snbt<'_> { mod tests { use super::*; #[test] + fn streamed_lists_reach_the_visitor_and_stay_empty_in_the_tree() { + let list = |n: i32| Tag::List((0..n).map(Tag::Int).collect()); + let root = NamedTag { + name: "".into(), + tag: Tag::compound([ + ("states", list(3)), + ("inner", Tag::compound([("states", list(2))])), + ( + "deep", + Tag::compound([("inner", Tag::compound([("states", list(1))]))]), + ), + ("other", list(4)), + ]), + }; + let bytes = write_named(&root, Limits::default()).unwrap(); + let mut seen = Vec::new(); + let (read, used) = read_named_streaming(&bytes, Limits::default(), "states", &mut |l| { + let mut values = vec![l.len() as i32]; + // Elements left unread are skipped. + if let Some(Tag::Int(v)) = l.next_element()? { + values.push(v); + } + seen.push(values); + Ok(()) + }) + .unwrap(); + assert_eq!(used, bytes.len()); + // Compounds are written in key order: `inner` before `states`. + assert_eq!(seen, [vec![2, 0], vec![3, 0]]); + assert_eq!(read.tag.get("states"), Some(&Tag::List(Vec::new()))); + assert_eq!( + read.tag.get("inner").unwrap().get("states"), + Some(&Tag::List(Vec::new())) + ); + // Only the root and its direct children stream. + assert_eq!(read.tag.get("deep"), root.tag.get("deep")); + assert_eq!(read.tag.get("other"), root.tag.get("other")); + // A visitor's error stops the read. + let failed = read_named_streaming(&bytes, Limits::default(), "states", &mut |l| { + Err(l.error("refused")) + }); + assert_eq!(failed.unwrap_err().reason, "refused"); + } + #[test] fn wire_node_budget_includes_mixed_list_wrappers() { let tag = Tag::List(vec![Tag::Int(1), Tag::Byte(2)]); let limits = Limits { @@ -675,6 +849,18 @@ mod tests { assert!(read_network(&bytes, limits).is_err()); } #[test] + fn templates_read_past_the_default_node_cap() { + // A big mod template (YUNG's monument start) holds more tags than the + // default cap; vanilla reads templates with an unlimited accounter. + let root = NamedTag { + name: JavaString::default(), + tag: Tag::compound([("blocks", Tag::List(vec![Tag::Byte(1); 1_000_001]))]), + }; + let bytes = write_named(&root, Limits::templates()).unwrap(); + assert!(read_named(&bytes, Limits::default()).is_err()); + assert_eq!(read_named(&bytes, Limits::templates()).unwrap().0, root); + } + #[test] fn depth_boundary_and_every_truncated_prefix() { let mut tag = Tag::Int(1); for _ in 0..512 { diff --git a/crates/horizon-world/src/region.rs b/crates/horizon-world/src/region.rs index 05bdc1a54..1e4ba176c 100644 --- a/crates/horizon-world/src/region.rs +++ b/crates/horizon-world/src/region.rs @@ -1,5 +1,7 @@ -//! Anvil region reading and export to a new region. Existing files are never -//! overwritten. Use a separate directory for offline edits and copied .mcc data. +//! Anvil region reading, export to a new region, and in-place chunk writes +//! as vanilla's `RegionFile` makes them (a file opened with `open_writable`). +//! Exports never overwrite a file: use a separate directory for offline +//! edits and copied .mcc data. use crate::{ compression::{Compression, invalid}, nbt::{self, Limits, NamedTag}, @@ -54,6 +56,9 @@ pub struct RegionFile { position: ChunkPos, offsets: [u32; 1024], timestamps: [u32; 1024], + /// The sectors in use (`RegionBitmap`): the header's two and every + /// chunk's. + used: Vec<bool>, } pub fn position_from_path(path: &Path) -> io::Result<ChunkPos> { @@ -94,6 +99,12 @@ fn position(region: ChunkPos, index: usize) -> ChunkPos { fn external_path(directory: &Path, chunk: ChunkPos) -> PathBuf { directory.join(format!("c.{}.{}.mcc", chunk.x, chunk.z)) } +fn remove_if_exists(path: &Path) -> io::Result<()> { + match fs::remove_file(path) { + Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e), + _ => Ok(()), + } +} impl RegionFile { pub fn position(&self) -> ChunkPos { @@ -101,8 +112,25 @@ impl RegionFile { } pub fn open(path: impl AsRef<Path>) -> io::Result<Self> { let path = path.as_ref().to_owned(); + let file = File::open(&path)?; + Self::from_file(path, file) + } + + /// Open for reading and in-place writes (`write`, `clear`), creating an + /// empty region with `create`. + pub fn open_writable(path: impl AsRef<Path>, create: bool) -> io::Result<Self> { + let path = path.as_ref().to_owned(); + let file = OpenOptions::new() + .read(true) + .write(true) + .create(create) + .truncate(false) + .open(&path)?; + Self::from_file(path, file) + } + + fn from_file(path: PathBuf, mut file: File) -> io::Result<Self> { let position = position_from_path(&path)?; - let mut file = File::open(&path)?; let len = file.metadata()?.len(); // RegionFile's constructor: a short header (an empty or truncated file) // reads as far as it goes, the rest stays zero (no chunks). @@ -134,13 +162,140 @@ impl RegionFile { offsets[i] = 0; } } - Ok(Self { + let mut region = Self { file, path, position, offsets, timestamps, - }) + used: Vec::new(), + }; + region.force(0, 2); + for offset in offsets.into_iter().filter(|&o| o != 0) { + region.force((offset >> 8) as usize, (offset & 255) as usize); + } + Ok(region) + } + + /// `RegionBitmap.force`. + fn force(&mut self, start: usize, count: usize) { + if self.used.len() < start + count { + self.used.resize(start + count, false); + } + self.used[start..start + count].fill(true); + } + /// `RegionBitmap.free`. + fn free(&mut self, start: usize, count: usize) { + let end = (start + count).min(self.used.len()); + if start < end { + self.used[start..end].fill(false); + } + } + /// `RegionBitmap.allocate`: the first run of free sectors long enough + /// (the end of the file is free). + fn allocate(&mut self, count: usize) -> usize { + let mut current = 0; + loop { + let start = (current..self.used.len()) + .find(|&s| !self.used[s]) + .unwrap_or(self.used.len()); + let end = (start..self.used.len()).find(|&s| self.used[s]); + if end.is_none_or(|end| end - start >= count) { + self.force(start, count); + return start; + } + current = end.unwrap_or(start); + } + } + + /// `RegionFile.write`: the chunk goes to the first free run of sectors + /// that holds it (an oversized one, 256 sectors or more, to its external + /// `c.X.Z.mcc` file with a one-sector stub), the header points to it, + /// and only then are its old sectors freed. The other chunks stay where + /// they are. A chunk's last sector is padded with zeros. + pub fn write(&mut self, chunk: ChunkPos, record: &ChunkRecord) -> io::Result<()> { + let i = slot(self.position, chunk)?; + if record.compressed.len() > MAX_COMPRESSED { + return Err(invalid("compressed chunk limit exceeded")); + } + let required = (record.compressed.len() + 5).div_ceil(SECTOR); + let external = required >= 256; + let sectors = if external { 1 } else { required }; + let start = self.allocate(sectors); + if start + sectors > 0x100_0000 { + self.free(start, sectors); + return Err(invalid("region sector address limit exceeded")); + } + let directory = self.path.parent().unwrap_or(Path::new(".")).to_owned(); + let external_file = external_path(&directory, chunk); + let mut data = Vec::with_capacity(sectors * SECTOR); + if external { + let temporary = directory.join(format!(".c.{}.{}.mcc.tmp", chunk.x, chunk.z)); + let written = File::create(&temporary) + .and_then(|mut f| f.write_all(&record.compressed)) + .and_then(|_| fs::rename(&temporary, &external_file)); + if let Err(e) = written { + let _ = fs::remove_file(&temporary); + self.free(start, sectors); + return Err(e); + } + data.extend_from_slice(&1u32.to_be_bytes()); + data.push(record.compression as u8 | 128); + } else { + data.extend_from_slice(&(record.compressed.len() as u32 + 1).to_be_bytes()); + data.push(record.compression as u8); + data.extend_from_slice(&record.compressed); + } + data.resize(sectors * SECTOR, 0); + let written = self + .file + .seek(SeekFrom::Start((start * SECTOR) as u64)) + .and_then(|_| self.file.write_all(&data)); + if let Err(e) = written { + self.free(start, sectors); + return Err(e); + } + let old = self.offsets[i]; + self.offsets[i] = (start as u32) << 8 | sectors as u32; + self.timestamps[i] = record.timestamp; + self.write_header_entry(i)?; + if !external { + remove_if_exists(&external_file)?; + } + if old != 0 { + self.free((old >> 8) as usize, (old & 255) as usize); + } + Ok(()) + } + + /// `RegionFile.clear`: the chunk is gone; `timestamp` marks when. + /// Returns whether the region held it. + pub fn clear(&mut self, chunk: ChunkPos, timestamp: u32) -> io::Result<bool> { + let i = slot(self.position, chunk)?; + let old = self.offsets[i]; + if old == 0 { + return Ok(false); + } + self.offsets[i] = 0; + self.timestamps[i] = timestamp; + self.write_header_entry(i)?; + let directory = self.path.parent().unwrap_or(Path::new(".")); + remove_if_exists(&external_path(directory, chunk))?; + self.free((old >> 8) as usize, (old & 255) as usize); + Ok(true) + } + + /// Flush the writes to the disk. + pub fn sync(&self) -> io::Result<()> { + self.file.sync_data() + } + + /// The header's offset and timestamp of slot `i`. + fn write_header_entry(&mut self, i: usize) -> io::Result<()> { + self.file.seek(SeekFrom::Start((i * 4) as u64))?; + self.file.write_all(&self.offsets[i].to_be_bytes())?; + self.file.seek(SeekFrom::Start((SECTOR + i * 4) as u64))?; + self.file.write_all(&self.timestamps[i].to_be_bytes()) } pub fn chunks(&self) -> impl Iterator<Item = (ChunkPos, u32)> + '_ { diff --git a/crates/horizon-world/src/registry.rs b/crates/horizon-world/src/registry.rs index 5ca2e994a..9ce9a6814 100644 --- a/crates/horizon-world/src/registry.rs +++ b/crates/horizon-world/src/registry.rs @@ -1,5 +1,6 @@ //! Runtime block-state IDs imported from a version-pinned registry data export. //! This supplies identities and default properties, not block behavior. +mod facts; mod json; use crate::{DATA_VERSION, chunk::BlockState, compression::invalid, nbt::Tag}; pub use json::BlockStateJsonCodec; @@ -45,17 +46,53 @@ impl BlockRegistry { let Some(Tag::Compound(defaults)) = tag.get("defaults") else { return Err(invalid("missing registry defaults")); }; - if entries.is_empty() || entries.len() > i32::MAX as usize { + let states = entries + .iter() + .map(BlockState::from_nbt) + .collect::<io::Result<_>>()?; + let defaults = defaults + .iter() + .map(|(name, id)| { + let name = name.to_string().map_err(|e| invalid(e.to_string()))?; + let Tag::Int(id) = id else { + return Err(invalid("default state ID is not an int")); + }; + Ok((name, i64::from(*id))) + }) + .collect::<io::Result<_>>()?; + Self::from_states(states, defaults) + } + + /// The registry of a resources `facts.json` (`{"states": [[..., ..., ..., + /// ..., state], ...], "defaults": {name: id}}`), read as it streams: no + /// JSON or NBT tree of the whole file is built. For a pack of 190,000 + /// states the two trees were several hundred megabytes at startup. + pub fn from_facts_json(reader: impl io::Read) -> io::Result<Self> { + Ok(Self::from_facts_json_with_flags(reader)?.0) + } + + /// [`Self::from_facts_json`], with each state's `(air, fluid)` columns. + pub fn from_facts_json_with_flags( + reader: impl io::Read, + ) -> io::Result<(Self, Vec<(bool, bool)>)> { + let facts: facts::Facts = serde_json::from_reader(io::BufReader::new(reader)) + .map_err(|e| invalid(e.to_string()))?; + let flags = facts.states.iter().map(|r| (r.air, r.fluid)).collect(); + let states = facts.states.into_iter().map(|r| r.state).collect(); + Ok((Self::from_states(states, facts.defaults)?, flags)) + } + + fn from_states(states: Vec<BlockState>, defaults: BTreeMap<String, i64>) -> io::Result<Self> { + if states.is_empty() || states.len() > i32::MAX as usize { return Err(invalid("invalid registry size")); } let mut result = Self { - states: Vec::with_capacity(entries.len()), - ids: HashMap::with_capacity(entries.len()), + states: Vec::with_capacity(states.len()), + ids: HashMap::with_capacity(states.len()), collided: BTreeMap::new(), defaults: BTreeMap::new(), }; - for (i, entry) in entries.iter().enumerate() { - let state = BlockState::from_nbt(entry)?; + for (i, state) in states.into_iter().enumerate() { if result.id(&state).is_some() { return Err(invalid("duplicate block registry state")); } @@ -72,19 +109,16 @@ impl BlockRegistry { result.states.push(state); } for (name, id) in defaults { - let name = name.to_string().map_err(|e| invalid(e.to_string()))?; - let Tag::Int(id) = id else { - return Err(invalid("default state ID is not an int")); - }; - if *id < 0 + if id < 0 + || id > i64::from(i32::MAX) || result .states - .get(*id as usize) + .get(id as usize) .is_none_or(|s| s.name != name) { return Err(invalid("invalid default block state ID")); } - result.defaults.insert(name, BlockStateId(*id as u32)); + result.defaults.insert(name, BlockStateId(id as u32)); } let names: BTreeSet<_> = result.states.iter().map(|s| &s.name).collect(); if names.len() != result.defaults.len() @@ -132,3 +166,120 @@ impl BlockRegistry { .ok_or_else(|| invalid("invalid block property value")) } } + +/// A per-state table (`occlusion.nbt`, `cached-collision.nbt`, ...) whose +/// `states` list, the identity of every state it describes in id order, has +/// been checked against `registry`. +#[derive(Clone, Copy)] +pub struct BlockTable<'t, 'r> { + tag: &'t Tag, + registry: &'r BlockRegistry, + /// How many levels, from this one down, [`BlockTableFile::read`] checked + /// while reading: their `states` lists are kept empty in the tree. + read_checked: u8, +} +impl<'t, 'r> BlockTable<'t, 'r> { + /// Checks that `tag`'s `states` names the registry's states in id order. + pub fn check(tag: &'t Tag, registry: &'r BlockRegistry, what: &str) -> io::Result<Self> { + Self { + tag, + registry, + read_checked: 0, + } + .checked(what) + } + fn checked(self, what: &str) -> io::Result<Self> { + let Some(Tag::List(states)) = self.tag.get("states") else { + return Err(invalid(format!("missing {what} state identities"))); + }; + if self.read_checked == 0 { + if states.len() != self.registry.len() { + return Err(invalid(format!("{what} registry size mismatch"))); + } + for (id, state) in states.iter().enumerate() { + if self.registry.state(BlockStateId(id as u32)) + != Some(&BlockState::from_nbt(state)?) + { + return Err(invalid(format!("{what} state identities differ"))); + } + } + } + Ok(self) + } + /// The table nested under `key` (`block-properties.nbt`'s `occlusion`), + /// with its own `states`, checked the same way. + pub fn nested(&self, key: &str, what: &str) -> io::Result<Self> { + Self { + tag: self + .tag + .get(key) + .ok_or_else(|| invalid(format!("missing {what}")))?, + registry: self.registry, + read_checked: self.read_checked.saturating_sub(1), + } + .checked(what) + } + pub fn tag(&self) -> &'t Tag { + self.tag + } + pub fn get(&self, key: &str) -> Option<&'t Tag> { + self.tag.get(key) + } + pub fn registry(&self) -> &'r BlockRegistry { + self.registry + } +} + +/// A per-state table read from its file with its state identities checked +/// while reading, so they never exist as a tree: for 190,000 states (a big +/// modpack) that tree took 300-600 MB per table. +pub struct BlockTableFile<'r> { + tag: Tag, + registry: &'r BlockRegistry, +} +impl<'r> BlockTableFile<'r> { + /// [`Self::read`] of the file at `path`. + pub fn open(path: &std::path::Path, registry: &'r BlockRegistry) -> io::Result<Self> { + let bytes = std::fs::read(path)?; + Self::read(&bytes, registry).map_err(|e| invalid(format!("{}: {e}", path.display()))) + } + /// Reads `bytes`, checking every `states` list of the root compound and + /// of the compounds directly under it against `registry`. + pub fn read(bytes: &[u8], registry: &'r BlockRegistry) -> io::Result<Self> { + let mut visit = |states: &mut crate::nbt::ListElements<'_, '_, '_>| { + if states.len() != registry.len() { + return Err(states.error("table registry size mismatch")); + } + let mut id = 0u32; + while let Some(tag) = states.next_element()? { + let state = + BlockState::from_nbt(&tag).map_err(|_| states.error("invalid table state"))?; + if registry.state(BlockStateId(id)) != Some(&state) { + return Err(states.error("table state identities differ")); + } + id += 1; + } + Ok(()) + }; + let (named, _) = crate::nbt::read_named_streaming( + bytes, + crate::nbt::Limits::tables(), + "states", + &mut visit, + ) + .map_err(|e| invalid(e.to_string()))?; + Ok(Self { + tag: named.tag, + registry, + }) + } + /// The table, checked (`what` names it in errors). + pub fn table(&self, what: &str) -> io::Result<BlockTable<'_, 'r>> { + BlockTable { + tag: &self.tag, + registry: self.registry, + read_checked: 2, + } + .checked(what) + } +} diff --git a/crates/horizon-world/src/registry/facts.rs b/crates/horizon-world/src/registry/facts.rs new file mode 100644 index 000000000..3371a8283 --- /dev/null +++ b/crates/horizon-world/src/registry/facts.rs @@ -0,0 +1,164 @@ +//! The part of `facts.json` the block registry reads, deserialized as it +//! streams: each row's state (its fifth column) and the defaults. +use crate::chunk::BlockState; +use serde::{ + Deserialize, Deserializer, + de::{self, IgnoredAny, SeqAccess, Visitor}, +}; +use std::{collections::BTreeMap, fmt}; + +#[derive(Deserialize)] +pub(super) struct Facts { + pub states: Vec<Row>, + pub defaults: BTreeMap<String, i64>, +} + +/// One `states` row: `[name, air, fluid, description, state, ...]`, keeping +/// the two flags and the state. +pub(super) struct Row { + pub air: bool, + pub fluid: bool, + pub state: BlockState, +} + +impl<'de> Deserialize<'de> for Row { + fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + struct RowVisitor; + impl<'de> Visitor<'de> for RowVisitor { + type Value = Row; + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a registry state row") + } + fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Row, A::Error> { + let length = |i| de::Error::invalid_length(i, &self); + seq.next_element::<IgnoredAny>()?.ok_or_else(|| length(0))?; + let air = seq.next_element::<bool>()?.ok_or_else(|| length(1))?; + let fluid = seq.next_element::<bool>()?.ok_or_else(|| length(2))?; + seq.next_element::<IgnoredAny>()?.ok_or_else(|| length(3))?; + let state = seq.next_element::<State>()?.ok_or_else(|| length(4))?; + while seq.next_element::<IgnoredAny>()?.is_some() {} + Ok(Row { + air, + fluid, + state: state.0, + }) + } + } + deserializer.deserialize_seq(RowVisitor) + } +} + +/// A state as BlockState::from_nbt reads it: a name, or `{"id", "properties"}`. +struct State(BlockState); + +impl<'de> Deserialize<'de> for State { + fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + #[derive(Deserialize)] + #[serde(untagged)] + enum Shape { + Name(String), + Full { + id: String, + #[serde(default)] + properties: BTreeMap<String, String>, + }, + } + Ok(State(match Shape::deserialize(deserializer)? { + Shape::Name(name) => BlockState { + name, + properties: BTreeMap::new(), + }, + Shape::Full { id, properties } => BlockState { + name: id, + properties, + }, + })) + } +} + +#[cfg(test)] +mod tests { + use crate::{ + DATA_VERSION, + chunk::BlockState, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, + }; + use serde_json::Value; + use std::path::Path; + + #[test] + fn reads_states_and_defaults() { + let json = br#"{"defaults": {"minecraft:air": 0, "minecraft:oak_slab": 2}, + "states": [ + ["minecraft:air", true, false, "Block{minecraft:air}", "minecraft:air"], + ["minecraft:oak_slab", false, false, "x", {"id": "minecraft:oak_slab", "properties": {"type": "top"}}, "extra"], + ["minecraft:oak_slab", false, true, "x", {"id": "minecraft:oak_slab", "properties": {"type": "bottom"}}] + ], "other": [1, 2]}"#; + let (registry, flags) = BlockRegistry::from_facts_json_with_flags(&json[..]).unwrap(); + assert_eq!(registry.len(), 3); + assert_eq!(flags, [(true, false), (false, false), (false, true)]); + assert_eq!( + registry.default_state("minecraft:oak_slab"), + Some(BlockStateId(2)) + ); + let top = BlockState { + name: "minecraft:oak_slab".into(), + properties: [("type".into(), "top".into())].into(), + }; + assert_eq!(registry.id(&top), Some(BlockStateId(1))); + // A default naming another block, a short row, a missing default. + for bad in [ + &br#"{"defaults": {"minecraft:air": 1}, "states": [["minecraft:air", true, false, "", "minecraft:air"], ["minecraft:stone", false, false, "", "minecraft:stone"]]}"#[..], + br#"{"defaults": {"minecraft:air": 0}, "states": [["minecraft:air", true, false, ""]]}"#, + br#"{"defaults": {}, "states": [["minecraft:air", true, false, "", "minecraft:air"]]}"#, + ] { + assert!(BlockRegistry::from_facts_json(bad).is_err()); + } + } + + /// The streamed registry is the one the JSON and NBT trees built. + #[test] + fn matches_the_tree_built_registry() { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client/26.3/facts.json"); + let Ok(bytes) = std::fs::read(&path) else { + eprintln!("skipped: no prepared facts.json"); + return; + }; + fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), + Value::Object(o) => { + Tag::Compound(o.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + _ => unreachable!(), + } + } + let facts: Value = serde_json::from_slice(&bytes).unwrap(); + let rows = facts["states"].as_array().unwrap(); + let tree = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ( + "states", + Tag::List(rows.iter().map(|r| tag(&r[4])).collect()), + ), + ("defaults", tag(&facts["defaults"])), + ])) + .unwrap(); + let (streamed, flags) = BlockRegistry::from_facts_json_with_flags(&bytes[..]).unwrap(); + assert_eq!(streamed.len(), tree.len()); + for (i, row) in rows.iter().enumerate() { + let id = BlockStateId(i as u32); + assert_eq!(streamed.state(id), tree.state(id)); + assert_eq!( + flags[i], + (row[1].as_bool().unwrap(), row[2].as_bool().unwrap()) + ); + } + for name in facts["defaults"].as_object().unwrap().keys() { + assert_eq!(streamed.default_state(name), tree.default_state(name)); + } + } +} diff --git a/crates/horizon-world/src/worldgen/block_feature.rs b/crates/horizon-world/src/worldgen/block_feature.rs index a901a583d..00f0c64c1 100644 --- a/crates/horizon-world/src/worldgen/block_feature.rs +++ b/crates/horizon-world/src/worldgen/block_feature.rs @@ -23,6 +23,7 @@ pub struct FeatureBlockBindings<'r> { )>, physical_properties: Option<[BoundBlockProperty; 4]>, pub(crate) occlusion_faces: Option<crate::block_properties::BoundOcclusionFaces>, + pub(crate) can_occlude: Option<BoundBlockProperty>, biomes: Option<Arc<super::biome_predicate::BiomePredicateBindings>>, pub(crate) fluids: super::fluid_predicate::FluidPredicateBindings, pub(crate) codec: BlockStateJsonCodec<'r>, @@ -88,6 +89,7 @@ impl<'r> FeatureBlockBindings<'r> { properties.bind(BlockProperty::SolidRender), ]); self.occlusion_faces = Some(properties.bind_occlusion_faces()); + self.can_occlude = Some(properties.bind_can_occlude()); Ok(self) } pub fn with_biomes( @@ -156,6 +158,7 @@ impl<'r> FeatureBlockBindings<'r> { biomes: None, physical_properties: None, occlusion_faces: None, + can_occlude: None, fluids: super::fluid_predicate::FluidPredicateBindings::new(registry)?, blocks: blocks .into_iter() diff --git a/crates/horizon-world/src/worldgen/decoration_order.rs b/crates/horizon-world/src/worldgen/decoration_order.rs index 52649ceed..6b0fb2252 100644 --- a/crates/horizon-world/src/worldgen/decoration_order.rs +++ b/crates/horizon-world/src/worldgen/decoration_order.rs @@ -121,7 +121,7 @@ fn ticket_hash(x: i32, z: i32) -> u64 { /// The chunks decorated around a player at `center`, in vanilla's order. pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { use std::cmp::Reverse; - use std::collections::{BinaryHeap, HashSet, VecDeque}; + use std::collections::{BinaryHeap, VecDeque}; let mut tickets: Vec<(i32, i32)> = (-radius..=radius) .flat_map(|dx| (-radius..=radius).map(move |dz| (center.0 + dx, center.1 + dz))) .collect(); @@ -133,35 +133,45 @@ pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { ) }); let mut tickets: VecDeque<_> = tickets.into(); + // Every chunk this touches lies within `half` of the centre: tickets + // reach `LIGHT_LEVEL - TICKET_LEVEL` further, and FULL tasks decorate + // one more ring. Dense grids over that square replace hash maps. + let reach = LIGHT_LEVEL - TICKET_LEVEL; + let half = radius.max(0) + reach + 1; + let side = (2 * half + 1) as usize; + let cell = |(x, z): (i32, i32)| { + ((x - center.0 + half) as usize) * side + (z - center.1 + half) as usize + }; let mut active: Vec<(i32, i32)> = Vec::new(); - // Queued task per chunk (level, sequence); stale heap entries are skipped. - let mut queued: HashMap<(i32, i32), (i32, u64)> = HashMap::new(); + // Queued task per chunk (level, sequence), `NONE` when there is none; + // stale heap entries are skipped. + const NONE: (i32, u64) = (i32::MAX, 0); + let mut queued = vec![NONE; side * side]; let mut heap = BinaryHeap::new(); let mut sequence = 0u64; - let mut full = HashSet::new(); - let mut seen = HashSet::new(); + let mut full = vec![false; side * side]; + let mut seen = vec![false; side * side]; let mut order = Vec::new(); // Each ticket lowers the levels around it to 31 + its Chebyshev distance. - let mut levels: HashMap<(i32, i32), i32> = HashMap::new(); + let mut levels = vec![i32::MAX; side * side]; let mut add = |ticket: (i32, i32), active: &mut Vec<(i32, i32)>, - queued: &mut HashMap<(i32, i32), (i32, u64)>, + queued: &mut [(i32, u64)], heap: &mut BinaryHeap<Reverse<(i32, u64, (i32, i32))>>, - full: &HashSet<(i32, i32)>| { + full: &[bool]| { active.push(ticket); - let reach = LIGHT_LEVEL - TICKET_LEVEL; for x in ticket.0 - reach..=ticket.0 + reach { for z in ticket.1 - reach..=ticket.1 + reach { let own = TICKET_LEVEL + (x - ticket.0).abs().max((z - ticket.1).abs()); - let l = levels.entry((x, z)).or_insert(i32::MAX); - *l = (*l).min(own); - let l = *l; - if full.contains(&(x, z)) { + let i = cell((x, z)); + levels[i] = levels[i].min(own); + let l = levels[i]; + if full[i] { continue; } - if queued.get(&(x, z)).is_none_or(|&(old, _)| l < old) { + if l < queued[i].0 { sequence += 1; - queued.insert((x, z), (l, sequence)); + queued[i] = (l, sequence); heap.push(Reverse((l, sequence, (x, z)))); } } @@ -173,24 +183,25 @@ pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { } } while let Some(Reverse((l, s, chunk))) = heap.pop() { - if queued.get(&chunk) != Some(&(l, s)) { + let i = cell(chunk); + if queued[i] != (l, s) { continue; } - queued.remove(&chunk); + queued[i] = NONE; let r = i32::from(l <= FULL_LEVEL); for x in chunk.0 - r..=chunk.0 + r { for z in chunk.1 - r..=chunk.1 + r { - if seen.insert((x, z)) { + let seen = &mut seen[cell((x, z))]; + if !*seen { + *seen = true; order.push((x, z)); } } } if l <= FULL_LEVEL { - full.insert(chunk); + full[i] = true; } - active.retain(|t| { - !(-2..=2).all(|dx| (-2..=2).all(|dz| full.contains(&(t.0 + dx, t.1 + dz)))) - }); + active.retain(|t| !(-2..=2).all(|dx| (-2..=2).all(|dz| full[cell((t.0 + dx, t.1 + dz))]))); while active.len() < TICKETS_IN_FLIGHT { let Some(t) = tickets.pop_front() else { break }; add(t, &mut active, &mut queued, &mut heap, &full); @@ -203,6 +214,106 @@ pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { mod tests { use super::*; + /// The hash map version this module had before its dense grids. + fn hashed_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { + use std::cmp::Reverse; + use std::collections::{BinaryHeap, HashSet, VecDeque}; + let mut tickets: Vec<(i32, i32)> = (-radius..=radius) + .flat_map(|dx| (-radius..=radius).map(move |dz| (center.0 + dx, center.1 + dz))) + .collect(); + // A fastutil open hash set iterates its slots from the last to the first. + tickets.sort_by_key(|&(x, z)| { + ( + (x - center.0).abs().max((z - center.1).abs()), + Reverse(ticket_hash(x, z) & (TICKET_SET_CAPACITY - 1)), + ) + }); + let mut tickets: VecDeque<_> = tickets.into(); + let mut active: Vec<(i32, i32)> = Vec::new(); + // Queued task per chunk (level, sequence); stale heap entries are skipped. + let mut queued: HashMap<(i32, i32), (i32, u64)> = HashMap::new(); + let mut heap = BinaryHeap::new(); + let mut sequence = 0u64; + let mut full = HashSet::new(); + let mut seen = HashSet::new(); + let mut order = Vec::new(); + // Each ticket lowers the levels around it to 31 + its Chebyshev distance. + let mut levels: HashMap<(i32, i32), i32> = HashMap::new(); + let mut add = |ticket: (i32, i32), + active: &mut Vec<(i32, i32)>, + queued: &mut HashMap<(i32, i32), (i32, u64)>, + heap: &mut BinaryHeap<Reverse<(i32, u64, (i32, i32))>>, + full: &HashSet<(i32, i32)>| { + active.push(ticket); + let reach = LIGHT_LEVEL - TICKET_LEVEL; + for x in ticket.0 - reach..=ticket.0 + reach { + for z in ticket.1 - reach..=ticket.1 + reach { + let own = TICKET_LEVEL + (x - ticket.0).abs().max((z - ticket.1).abs()); + let l = levels.entry((x, z)).or_insert(i32::MAX); + *l = (*l).min(own); + let l = *l; + if full.contains(&(x, z)) { + continue; + } + if queued.get(&(x, z)).is_none_or(|&(old, _)| l < old) { + sequence += 1; + queued.insert((x, z), (l, sequence)); + heap.push(Reverse((l, sequence, (x, z)))); + } + } + } + }; + for _ in 0..TICKETS_IN_FLIGHT { + if let Some(t) = tickets.pop_front() { + add(t, &mut active, &mut queued, &mut heap, &full); + } + } + while let Some(Reverse((l, s, chunk))) = heap.pop() { + if queued.get(&chunk) != Some(&(l, s)) { + continue; + } + queued.remove(&chunk); + let r = i32::from(l <= FULL_LEVEL); + for x in chunk.0 - r..=chunk.0 + r { + for z in chunk.1 - r..=chunk.1 + r { + if seen.insert((x, z)) { + order.push((x, z)); + } + } + } + if l <= FULL_LEVEL { + full.insert(chunk); + } + active.retain(|t| { + !(-2..=2).all(|dx| (-2..=2).all(|dz| full.contains(&(t.0 + dx, t.1 + dz)))) + }); + while active.len() < TICKETS_IN_FLIGHT { + let Some(t) = tickets.pop_front() else { break }; + add(t, &mut active, &mut queued, &mut heap, &full); + } + } + order + } + + #[test] + fn dense_grids_keep_the_hashed_order() { + for (center, radius) in [ + ((0, 0), -1), + ((0, 0), 0), + ((0, 0), 1), + ((12, -15), 8), + ((-30_000, 29_999), 5), + ((7, 3), 12), + ((-61, 1234), 32), + ] { + assert_eq!( + vanilla_order(center, radius), + hashed_order(center, radius), + "{center:?} radius {radius}" + ); + } + } + #[test] fn first_wave_matches_vanilla() { // Seed 1891623539983467248, player teleported into chunk 12,-15 with diff --git a/crates/horizon-world/src/worldgen/fluid_predicate.rs b/crates/horizon-world/src/worldgen/fluid_predicate.rs index d8bcb10ab..1394445c9 100644 --- a/crates/horizon-world/src/worldgen/fluid_predicate.rs +++ b/crates/horizon-world/src/worldgen/fluid_predicate.rs @@ -45,6 +45,9 @@ impl FluidPredicateBindings { self.tags = resolved; Ok(self) } + pub(crate) fn table(&self) -> &Arc<FluidStateTable> { + &self.table + } pub fn state(&self, block: BlockStateId) -> Option<crate::fluid::FluidState> { self.table.get(block) } diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 12dfc10d9..7b73d35a8 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -1764,6 +1764,18 @@ impl OverworldGenerator { ) -> Result<Self, GeneratorError> { Self::build(data, seed, preset, dimension, true) } + /// A dimension of a world preset, with or without structures (the + /// world's `generate_structures`: without, no starts, terrain adaptation, + /// structure pieces or structure locating). + pub fn for_world( + data: Arc<GeneratorData>, + seed: i64, + preset: &str, + dimension: &str, + structures: bool, + ) -> Result<Self, GeneratorError> { + Self::build(data, seed, preset, dimension, structures) + } fn build( data: Arc<GeneratorData>, seed: i64, diff --git a/crates/horizon-world/src/worldgen/generator_blocks.rs b/crates/horizon-world/src/worldgen/generator_blocks.rs index dc7db7d20..ed1182f36 100644 --- a/crates/horizon-world/src/worldgen/generator_blocks.rs +++ b/crates/horizon-world/src/worldgen/generator_blocks.rs @@ -8,8 +8,7 @@ use crate::{ block_support::BlockSupportRegistry, block_survival::{BlockSurvivalRegistry, SurvivalDefinitions, SurvivalRule}, collision::CachedCollisionRegistry, - nbt::{self, Limits, Tag}, - registry::BlockRegistry, + registry::{BlockRegistry, BlockTableFile}, }; use serde_json::Value; use std::{ @@ -102,24 +101,21 @@ impl BlockBehavior { if !dir.join("block-properties.nbt").exists() { return Ok(None); } - let read = |name: &str| -> Result<Tag, GeneratorError> { - Ok( - nbt::read_named(&fs::read(dir.join(name))?, Limits::tables()) - .map_err(|e| resource(format!("{name}: {e:?}")))? - .0 - .tag, - ) + let read = |name: &str| -> Result<BlockTableFile<'static>, GeneratorError> { + BlockTableFile::open(&dir.join(name), registry) + .map_err(|e| resource(format!("{name}: {e}"))) }; let json = |name: &str| -> Result<Value, GeneratorError> { Ok(serde_json::from_str(&fs::read_to_string(dir.join(name))?)?) }; let collisions = - CachedCollisionRegistry::from_nbt(&read("cached-collision.nbt")?, registry)?; - let properties = - BlockPropertiesRegistry::from_nbt(&read("block-properties.nbt")?, &collisions)?; - let support = Arc::new(BlockSupportRegistry::from_nbt( - &read("cached-support.nbt")?, - registry, + CachedCollisionRegistry::from_table(read("cached-collision.nbt")?.table("collision")?)?; + let properties = BlockPropertiesRegistry::from_table( + read("block-properties.nbt")?.table("block property")?, + &collisions, + )?; + let support = Arc::new(BlockSupportRegistry::from_table( + read("cached-support.nbt")?.table("support")?, )?); let collision = Arc::new(BlockCollisionRegistry::new(Arc::new(collisions))?); let rules = json("survival-rules.json")? diff --git a/crates/horizon-world/src/worldgen/generator_structures.rs b/crates/horizon-world/src/worldgen/generator_structures.rs index e78ce0772..11765ab57 100644 --- a/crates/horizon-world/src/worldgen/generator_structures.rs +++ b/crates/horizon-world/src/worldgen/generator_structures.rs @@ -17,7 +17,7 @@ use std::collections::BTreeMap; use std::{ collections::{BTreeSet, HashMap}, sync::{ - Arc, Condvar, Mutex, OnceLock, + Arc, Condvar, Mutex, OnceLock, RwLock, atomic::{AtomicUsize, Ordering}, }, }; @@ -30,7 +30,7 @@ pub(super) struct StructureState { possible_sets: Vec<usize>, /// Structure indices of each decoration step, in registry order. pub(super) by_step: Vec<Vec<usize>>, - starts: Mutex<HashMap<(i32, i32), Starts>>, + starts: StartCache, /// Concentric ring positions, computed on first use and shared with /// later generators of the same seed and dimension. rings: Arc<OnceLock<Rings>>, @@ -108,6 +108,45 @@ impl RingWork { } } const START_CACHE_LIMIT: usize = 65536; +const START_SHARDS: usize = 64; + +/// The built starts by chunk, in shards: a lookup locks one shard for +/// reading. Each generated chunk reads the 289 start chunks around it +/// (`references`) and the server thread reads the starts of the chunks its +/// mobs and players are in; with one lock for all, the server thread waited +/// on the workers. +struct StartCache { + shards: Box<[RwLock<HashMap<(i32, i32), Starts>>]>, +} +impl StartCache { + fn new() -> Self { + Self { + shards: (0..START_SHARDS).map(|_| RwLock::default()).collect(), + } + } + fn shard(&self, key: (i32, i32)) -> &RwLock<HashMap<(i32, i32), Starts>> { + let hash = + (key.0 as u32).wrapping_mul(0x9E37_79B9) ^ (key.1 as u32).wrapping_mul(0x85EB_CA6B); + &self.shards[(hash >> (32 - START_SHARDS.trailing_zeros())) as usize] + } + fn get(&self, key: (i32, i32)) -> Option<Starts> { + self.shard(key).read().unwrap().get(&key).cloned() + } + /// Keeps `starts` unless another thread built the same chunk's first: + /// everyone keeps the first, so placement state on its pieces is shared. + fn insert_first(&self, key: (i32, i32), starts: Starts) -> Starts { + let mut shard = self.shard(key).write().unwrap(); + if shard.len() >= START_CACHE_LIMIT / START_SHARDS { + shard.clear(); + } + shard.entry(key).or_insert(starts).clone() + } + fn clear(&self) { + for shard in &self.shards { + shard.write().unwrap().clear(); + } + } +} fn biome_set(data: &GeneratorData, value: &Value) -> Result<BTreeSet<BiomeId>, super::DecodeError> { let names: Vec<&str> = match value { @@ -156,18 +195,26 @@ impl StructureState { for (i, def) in registry.structures.iter().enumerate() { by_step[def.step].push(i); } - let bindings = FeatureBlockBindings::with_tags( + let mut bindings = FeatureBlockBindings::with_tags( data.registry(), data.integers().clone(), &data.block_tags, )?; + // Processors that test what a block is made of read canOcclude. + if let Some(blocks) = data + .feature_resources + .as_ref() + .and_then(|r| r.blocks.as_ref()) + { + bindings = bindings.with_block_properties(&blocks.properties)?; + } Ok(Some(Self { registry, resources: resources.clone(), bindings, possible_sets, by_step, - starts: Mutex::new(HashMap::new()), + starts: StartCache::new(), rings, ring_work: OnceLock::new(), })) @@ -199,7 +246,7 @@ impl StructureState { /// Drop the cached starts, so that later chunks build fresh pieces (the /// pieces keep per-start placement state such as a shipwreck's height). pub(super) fn forget_starts(&self) { - self.starts.lock().unwrap().clear(); + self.starts.clear(); } /// The (cached) structure starts owned by a chunk. pub(super) fn starts_at( @@ -207,8 +254,8 @@ impl StructureState { context: &mut impl super::structure::start::StartContext, chunk: ChunkPos, ) -> Starts { - if let Some(found) = self.starts.lock().unwrap().get(&(chunk.x, chunk.z)) { - return found.clone(); + if let Some(found) = self.starts.get((chunk.x, chunk.z)) { + return found; } let rings = self.rings(context); let starts: Starts = Arc::new( @@ -225,13 +272,7 @@ impl StructureState { .map(Arc::new) .collect(), ); - let mut cache = self.starts.lock().unwrap(); - if cache.len() >= START_CACHE_LIMIT { - cache.clear(); - } - // Another thread may have built the same starts meanwhile: everyone - // keeps the first, so placement state on its pieces is shared. - cache.entry((chunk.x, chunk.z)).or_insert(starts).clone() + self.starts.insert_first((chunk.x, chunk.z), starts) } /// ChunkGenerator.findNearestMapStructure: the nearest start of one of /// `names` from block `from` (rings: every ring chunk; random spreads: @@ -385,6 +426,39 @@ mod tests { use super::*; use crate::worldgen::structure::stronghold::{ring_positions, ring_searches}; + /// The start cache keeps the first starts built for a chunk, spreads a + /// chunk's 289 reference lookups over the shards, and forgets on clear. + #[test] + fn start_cache_keeps_first_and_spreads_neighbours() { + let cache = StartCache::new(); + let first: Starts = Arc::new(Vec::new()); + let second: Starts = Arc::new(Vec::new()); + assert!(cache.get((3, -4)).is_none()); + assert!(Arc::ptr_eq( + &cache.insert_first((3, -4), first.clone()), + &first + )); + assert!(Arc::ptr_eq(&cache.insert_first((3, -4), second), &first)); + assert!(Arc::ptr_eq(&cache.get((3, -4)).unwrap(), &first)); + for (cx, cz) in [(0, 0), (-1000, 77), (i32::MAX - 8, i32::MIN + 8)] { + let mut used = vec![0; START_SHARDS]; + for x in cx - 8..=cx + 8 { + for z in cz - 8..=cz + 8 { + let shard = cache.shard((x, z)) as *const _; + let i = cache + .shards + .iter() + .position(|s| std::ptr::eq(s, shard)) + .unwrap(); + used[i] += 1; + } + } + assert!(used.iter().all(|&n| n > 0 && n < 20), "{used:?}"); + } + cache.clear(); + assert!(cache.get((3, -4)).is_none()); + } + /// Searches shared between threads give the positions of one thread /// running them in order, set by set. #[test] diff --git a/crates/horizon-world/src/worldgen/material_condition.rs b/crates/horizon-world/src/worldgen/material_condition.rs index 30eb26ec8..6433b09a4 100644 --- a/crates/horizon-world/src/worldgen/material_condition.rs +++ b/crates/horizon-world/src/worldgen/material_condition.rs @@ -300,6 +300,14 @@ enum Kind<R: RandomSource> { Not(Box<Compiled<R>>), } impl<R: RandomSource> Compiled<R> { + fn constant_result(&self) -> Option<bool> { + match &self.kind { + Kind::Constant(value) => Some(*value), + Kind::Not(child) => child.constant_result().map(|value| !value), + _ => None, + } + } + fn compile<S: MaterialSurfaceQueries>( condition: MaterialCondition, root: &R::Positional, diff --git a/crates/horizon-world/src/worldgen/material_condition/density.rs b/crates/horizon-world/src/worldgen/material_condition/density.rs index 5c98c75e0..b10ea815a 100644 --- a/crates/horizon-world/src/worldgen/material_condition/density.rs +++ b/crates/horizon-world/src/worldgen/material_condition/density.rs @@ -15,6 +15,8 @@ pub struct MaterialDensitySources<S: MaterialSurfaceQueries> { surface: S, expected: DensityVolume, densities: Vec<BoundDensity>, + /// Eagerly sampled volumes, shared by bindings of the same density root. + buffers: Vec<Vec<f32>>, retained_samples: usize, plane: DensityVolume, sampler: Arc<dyn DensitySampler>, @@ -23,7 +25,7 @@ pub struct MaterialDensitySources<S: MaterialSurfaceQueries> { } struct BoundDensity { sampler: Arc<dyn DensitySampler>, - buffer: Option<Vec<f32>>, + buffer: Option<usize>, } impl<S: MaterialSurfaceQueries> MaterialDensitySources<S> { pub fn sampler_context_mut(&mut self) -> &mut SamplerContext { @@ -50,6 +52,7 @@ impl<S: MaterialSurfaceQueries> MaterialDensitySources<S> { surface, expected, densities: Vec::new(), + buffers: Vec::new(), retained_samples: 0, plane, sampler, @@ -71,13 +74,23 @@ impl<S: MaterialSurfaceQueries> MaterialSurfaceQueries for MaterialDensitySource { return Err(DecodeError::Field("material density storage bound")); } - let buffer = if eager { - let mut buffer = vec![0.0; self.expected.size()]; - sampler.sample_volume(&mut self.context, &mut buffer, self.expected)?; - self.retained_samples += buffer.len(); - Some(buffer) - } else { - None + let shared = self + .densities + .iter() + .find(|bound| bound.buffer.is_some() && Arc::ptr_eq(&bound.sampler, &sampler)) + .and_then(|bound| bound.buffer); + let buffer = match (eager, shared) { + (false, _) => None, + // Sampling a root over the same volume and context is deterministic, + // so a second binding (iron and copper veins' richness) reuses it. + (true, Some(buffer)) => Some(buffer), + (true, None) => { + let mut buffer = vec![0.0; self.expected.size()]; + sampler.sample_volume(&mut self.context, &mut buffer, self.expected)?; + self.retained_samples += buffer.len(); + self.buffers.push(buffer); + Some(self.buffers.len() - 1) + } }; let index = self.densities.len(); self.densities.push(BoundDensity { sampler, buffer }); @@ -89,9 +102,9 @@ impl<S: MaterialSurfaceQueries> MaterialSurfaceQueries for MaterialDensitySource .get(index) .ok_or(MaterialRuleError::MissingDensityProvider)?; let position = [position.x, position.y, position.z]; - if let Some(buffer) = &source.buffer { - if let Some(index) = self.expected.index_of_block(position) { - return Ok(buffer[index]); + if let Some(buffer) = source.buffer { + if let Some(index) = block_index(self.expected, position) { + return Ok(self.buffers[buffer][index]); } } Ok(source.sampler.sample_value(&mut self.context, position)?) @@ -145,3 +158,121 @@ impl<S: MaterialSurfaceQueries> MaterialSurfaceQueries for MaterialDensitySource self.surface.band(position) } } + +/// `DensityVolume::index_of_block` without its per-axis divisions for the +/// unit-step volumes the material stage samples (one or two lookups per block). +#[inline] +fn block_index(volume: DensityVolume, position: [i32; 3]) -> Option<usize> { + if volume.steps() != [1; 3] { + return volume.index_of_block(position); + } + let [mx, my, mz] = volume.minimum(); + let [sx, sy, sz] = volume.sizes(); + let x = position[0].wrapping_sub(mx) as u32 as usize; + let y = position[1].wrapping_sub(my) as u32 as usize; + let z = position[2].wrapping_sub(mz) as u32 as usize; + (x < sx && y < sy && z < sz).then(|| y + (x + z * sx) * sy) +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_core::density::SampleError; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct Surface; + impl MaterialSurfaceQueries for Surface { + fn surface_depth(&mut self, _: i32, _: i32) -> i32 { + 0 + } + fn surface_secondary(&mut self, _: i32, _: i32) -> f64 { + 0.0 + } + } + /// Position-dependent values; counts bulk samples. + #[derive(Debug, Default)] + struct Counted(AtomicUsize); + impl DensitySampler for Counted { + fn sample_value(&self, _: &mut SamplerContext, p: [i32; 3]) -> Result<f32, SampleError> { + Ok((p[0] * 10_000 + p[1] * 100 + p[2]) as f32) + } + fn sample_volume( + &self, + context: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + self.0.fetch_add(1, Ordering::Relaxed); + for z in 0..volume.sizes()[2] { + for x in 0..volume.sizes()[0] { + for y in 0..volume.sizes()[1] { + let [mx, my, mz] = volume.minimum(); + let p = [mx + x as i32, my + y as i32, mz + z as i32]; + buffer[volume.index([x, y, z]).unwrap()] = self.sample_value(context, p)?; + } + } + } + Ok(()) + } + } + fn sources() -> MaterialDensitySources<Surface> { + let volume = DensityVolume::new([16, 24, 16], [32, -64, -16], [1; 3]).unwrap(); + MaterialDensitySources::new( + Surface, + volume, + Arc::new(Counted::default()), + SamplerContext::default(), + ) + .unwrap() + } + + #[test] + fn eager_bindings_of_one_root_share_a_single_sample() { + let mut sources = sources(); + let shared = Arc::new(Counted::default()); + let other = Arc::new(Counted::default()); + let a = sources.bind_density(shared.clone(), true).unwrap(); + let lazy = sources.bind_density(shared.clone(), false).unwrap(); + let b = sources.bind_density(shared.clone(), true).unwrap(); + let c = sources.bind_density(other.clone(), true).unwrap(); + assert_eq!(shared.0.load(Ordering::Relaxed), 1); + assert_eq!(other.0.load(Ordering::Relaxed), 1); + assert_eq!([a, lazy, b, c], [0, 1, 2, 3]); + for p in [[32, -64, -16], [47, -41, -1], [40, -50, -9], [48, 0, 0]] { + let position = BlockPos::new(p[0], p[1], p[2]); + let expected = (p[0] * 10_000 + p[1] * 100 + p[2]) as f32; + for index in [a, lazy, b, c] { + assert_eq!(sources.density(index, position).unwrap(), expected); + } + } + assert_eq!(shared.0.load(Ordering::Relaxed), 1); + } + + #[test] + fn block_index_matches_index_of_block() { + let unit = DensityVolume::new([16, 24, 16], [i32::MAX - 7, -64, -16], [1; 3]).unwrap(); + let strided = DensityVolume::new([5, 3, 5], [-8, -64, 0], [4, 8, 4]).unwrap(); + for volume in [unit, strided] { + let [mx, my, mz] = volume.minimum(); + for dx in [-1, 0, 1, 4, 7, 8, 15, 16, 17, 20] { + for dy in [-9, -1, 0, 8, 16, 23, 24] { + for dz in [-1, 0, 3, 15, 16, 20] { + let p = [ + mx.wrapping_add(dx), + my.wrapping_add(dy), + mz.wrapping_add(dz), + ]; + assert_eq!(block_index(volume, p), volume.index_of_block(p), "{p:?}"); + } + } + } + for p in [ + [i32::MIN, 0, 0], + [i32::MAX, i32::MAX, i32::MAX], + [0, i32::MIN, 0], + ] { + assert_eq!(block_index(volume, p), volume.index_of_block(p), "{p:?}"); + } + } + } +} diff --git a/crates/horizon-world/src/worldgen/material_condition/rule.rs b/crates/horizon-world/src/worldgen/material_condition/rule.rs index 9dfc2ff1e..cf4fc8547 100644 --- a/crates/horizon-world/src/worldgen/material_condition/rule.rs +++ b/crates/horizon-world/src/worldgen/material_condition/rule.rs @@ -70,6 +70,7 @@ impl From<horizon_core::density::SampleError> for MaterialRuleError { } pub(super) enum CompiledRule<R: RandomSource> { + Empty, Block(BlockStateId), OreVein { blocks: [BlockStateId; 3], @@ -127,7 +128,12 @@ impl<R: RandomSource> CompiledRule<R> { // whether the predicate will match any subsequent position. let condition = Compiled::compile(if_true, root, context, depth + 1)?; let rule = Box::new(Self::compile(*then_run, root, context, depth + 1, nodes)?); - Self::Condition { condition, rule } + // Compile both sides first: binding and errors must retain their order. + match condition.constant_result() { + Some(false) => Self::Empty, + Some(true) => *rule, + None => Self::Condition { condition, rule }, + } } MaterialRule::Sequence(mut children) => { if children.len() == 1 { @@ -135,9 +141,16 @@ impl<R: RandomSource> CompiledRule<R> { } let mut result = Vec::with_capacity(children.len()); for child in children { - result.push(Self::compile(child, root, context, depth + 1, nodes)?); + let child = Self::compile(child, root, context, depth + 1, nodes)?; + if !matches!(child, Self::Empty) { + result.push(child); + } + } + match result.len() { + 0 => Self::Empty, + 1 => result.pop().unwrap(), + _ => Self::Sequence(result), } - Self::Sequence(result) } }) } @@ -147,6 +160,7 @@ impl<R: RandomSource> CompiledRule<R> { context: &mut Context<S>, ) -> Result<Option<BlockStateId>, MaterialRuleError> { match self { + Self::Empty => Ok(None), Self::Block(block) => Ok(Some(*block)), Self::OreVein { blocks, diff --git a/crates/horizon-world/src/worldgen/rule_test.rs b/crates/horizon-world/src/worldgen/rule_test.rs index d9f836961..5202baa31 100644 --- a/crates/horizon-world/src/worldgen/rule_test.rs +++ b/crates/horizon-world/src/worldgen/rule_test.rs @@ -3,7 +3,11 @@ use super::{ DecodeError, Object, block_feature::FeatureBlockBindings, density::identifier, integer, number_text, required, }; -use crate::registry::BlockStateId; +use crate::{ + block_properties::BoundBlockProperty, + fluid::{FluidKind, FluidStateTable}, + registry::BlockStateId, +}; use horizon_core::random::RandomSource; use serde_json::value::RawValue; use std::{collections::BTreeSet, sync::Arc}; @@ -21,6 +25,85 @@ enum Node { RandomStates(Arc<BTreeSet<BlockStateId>>, f32), RandomState(BlockStateId, f32), Height(i32, i32), + Phase(Box<MatterPhase>), +} +/// `horizon:matter_phase`: Repurposed Structures' MatterPhaseRuleTest, which +/// its mineshafts and Nether monument use to match a block by what it is +/// made of (`phase_to_test_for`), optionally inverted (`invert_condition`). +#[derive(Clone, Debug)] +struct MatterPhase { + phase: Phase, + invert: bool, + air: [BlockStateId; 3], + fluids: Arc<FluidStateTable>, + /// Only for `SOLID`. + can_occlude: Option<BoundBlockProperty>, + /// Blocks.RAIL and Blocks.CHAIN (26.3's iron chain). + rail_or_chain: BTreeSet<BlockStateId>, +} +#[derive(Clone, Copy, Debug)] +enum Phase { + Solid, + Liquid, + Air, + AirRailOrChain, + LiquidRailOrChain, +} +impl MatterPhase { + fn decode(object: &Object, bindings: &FeatureBlockBindings<'_>) -> Result<Self, DecodeError> { + let name: String = serde_json::from_str(required(object, "phase_to_test_for")?.get())?; + let phase = match name.as_str() { + "SOLID" => Phase::Solid, + "LIQUID" => Phase::Liquid, + "AIR" => Phase::Air, + "AIR_RAIL_OR_CHAIN" => Phase::AirRailOrChain, + "LIQUID_RAIL_OR_CHAIN" => Phase::LiquidRailOrChain, + _ => return Err(DecodeError::Field("matter phase")), + }; + let invert = match object.get("invert_condition") { + Some(v) => serde_json::from_str(v.get())?, + None => false, + }; + let can_occlude = match phase { + Phase::Solid => Some( + bindings + .can_occlude + .clone() + .ok_or(DecodeError::Field("matter phase block properties"))?, + ), + _ => None, + }; + let mut rail_or_chain = BTreeSet::new(); + for name in ["minecraft:rail", "minecraft:iron_chain"] { + rail_or_chain.extend(bindings.blocks.get(name).into_iter().flat_map(|s| s.iter())); + } + Ok(Self { + phase, + invert, + air: bindings.air, + fluids: bindings.fluids.table().clone(), + can_occlude, + rail_or_chain, + }) + } + fn test(&self, state: BlockStateId) -> bool { + let air = self.air.contains(&state); + let liquid = self + .fluids + .get(state) + .is_some_and(|f| f.kind() != FluidKind::Empty); + let rail_or_chain = || self.rail_or_chain.contains(&state); + let matched = match self.phase { + Phase::Solid => { + !air && !liquid && self.can_occlude.as_ref().is_some_and(|c| c.contains(state)) + } + Phase::Liquid => liquid, + Phase::Air => air, + Phase::AirRailOrChain => air || rail_or_chain(), + Phase::LiquidRailOrChain => liquid || rail_or_chain(), + }; + matched != self.invert + } } impl RuleTest { pub fn from_json(json: &str, bindings: &FeatureBlockBindings<'_>) -> Result<Self, DecodeError> { @@ -104,6 +187,9 @@ impl RuleTest { Node::Any(values) } } + "horizon:matter_phase" => { + Node::Phase(Box::new(MatterPhase::decode(&object, bindings)?)) + } _ => return Err(DecodeError::Field("replacement rule type")), }; Ok(Self(node)) @@ -128,6 +214,7 @@ impl RuleTest { state == *expected && random.next_float() < *probability } Node::Height(min, max) => *min <= position[1] && position[1] <= *max, + Node::Phase(phase) => phase.test(state), } } } diff --git a/crates/horizon-world/src/worldgen/structure.rs b/crates/horizon-world/src/worldgen/structure.rs index f15c37dc2..4dbbc9ade 100644 --- a/crates/horizon-world/src/worldgen/structure.rs +++ b/crates/horizon-world/src/worldgen/structure.rs @@ -10,13 +10,16 @@ pub mod mineshaft; pub mod monument; pub mod nether_fossil; pub mod ocean_ruin; +pub mod piece_limited; pub mod processor; pub mod ruined_portal; pub mod simple; pub mod start; +pub mod start_checks; pub mod stronghold; pub mod template; pub mod temple; +pub mod yung; use crate::{ nbt::{self, Limits}, @@ -341,11 +344,7 @@ impl StructureResources { flate2::read::GzDecoder::new(bytes.as_slice()) .read_to_end(&mut raw) .ok()?; - let limits = Limits { - max_bytes: 1 << 28, - ..Limits::default() - }; - let tag = nbt::read_named(&raw, limits).ok()?.0.tag; + let tag = nbt::read_named(&raw, Limits::templates()).ok()?.0.tag; Some(Arc::new(StructureTemplate::from_nbt( &tag, self.registry, diff --git a/crates/horizon-world/src/worldgen/structure/jigsaw.rs b/crates/horizon-world/src/worldgen/structure/jigsaw.rs index a50275941..34a2728f4 100644 --- a/crates/horizon-world/src/worldgen/structure/jigsaw.rs +++ b/crates/horizon-world/src/worldgen/structure/jigsaw.rs @@ -39,6 +39,9 @@ pub enum PoolElement { legacy: bool, projection: Projection, waterlogging: Option<bool>, + /// YUNG's API's rules on the piece (`"horizon:yungsapi"`), read only + /// by its assembler ([`super::yung`]). + yung: Option<Box<super::yung::Rules>>, }, Feature { feature: String, @@ -81,11 +84,12 @@ fn opposite(d: Direction) -> Direction { Direction::East => Direction::West, } } -fn step(d: Direction) -> [i32; 3] { +pub(super) fn step(d: Direction) -> [i32; 3] { let n = d.normal(); [n[0], n[1], n[2]] } -fn shuffle<T>(list: &mut [T], random: &mut impl RandomSource) { +/// Util.shuffle. +pub(super) fn shuffle<T>(list: &mut [T], random: &mut impl RandomSource) { for i in (2..=list.len()).rev() { let swap = random.next_int_bound(i as i32).unwrap_or(0) as usize; list.swap(i - 1, swap); @@ -135,6 +139,10 @@ impl PoolElement { Some("ignore_waterlogging") => Some(false), _ => None, }, + yung: value + .get("horizon:yungsapi") + .map(|rules| super::yung::Rules::decode(rules, resources).map(Box::new)) + .transpose()?, } } "minecraft:feature_pool_element" => Self::Feature { @@ -219,10 +227,13 @@ impl PoolElement { .first() .map(|e| e.shuffled_jigsaws(resources, position, rotation, random)) .unwrap_or_default(), - Self::Single { template, .. } => { + Self::Single { template, yung, .. } => { let mut jigsaws = template_jigsaws(resources, template, position, rotation); shuffle(&mut jigsaws, random); - jigsaws.sort_by_key(|j| std::cmp::Reverse(j.selection_priority)); + // YUNG's elements keep the shuffled order. + if yung.is_none() { + jigsaws.sort_by_key(|j| std::cmp::Reverse(j.selection_priority)); + } jigsaws } } @@ -230,6 +241,13 @@ impl PoolElement { pub fn ground_level_delta(&self) -> i32 { 1 } + /// YUNG's API's rules, on a piece of one of its structures. + pub fn yung(&self) -> Option<&super::yung::Rules> { + match self { + Self::Single { yung, .. } => yung.as_deref(), + _ => None, + } + } } /// StructureTemplate.getJigsaws: palette chosen by a position-seeded random. fn template_jigsaws( @@ -274,7 +292,7 @@ fn template_jigsaws( }) .collect() } -fn can_attach(source: &Jigsaw, target: &Jigsaw) -> bool { +pub(super) fn can_attach(source: &Jigsaw, target: &Jigsaw) -> bool { source.front == opposite(target.front) && (source.rollable || source.top == target.top) && target @@ -285,12 +303,15 @@ fn can_attach(source: &Jigsaw, target: &Jigsaw) -> bool { #[derive(Debug)] pub struct Pool { - templates: Vec<Arc<PoolElement>>, - fallback: String, + /// Each element repeated by its weight. + pub(super) templates: Vec<Arc<PoolElement>>, + /// The elements with their weights, in file order (`rawTemplates`). + pub(super) raw: Vec<(Arc<PoolElement>, i32)>, + pub(super) fallback: String, max_size: OnceLock<i32>, } impl Pool { - fn random_template(&self, random: &mut impl RandomSource) -> Arc<PoolElement> { + pub(super) fn random_template(&self, random: &mut impl RandomSource) -> Arc<PoolElement> { if self.templates.is_empty() { return Arc::new(PoolElement::Empty); } @@ -304,7 +325,7 @@ impl Pool { shuffle(&mut copy, random); copy } - fn max_size(&self) -> i32 { + pub(super) fn max_size(&self) -> i32 { *self.max_size.get_or_init(|| { self.templates .iter() @@ -343,7 +364,7 @@ impl Pools { } let pool = self.raw.get(name).and_then(|json| { let value: Value = serde_json::from_str(json).ok()?; - let mut templates = Vec::new(); + let (mut templates, mut raw) = (Vec::new(), Vec::new()); for entry in value["elements"].as_array()? { let element = match PoolElement::decode(&entry["element"], resources, bindings, None) { @@ -355,12 +376,15 @@ impl Pools { return None; } }; - for _ in 0..entry["weight"].as_i64().unwrap_or(1) { + let weight = entry["weight"].as_i64().unwrap_or(1); + for _ in 0..weight { templates.push(element.clone()); } + raw.push((element, weight as i32)); } Some(Arc::new(Pool { templates, + raw, fallback: value["fallback"] .as_str() .unwrap_or("minecraft:empty") @@ -393,7 +417,7 @@ pub struct PoolPiece { pub waterlogging: bool, } impl PoolPiece { - fn moved(&mut self, dy: i32) { + pub(super) fn moved(&mut self, dy: i32) { self.position[1] += dy; self.bounding_box = self.bounding_box.moved([0, dy, 0]); } @@ -466,6 +490,7 @@ fn place_element<W: FeatureWorld + PlacementContext, R: RandomSource>( legacy, projection, waterlogging: override_liquid, + .. } => { let ignore = if *legacy { IGNORE_STRUCTURE_AND_AIR.get_or_init(|| { @@ -547,13 +572,13 @@ pub struct JigsawConfig<'a> { /// Free space for children: an inclusive container box minus placed boxes. #[derive(Debug)] -struct Free { - container: BoundingBox, - removed: Vec<BoundingBox>, +pub(super) struct Free { + pub(super) container: BoundingBox, + pub(super) removed: Vec<BoundingBox>, } impl Free { /// Whether every point of the (0.25-deflated) box lies in free space. - fn fits(&self, b: &BoundingBox) -> bool { + pub(super) fn fits(&self, b: &BoundingBox) -> bool { (0..3).all(|i| b.min[i] >= self.container.min[i] && b.max[i] <= self.container.max[i]) && !self.removed.iter().any(|r| r.intersects(b)) } diff --git a/crates/horizon-world/src/worldgen/structure/piece_limited.rs b/crates/horizon-world/src/worldgen/structure/piece_limited.rs new file mode 100644 index 000000000..753df0258 --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/piece_limited.rs @@ -0,0 +1,1055 @@ +//! The piece-limited jigsaw assembler of Repurposed Structures and Moog's +//! Structure Lib (PieceLimitedJigsawManager, the same code in both), for +//! their structures carried over from a modpack (docs/modpacks.md). Carry +//! maps their jigsaw types to `minecraft:jigsaw` with a +//! `"horizon:piece_limited"` key; vanilla data never has it. +//! +//! ```json +//! "horizon:piece_limited": { +//! "library": "moogs", // or "repurposed": their few differences +//! "min_y": 40, "max_y": 120, // y_allowance: pieces stay inside, unless buried +//! "burying": "lowest_corner", // or "average_land", "lowest_side" +//! "no_liquid": true, // cannot_spawn_in_liquid, as burying reads it +//! "ignore_bounds_pools": ["x:pool"], +//! "land_search": "highest_land", // the Nether variants: or "lowest_land", "fixed_height" +//! "ledge_offset_y": 2, +//! "pieces": [{"name": "x:piece", "required": 1, "min_depth": 3, "max": 2}], +//! "layout": "mineshaft" // Repurposed's mineshafts: moved under the terrain +//! } +//! ``` +//! +//! It differs from vanilla's JigsawPlacement: a fresh random seeded by the +//! chunk, the start piece drawn uniformly and moved to the surface at its +//! center, a bounding volume 120 blocks down and 180 up, children drawn by +//! weight from the pools' weighted entries in order (`nextInt(total) + 1`, +//! counted down), pieces capped by template (`max`) and some required +//! (`required`, from `min_depth`), the whole layout retried up to 40 times +//! until every required piece is in, and after it the pieces centred on the +//! chunk corner, then buried in the terrain or moved onto Nether land. +//! Repurposed's overworld mineshafts are not centred: their top goes 15 +//! blocks under the terrain around the chunk. +use super::{ + BoundingBox, Rotation, StructureResources, StructureTemplate, + jigsaw::{ + Free, JigsawConfig, Junction, PoolElement, PoolPiece, Pools, Projection, can_attach, + shuffle, step, + }, + start::StartContext, +}; +use crate::{ + heightmap::HeightmapType, identifier::Identifier, java_hash_map::JavaHashMap, + worldgen::block_feature::FeatureBlockBindings, +}; +use horizon_core::{ + position::ChunkPos, + random::{LegacyRandom, RandomSource, WorldgenRandom}, +}; +use serde_json::Value; +use std::{ + cell::RefCell, + collections::{HashSet, VecDeque}, + rc::Rc, + sync::Arc, +}; + +/// Which mod's copy of the code: they differ in a few post-layout steps. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Library { + Moogs, + Repurposed, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Burying { + LowestCorner, + AverageLand, + LowestSide, +} + +/// The structure type's postLayoutAdjustments. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Layout { + /// GenericJigsawStructure's: centred, then buried or moved onto land. + Generic, + /// Repurposed Structures' MineshaftStructure. + Mineshaft, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LandSearch { + Highest, + Lowest, + Fixed, +} + +/// One template's counts (`*_pieces_spawn_counts`). +#[derive(Clone, Debug)] +struct Counted { + required: Option<i32>, + min_depth: i32, + max: Option<i32>, +} + +/// `"horizon:piece_limited"` of a jigsaw structure. +#[derive(Debug)] +pub struct Config { + library: Library, + min_y: Option<i32>, + max_y: Option<i32>, + burying: Option<Burying>, + no_liquid: bool, + ignore_bounds: HashSet<String>, + land_search: Option<LandSearch>, + ledge: i32, + layout: Layout, + /// Counted templates by id, in the order of Java's HashMap of the + /// required pieces (the first one still short is forced in first). + pieces: Vec<(Identifier, Counted)>, +} + +impl Config { + pub fn decode(v: &Value) -> Self { + let int = |k: &str| v[k].as_i64().map(|n| n as i32); + let mut pieces: Vec<(Identifier, Counted)> = Vec::new(); + for p in v["pieces"].as_array().into_iter().flatten() { + let Some(id) = p["name"].as_str().and_then(|n| Identifier::parse(n).ok()) else { + continue; + }; + let counted = Counted { + required: p["required"].as_i64().map(|n| n as i32), + min_depth: p["min_depth"].as_i64().unwrap_or(0) as i32, + max: p["max"].as_i64().map(|n| n as i32), + }; + // A later entry for the same piece replaces it, as HashMap.put. + match pieces.iter_mut().find(|(k, _)| *k == id) { + Some(slot) => slot.1 = counted, + None => pieces.push((id, counted)), + } + } + // getRequirePieces builds a HashMap of the required ones and the + // assembler copies it (new HashMap(map)): iterate as that copy does. + let mut map = JavaHashMap::default(); + for (i, (id, c)) in pieces.iter().enumerate() { + if c.required.is_some() { + map.put(id.clone(), i); + } + } + let order: Vec<usize> = map.copied().entries().map(|(_, &i)| i).collect(); + let mut sorted: Vec<(Identifier, Counted)> = + order.iter().map(|&i| pieces[i].clone()).collect(); + sorted.extend(pieces.iter().filter(|(_, c)| c.required.is_none()).cloned()); + Self { + library: match v["library"].as_str() { + Some("repurposed") => Library::Repurposed, + _ => Library::Moogs, + }, + min_y: int("min_y"), + max_y: int("max_y"), + burying: match v["burying"].as_str() { + Some("lowest_corner") => Some(Burying::LowestCorner), + Some("average_land") => Some(Burying::AverageLand), + Some("lowest_side") => Some(Burying::LowestSide), + _ => None, + }, + no_liquid: v["no_liquid"].as_bool().unwrap_or(false), + ignore_bounds: v["ignore_bounds_pools"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| Some(p.as_str()?.to_owned())) + .collect(), + land_search: match v["land_search"].as_str() { + Some("highest_land") => Some(LandSearch::Highest), + Some("lowest_land") => Some(LandSearch::Lowest), + Some("fixed_height") => Some(LandSearch::Fixed), + _ => None, + }, + ledge: int("ledge_offset_y").unwrap_or(0), + layout: match v["layout"].as_str() { + Some("mineshaft") => Layout::Mineshaft, + _ => Layout::Generic, + }, + pieces: sorted, + } + } + fn required(&self) -> impl Iterator<Item = &Counted> { + self.pieces + .iter() + .map(|(_, c)| c) + .filter(|c| c.required.is_some()) + } +} + +/// The counted templates, loaded, in [`Config::pieces`] order. +struct Counts(Vec<Arc<StructureTemplate>>); +impl Counts { + fn new(limits: &Config, resources: &StructureResources) -> Self { + Self( + limits + .pieces + .iter() + .map(|(id, _)| { + resources + .template(&id.to_string()) + .unwrap_or_else(|| Arc::new(StructureTemplate::empty())) + }) + .collect(), + ) + } + /// The index of a single element's template among the counted ones. + fn of(&self, element: &PoolElement) -> Option<usize> { + let PoolElement::Single { template, .. } = element else { + return None; + }; + self.0.iter().position(|t| Arc::ptr_eq(t, template)) + } +} + +/// PieceLimitedJigsawManager.assembleJigsawStructure and the structure's +/// postLayoutAdjustments: the start's center and the pieces, or None when +/// nothing starts. `start` is the chunk's corner at the sampled start height. +#[allow(clippy::too_many_arguments)] +pub fn assemble( + config: &JigsawConfig<'_>, + limits: &Config, + context: &mut impl StartContext, + pools: &Pools, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + chunk: ChunkPos, + start: [i32; 3], +) -> Option<([i32; 3], Vec<PoolPiece>)> { + let mut random = WorldgenRandom::new(LegacyRandom::new(0)); + random.set_large_feature_seed(context.seed(), chunk.x, chunk.z); + let rotation = Rotation::random(&mut random); + let pool = pools.get(config.start_pool, resources, bindings)?; + // An empty start pool crashes the mod's generation; nothing starts. + if pool.templates.is_empty() { + return None; + } + let element = pool.random_template(&mut random); + if matches!(element.as_ref(), PoolElement::Empty) { + return None; + } + let mut first = PoolPiece { + bounding_box: element.bounding_box(start, rotation), + ground_level_delta: element.ground_level_delta(), + element, + position: start, + rotation, + junctions: Vec::new(), + waterlogging: config.waterlogging, + }; + let b = first.bounding_box; + let (cx, cz) = ((b.max[0] + b.min[0]) / 2, (b.max[2] + b.min[2]) / 2); + let top = limits.max_y.unwrap_or(i32::MAX); + let bottom = limits.min_y.unwrap_or(i32::MIN); + let cy = match config.project_to { + Some(kind) => { + let y = start[1] + context.base_height(cx, cz, kind); + if y > top || y < bottom { + return None; + } + y + } + None => start[1], + }; + first.moved(cy - (b.min[1] + first.ground_level_delta)); + let start_box = first.bounding_box; + let (start_position, start_rotation) = (first.position, first.rotation); + let counts = Counts::new(limits, resources); + let run_once = limits.required().next().is_none(); + let mut pieces = vec![first]; + let mut attempts = 0; + // `for (attempts = 0; runOnce || doesNotHaveAllRequiredPieces(...); attempts++)`: + // the first test sees the start piece alone. + while run_once || lacks_required(limits, &counts, &pieces) { + if attempts == 40 { + break; + } + if attempts > 0 { + let element = pool.random_template(&mut random); + pieces = vec![PoolPiece { + bounding_box: element.bounding_box(start_position, start_rotation), + ground_level_delta: element.ground_level_delta(), + element, + position: start_position, + rotation: start_rotation, + junctions: Vec::new(), + waterlogging: config.waterlogging, + }]; + } else { + pieces.truncate(1); + } + if config.max_depth > 0 { + let r = config.max_distance[0]; + let free = Rc::new(RefCell::new(Free { + container: BoundingBox::new([cx - r, cy - 120, cz - r], [cx + r, cy + 180, cz + r]), + removed: vec![start_box], + })); + let buried = limits.burying.is_some(); + let mut assembler = Assembler { + config, + limits, + counted: &counts, + pools, + resources, + bindings, + pieces: std::mem::take(&mut pieces), + states: vec![(free, 0)], + counts: vec![0; limits.pieces.len()], + max_y: if buried { i32::MAX } else { top }, + min_y: if buried { i32::MIN } else { bottom }, + }; + let mut queue = VecDeque::from([0]); + while let Some(piece) = queue.pop_front() { + assembler.children(piece, &mut queue, context, &mut random); + } + pieces = assembler.pieces; + } + if run_once { + break; + } + attempts += 1; + } + adjust(config, limits, context, start, &mut pieces); + if pieces.is_empty() { + return None; + } + let mut whole = pieces[0].bounding_box; + for p in &pieces[1..] { + whole.encapsulate(&p.bounding_box); + } + // The builder is cleared when the layout reaches past the build height. + if whole.max[1] > context.max_y() + 1 { + return None; + } + Some(([cx, cy, cz], pieces)) +} + +/// doesNotHaveAllRequiredPieces. +fn lacks_required(limits: &Config, counts: &Counts, pieces: &[PoolPiece]) -> bool { + let mut left: Vec<i32> = limits + .pieces + .iter() + .map(|(_, c)| c.required.unwrap_or(0)) + .collect(); + for p in pieces { + if let Some(i) = counts.of(&p.element) { + left[i] -= 1; + } + } + left.iter().any(|&n| n > 0) +} + +/// Moves a piece; Repurposed Structures' movePieceProperly also writes its +/// junctions, all three setters into the source X, so only the last sticks. +fn shift(limits: &Config, piece: &mut PoolPiece, d: [i32; 3]) { + piece.position = std::array::from_fn(|i| piece.position[i] + d[i]); + piece.bounding_box = piece.bounding_box.moved(d); + if limits.library == Library::Repurposed { + for j in &mut piece.junctions { + j.source_x = j.source_z + d[2]; + } + } +} +fn shift_all(limits: &Config, pieces: &mut [PoolPiece], d: [i32; 3]) { + for p in pieces { + shift(limits, p, d); + } +} + +/// The structure's postLayoutAdjustments. +fn adjust( + config: &JigsawConfig<'_>, + limits: &Config, + context: &mut impl StartContext, + start: [i32; 3], + pieces: &mut Vec<PoolPiece>, +) { + if pieces.is_empty() { + return; + } + if limits.layout == Layout::Mineshaft { + below_terrain(limits, context, start, pieces); + return; + } + // GeneralUtils.centerAllPieces on the chunk's corner. + let center = pieces[0].bounding_box.center(); + let d = [start[0] - center[0], 0, start[2] - center[2]]; + for p in pieces.iter_mut() { + // Centring uses StructurePiece.move in both mods. + p.position = std::array::from_fn(|i| p.position[i] + d[i]); + p.bounding_box = p.bounding_box.moved(d); + } + let offset_y = start[1]; + let sea = context.sea_level(); + if let Some(search) = limits.land_search { + nether(limits, context, search, offset_y, pieces); + return; + } + let Some(burying) = limits.burying else { + return; + }; + let kind = config.project_to.unwrap_or(HeightmapType::WorldSurfaceWg); + let ocean_floor = matches!( + kind, + HeightmapType::OceanFloorWg | HeightmapType::OceanFloor + ); + let box0 = pieces[0].bounding_box; + let mut land = match burying { + Burying::LowestCorner => [ + (box0.min[0], box0.min[2]), + (box0.min[0], box0.max[2]), + (box0.max[0], box0.min[2]), + (box0.max[0], box0.max[2]), + ] + .into_iter() + .map(|(x, z)| context.base_height(x, z, kind) - 1) + .min() + .unwrap_or(0), + Burying::LowestSide => { + let c = box0.center(); + let mut highest = i32::MAX; + for (x, z) in [ + (box0.min[0], c[2]), + (c[0], box0.max[2]), + (c[0], box0.min[2]), + (box0.max[0], c[2]), + ] { + // getFirstOccupiedHeight (Repurposed's cached free height - 1). + let land = context.base_height(x, z, kind) - 1; + match limits.min_y { + Some(min) if land >= min => highest = land, + Some(_) => {} + None => highest = highest.min(land), + } + } + if let Some(min) = limits.min_y.filter(|_| highest == i32::MAX) { + highest = min; + } + highest + } + Burying::AverageLand => { + average_land(limits, context, kind, ocean_floor, offset_y, pieces); + return; + } + }; + if limits.no_liquid || !ocean_floor { + land = land.max(sea); + } else { + land = land.min(sea - box0.span()[1]); + } + // offsetToNewHeight. + if limits.max_y.is_some() + && let Some(min) = limits.min_y + && box0.max[1] + offset_y < min + { + land = land.max(limits.max_y.unwrap_or(land)); + } + if let Some(min) = limits.min_y + && box0.min[1] + offset_y < min + { + land = land.min(min); + } + let dy = land - box0.min[1] + offset_y; + shift_all(limits, pieces, [0, dy, 0]); +} + +/// MineshaftStructure.postLayoutAdjustments: the layout's top moved to 15 +/// blocks under the lowest ocean floor at the chunk's middle and 16 blocks +/// to each side, within y_allowance; never up. +fn below_terrain( + limits: &Config, + context: &mut impl StartContext, + start: [i32; 3], + pieces: &mut [PoolPiece], +) { + let target = mineshaft_top(start, limits.min_y, |x, z| { + context.base_height(x, z, HeightmapType::OceanFloorWg) + }); + let top = pieces + .iter() + .map(|p| p.bounding_box.max[1]) + .max() + .unwrap_or(i32::MIN); + if target < limits.max_y.unwrap_or(i32::MAX) && target < top { + shift_all(limits, pieces, [0, target - top, 0]); + } +} + +/// Where [`below_terrain`] puts a mineshaft's top: `floor` is the first free +/// height over the ocean floor (getFirstFreeHeight, OCEAN_FLOOR_WG). +fn mineshaft_top( + start: [i32; 3], + min_y: Option<i32>, + mut floor: impl FnMut(i32, i32) -> i32, +) -> i32 { + let (x, z) = (start[0] + 7, start[2] + 7); + let mut terrain = floor(x, z) - 1; + // Plane.HORIZONTAL's order; the mod takes one more off after each. + for (dx, dz) in [(0, -16), (16, 0), (0, 16), (-16, 0)] { + terrain = terrain.min(floor(x + dx, z + dz)) - 1; + } + (terrain - 15).max(min_y.unwrap_or(i32::MIN)) +} + +/// AVERAGE_LAND: the mean land height over a grid on the first piece's +/// footprint; no structure when none of the heights is allowed. +fn average_land( + limits: &Config, + context: &mut impl StartContext, + kind: HeightmapType, + ocean_floor: bool, + offset_y: i32, + pieces: &mut Vec<PoolPiece>, +) { + let b = pieces[0].bounding_box; + let c = b.center(); + let (lx, lz) = (b.max[0] - b.min[0], b.max[2] - b.min[2]); + let radius = (f64::from(lx * lx + lz * lz).sqrt() as i32) / 2; + // The mod's loop never ends with a step of 0; one block apart instead. + let step = (radius / 2).max(1); + let (min, max) = ( + limits.min_y.unwrap_or(i32::MIN), + limits.max_y.unwrap_or(i32::MAX), + ); + let (mut sum, mut n) = (0i64, 0i64); + let mut x = -radius; + while x <= radius { + let mut z = -radius; + while z <= radius { + let h = context.base_height(c[0] + x, c[2] + z, kind) - 1; + if h > min && h < max { + sum += i64::from(h); + n += 1; + } + z += step; + } + x += step; + } + let mut average = (n > 0).then(|| sum as f64 / n as f64); + if average.is_none() { + average = limits.max_y.or(limits.min_y).map(f64::from); + } + let Some(mut average) = average else { + pieces.clear(); + return; + }; + if limits.no_liquid && !ocean_floor { + average = average.max(f64::from(context.sea_level())); + if let Some(max) = limits.max_y { + // Math.max, as the mod has it. + average = average.max(f64::from(max)); + } + } + let dy = average as i32 - b.min[1] + offset_y; + shift_all(limits, pieces, [0, dy, 0]); +} + +/// The Nether variants: onto the highest or lowest land at the layout's +/// center (or a fixed height), a ledge above it, within y_allowance. +fn nether( + limits: &Config, + context: &mut impl StartContext, + search: LandSearch, + offset_y: i32, + pieces: &mut [PoolPiece], +) { + let mut whole = pieces[0].bounding_box; + for p in &pieces[1..] { + whole.encapsulate(&p.bounding_box); + } + let sea = context.sea_level(); + let generation = context.generation(); + let terrain_limit = generation.min_y + generation.height; + let base = pieces[0].bounding_box.min[1]; + let found = |context: &mut dyn ColumnQuery, highest: bool| { + let c = whole.center(); + context.land(c[0], c[2], highest, !limits.no_liquid, sea, terrain_limit) + }; + let mut target = match (limits.library, search) { + (Library::Moogs, LandSearch::Fixed) => offset_y + limits.ledge, + (library, search) => { + let y = found(context, search == LandSearch::Highest); + let at = if y < terrain_limit && y > sea + 1 { + y + } else { + sea + }; + if library == Library::Repurposed { + shift_all(limits, pieces, [0, at + limits.ledge - base, 0]); + return; + } + at + limits.ledge + offset_y + } + }; + let height = whole.max[1] - whole.min[1]; + let below = whole.min[1] - base; + if let Some(top) = limits.max_y { + target = target.min(top - height - below); + } + if let Some(bottom) = limits.min_y { + target = target.max(bottom - below); + } + shift_all(limits, pieces, [0, target - base, 0]); +} + +/// GeneralUtils.getHighestLand and getLowestLand on the noise column. +trait ColumnQuery { + fn land( + &mut self, + x: i32, + z: i32, + highest: bool, + on_liquid: bool, + sea: i32, + terrain_limit: i32, + ) -> i32; +} +impl<C: StartContext> ColumnQuery for C { + fn land( + &mut self, + x: i32, + z: i32, + highest: bool, + on_liquid: bool, + sea: i32, + terrain_limit: i32, + ) -> i32 { + let min = self.generation().min_y; + let mut columns = self.base_columns( + x, + z, + &[HeightmapType::WorldSurfaceWg, HeightmapType::OceanFloorWg], + ); + let solid = columns.pop().unwrap_or_default(); + let filled = columns.pop().unwrap_or_default(); + land_in(&filled, &solid, min, highest, on_liquid, sea, terrain_limit) + } +} + +/// The land search over one noise column: `filled` (not air) and `solid` +/// (canOcclude, for the noise's own blocks) from `min` up; past the +/// column's ends a NoiseColumn reads air. +fn land_in( + filled: &[bool], + solid: &[bool], + min: i32, + highest: bool, + on_liquid: bool, + sea: i32, + terrain_limit: i32, +) -> i32 { + let at = |c: &[bool], y: i32| { + usize::try_from(y - min) + .ok() + .and_then(|i| c.get(i).copied()) + .unwrap_or(false) + }; + let air = |y: i32| !at(filled, y); + let stands = |y: i32| if on_liquid { !air(y) } else { at(solid, y) }; + if highest { + let mut y = terrain_limit - 40; + while y > sea { + if at(solid, y) && air(y + 3) && stands(y) { + return y; + } + y -= 1; + } + y + } else { + let mut y = sea + 1; + while y <= terrain_limit - 40 { + if stands(y) && air(y + 1) && air(y + 5) { + return y + 1; + } + y += 1; + } + sea + } +} + +/// PieceLimitedJigsawManager.Assembler. +struct Assembler<'a> { + config: &'a JigsawConfig<'a>, + limits: &'a Config, + counted: &'a Counts, + pools: &'a Pools, + resources: &'a StructureResources, + bindings: &'a FeatureBlockBindings<'a>, + pieces: Vec<PoolPiece>, + /// Per piece: the free space it was placed in, and its depth. + states: Vec<(Rc<RefCell<Free>>, i32)>, + /// Pieces placed per counted template. + counts: Vec<i32>, + max_y: i32, + min_y: i32, +} + +/// Where a child goes: the parent's jigsaw and what it needs. +struct Slot<'s> { + source: usize, + jigsaw: &'s super::jigsaw::Jigsaw, + target_pos: [i32; 3], + free: Rc<RefCell<Free>>, + depth: i32, +} + +impl Assembler<'_> { + fn pool(&self, name: &str) -> Option<Arc<super::jigsaw::Pool>> { + let name = self.config.aliases.get(name).map_or(name, String::as_str); + self.pools.get(name, self.resources, self.bindings) + } + /// generatePiece: one child per jigsaw where one fits, from the target + /// pool unless the piece is at the last depth, else from its fallback. + fn children( + &mut self, + source: usize, + queue: &mut VecDeque<usize>, + context: &mut impl StartContext, + random: &mut impl RandomSource, + ) { + let (element, position, rotation, source_box) = { + let s = &self.pieces[source]; + (s.element.clone(), s.position, s.rotation, s.bounding_box) + }; + let (context_free, depth) = self.states[source].clone(); + let mut source_free: Option<Rc<RefCell<Free>>> = None; + for jigsaw in element.shuffled_jigsaws(self.resources, position, rotation, random) { + let Some(target) = self.pool(&jigsaw.pool) else { + continue; + }; + if target.templates.is_empty() && jigsaw.pool != "minecraft:empty" { + continue; + } + let s = step(jigsaw.front); + let target_pos: [i32; 3] = std::array::from_fn(|i| jigsaw.pos[i] + s[i]); + let free = if source_box.is_inside(target_pos) { + source_free + .get_or_insert_with(|| { + Rc::new(RefCell::new(Free { + container: source_box, + removed: Vec::new(), + })) + }) + .clone() + } else { + context_free.clone() + }; + let slot = Slot { + source, + jigsaw: &jigsaw, + target_pos, + free, + depth, + }; + if depth != self.config.max_depth + && self.process(&slot, target.raw.clone(), false, queue, context, random) + { + continue; + } + let Some(fallback) = self.pool(&target.fallback) else { + continue; + }; + let ignore = self.limits.ignore_bounds.contains(&target.fallback); + self.process(&slot, fallback.raw.clone(), ignore, queue, context, random); + } + } + /// processList: whether a piece was placed. + fn process( + &mut self, + slot: &Slot<'_>, + mut candidates: Vec<(Arc<PoolElement>, i32)>, + ignore_bounds: bool, + queue: &mut VecDeque<usize>, + context: &mut impl StartContext, + random: &mut impl RandomSource, + ) -> bool { + let jigsaw = slot.jigsaw; + let (source_rigid, source_y, source_ground) = { + let s = &self.pieces[slot.source]; + ( + s.element.projection() == Projection::Rigid, + s.bounding_box.min[1], + s.ground_level_delta, + ) + }; + let local_y = jigsaw.pos[1] - source_y; + let mut surface = None; + let (x, z) = (jigsaw.pos[0], jigsaw.pos[2]); + let mut base = + |context: &mut dyn SurfaceQuery| *surface.get_or_insert_with(|| context.surface(x, z)); + let mut total: i32 = candidates.iter().map(|c| c.1).sum(); + while !candidates.is_empty() { + let mut chosen = None; + // The first required piece still short is forced in once deep enough. + let needed = self + .limits + .pieces + .iter() + .enumerate() + .find(|(i, (_, c))| c.required.is_some_and(|r| self.counts[*i] < r)); + if let Some((need_index, (_, need))) = needed { + let need_template = &self.counted.0[need_index]; + let found = candidates.iter().position(|(e, _)| { + matches!(e.as_ref(), PoolElement::Single { template, .. } + if Arc::ptr_eq(template, need_template)) + }); + if let Some(i) = found { + if slot.depth >= (self.config.max_depth - 1).min(need.min_depth) { + chosen = Some(i); + } else { + total -= candidates[i].1; + candidates.remove(i); + } + } + } + let index = match chosen { + Some(i) => i, + None => { + if total <= 0 || candidates.is_empty() { + return false; + } + let mut weight = random.next_int_bound(total).unwrap_or(0) + 1; + let mut found = candidates.len() - 1; + for (i, (_, w)) in candidates.iter().enumerate() { + weight -= w; + if weight <= 0 { + found = i; + break; + } + } + found + } + }; + let (target, weight) = candidates[index].clone(); + if matches!(target.as_ref(), PoolElement::Empty) { + return false; + } + let counted = self.counted.of(&target); + let full = counted.is_some_and(|i| { + self.limits.pieces[i] + .1 + .max + .is_some_and(|m| self.counts[i] >= m) + }); + if full { + total -= weight; + candidates.remove(index); + continue; + } + let mut rotations = Rotation::ALL; + shuffle(&mut rotations, random); + for rotation in rotations { + let target_jigsaws = + target.shuffled_jigsaws(self.resources, [0; 3], rotation, random); + let hack_box = target.bounding_box([0; 3], rotation); + let expand_to = if self.config.use_expansion_hack && hack_box.span()[1] <= 16 { + target_jigsaws + .iter() + .map(|tj| { + let st = step(tj.front); + if !hack_box.is_inside(std::array::from_fn(|i| tj.pos[i] + st[i])) { + return 0; + } + let child = self.pool(&tj.pool); + let child_size = child.as_ref().map_or(0, |p| p.max_size()); + let fallback_size = child + .and_then(|p| self.pool(&p.fallback)) + .map_or(0, |p| p.max_size()); + child_size.max(fallback_size) + }) + .max() + .unwrap_or(0) + } else { + 0 + }; + for target_jigsaw in &target_jigsaws { + if !can_attach(jigsaw, target_jigsaw) { + continue; + } + let target_local = target_jigsaw.pos; + let raw_position: [i32; 3] = + std::array::from_fn(|i| slot.target_pos[i] - target_local[i]); + let raw_box = target.bounding_box(raw_position, rotation); + let target_rigid = target.projection() == Projection::Rigid; + let delta_y = local_y - target_local[1] + step(jigsaw.front)[1]; + let target_y = if source_rigid && target_rigid { + source_y + delta_y + } else { + base(context) - target_local[1] + }; + let offset = target_y - raw_box.min[1]; + let mut target_box = raw_box.moved([0, offset, 0]); + let target_position = + [raw_position[0], raw_position[1] + offset, raw_position[2]]; + if expand_to > 0 { + let size = (expand_to + 1).max(target_box.max[1] - target_box.min[1]); + target_box.max[1] = target_box.min[1] + size; + } + if target_box.max[1] > self.max_y || target_box.min[1] < self.min_y { + continue; + } + if !ignore_bounds && !slot.free.borrow().fits(&target_box) { + continue; + } + let target_ground = if target_rigid { + source_ground - delta_y + } else { + target.ground_level_delta() + }; + let junction_y = if source_rigid { + source_y + local_y + } else if target_rigid { + target_y + target_local[1] + } else { + base(context) + delta_y / 2 + }; + self.pieces[slot.source].junctions.push(Junction { + source_x: slot.target_pos[0], + source_ground_y: junction_y - local_y + source_ground, + source_z: slot.target_pos[2], + }); + slot.free.borrow_mut().removed.push(target_box); + self.pieces.push(PoolPiece { + element: target.clone(), + position: target_position, + ground_level_delta: target_ground, + rotation, + bounding_box: target_box, + junctions: vec![Junction { + source_x: jigsaw.pos[0], + source_ground_y: junction_y - target_local[1] + target_ground, + source_z: jigsaw.pos[2], + }], + waterlogging: self.config.waterlogging, + }); + self.states.push((slot.free.clone(), slot.depth + 1)); + if slot.depth < self.config.max_depth { + queue.push_back(self.pieces.len() - 1); + } + if let Some(i) = counted { + self.counts[i] += 1; + } + return true; + } + } + total -= weight; + candidates.remove(index); + } + false + } +} + +/// The surface height query, object-safe for the per-call cache. +trait SurfaceQuery { + fn surface(&mut self, x: i32, z: i32) -> i32; +} +impl<C: StartContext> SurfaceQuery for C { + fn surface(&mut self, x: i32, z: i32) -> i32 { + self.base_height(x, z, HeightmapType::WorldSurfaceWg) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn required_pieces_follow_javas_hash_map() { + let limits = Config::decode(&json!({"library": "repurposed", "pieces": [ + {"name": "rs:city/a", "required": 1}, + {"name": "rs:city/x", "max": 2}, + {"name": "rs:city/b", "required": 1, "min_depth": 3}, + {"name": "rs:city/c", "required": 2}, + {"name": "rs:city/a", "required": 4}]})); + let names: Vec<String> = limits.pieces.iter().map(|(id, _)| id.to_string()).collect(); + // Buckets 3, 2, 1 of the copied map's 4: c, b, a; then the capped one. + assert_eq!(names, ["rs:city/c", "rs:city/b", "rs:city/a", "rs:city/x"]); + assert_eq!( + limits.pieces[2].1.required, + Some(4), + "a later entry replaces" + ); + assert_eq!(limits.pieces[1].1.min_depth, 3); + assert_eq!(limits.library, Library::Repurposed); + } + + #[test] + fn mineshafts_go_under_the_lowest_floor_around() { + // Floor 80 at the middle (7, 7), 70 north, 90 east, 60 south, 85 west. + let floor = |x, z| match (x, z) { + (7, 7) => 80, + (7, -9) => 70, + (23, 7) => 90, + (7, 23) => 60, + (-9, 7) => 85, + other => panic!("{other:?}"), + }; + // 79, min(79, 70) - 1 = 69, 68, min(68, 60) - 1 = 59, 58; 15 under it. + assert_eq!(mineshaft_top([0, 50, 0], None, floor), 43); + assert_eq!(mineshaft_top([0, 50, 0], Some(48), floor), 48); + } + + #[test] + fn nether_land_is_found_in_the_column() { + // A column from y 0: netherrack to 40, lava 41..=45, air, a ledge 70..=72. + let (mut filled, mut solid) = (vec![false; 128], vec![false; 128]); + for y in 0..=45 { + filled[y] = true; + solid[y] = y <= 40; + } + for y in 70..=72 { + filled[y] = true; + solid[y] = true; + } + // Highest: from 88 down, a solid block with air 3 above. + assert_eq!(land_in(&filled, &solid, 0, true, true, 32, 128), 72); + // Lowest: from 33 up, a block to stand on with air 1 and 5 above; one up. + assert_eq!(land_in(&filled, &solid, 0, false, true, 32, 128), 46); + assert_eq!(land_in(&filled, &solid, 0, false, false, 32, 128), 73); + // Nothing found: the highest search stops at the sea level. + let empty = vec![false; 128]; + assert_eq!(land_in(&empty, &empty, 0, true, true, 32, 128), 32); + assert_eq!(land_in(&empty, &empty, 0, false, true, 32, 128), 32); + } + + #[test] + fn repurposed_moves_junctions_as_its_code_does() { + let template = Arc::new(StructureTemplate::empty()); + let element = Arc::new(PoolElement::Single { + template, + processors: Default::default(), + legacy: false, + projection: Projection::Rigid, + waterlogging: None, + yung: None, + }); + let piece = || PoolPiece { + bounding_box: BoundingBox::new([0; 3], [4; 3]), + ground_level_delta: 1, + element: element.clone(), + position: [0; 3], + rotation: Rotation::None, + junctions: vec![Junction { + source_x: 1, + source_ground_y: 2, + source_z: 3, + }], + waterlogging: true, + }; + let moogs = Config::decode(&json!({})); + let rs = Config::decode(&json!({"library": "repurposed"})); + let (mut a, mut b) = (piece(), piece()); + shift(&moogs, &mut a, [10, 20, 30]); + shift(&rs, &mut b, [10, 20, 30]); + assert_eq!(a.bounding_box, BoundingBox::new([10, 20, 30], [14, 24, 34])); + assert_eq!(a.position, [10, 20, 30]); + assert_eq!(a.junctions[0].source_x, 1); + // movePieceProperly sets the source X three times; Z + dz is left. + assert_eq!(b.junctions[0].source_x, 33); + assert_eq!(b.junctions[0].source_ground_y, 2); + } +} diff --git a/crates/horizon-world/src/worldgen/structure/processor.rs b/crates/horizon-world/src/worldgen/structure/processor.rs index b5bf2e22f..980a90848 100644 --- a/crates/horizon-world/src/worldgen/structure/processor.rs +++ b/crates/horizon-world/src/worldgen/structure/processor.rs @@ -49,6 +49,22 @@ enum PosRule { max_dist: i32, axis: Option<usize>, }, + /// `horizon:piece_origin_axis_aligned_linear_pos`: Repurposed Structures' + /// PieceOriginAxisAlignedLinearPosRuleTest, vanilla's axis-aligned chance + /// over the block's distance from the template's origin along one axis. + PieceOrigin { + min_chance: f32, + max_chance: f32, + min_dist: i32, + max_dist: i32, + axis: usize, + }, + /// `horizon:y_value`: Repurposed Structures' YValuePosRuleTest, the + /// block's world height in `min_y_value..=max_y_value`. + YValue { + min: i32, + max: i32, + }, } #[derive(Clone, Debug)] enum Modifier { @@ -56,6 +72,188 @@ enum Modifier { Clear, AppendLoot(String), AppendStatic(Compound), + /// `horizon:edit`: `remove`'s keys taken out of the block entity, then + /// `data` merged in as append_static does. The data form of the mods' + /// processors that copy a block entity and change parts of it (Moog's + /// trial spawners and vaults drop their saved state). + Edit { + remove: Vec<String>, + data: Compound, + }, +} +impl PosRule { + /// A rule's `position_predicate` (always true when missing). Types are + /// identifiers: `"always_true"` is `minecraft:always_true`, as vanilla + /// reads it. + fn decode(value: Option<&Value>) -> Result<Self, DecodeError> { + let Some(p) = value else { + return Ok(Self::Always); + }; + let kind = p["predicate_type"] + .as_str() + .unwrap_or("minecraft:always_true"); + Ok(match super::super::tags::identifier(kind)?.as_str() { + "minecraft:always_true" => Self::Always, + kind @ ("minecraft:linear_pos" | "minecraft:axis_aligned_linear_pos") => Self::Linear { + min_chance: p.get("min_chance").and_then(Value::as_f64).unwrap_or(0.) as f32, + max_chance: p.get("max_chance").and_then(Value::as_f64).unwrap_or(0.) as f32, + min_dist: p.get("min_dist").and_then(Value::as_i64).unwrap_or(0) as i32, + max_dist: p.get("max_dist").and_then(Value::as_i64).unwrap_or(0) as i32, + axis: (kind == "minecraft:axis_aligned_linear_pos").then(|| { + match p.get("axis").and_then(Value::as_str) { + Some("x") => 0, + Some("z") => 2, + _ => 1, + } + }), + }, + "horizon:piece_origin_axis_aligned_linear_pos" => { + let int = |key| p.get(key).and_then(Value::as_i64).unwrap_or(0) as i32; + let (min_dist, max_dist) = (int("min_dist"), int("max_dist")); + if min_dist >= max_dist { + return Err(DecodeError::Field("position predicate distance range")); + } + Self::PieceOrigin { + min_chance: p.get("min_chance").and_then(Value::as_f64).unwrap_or(0.) as f32, + max_chance: p.get("max_chance").and_then(Value::as_f64).unwrap_or(0.) as f32, + min_dist, + max_dist, + axis: match p.get("axis").map(|a| a.as_str()) { + Some(Some("x")) => 0, + None | Some(Some("y")) => 1, + Some(Some("z")) => 2, + _ => return Err(DecodeError::Field("position predicate axis")), + }, + } + } + "horizon:y_value" => { + let int = |key| { + p.get(key) + .and_then(Value::as_i64) + .map(|v| v as i32) + .ok_or(DecodeError::Field("position predicate y value")) + }; + let (min, max) = (int("min_y_value")?, int("max_y_value")?); + if min > max { + return Err(DecodeError::Field("position predicate y range")); + } + Self::YValue { min, max } + } + _ => return Err(DecodeError::Field("position predicate")), + }) + } + /// PosRuleTest.test for a block at `world`, `relative` in its template, + /// in a piece placed at `reference`. + fn test( + &self, + relative: [i32; 3], + world: [i32; 3], + reference: [i32; 3], + random: &mut impl RandomSource, + ) -> bool { + match *self { + Self::Always => true, + Self::Linear { + min_chance, + max_chance, + min_dist, + max_dist, + axis, + } => { + let dist = match axis { + None => (0..3).map(|i| (world[i] - reference[i]).abs()).sum::<i32>(), + Some(a) => ((world[a] - reference[a]) as f32).abs() as i32, + }; + random.next_float() + <= clamped_chance(min_chance, max_chance, min_dist, max_dist, dist) + } + Self::PieceOrigin { + min_chance, + max_chance, + min_dist, + max_dist, + axis, + } => { + let dist = (relative[axis] as f32).abs() as i32; + random.next_float() + <= clamped_chance(min_chance, max_chance, min_dist, max_dist, dist) + } + Self::YValue { min, max } => (min..=max).contains(&world[1]), + } + } +} +/// Mth.clampedLerp(min_chance, max_chance, Mth.inverseLerp(dist, min_dist, max_dist)). +fn clamped_chance( + min_chance: f32, + max_chance: f32, + min_dist: i32, + max_dist: i32, + dist: i32, +) -> f32 { + let t = (dist - min_dist) as f32 / (max_dist - min_dist) as f32; + if t < 0. { + min_chance + } else if t > 1. { + max_chance + } else { + min_chance + t * (max_chance - min_chance) + } +} +impl Modifier { + /// A rule's `block_entity_modifier` (passthrough when missing). + fn decode(value: Option<&Value>) -> Result<Self, DecodeError> { + let Some(m) = value else { + return Ok(Self::Passthrough); + }; + Ok( + match super::super::tags::identifier(m["type"].as_str().unwrap_or(""))?.as_str() { + "minecraft:passthrough" => Self::Passthrough, + "minecraft:clear" => Self::Clear, + "minecraft:append_loot" => { + Self::AppendLoot(m["loot_table"].as_str().unwrap_or_default().to_owned()) + } + "minecraft:append_static" => match json_to_nbt(&m["data"]) { + Tag::Compound(c) => Self::AppendStatic(c), + _ => Self::AppendStatic(Compound::new()), + }, + "horizon:edit" => Self::Edit { + remove: m["remove"] + .as_array() + .into_iter() + .flatten() + .map(|k| k.as_str().map(str::to_owned)) + .collect::<Option<_>>() + .ok_or(DecodeError::Field("block entity modifier keys"))?, + data: match json_to_nbt(&m["data"]) { + Tag::Compound(c) => c, + _ => Compound::new(), + }, + }, + _ => return Err(DecodeError::Field("block entity modifier")), + }, + ) + } +} +/// A block entity with `remove`'s keys taken out and `data` merged in +/// (append_static is the one with nothing to remove). +fn edited(nbt: Option<&Compound>, remove: &[String], data: &Compound) -> Compound { + let mut nbt = nbt.cloned().unwrap_or_default(); + for key in remove { + nbt.remove(&JavaString::from(key.as_str())); + } + merge(&mut nbt, data); + nbt +} +/// CompoundTag.merge: compounds in both are merged, anything else replaced. +fn merge(into: &mut Compound, other: &Compound) { + for (key, value) in other { + match (into.get_mut(key), value) { + (Some(Tag::Compound(mine)), Tag::Compound(theirs)) => merge(mine, theirs), + _ => { + into.insert(key.clone(), value.clone()); + } + } + } } #[derive(Clone, Debug)] pub struct Rule { @@ -87,10 +285,314 @@ pub enum Processor { BlockAge(f32), LavaSubmerged, BlackstoneReplace, + SpawnerMobs(Box<SpawnerMobs>), + Pick(Box<Pick>), + CountCap(Box<CountCap>), + /// `horizon:block_swap` (Lithostitched's `block_swap`): blocks by name + /// become others, keeping the properties both have. + BlockSwap(std::collections::BTreeMap<String, String>), } #[derive(Clone, Debug, Default)] pub struct ProcessorList(pub Vec<Processor>); +/// The spawner fields `horizon:spawner_mobs` writes: its JSON key, the NBT +/// key and the default (BaseSpawner's). +const SPAWNER_FIELDS: [(&str, &str, i16); 7] = [ + ("delay", "Delay", 20), + ("min_spawn_delay", "MinSpawnDelay", 200), + ("max_spawn_delay", "MaxSpawnDelay", 800), + ("spawn_count", "SpawnCount", 4), + ("max_nearby_entities", "MaxNearbyEntities", 6), + ("required_player_range", "RequiredPlayerRange", 16), + ("spawn_range", "SpawnRange", 4), +]; + +/// `horizon:pick`, which `horizon-port-pack` writes for the mods' processors +/// that turn a placeholder block into one of several (YUNG's, written in +/// Java): a block of `block` takes the first of `picks` whose `below` is past +/// one `settings.getRandom(pos).nextFloat()`, else `default` (no float is +/// drawn when there are no picks; with no default the block stays). +#[derive(Clone, Debug)] +pub struct Pick { + block: String, + picks: Vec<(f32, Outcome)>, + default: Option<Outcome>, +} +#[derive(Clone, Debug)] +struct Outcome { + /// The state, or one of them by `nextInt(len)` (Util.getRandom), drawn + /// after the pick. + states: Vec<BlockStateId>, + /// The new block entity; the block's own stays when missing. + nbt: Option<Compound>, + /// Keys set to lists of `count` strings, each the first of `values` + /// whose bound is past a new `nextFloat`, else `default` (pot sherds). + lists: Vec<PickedList>, +} +#[derive(Clone, Debug)] +struct PickedList { + key: String, + count: usize, + values: Vec<(f32, String)>, + default: String, +} +fn below(v: &Value) -> Result<f32, DecodeError> { + v["below"] + .as_f64() + .map(|b| b as f32) + .ok_or(DecodeError::Field("pick bound")) +} +impl Pick { + fn decode( + value: &Value, + state: impl Fn(&Value) -> Result<BlockStateId, DecodeError>, + ) -> Result<Self, DecodeError> { + let outcome = |v: &Value| -> Result<Outcome, DecodeError> { + let states = match v.get("states") { + Some(list) => list + .as_array() + .ok_or(DecodeError::Field("pick states"))? + .iter() + .map(&state) + .collect::<Result<Vec<_>, _>>()?, + None => vec![state(&v["state"])?], + }; + if states.is_empty() { + return Err(DecodeError::Field("pick states")); + } + let nbt = match v.get("nbt").map(json_to_nbt) { + Some(Tag::Compound(c)) => Some(c), + Some(_) => return Err(DecodeError::Field("pick nbt")), + None => None, + }; + let text = |v: &Value| { + v.as_str() + .map(str::to_owned) + .ok_or(DecodeError::Field("pick list")) + }; + let lists = v["lists"] + .as_array() + .into_iter() + .flatten() + .map(|l| { + Ok(PickedList { + key: text(&l["key"])?, + count: l["count"].as_u64().ok_or(DecodeError::Field("pick list"))? as usize, + values: l["values"] + .as_array() + .into_iter() + .flatten() + .map(|e| Ok((below(e)?, text(&e["value"])?))) + .collect::<Result<_, DecodeError>>()?, + default: text(&l["default"])?, + }) + }) + .collect::<Result<_, DecodeError>>()?; + Ok(Outcome { states, nbt, lists }) + }; + Ok(Self { + block: value["block"] + .as_str() + .map(|b| super::super::tags::identifier(b).map(|i| i.to_string())) + .ok_or(DecodeError::Field("pick block"))??, + picks: value["picks"] + .as_array() + .into_iter() + .flatten() + .map(|p| Ok((below(p)?, outcome(p)?))) + .collect::<Result<_, DecodeError>>()?, + default: value.get("default").map(outcome).transpose()?, + }) + } + fn apply(&self, info: BlockInfo, random: &mut dyn ProcessorRandom) -> BlockInfo { + let outcome = match self.picks.is_empty() { + true => self.default.as_ref(), + false => { + let f = random.float(); + self.picks + .iter() + .find(|(b, _)| f < *b) + .map(|(_, o)| o) + .or(self.default.as_ref()) + } + }; + let Some(outcome) = outcome else { + return info; + }; + let state = match outcome.states.as_slice() { + [one] => *one, + many => many[random.int(many.len() as i32) as usize], + }; + let mut nbt = outcome.nbt.clone().or(info.nbt); + for list in &outcome.lists { + let values = (0..list.count) + .map(|_| { + let f = random.float(); + let v = list + .values + .iter() + .find(|(b, _)| f < *b) + .map_or(&list.default, |(_, v)| v); + Tag::String(v.as_str().into()) + }) + .collect(); + nbt.get_or_insert_with(Compound::new) + .insert(list.key.as_str().into(), Tag::List(values)); + } + BlockInfo { + pos: info.pos, + state, + nbt, + } + } +} + +/// `horizon:count_cap`, which `horizon-port-pack` writes for Better +/// Dungeons' chest processor (Java in the mod): of the `blocks` one +/// placement meets, the first `min` stay, the rest each stay when +/// `settings.getRandom(pos).nextFloat() <= chance` until `max` have, and the +/// others become `replacement`. The count is the placement's (the mod's +/// DungeonContext, set up per StructureTemplate.placeInWorld: one chunk of +/// the piece), shared by every such processor in it. +#[derive(Clone, Debug)] +pub struct CountCap { + blocks: BTreeSet<String>, + min: u32, + max: u32, + chance: f32, + replacement: BlockStateId, +} +impl CountCap { + fn decode( + value: &Value, + state: impl Fn(&Value) -> Result<BlockStateId, DecodeError>, + ) -> Result<Self, DecodeError> { + let count = |key: &'static str| { + value[key] + .as_u64() + .and_then(|n| u32::try_from(n).ok()) + .ok_or(DecodeError::Field(key)) + }; + Ok(Self { + blocks: value["blocks"] + .as_array() + .ok_or(DecodeError::Field("blocks"))? + .iter() + .map(|b| { + let b = b.as_str().ok_or(DecodeError::Field("blocks"))?; + Ok(super::super::tags::identifier(b)?.to_string()) + }) + .collect::<Result<_, DecodeError>>()?, + min: count("min")?, + max: count("max")?, + chance: float(value, "chance")?, + replacement: state(&value["replacement"])?, + }) + } + /// Whether a counted block stays, counting it if so. + fn keeps(&self, counted: &mut u32, roll: impl FnOnce() -> f32) -> bool { + let keep = *counted < self.min || (*counted < self.max && roll() <= self.chance); + *counted += u32::from(keep); + keep + } +} + +/// `horizon:spawner_mobs`, which `horizon-port-pack` writes for the spawner +/// randomizing processors of Moog's Structure Lib and Repurposed Structures +/// (Java code in the mods): a spawner gets one mob of a weighted list, +/// picked with `settings.getRandom(pos).nextFloat()` as theirs do, and the +/// spawner NBT they write. With no mob to pick it becomes `replacement`. +#[derive(Clone, Debug)] +pub struct SpawnerMobs { + /// Each mob's entity compound (its `id` and any NBT) and weight. + mobs: Vec<(Compound, f64)>, + /// [`SPAWNER_FIELDS`]' values. + fields: [i16; 7], + /// `custom_spawn_rules`, in `SpawnData` and the potential alike. + rules: Option<Compound>, + replacement: BlockStateId, +} +impl SpawnerMobs { + fn decode( + value: &Value, + replacement: impl FnOnce(Option<&Value>) -> Result<BlockStateId, DecodeError>, + ) -> Result<Self, DecodeError> { + let mobs = value["mobs"] + .as_array() + .ok_or(DecodeError::Field("spawner_mobs mobs"))? + .iter() + .map( + |m| match (json_to_nbt(&m["entity"]), m["weight"].as_f64()) { + (Tag::Compound(entity), Some(weight)) + if entity.contains_key(&JavaString::from("id")) => + { + Ok((entity, weight)) + } + _ => Err(DecodeError::Field("spawner_mobs mob")), + }, + ) + .collect::<Result<_, _>>()?; + let mut fields = [0; 7]; + for (field, (key, _, default)) in fields.iter_mut().zip(SPAWNER_FIELDS) { + // The mods' codecs read ints; the spawner saves them as shorts. + *field = value + .get(key) + .map_or(Some(default), |v| v.as_i64().map(|v| v as i16)) + .ok_or(DecodeError::Field("spawner_mobs field"))?; + } + let rules = match value.get("custom_spawn_rules").map(json_to_nbt) { + None => None, + Some(Tag::Compound(c)) => Some(c), + Some(_) => return Err(DecodeError::Field("spawner_mobs custom_spawn_rules")), + }; + Ok(Self { + mobs, + fields, + rules, + replacement: replacement(value.get("replacement"))?, + }) + } + /// The mob for a spawner, drawing from `random` only when there is one + /// to pick (pickWeightedRandom; Repurposed Structures' getSpawnerMob, + /// whose float product can round differently only on a boundary). + fn pick(&self, random: impl FnOnce() -> f32) -> Option<&Compound> { + let total: f64 = self.mobs.iter().map(|m| m.1).sum(); + if self.mobs.is_empty() || total <= 0. { + return None; + } + let mut pick = f64::from(random()) * total; + for (entity, weight) in &self.mobs { + pick -= weight; + if pick <= 0. { + return Some(entity); + } + } + self.mobs.last().map(|m| &m.0) + } + /// The spawner's NBT with `entity` as its only potential and next spawn. + fn nbt(&self, entity: &Compound) -> Compound { + let mut data = Compound::new(); + data.insert("entity".into(), Tag::Compound(entity.clone())); + if let Some(rules) = &self.rules { + data.insert("custom_spawn_rules".into(), Tag::Compound(rules.clone())); + } + let mut potential = Compound::new(); + potential.insert("data".into(), Tag::Compound(data.clone())); + potential.insert("weight".into(), Tag::Int(1)); + let mut nbt: Compound = SPAWNER_FIELDS + .iter() + .zip(self.fields) + .map(|((_, key, _), v)| (JavaString::from(*key), Tag::Short(v))) + .collect(); + nbt.insert( + "SpawnPotentials".into(), + Tag::List(vec![Tag::Compound(potential)]), + ); + nbt.insert("SpawnData".into(), Tag::Compound(data)); + nbt + } +} + fn holder_set( value: &Value, bindings: &FeatureBlockBindings<'_>, @@ -208,55 +710,8 @@ impl Processor { .iter() .map(|rule| { let test = |key| RuleTest::from_json(&rule[key].to_string(), bindings); - let position = match rule.get("position_predicate") { - Some(p) => match p["predicate_type"] - .as_str() - .unwrap_or("minecraft:always_true") - { - "minecraft:always_true" => PosRule::Always, - kind @ ("minecraft:linear_pos" - | "minecraft:axis_aligned_linear_pos") => PosRule::Linear { - min_chance: p - .get("min_chance") - .and_then(Value::as_f64) - .unwrap_or(0.) - as f32, - max_chance: p - .get("max_chance") - .and_then(Value::as_f64) - .unwrap_or(0.) - as f32, - min_dist: p.get("min_dist").and_then(Value::as_i64).unwrap_or(0) - as i32, - max_dist: p.get("max_dist").and_then(Value::as_i64).unwrap_or(0) - as i32, - axis: (kind == "minecraft:axis_aligned_linear_pos").then( - || match p.get("axis").and_then(Value::as_str) { - Some("x") => 0, - Some("z") => 2, - _ => 1, - }, - ), - }, - _ => return Err(DecodeError::Field("position predicate")), - }, - None => PosRule::Always, - }; - let modifier = match rule.get("block_entity_modifier") { - None => Modifier::Passthrough, - Some(m) => match m["type"].as_str().unwrap_or("") { - "minecraft:passthrough" => Modifier::Passthrough, - "minecraft:clear" => Modifier::Clear, - "minecraft:append_loot" => Modifier::AppendLoot( - m["loot_table"].as_str().unwrap_or_default().to_owned(), - ), - "minecraft:append_static" => match json_to_nbt(&m["data"]) { - Tag::Compound(c) => Modifier::AppendStatic(c), - _ => Modifier::AppendStatic(Compound::new()), - }, - _ => return Err(DecodeError::Field("block entity modifier")), - }, - }; + let position = PosRule::decode(rule.get("position_predicate"))?; + let modifier = Modifier::decode(rule.get("block_entity_modifier"))?; Ok(Rule { input: test("input_predicate")?, location: test("location_predicate")?, @@ -267,6 +722,28 @@ impl Processor { }) .collect::<Result<_, DecodeError>>()?, ), + "horizon:spawner_mobs" => { + Self::SpawnerMobs(Box::new(SpawnerMobs::decode(value, |v| match v { + Some(v) => state(v), + None => Ok(resources.registry.default_state("minecraft:air").unwrap()), + })?)) + } + "horizon:pick" => Self::Pick(Box::new(Pick::decode(value, state)?)), + "horizon:block_swap" => Self::BlockSwap( + value["blocks"] + .as_object() + .ok_or(DecodeError::Field("blocks"))? + .iter() + .map(|(from, to)| { + let to = to.as_str().ok_or(DecodeError::Field("blocks"))?; + Ok(( + super::super::tags::identifier(from)?.to_string(), + super::super::tags::identifier(to)?.to_string(), + )) + }) + .collect::<Result<_, DecodeError>>()?, + ), + "horizon:count_cap" => Self::CountCap(Box::new(CountCap::decode(value, state)?)), _ => return Err(DecodeError::Field("structure processor type")), }) } @@ -320,6 +797,8 @@ pub struct PlaceSettings<'a> { /// StructurePlaceSettings.ignoreEntities / finalizeEntities. pub ignore_entities: bool, pub finalize_entities: bool, + /// The blocks `horizon:count_cap` kept in this placement. + counted: u32, } impl<'a> PlaceSettings<'a> { pub fn new(rotation: Rotation) -> Self { @@ -334,6 +813,7 @@ impl<'a> PlaceSettings<'a> { known_shape: false, ignore_entities: false, finalize_entities: false, + counted: 0, } } pub fn with_processors(mut self, list: &'a ProcessorList) -> Self { @@ -355,6 +835,30 @@ impl<'a> PlaceSettings<'a> { } } +/// Block.withPropertiesOf: `block`'s default state with each property of +/// `from` it has too (by name, when the value is one of its own). None for +/// a block the registry does not know (the mod keeps the block then). +fn with_properties_of( + registry: &crate::registry::BlockRegistry, + block: &str, + from: BlockStateId, +) -> Option<BlockStateId> { + let default = registry.default_state(block)?; + let mut state = registry.state(default)?.clone(); + for (key, value) in ®istry.state(from)?.properties { + if let Some(own) = state.properties.get(key) + && own != value + { + let mut changed = state.clone(); + changed.properties.insert(key.clone(), value.clone()); + if registry.id(&changed).is_some() { + state = changed; + } + } + } + registry.id(&state) +} + /// BlackstoneReplaceProcessor's block map. fn blackstone(name: &str) -> Option<&'static str> { Some(match name.strip_prefix("minecraft:")? { @@ -469,42 +973,9 @@ fn process_block<W: PlacementContext>( if !rule.location.test(located, info.pos, &mut random) { continue; } - let position_ok = match &rule.position { - PosRule::Always => true, - PosRule::Linear { - min_chance, - max_chance, - min_dist, - max_dist, - axis, - } => { - let dist = match axis { - None => (0..3) - .map(|i| (info.pos[i] - reference[i]).abs()) - .sum::<i32>(), - Some(a) => { - let d: [f32; 3] = std::array::from_fn(|i| { - if i == *a { - ((info.pos[i] - reference[i]) as f32).abs() - } else { - 0. - } - }); - (d[0] + d[1] + d[2]) as i32 - } - }; - let roll = random.next_float(); - let t = (dist - min_dist) as f32 / (max_dist - min_dist) as f32; - let chance = if t < 0. { - *min_chance - } else if t > 1. { - *max_chance - } else { - min_chance + t * (max_chance - min_chance) - }; - roll <= chance - } - }; + let position_ok = rule + .position + .test(relative, info.pos, reference, &mut random); if !position_ok { continue; } @@ -517,10 +988,9 @@ fn process_block<W: PlacementContext>( nbt.insert("LootTableSeed".into(), Tag::Long(random.next_long())); Some(nbt) } - Modifier::AppendStatic(data) => { - let mut nbt = info.nbt.clone().unwrap_or_default(); - nbt.extend(data.clone()); - Some(nbt) + Modifier::AppendStatic(data) => Some(edited(info.nbt.as_ref(), &[], data)), + Modifier::Edit { remove, data } => { + Some(edited(info.nbt.as_ref(), remove, data)) } }; return Ok(Some(BlockInfo { @@ -532,6 +1002,54 @@ fn process_block<W: PlacementContext>( Some(info) } Processor::Capped { .. } => Some(info), + Processor::BlockSwap(blocks) => { + let swapped = blocks + .get(name(info.state)) + .and_then(|to| with_properties_of(registry, to, info.state)); + Some(match swapped { + Some(state) => BlockInfo { state, ..info }, + None => info, + }) + } + Processor::CountCap(cap) => match cap.blocks.contains(name(info.state)) { + true => { + let pos = info.pos; + let mut counted = settings.counted; + let keep = cap.keeps(&mut counted, || settings.with_random(pos, |r| r.float())); + settings.counted = counted; + Some(match keep { + true => info, + false => BlockInfo { + pos, + state: cap.replacement, + nbt: None, + }, + }) + } + false => Some(info), + }, + Processor::Pick(pick) => match name(info.state) == pick.block { + true => Some(settings.with_random(info.pos, |r| pick.apply(info, r))), + false => Some(info), + }, + Processor::SpawnerMobs(spawner) => { + if name(info.state) != "minecraft:spawner" { + return Ok(Some(info)); + } + let pos = info.pos; + let entity = spawner.pick(|| settings.with_random(pos, |r| r.float())); + Some(match entity { + Some(entity) => BlockInfo { + nbt: Some(spawner.nbt(entity)), + ..info + }, + None => BlockInfo { + pos, + state: spawner.replacement, + nbt: None, + }, + }) + } }) } fn block_age( @@ -631,6 +1149,7 @@ fn process_infos<W: PlacementContext>( reference: [i32; 3], settings: &mut PlaceSettings<'_>, ) -> Result<Vec<BlockInfo>, PlacementQueryError> { + settings.counted = 0; let whole = settings .processors .iter() @@ -1021,3 +1540,365 @@ fn update_shape_at_edge<W: PlacementContext>( } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn spawner(value: Value) -> SpawnerMobs { + SpawnerMobs::decode(&value, |v| { + assert_eq!(v, Some(&json!({"id": "minecraft:cobblestone"}))); + Ok(BlockStateId(7)) + }) + .unwrap() + } + fn id(entity: Option<&Compound>) -> Option<String> { + match entity?.get(&JavaString::from("id")) { + Some(Tag::String(s)) => Some(s.to_string_lossy()), + _ => None, + } + } + + #[test] + fn spawner_mobs_pick_by_weight() { + let s = spawner(json!({ + "mobs": [ + {"entity": {"id": "minecraft:zombie"}, "weight": 1}, + {"entity": {"id": "minecraft:husk"}, "weight": 3}], + "replacement": {"id": "minecraft:cobblestone"}})); + // pick = nextFloat * 4, less each weight in turn, until <= 0. + for (r, mob) in [ + (0., "zombie"), + (0.25, "zombie"), + (0.2501, "husk"), + (0.999, "husk"), + ] { + assert_eq!(id(s.pick(|| r)), Some(format!("minecraft:{mob}")), "{r}"); + } + let empty = spawner(json!({"mobs": [], "replacement": {"id": "minecraft:cobblestone"}})); + assert_eq!(empty.pick(|| unreachable!()), None); + assert_eq!(empty.replacement, BlockStateId(7)); + } + + #[test] + fn spawner_mobs_write_the_mods_nbt() { + let s = spawner(json!({ + "mobs": [{"entity": {"id": "minecraft:skeleton", "Health": 30}, "weight": 2}], + "delay": 10, "spawn_count": 2, + "custom_spawn_rules": {"block_light_limit": {"min_inclusive": 0, "max_inclusive": 7}}, + "replacement": {"id": "minecraft:cobblestone"}})); + let nbt = s.nbt(s.pick(|| 0.5).unwrap()); + let short = |k: &str| nbt.get(&JavaString::from(k)).cloned(); + for (k, v) in [ + ("Delay", 10), + ("MinSpawnDelay", 200), + ("MaxSpawnDelay", 800), + ("SpawnCount", 2), + ("MaxNearbyEntities", 6), + ("RequiredPlayerRange", 16), + ("SpawnRange", 4), + ] { + assert_eq!(short(k), Some(Tag::Short(v)), "{k}"); + } + let Some(Tag::Compound(data)) = short("SpawnData") else { + panic!("SpawnData") + }; + assert!(data.contains_key(&JavaString::from("custom_spawn_rules"))); + let Some(Tag::Compound(entity)) = data.get(&JavaString::from("entity")) else { + panic!("entity") + }; + assert_eq!(entity.get(&JavaString::from("Health")), Some(&Tag::Int(30))); + let Some(Tag::List(potentials)) = short("SpawnPotentials") else { + panic!("SpawnPotentials") + }; + let Tag::Compound(potential) = &potentials[0] else { + panic!("potential") + }; + assert_eq!( + potential.get(&JavaString::from("weight")), + Some(&Tag::Int(1)) + ); + assert_eq!( + potential.get(&JavaString::from("data")), + Some(&Tag::Compound(data.clone())) + ); + } + + #[test] + fn spawner_mobs_refuse_a_mob_without_an_id() { + let bad = json!({"mobs": [{"entity": {}, "weight": 1}]}); + assert!(SpawnerMobs::decode(&bad, |_| Ok(BlockStateId(0))).is_err()); + } + + #[test] + fn repurposed_position_rules() { + let decode = |v: Value| PosRule::decode(Some(&v)); + // Over 3..4 blocks from the template's origin along y, 0 to 1. + let rule = decode( + json!({"predicate_type": "horizon:piece_origin_axis_aligned_linear_pos", + "axis": "y", "min_chance": 0, "max_chance": 1, "min_dist": 3, "max_dist": 4}), + ) + .unwrap(); + let mut random = LegacyRandom::new(1); + let world = [100, 64, -100]; + // At or under min_dist the chance is 0, a roll of 0 aside; past max_dist it is 1. + assert!(!rule.test([9, 2, 9], world, world, &mut random)); + assert!(rule.test([0, -5, 0], world, world, &mut random)); + // The world position and the piece's do not count. + assert!(rule.test([0, 4, 0], [0, 0, 0], [50, 50, 50], &mut random)); + // Repurposed refuses an empty distance range and an unknown axis. + for bad in [ + json!({"predicate_type": "horizon:piece_origin_axis_aligned_linear_pos"}), + json!({"predicate_type": "horizon:piece_origin_axis_aligned_linear_pos", + "min_dist": 0, "max_dist": 1, "axis": "w"}), + json!({"predicate_type": "horizon:y_value", "min_y_value": 5, "max_y_value": 4}), + json!({"predicate_type": "horizon:y_value", "min_y_value": 5}), + ] { + assert!(decode(bad.clone()).is_err(), "{bad}"); + } + let y = decode( + json!({"predicate_type": "horizon:y_value", "min_y_value": 0, "max_y_value": 31}), + ) + .unwrap(); + assert!(y.test([0; 3], [7, 31, 7], [0; 3], &mut random)); + assert!(y.test([0, 99, 0], [7, 0, 7], [0; 3], &mut random)); + assert!(!y.test([0; 3], [7, 32, 7], [0; 3], &mut random)); + assert!(!y.test([0; 3], [7, -1, 7], [0; 3], &mut random)); + } + + #[test] + fn rule_parts_read_ids_without_a_namespace() { + // CTOV writes "always_true"; vanilla reads it as minecraft:always_true. + for kind in ["always_true", "minecraft:always_true"] { + let p = json!({"predicate_type": kind}); + assert!( + matches!(PosRule::decode(Some(&p)), Ok(PosRule::Always)), + "{kind}" + ); + } + let linear = json!({"predicate_type": "axis_aligned_linear_pos", "axis": "z", + "min_chance": 0.1, "max_dist": 8}); + assert!(matches!( + PosRule::decode(Some(&linear)), + Ok(PosRule::Linear { + axis: Some(2), + max_dist: 8, + .. + }) + )); + assert!(PosRule::decode(Some(&json!({"predicate_type": "x:unknown"}))).is_err()); + assert!(matches!(PosRule::decode(None), Ok(PosRule::Always))); + let loot = json!({"type": "append_loot", "loot_table": "minecraft:chests/x"}); + assert!( + matches!(Modifier::decode(Some(&loot)), Ok(Modifier::AppendLoot(t)) if t == "minecraft:chests/x") + ); + assert!(matches!( + Modifier::decode(Some(&json!({"type": "clear"}))), + Ok(Modifier::Clear) + )); + assert!(Modifier::decode(Some(&json!({"type": ""}))).is_err()); + } + + #[test] + fn block_entity_edits_merge_deep_and_drop_keys() { + let nbt = |v: Value| match json_to_nbt(&v) { + Tag::Compound(c) => c, + _ => unreachable!(), + }; + let vault = nbt(json!({"id": "minecraft:vault", + "config": {"loot_table": "x:old", "key_item": {"id": "minecraft:trial_key"}}, + "server_data": {"state_updating_resumes_at": 533162741}})); + // append_static merges compounds the way CompoundTag.merge does. + let Ok(Modifier::AppendStatic(data)) = Modifier::decode(Some(&json!({ + "type": "append_static", "data": {"config": {"loot_table": "x:new"}}}))) + else { + panic!("append_static") + }; + let merged = edited(Some(&vault), &[], &data); + assert_eq!( + merged, + nbt(json!({"id": "minecraft:vault", + "config": {"loot_table": "x:new", "key_item": {"id": "minecraft:trial_key"}}, + "server_data": {"state_updating_resumes_at": 533162741}})) + ); + let Ok(Modifier::Edit { remove, data }) = Modifier::decode(Some(&json!({ + "type": "horizon:edit", "remove": ["server_data"], + "data": {"config": {"loot_table": "x:new"}}}))) + else { + panic!("horizon:edit") + }; + assert_eq!( + edited(Some(&vault), &remove, &data), + nbt(json!({"id": "minecraft:vault", + "config": {"loot_table": "x:new", "key_item": {"id": "minecraft:trial_key"}}})) + ); + assert_eq!( + edited(None, &remove, &data), + nbt(json!({"config": {"loot_table": "x:new"}})) + ); + let bad = json!({"type": "horizon:edit", "remove": [1], "data": {}}); + assert!(Modifier::decode(Some(&bad)).is_err()); + } + + /// Scripted draws: floats in turn, then ints. + struct Draws(Vec<f32>, Vec<i32>); + impl ProcessorRandom for Draws { + fn float(&mut self) -> f32 { + self.0.remove(0) + } + fn int(&mut self, bound: i32) -> i32 { + let i = self.1.remove(0); + assert!(i < bound); + i + } + fn long(&mut self) -> i64 { + unreachable!() + } + } + + #[test] + fn picks_follow_yungs_cascade() { + // States by name: sand 1, sandstone 2, the four stairs 10..13. + let id = |v: &Value| { + Ok(BlockStateId(match v["Name"].as_str() { + Some("minecraft:sand") => 1, + Some("minecraft:sandstone") => 2, + Some("minecraft:suspicious_sand") => 3, + _ => { + 10 + ["north", "east", "south", "west"] + .iter() + .position(|f| v["Properties"]["facing"] == *f) + .unwrap_or(9) as u32 + } + })) + }; + let stairs: Vec<Value> = ["north", "east", "south", "west"] + .iter() + .map(|f| json!({"Name": "minecraft:sandstone_stairs", "Properties": {"facing": f}})) + .collect(); + let pick = Pick::decode( + &json!({"block": "red_stained_glass", "picks": [ + {"below": 0.01, "state": {"Name": "minecraft:suspicious_sand"}, + "nbt": {"LootTable": "minecraft:archaeology/desert_pyramid"}}, + {"below": 0.3, "state": {"Name": "minecraft:sand"}}, + {"below": 0.75, "state": {"Name": "minecraft:sandstone"}}], + "default": {"states": stairs}}), + id, + ) + .unwrap(); + assert_eq!(pick.block, "minecraft:red_stained_glass"); + let glass = || BlockInfo { + pos: [1, 2, 3], + state: BlockStateId(0), + nbt: Some(Compound::new()), + }; + let run = |f: f32, i: Vec<i32>| pick.apply(glass(), &mut Draws(vec![f], i)); + let sus = run(0.005, vec![]); + assert_eq!(sus.state, BlockStateId(3)); + assert!( + sus.nbt + .unwrap() + .contains_key(&JavaString::from("LootTable")) + ); + assert_eq!(run(0.01, vec![]).state, BlockStateId(1)); + assert_eq!(run(0.2999, vec![]).nbt, Some(Compound::new())); + assert_eq!(run(0.3, vec![]).state, BlockStateId(2)); + // The stairs' facing: Plane.HORIZONTAL[nextInt(4)] after the pick. + assert_eq!(run(0.75, vec![2]).state, BlockStateId(12)); + assert_eq!(run(0.99, vec![1]).state, BlockStateId(11)); + + let pot = Pick::decode( + &json!({"block": "minecraft:decorated_pot", "default": { + "state": {"Name": "minecraft:sand"}, + "lists": [{"key": "sherds", "count": 4, "default": "minecraft:brick", + "values": [{"below": 0.05, "value": "minecraft:archer_pottery_sherd"}, + {"below": 0.1, "value": "minecraft:miner_pottery_sherd"}]}]}}), + id, + ) + .unwrap(); + // No picks: no float for them; one float per sherd. + let out = pot.apply( + BlockInfo { + nbt: None, + ..glass() + }, + &mut Draws(vec![0.5, 0.01, 0.07, 0.1], vec![]), + ); + let Some(Tag::List(sherds)) = out.nbt.unwrap().get(&JavaString::from("sherds")).cloned() + else { + panic!("sherds") + }; + let names: Vec<String> = sherds + .iter() + .map(|t| match t { + Tag::String(s) => s.to_string_lossy(), + _ => String::new(), + }) + .collect(); + assert_eq!( + names, + [ + "minecraft:brick", + "minecraft:archer_pottery_sherd", + "minecraft:miner_pottery_sherd", + "minecraft:brick" + ] + ); + assert!(Pick::decode(&json!({"block": "a", "default": {"states": []}}), id).is_err()); + } + + #[test] + fn count_caps_keep_the_first_then_some() { + let cap = CountCap::decode( + &json!({"blocks": ["chest", "minecraft:trapped_chest"], "min": 1, "max": 2, + "chance": 0.2, "replacement": {"id": "minecraft:cave_air"}}), + |_| Ok(BlockStateId(5)), + ) + .unwrap(); + assert!(cap.blocks.contains("minecraft:chest")); + let mut counted = 0; + // The first stays without a roll. + assert!(cap.keeps(&mut counted, || unreachable!())); + // Then each stays on nextFloat <= 0.2, until two have. + assert!(!cap.keeps(&mut counted, || 0.21)); + assert!(cap.keeps(&mut counted, || 0.2)); + assert!(!cap.keeps(&mut counted, || unreachable!())); + assert_eq!(counted, 2); + assert!( + CountCap::decode(&json!({"blocks": [], "min": -1}), |_| Ok(BlockStateId(5))).is_err() + ); + } + + #[test] + fn block_swaps_keep_the_properties_both_blocks_have() { + let row = |name: &str, props: Value| json!([name, false, false, "", {"id": name, "properties": props}]); + let facts = json!({"defaults": {"a:log": 1, "a:stairs": 4, "a:stone": 6}, + "states": [ + row("a:log", json!({"axis": "x"})), row("a:log", json!({"axis": "y"})), + row("a:stairs", json!({"facing": "east", "half": "top"})), + row("a:stairs", json!({"facing": "east", "half": "bottom"})), + row("a:stairs", json!({"facing": "north", "half": "bottom"})), + row("a:stairs", json!({"facing": "north", "half": "top"})), + ["a:stone", false, false, "", "a:stone"]]}); + let registry = + crate::registry::BlockRegistry::from_facts_json(facts.to_string().as_bytes()).unwrap(); + // facing and half carried over; the default where `from` has none. + assert_eq!( + with_properties_of(®istry, "a:stairs", BlockStateId(2)), + Some(BlockStateId(2)) + ); + assert_eq!( + with_properties_of(®istry, "a:stairs", BlockStateId(0)), + Some(BlockStateId(4)) + ); + assert_eq!( + with_properties_of(®istry, "a:stone", BlockStateId(5)), + Some(BlockStateId(6)) + ); + assert_eq!( + with_properties_of(®istry, "a:missing", BlockStateId(0)), + None + ); + } +} diff --git a/crates/horizon-world/src/worldgen/structure/start.rs b/crates/horizon-world/src/worldgen/structure/start.rs index 1b443eba5..3d61bf168 100644 --- a/crates/horizon-world/src/worldgen/structure/start.rs +++ b/crates/horizon-world/src/worldgen/structure/start.rs @@ -55,6 +55,13 @@ pub struct JigsawDef { aliases: Vec<Value>, padding: [i32; 2], waterlogging: bool, + /// A carried mod's start rules (`"horizon:start_checks"`). + checks: super::start_checks::StartChecks, + /// Laid out by YUNG's API's assembler (`"horizon:yungsapi"`). + yung: Option<super::yung::Config>, + /// Laid out by Repurposed Structures' and Moog's piece-limited + /// assembler (`"horizon:piece_limited"`). + piece_limited: Option<super::piece_limited::Config>, } #[derive(Debug)] pub enum StructureKind { @@ -95,6 +102,9 @@ pub struct StructureDef { pub biomes: BTreeSet<BiomeId>, pub step: usize, pub terrain: TerrainAdjustment, + /// Another loaded structure turns this one's type off + /// (`"horizon:disables"`): it never starts. + pub disabled: bool, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Reduction { @@ -129,6 +139,113 @@ pub struct StructureSet { frequency: f32, reduction: Reduction, exclusion: Option<(String, i32)>, + /// A carried mod's placement rules: no start nearer the world origin + /// than this many blocks (`"horizon:min_distance_from_world_origin"`), + /// and none within `chunk_count` chunks of any of several sets + /// (`"horizon:exclusion_zone"`: `other_sets`, `chunk_count`). + min_distance: Option<i64>, + avoid: Option<(Vec<String>, i32)>, + /// `"horizon:ring_sections"`: starts only in odd rings around the origin. + rings: Option<RingSections>, + /// `"horizon:avoid_biomes"`: no start with one of these biomes near. + avoid_biomes: Option<AvoidBiomes>, +} + +/// YUNG's Better Strongholds' placement (BetterStrongholdsPlacement +/// .isPlacementChunk): the world is cut into rings `thickness` chunks wide, +/// the first one starting `distance_to_first_ring` chunks out; a start is +/// placed only in the odd ones, and in none past `max_section`. +/// +/// ```json +/// "horizon:ring_sections": {"distance_to_first_ring": 80, "thickness": 96, "max_section": 5} +/// ``` +#[derive(Debug, Clone, PartialEq, Eq)] +struct RingSections { + first: i32, + thickness: i32, + max: Option<i32>, +} +impl RingSections { + fn decode(v: &Value) -> Self { + let int = |k: &str| v[k].as_i64().map(|n| n as i32); + Self { + first: int("distance_to_first_ring").unwrap_or(0), + thickness: int("thickness").unwrap_or(1).max(1), + max: int("max_section"), + } + } + fn allows(&self, x: i32, z: i32) -> bool { + // Java int arithmetic: the squares wrap past 46,340 chunks, and the + // square root of a negative int is NaN, which casts to 0. + let squared = x.wrapping_mul(x).wrapping_add(z.wrapping_mul(z)); + let distance = f64::from(squared).sqrt() as i32; + let section = distance.wrapping_add(self.thickness - self.first) / self.thickness; + !self.max.is_some_and(|max| section > max) && section % 2 == 1 + } +} + +/// YUNG's Better Desert and Jungle Temples' placement: no start when a +/// biome of the set is found around the chunk's middle block at height `y` +/// (BiomeSource.findBiomeHorizontal with `radius` blocks and `step` quarts +/// between samples, closest first). +/// +/// ```json +/// "horizon:avoid_biomes": {"biomes": ["#minecraft:is_river", "#minecraft:is_ocean"], +/// "radius": 48, "step": 2, "y": 120} +/// ``` +#[derive(Debug)] +struct AvoidBiomes { + biomes: BTreeSet<BiomeId>, + radius: i32, + step: i32, + y: i32, +} +impl AvoidBiomes { + fn decode( + v: &Value, + biome_set: &dyn Fn(&Value) -> Result<BTreeSet<BiomeId>, DecodeError>, + ) -> Result<Self, DecodeError> { + let mut biomes = BTreeSet::new(); + match &v["biomes"] { + Value::Array(list) => { + for entry in list { + biomes.extend(biome_set(entry)?); + } + } + other => biomes = biome_set(other)?, + } + let int = |k: &str, default: i32| v[k].as_i64().map_or(default, |n| n as i32); + Ok(Self { + biomes, + radius: int("radius", 0), + step: int("step", 1).max(1), + y: int("y", 0), + }) + } + fn near(&self, chunk: ChunkPos, mut biome: impl FnMut([i32; 3]) -> BiomeId) -> bool { + // ChunkPos.getMiddleBlockPosition, then QuartPos.fromBlock. + let (cx, cz) = ((chunk.x * 16 + 8) >> 2, (chunk.z * 16 + 8) >> 2); + let (radius, y) = (self.radius >> 2, self.y >> 2); + let mut r = 0; + while r <= radius { + let mut dz = -r; + while dz <= r { + let z_edge = dz.abs() == r; + let mut dx = -r; + while dx <= r { + if (z_edge || dx.abs() == r) + && self.biomes.contains(&biome([cx + dx, y, cz + dz])) + { + return true; + } + dx += self.step; + } + dz += self.step; + } + r += self.step; + } + false + } } fn heightmap(name: &str) -> Option<HeightmapType> { @@ -174,8 +291,19 @@ impl StructureRegistry { biome_set: &dyn Fn(&Value) -> Result<BTreeSet<BiomeId>, DecodeError>, ) -> Result<Self, DecodeError> { let mut defs = Vec::new(); + let (mut types, mut disables) = (Vec::new(), BTreeSet::new()); for (name, json) in structures { let v: Value = serde_json::from_str(json)?; + types.push(v["type"].as_str().unwrap_or_default().to_owned()); + // YUNG's mods turn their vanilla counterparts off (the + // DisableVanilla*Mixin on ChunkGenerator.tryGenerateStructure). + disables.extend( + v["horizon:disables"] + .as_array() + .into_iter() + .flatten() + .filter_map(|t| Some(t.as_str()?.to_owned())), + ); let kind = match v["type"].as_str().unwrap_or_default() { "minecraft:jigsaw" => StructureKind::Jigsaw(JigsawDef { start_pool: v["start_pool"].as_str().unwrap_or_default().to_owned(), @@ -193,6 +321,11 @@ impl StructureRegistry { aliases: v["pool_aliases"].as_array().cloned().unwrap_or_default(), padding: pair(v.get("dimension_padding"), "bottom", "top", 0), waterlogging: v["liquid_settings"].as_str() != Some("ignore_waterlogging"), + checks: super::start_checks::StartChecks::decode(v.get("horizon:start_checks")), + yung: v.get("horizon:yungsapi").map(super::yung::Config::decode), + piece_limited: v + .get("horizon:piece_limited") + .map(super::piece_limited::Config::decode), }), "minecraft:buried_treasure" => StructureKind::BuriedTreasure, "minecraft:igloo" => StructureKind::Igloo, @@ -242,8 +375,12 @@ impl StructureRegistry { .position(|s| Some(*s) == v["step"].as_str()) .unwrap_or(4), terrain: terrain(v["terrain_adaptation"].as_str()), + disabled: false, }); } + for (def, kind) in defs.iter_mut().zip(&types) { + def.disabled = disables.contains(kind); + } let index = |name: &str| defs.iter().position(|d| d.name == name); let mut out = Vec::new(); for (name, json) in sets { @@ -291,6 +428,25 @@ impl StructureRegistry { z["chunk_count"].as_i64().unwrap_or(0) as i32, ) }), + min_distance: p + .get("horizon:min_distance_from_world_origin") + .and_then(Value::as_i64), + avoid: p.get("horizon:exclusion_zone").map(|z| { + ( + z["other_sets"] + .as_array() + .into_iter() + .flatten() + .filter_map(|s| Some(s.as_str()?.to_owned())) + .collect(), + z["chunk_count"].as_i64().unwrap_or(0) as i32, + ) + }), + rings: p.get("horizon:ring_sections").map(RingSections::decode), + avoid_biomes: p + .get("horizon:avoid_biomes") + .map(|a| AvoidBiomes::decode(a, biome_set)) + .transpose()?, }); } Ok(Self { @@ -397,26 +553,50 @@ impl StructureRegistry { if !placed { return false; } + if set.rings.as_ref().is_some_and(|r| !r.allows(x, z)) { + return false; + } + // AdvancedRandomSpread.isPlacementChunk, in blocks from the chunk's corner. + if let Some(d) = set.min_distance { + let (bx, bz) = (i64::from(x) * 16, i64::from(z) * 16); + if bx * bx + bz * bz < d * d { + return false; + } + } + if let Some((others, range)) = &set.avoid { + if others + .iter() + .any(|other| self.has_start_in_range(other, seed, x, z, *range, rings)) + { + return false; + } + } if set.frequency < 1. && !reduce(set.reduction, seed, set.salt, x, z, set.frequency) { return false; } match &set.exclusion { - Some((other, range)) => { - let Some(other) = self.sets.iter().find(|s| s.name == *other) else { - return true; - }; - for tx in x - range..=x + range { - for tz in z - range..=z + range { - if self.is_structure_chunk(other, seed, tx, tz, rings) { - return false; - } - } - } - true - } + Some((other, range)) => !self.has_start_in_range(other, seed, x, z, *range, rings), None => true, } } + /// ChunkGeneratorStructureState.hasStructureChunkInRange: whether set + /// `other` places a structure within `range` chunks of (`x`, `z`). + fn has_start_in_range( + &self, + other: &str, + seed: i64, + x: i32, + z: i32, + range: i32, + rings: &Rings, + ) -> bool { + let Some(other) = self.sets.iter().find(|s| s.name == other) else { + return false; + }; + (x - range..=x + range).any(|tx| { + (z - range..=z + range).any(|tz| self.is_structure_chunk(other, seed, tx, tz, rings)) + }) + } } impl StructureSet { /// The random spread's spacing in chunks (`None` for rings). @@ -547,6 +727,16 @@ pub fn create_starts( if !registry.is_structure_chunk(set, seed, chunk.x, chunk.z, rings) { continue; } + // Part of the set's placement in YUNG's mods; checked here, where the + // biome source is at hand, so another set's exclusion zone naming + // this one does not see it. + if set + .avoid_biomes + .as_ref() + .is_some_and(|a| a.near(chunk, |q| context.noise_biome(q))) + { + continue; + } if set.structures.len() == 1 { if let Some(start) = try_generate( registry, @@ -596,6 +786,9 @@ fn try_generate( chunk: ChunkPos, ) -> Option<StructureStart> { let def = ®istry.structures[structure]; + if def.disabled { + return None; + } context.set_valid_biomes(&def.biomes); let seed = context.seed(); let mut random = WorldgenRandom::new(LegacyRandom::new(0)); @@ -606,6 +799,12 @@ fn try_generate( .start_height .sample(&mut random, context.generation()) .ok()?; + if !jigsaw + .checks + .pass(context, &def.biomes, chunk, height, jigsaw.project_to) + { + return None; + } let start = [chunk.x * 16, height, chunk.z * 16]; let aliases = resolve_aliases(&jigsaw.aliases, start, seed); let config = JigsawConfig { @@ -619,16 +818,40 @@ fn try_generate( padding: jigsaw.padding, waterlogging: jigsaw.waterlogging, }; - let (position, mut pieces) = assemble( - &config, - context, - ®istry.pools, - resources, - bindings, - &mut random, - start, - )?; - if jigsaw.max_depth <= 0 { + let (position, mut pieces) = match (&jigsaw.yung, &jigsaw.piece_limited) { + (_, Some(limits)) => super::piece_limited::assemble( + &config, + limits, + context, + ®istry.pools, + resources, + bindings, + chunk, + start, + )?, + (Some(yung), None) => super::yung::assemble( + &config, + yung, + context, + ®istry.pools, + resources, + bindings, + &mut random, + start, + )?, + (None, None) => assemble( + &config, + context, + ®istry.pools, + resources, + bindings, + &mut random, + start, + )?, + }; + // Vanilla's JigsawPlacement keeps no piece at size 0; the + // piece-limited assembler keeps the start piece. + if jigsaw.max_depth <= 0 && jigsaw.piece_limited.is_none() { pieces.clear(); } ( @@ -1064,3 +1287,106 @@ pub fn place_in_chunk<W: FeatureWorld + PlacementContext, R: RandomSource + 'sta } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn registry(structures: &[(&str, Value)], sets: &[(&str, Value)]) -> StructureRegistry { + let text = |l: &[(&str, Value)]| { + l.iter() + .map(|(k, v)| ((*k).to_owned(), v.to_string())) + .collect::<BTreeMap<_, _>>() + }; + // Biome tags: `#t:one` is biome 1, `#t:two` biome 2. + StructureRegistry::new(&text(structures), &text(sets), BTreeMap::new(), &|v| { + Ok(match v.as_str() { + Some("#t:one") => BTreeSet::from([BiomeId(1)]), + Some("#t:two") => BTreeSet::from([BiomeId(2)]), + _ => BTreeSet::new(), + }) + }) + .unwrap() + } + + #[test] + fn a_structure_turns_its_vanilla_counterpart_off() { + let r = registry( + &[ + ( + "minecraft:pyramid", + json!({"type": "minecraft:desert_pyramid"}), + ), + ("minecraft:igloo", json!({"type": "minecraft:igloo"})), + ( + "yung:temple", + json!({"type": "minecraft:swamp_hut", "horizon:disables": ["minecraft:desert_pyramid"]}), + ), + ], + &[], + ); + let disabled: Vec<_> = r + .structures + .iter() + .map(|d| (d.name.as_str(), d.disabled)) + .collect(); + assert_eq!( + disabled, + [ + ("minecraft:igloo", false), + ("minecraft:pyramid", true), + ("yung:temple", false) + ] + ); + } + + #[test] + fn ring_sections_keep_the_odd_rings() { + let rings = RingSections::decode( + &json!({"distance_to_first_ring": 80, "thickness": 96, "max_section": 3}), + ); + // (d + 16) / 96: 0 inside 80 chunks, 1 to 175, 2 to 271, 3 to 367. + assert!(!rings.allows(79, 0)); + assert!(rings.allows(80, 0)); + assert!(rings.allows(0, -175)); + assert!(!rings.allows(176, 0)); + assert!(rings.allows(272, 0)); + assert!(!rings.allows(464, 0), "section 5 is past max_section 3"); + // Java's int square wraps: 50,000² + 0 is negative, its root NaN, 0. + assert!(!rings.allows(50_000, 0)); + let open = RingSections::decode(&json!({"distance_to_first_ring": 80, "thickness": 96})); + assert!(open.allows(464, 0)); + } + + #[test] + fn avoid_biomes_samples_around_the_middle_block() { + let r = registry( + &[], + &[( + "yung:temples", + json!({"structures": [], "placement": {"type": "minecraft:random_spread", + "spacing": 24, "separation": 8, "salt": 1, + "horizon:avoid_biomes": {"biomes": ["#t:one", "#t:two"], + "radius": 48, "step": 2, "y": 120}}}), + )], + ); + let avoid = r.sets[0].avoid_biomes.as_ref().unwrap(); + assert_eq!(avoid.biomes, BTreeSet::from([BiomeId(1), BiomeId(2)])); + // Chunk (1, -1): middle block (24, 120, -8), quart (6, 30, -2). + let mut asked = Vec::new(); + assert!(!avoid.near(ChunkPos::new(1, -1), |q| { + asked.push(q); + BiomeId(0) + })); + assert_eq!(asked[0], [6, 30, -2]); + // Every even offset within 12 quarts, once: 13 x 13. + assert_eq!(asked.len(), 169); + assert!(asked.contains(&[6 - 12, 30, -2 + 12])); + assert!(!asked.contains(&[7, 30, -2])); + // An ocean on the edge of the square is found. + assert!(avoid.near(ChunkPos::new(1, -1), |q| { + BiomeId(if q == [18, 30, 10] { 2 } else { 0 }) + })); + } +} diff --git a/crates/horizon-world/src/worldgen/structure/start_checks.rs b/crates/horizon-world/src/worldgen/structure/start_checks.rs new file mode 100644 index 000000000..f182706a8 --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/start_checks.rs @@ -0,0 +1,462 @@ +//! Start rules a carried structure mod adds on top of vanilla's jigsaw. +//! +//! Repurposed Structures and Moog's Structure Lib give their jigsaw +//! structures checks that run before the pieces are laid out: every biome +//! in a radius must be one the structure allows, the start column may not +//! end in liquid, and the terrain in a radius must lie within a height range. +//! Carry (`horizon-port-pack`) maps those structures to `minecraft:jigsaw` +//! and writes the checks under `"horizon:start_checks"`; vanilla data never +//! has the key, so vanilla structures are unchanged. +//! +//! ```json +//! "horizon:start_checks": { +//! "biome_radius": 2, // chunks; every noise biome must be allowed +//! "liquid": "top", // "top": the column's highest block; "lowest": the block above min_y +//! "terrain_radius": 1, // chunks, with terrain_range and/or min_y, max_y +//! "terrain_range": 15, +//! "min_y": 60, +//! "max_y": 200, +//! "repurposed": "city_nether" // or "shipwreck_nether", "stronghold_end": below +//! } +//! ``` +//! +//! `repurposed` is the extra check of one of Repurposed Structures' jigsaw +//! types, after the others: its Nether city needs open air above the lava sea +//! in the chunks around, its Nether shipwreck open air or lava around the +//! start, and its End stronghold land around the chunk. +use crate::{heightmap::HeightmapType, worldgen::biome::BiomeId}; +use horizon_core::position::ChunkPos; +use serde_json::Value; +use std::collections::BTreeSet; + +/// Which block of the start column must not be a liquid. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LiquidCheck { + /// The highest non-air block of the noise column (Moog's). + Top, + /// The block above the column's bottom (Repurposed Structures: its loop + /// keeps the last block it reads, not the first solid one). + Lowest, +} + +/// The extra start check of a Repurposed Structures jigsaw type. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Repurposed { + /// CityNetherStructure: air from sea level + 20 to + 45 (or the top of + /// the noise) at the corner of each of the 8 chunks around. + CityNether, + /// ShipwreckNetherStructure: no solid block at 5×5 columns 8 apart + /// around the chunk corner, from the start height up 30 in steps of 5. + ShipwreckNether, + /// StrongholdEndStructure: land at least 45 above the bottom 35 and 70 + /// blocks away in each direction and at the chunk corner. + StrongholdEnd, +} + +/// The checks of one structure; all empty for vanilla's. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct StartChecks { + biome_radius: Option<i32>, + liquid: Option<LiquidCheck>, + terrain_radius: Option<i32>, + terrain_range: Option<i32>, + min_y: Option<i32>, + max_y: Option<i32>, + repurposed: Option<Repurposed>, +} + +/// The column and biome queries the checks need. +pub trait CheckQueries { + /// ChunkGenerator.getFirstFreeHeight. + fn first_free_height(&mut self, x: i32, z: i32, kind: HeightmapType) -> i32; + /// The noise column at (`x`, `z`) as (not air, blocks motion) per block + /// from the noise's bottom up: in a noise column a block that is not air + /// and does not block motion is a liquid. + fn liquid_column(&mut self, x: i32, z: i32) -> (Vec<bool>, Vec<bool>); + fn noise_biome(&mut self, quart: [i32; 3]) -> BiomeId; + fn sea_level(&self) -> i32; + /// The noise's bottom, where the columns start. + fn bottom(&self) -> i32; +} + +impl<T: super::start::StartContext> CheckQueries for T { + fn first_free_height(&mut self, x: i32, z: i32, kind: HeightmapType) -> i32 { + self.base_height(x, z, kind) + } + fn liquid_column(&mut self, x: i32, z: i32) -> (Vec<bool>, Vec<bool>) { + let mut columns = self.base_columns( + x, + z, + &[HeightmapType::WorldSurfaceWg, HeightmapType::OceanFloorWg], + ); + let solid = columns.pop().unwrap_or_default(); + (columns.pop().unwrap_or_default(), solid) + } + fn noise_biome(&mut self, quart: [i32; 3]) -> BiomeId { + super::start::StartContext::noise_biome(self, quart) + } + fn sea_level(&self) -> i32 { + super::start::StartContext::sea_level(self) + } + fn bottom(&self) -> i32 { + self.min_y() + } +} + +impl StartChecks { + /// `"horizon:start_checks"` of a structure, or none. + pub fn decode(value: Option<&Value>) -> Self { + let Some(v) = value else { + return Self::default(); + }; + let int = |k: &str| v.get(k).and_then(Value::as_i64).map(|n| n as i32); + Self { + biome_radius: int("biome_radius"), + liquid: match v.get("liquid").and_then(Value::as_str) { + Some("top") => Some(LiquidCheck::Top), + Some("lowest") => Some(LiquidCheck::Lowest), + _ => None, + }, + terrain_radius: int("terrain_radius"), + terrain_range: int("terrain_range"), + min_y: int("min_y"), + max_y: int("max_y"), + repurposed: match v.get("repurposed").and_then(Value::as_str) { + Some("city_nether") => Some(Repurposed::CityNether), + Some("shipwreck_nether") => Some(Repurposed::ShipwreckNether), + Some("stronghold_end") => Some(Repurposed::StrongholdEnd), + _ => None, + }, + } + } + + /// GenericJigsawStructure.extraSpawningChecks: whether the structure may + /// start in `chunk` at `y` (the sampled start height). + pub fn pass( + &self, + queries: &mut impl CheckQueries, + biomes: &BTreeSet<BiomeId>, + chunk: ChunkPos, + y: i32, + project_to: Option<HeightmapType>, + ) -> bool { + let (x0, z0) = (chunk.x * 16, chunk.z * 16); + if let Some(radius) = self.biome_radius { + let mut section_y = y; + if let Some(kind) = project_to { + section_y += queries.first_free_height(x0 + 7, z0 + 7, kind) - 1; + } + for cx in chunk.x - radius..=chunk.x + radius { + for cz in chunk.z - radius..=chunk.z + radius { + if !biomes.contains(&queries.noise_biome([cx << 2, section_y >> 2, cz << 2])) { + return false; + } + } + } + } + if let Some(check) = self.liquid { + let (filled, solid) = queries.liquid_column(x0 + 7, z0 + 7); + // From the top down to the block above the bottom, as the mods loop. + let index = match check { + LiquidCheck::Top => (1..filled.len()).rev().find(|&i| filled[i]), + LiquidCheck::Lowest => Some(1).filter(|&i| i < filled.len()), + }; + if index.is_some_and(|i| filled[i] && !solid[i]) { + return false; + } + } + if let Some(radius) = self + .terrain_radius + .filter(|_| self.terrain_range.is_some() || self.min_y.is_some()) + { + let kind = project_to.unwrap_or(HeightmapType::WorldSurfaceWg); + let (mut highest, mut lowest) = (i32::MIN, i32::MAX); + for cx in chunk.x - radius..=chunk.x + radius { + for cz in chunk.z - radius..=chunk.z + radius { + let height = queries.first_free_height((cx << 4) + 7, (cz << 4) + 7, kind); + highest = highest.max(height); + lowest = lowest.min(height); + // Both bounds test the lowest height so far, as the mods do. + if self.min_y.is_some_and(|m| lowest < m) + || self.max_y.is_some_and(|m| lowest > m) + { + return false; + } + } + } + if self + .terrain_range + .is_some_and(|range| highest - lowest > range) + { + return false; + } + } + match self.repurposed { + Some(check) => repurposed(check, queries, chunk, y), + None => true, + } + } +} + +/// [`Repurposed`]'s checks. A noise column reads air past its ends; its +/// length is the noise's depth (GeneralUtils.getMaxTerrainLimit). +fn repurposed(check: Repurposed, queries: &mut impl CheckQueries, chunk: ChunkPos, y: i32) -> bool { + let (x0, z0) = (chunk.x * 16, chunk.z * 16); + let bottom = queries.bottom(); + let at = |column: &[bool], y: i32| { + usize::try_from(y - bottom) + .ok() + .and_then(|i| column.get(i).copied()) + .unwrap_or(false) + }; + match check { + Repurposed::CityNether => { + let sea = queries.sea_level(); + for cx in chunk.x - 1..=chunk.x + 1 { + for cz in chunk.z - 1..=chunk.z + 1 { + if (cx, cz) == (chunk.x, chunk.z) { + continue; + } + let (filled, _) = queries.liquid_column(cx << 4, cz << 4); + let top = (bottom + filled.len() as i32).min(sea + 45); + if (sea + 20..top).any(|y| at(&filled, y)) { + return false; + } + } + } + true + } + Repurposed::ShipwreckNether => { + for dx in (-16..=16).step_by(8) { + for dz in (-16..=16).step_by(8) { + let (filled, solid) = queries.liquid_column(x0 + dx, z0 + dz); + // Not air and no fluid: in a noise column, a solid block. + if (0..=30) + .step_by(5) + .any(|dy| at(&filled, y + dy) && at(&solid, y + dy)) + { + return false; + } + } + } + true + } + Repurposed::StrongholdEnd => { + let (filled, _) = queries.liquid_column(x0, z0); + let min_land = (bottom + filled.len() as i32).min(bottom + 45); + // getHeightAt: the lowest height so far, less one at every sample. + let mut land = i32::MAX; + let mut sample = |x: i32, z: i32, land: &mut i32| { + let h = queries.first_free_height(x, z, HeightmapType::WorldSurfaceWg); + *land = (*land).min(h) - 1; + *land >= min_land + }; + for distance in [70, 35] { + // Direction.Plane.HORIZONTAL: north, east, south, west. + for (dx, dz) in [(0, -1), (1, 0), (0, 1), (-1, 0)] { + if !sample(x0 + dx * distance, z0 + dz * distance, &mut land) { + return false; + } + } + } + sample(x0, z0, &mut land) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + use std::collections::BTreeMap; + + /// Heights per (x, z), a liquid column, one biome per quart column. + #[derive(Default)] + struct Fake { + heights: BTreeMap<(i32, i32), i32>, + column: Vec<char>, + biomes: BTreeMap<(i32, i32), u32>, + asked: Vec<[i32; 3]>, + /// Columns by (x, z), instead of `column`, from y 0. + columns: BTreeMap<(i32, i32), Vec<char>>, + } + impl CheckQueries for Fake { + fn first_free_height(&mut self, x: i32, z: i32, _: HeightmapType) -> i32 { + self.heights.get(&(x, z)).copied().unwrap_or(64) + } + fn liquid_column(&mut self, x: i32, z: i32) -> (Vec<bool>, Vec<bool>) { + // '.' air, '#' stone, '~' water, from the bottom up. + let column = self.columns.get(&(x, z)).unwrap_or(&self.column); + ( + column.iter().map(|&c| c != '.').collect(), + column.iter().map(|&c| c == '#').collect(), + ) + } + fn sea_level(&self) -> i32 { + 32 + } + fn bottom(&self) -> i32 { + 0 + } + fn noise_biome(&mut self, quart: [i32; 3]) -> BiomeId { + self.asked.push(quart); + BiomeId(self.biomes.get(&(quart[0], quart[2])).copied().unwrap_or(1)) + } + } + fn checks(v: Value) -> StartChecks { + StartChecks::decode(Some(&v)) + } + const CHUNK: ChunkPos = ChunkPos { x: 2, z: -1 }; + + #[test] + fn vanilla_structures_pass_everything() { + let mut fake = Fake { + column: "#~~.".chars().collect(), + ..Fake::default() + }; + let none = StartChecks::decode(None); + assert_eq!(none, StartChecks::default()); + assert!(none.pass(&mut fake, &BTreeSet::new(), CHUNK, 0, None)); + assert!(fake.asked.is_empty()); + } + + #[test] + fn every_biome_in_the_radius_must_be_allowed() { + let allowed = BTreeSet::from([BiomeId(1)]); + let mut fake = Fake::default(); + fake.heights.insert((39, -9), 70); + let c = checks(json!({"biome_radius": 1})); + assert!(c.pass( + &mut fake, + &allowed, + CHUNK, + 10, + Some(HeightmapType::WorldSurfaceWg) + )); + // Section y: start height plus the projected height minus one, in quarts. + assert_eq!(fake.asked.len(), 9); + assert!(fake.asked.iter().all(|q| q[1] == (10 + 70 - 1) >> 2)); + assert_eq!(fake.asked[0], [4, 19, -8]); + fake.biomes.insert((12, 0), 2); // chunk (3, 0), the radius' corner + assert!(!c.pass(&mut fake, &allowed, CHUNK, 10, None)); + } + + #[test] + fn liquid_checks_read_the_mods_block() { + let top = checks(json!({"liquid": "top"})); + let lowest = checks(json!({"liquid": "lowest"})); + let none = BTreeSet::new(); + let mut ocean = Fake { + column: "##~~~..".chars().collect(), + ..Fake::default() + }; + assert!(!top.pass(&mut ocean, &none, CHUNK, 0, None)); + assert!(lowest.pass(&mut ocean, &none, CHUNK, 0, None)); + let mut land = Fake { + column: "#~###..".chars().collect(), + ..Fake::default() + }; + assert!(top.pass(&mut land, &none, CHUNK, 0, None)); + assert!(!lowest.pass(&mut land, &none, CHUNK, 0, None)); + // The bottom block itself is never read; an empty column passes. + let mut empty = Fake { + column: "~....".chars().collect(), + ..Fake::default() + }; + assert!(top.pass(&mut empty, &none, CHUNK, 0, None)); + } + + #[test] + fn terrain_must_lie_within_its_range() { + let none = BTreeSet::new(); + let mut fake = Fake::default(); + // Chunk centres around (2, -1): x 23, 39, 55; z -25, -9, 7. + fake.heights.insert((23, -25), 60); + fake.heights.insert((55, 7), 75); + let range = |r: i32| checks(json!({"terrain_radius": 1, "terrain_range": r})); + assert!(range(15).pass(&mut fake, &none, CHUNK, 0, None)); + assert!(!range(14).pass(&mut fake, &none, CHUNK, 0, None)); + // The radius alone, or with only max_y, checks nothing. + assert!( + checks(json!({"terrain_radius": 1, "max_y": 0})).pass(&mut fake, &none, CHUNK, 0, None) + ); + let bounds = + |min: i32, max: i32| checks(json!({"terrain_radius": 1, "min_y": min, "max_y": max})); + assert!(bounds(60, 64).pass(&mut fake, &none, CHUNK, 0, None)); + assert!(!bounds(61, 100).pass(&mut fake, &none, CHUNK, 0, None)); + // max_y is compared with the lowest height so far: 75 never fails it. + assert!(bounds(0, 64).pass(&mut fake, &none, CHUNK, 0, None)); + assert!(!bounds(0, 59).pass(&mut fake, &none, CHUNK, 0, None)); + } + + /// A column of `n` blocks: `fill` up to `top` (exclusive), air above. + fn column(n: usize, top: usize, fill: char) -> Vec<char> { + (0..n).map(|y| if y < top { fill } else { '.' }).collect() + } + + #[test] + fn repurposed_city_needs_air_above_the_lava_sea_around() { + let none = BTreeSet::new(); + let city = checks(json!({"repurposed": "city_nether"})); + // Sea 32: air needed from 52 to 76 (128 deep), in the 8 chunks around. + let mut fake = Fake { + column: column(128, 52, '#'), + ..Fake::default() + }; + // The chunk itself is not read. + fake.columns.insert((32, -16), column(128, 100, '#')); + assert!(city.pass(&mut fake, &none, CHUNK, 33, None)); + fake.columns.insert((48, 0), column(128, 53, '#')); + assert!(!city.pass(&mut fake, &none, CHUNK, 33, None)); + // Above sea + 45 nothing is read. + fake.columns.insert((48, 0), { + let mut c = column(128, 52, '#'); + c[77] = '#'; + c + }); + assert!(city.pass(&mut fake, &none, CHUNK, 33, None)); + } + + #[test] + fn repurposed_shipwreck_needs_no_solid_block_around() { + let none = BTreeSet::new(); + let wreck = checks(json!({"repurposed": "shipwreck_nether"})); + // Lava up to 40, air above: the samples at 28..=58 meet only lava and air. + let mut fake = Fake { + column: column(128, 40, '~'), + ..Fake::default() + }; + assert!(wreck.pass(&mut fake, &none, CHUNK, 28, None)); + // Netherrack at y 43, between samples (28 + 15, + 20 are 43, 48). + let mut rock = column(128, 40, '~'); + rock[43] = '#'; + fake.columns.insert((32 - 16, -16 + 16), rock.clone()); + assert!(!wreck.pass(&mut fake, &none, CHUNK, 28, None)); + rock[43] = '.'; + rock[44] = '#'; + fake.columns.insert((16, 0), rock); + assert!(wreck.pass(&mut fake, &none, CHUNK, 28, None)); + } + + #[test] + fn repurposed_end_stronghold_needs_land_around() { + let none = BTreeSet::new(); + let end = checks(json!({"repurposed": "stronghold_end"})); + let mut fake = Fake { + column: column(256, 0, '#'), + ..Fake::default() + }; + // Every height 64 by default: 63, 62, ... 55 after the 9 samples. + assert!(end.pass(&mut fake, &none, CHUNK, 0, None)); + // Land at least 45 above the bottom, after the sample's minus one: + // 46 at the corner passes, 45 fails. + fake.heights.insert((32, -16), 46); + assert!(end.pass(&mut fake, &none, CHUNK, 0, None)); + fake.heights.insert((32, -16), 45); + assert!(!end.pass(&mut fake, &none, CHUNK, 0, None)); + // Void 70 blocks north fails at once. + fake.heights.clear(); + fake.heights.insert((32, -86), 0); + assert!(!end.pass(&mut fake, &none, CHUNK, 0, None)); + } +} diff --git a/crates/horizon-world/src/worldgen/structure/yung.rs b/crates/horizon-world/src/worldgen/structure/yung.rs new file mode 100644 index 000000000..07b363cfb --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/yung.rs @@ -0,0 +1,727 @@ +//! YUNG's API's jigsaw assembler, for the structures of the "YUNG's Better" +//! mods carried over from a modpack (docs/modpacks.md). Carry maps +//! `yungsapi:yung_jigsaw` to `minecraft:jigsaw` with a `"horizon:yungsapi"` +//! key, and its pool elements to vanilla's single element with the piece's +//! rules under the same key; vanilla data never has it. +//! +//! The assembler differs from vanilla's JigsawPlacement: it picks the start +//! piece and every child by weight from the pool's weighted entries (a +//! priority piece first), lays pieces out breadth first, caps pieces by name +//! (`max_count`), limits them by depth, lets some ignore the bounds, checks +//! each piece's condition, and keeps every piece between `min_y` and +//! `max_y`. Pieces fit the same free space as vanilla's. +use super::{ + BoundingBox, Rotation, StructureResources, StructureTemplate, + jigsaw::{ + Free, JigsawConfig, JigsawContext, Junction, PoolElement, PoolPiece, Pools, Projection, + can_attach, shuffle, step, + }, +}; +use crate::{ + heightmap::HeightmapType, + worldgen::{DecodeError, block_feature::FeatureBlockBindings}, +}; +use horizon_core::random::RandomSource; +use serde_json::Value; +use std::{ + cell::RefCell, + collections::{HashMap, VecDeque}, + rc::Rc, + sync::Arc, +}; + +/// A YUNG structure's own settings (`"horizon:yungsapi"` on the structure): +/// the heights every piece must stay within. +#[derive(Debug, Default)] +pub struct Config { + pub min_y: Option<i32>, + pub max_y: Option<i32>, +} +impl Config { + pub fn decode(v: &Value) -> Self { + let y = |k: &str| v[k].as_i64().map(|n| n as i32); + Self { + min_y: y("min_y"), + max_y: y("max_y"), + } + } +} + +/// A piece's rules (`"horizon:yungsapi"` on a pool element). +#[derive(Debug, Default)] +pub struct Rules { + /// Pieces sharing a name share the cap `max_count`. + name: Option<String>, + max_count: Option<i32>, + min_depth: Option<i32>, + max_depth: Option<i32>, + /// Chosen before any other piece of its pool. + priority: bool, + /// Placed even where it overlaps other pieces or leaves the bounds. + ignore_bounds: bool, + condition: Condition, +} +impl Rules { + pub fn decode(v: &Value, resources: &StructureResources) -> Result<Self, DecodeError> { + let int = |k: &str| v[k].as_i64().map(|n| n as i32); + Ok(Self { + name: v["name"].as_str().map(str::to_owned), + max_count: int("max_count"), + min_depth: int("min_depth"), + max_depth: int("max_depth"), + priority: v["priority"].as_bool().unwrap_or(false), + ignore_bounds: v["ignore_bounds"].as_bool().unwrap_or(false), + condition: match v.get("condition") { + Some(c) => Condition::decode(c, resources)?, + None => Condition::True, + }, + }) + } + /// YungJigsawPoolElement.isAtValidDepth. + fn at_valid_depth(&self, depth: i32) -> bool { + self.min_depth.is_none_or(|d| d <= depth) && self.max_depth.is_none_or(|d| d >= depth) + } + /// The name a capped piece counts under: `max_count` without a name is + /// ignored, as YUNG's does. + fn capped(&self) -> Option<(&str, i32)> { + Some((self.name.as_deref()?, self.max_count?)) + } +} + +/// YUNG's structure conditions, as carry writes them. +#[derive(Debug, Default)] +enum Condition { + #[default] + True, + False, + Not(Box<Condition>), + AllOf(Vec<Condition>), + AnyOf(Vec<Condition>), + Depth { + min: Option<i32>, + max: Option<i32>, + }, + Altitude { + bottom: Option<f64>, + top: Option<f64>, + }, + RandomChance(f32), + Rotation(Vec<Rotation>), + /// Another piece (of these templates, or any) within `range` blocks in + /// the direction `rotation` turns the piece's own north. + PieceInDirection { + templates: Vec<Arc<StructureTemplate>>, + range: i32, + rotation: Rotation, + }, +} +impl Condition { + fn decode(v: &Value, resources: &StructureResources) -> Result<Self, DecodeError> { + let list = |k: &'static str| -> Result<Vec<Condition>, DecodeError> { + v[k].as_array() + .ok_or(DecodeError::Field(k))? + .iter() + .map(|c| Self::decode(c, resources)) + .collect() + }; + let int = |k: &str| v[k].as_i64().map(|n| n as i32); + let rotation = |r: &Value| { + r.as_str() + .and_then(Rotation::from_name) + .ok_or(DecodeError::Field("condition rotation")) + }; + Ok(match v["type"].as_str().unwrap_or_default() { + "true" => Self::True, + "false" => Self::False, + "not" => Self::Not(Box::new(Self::decode(&v["condition"], resources)?)), + "all_of" => Self::AllOf(list("conditions")?), + "any_of" => Self::AnyOf(list("conditions")?), + "depth" => Self::Depth { + min: int("min_depth"), + max: int("max_depth"), + }, + "altitude" => Self::Altitude { + bottom: v["bottom"].as_f64(), + top: v["top"].as_f64(), + }, + "random_chance" => Self::RandomChance(v["chance"].as_f64().unwrap_or(0.) as f32), + "rotation" => Self::Rotation( + v["rotations"] + .as_array() + .into_iter() + .flatten() + .map(rotation) + .collect::<Result<_, _>>()?, + ), + "piece_in_horizontal_direction" => Self::PieceInDirection { + templates: v["pieces"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| resources.template(p.as_str()?)) + .collect(), + range: int("range").unwrap_or(0), + rotation: rotation(&v["rotation"])?, + }, + _ => return Err(DecodeError::Field("YUNG condition type")), + }) + } + /// StructureCondition.passes. `at` is the piece being placed: its box, + /// rotation and depth; the start piece has no box yet. + fn passes(&self, at: &At<'_>, random: &mut impl RandomSource) -> bool { + match self { + Self::True => true, + Self::False => false, + Self::Not(c) => !c.passes(at, random), + Self::AllOf(all) => all.iter().all(|c| c.passes(at, random)), + Self::AnyOf(any) => any.iter().any(|c| c.passes(at, random)), + Self::Depth { min, max } => { + min.is_none_or(|d| d <= at.depth) && max.is_none_or(|d| d >= at.depth) + } + Self::Altitude { bottom, top } => { + let [low, high] = at.piece.map_or([0, 0], |b| [b.min[1], b.max[1]]); + bottom.is_none_or(|y| f64::from(low) >= y) + && top.is_none_or(|y| f64::from(high) <= y) + } + Self::RandomChance(chance) => random.next_float() < *chance, + Self::Rotation(valid) => valid.contains(&at.rotation), + Self::PieceInDirection { + templates, + range, + rotation, + } => { + let Some(piece) = at.piece else { + return false; + }; + let mut search = piece; + match at.rotation.get_rotated(*rotation) { + Rotation::None => search.min[2] -= range, + Rotation::Clockwise90 => search.max[0] += range, + Rotation::Clockwise180 => search.max[2] += range, + Rotation::Counterclockwise90 => search.min[0] -= range, + } + at.pieces.iter().any(|other| { + let PoolElement::Single { template, .. } = other.element.as_ref() else { + return false; + }; + let b = other.bounding_box; + b != piece + && (templates.is_empty() + || templates.iter().any(|t| Arc::ptr_eq(t, template))) + && b.intersects(&search) + && !b.intersects(&piece) + }) + } + } + } +} + +/// The surface height query, object-safe for the per-call cache. +trait JigsawContextDyn { + fn surface(&mut self, x: i32, z: i32) -> i32; +} +impl<C: JigsawContext> JigsawContextDyn for C { + fn surface(&mut self, x: i32, z: i32) -> i32 { + self.base_height(x, z, HeightmapType::WorldSurfaceWg) + } +} + +/// What a condition sees of the piece being placed. +struct At<'a> { + depth: i32, + rotation: Rotation, + piece: Option<BoundingBox>, + pieces: &'a [PoolPiece], +} + +/// The index of the entry to try: the first priority piece, else one drawn +/// by weight (`nextInt(total) + 1`, counted down). +fn pick( + candidates: &[(Arc<PoolElement>, i32)], + total: i32, + random: &mut impl RandomSource, +) -> usize { + if let Some(i) = candidates + .iter() + .position(|(e, _)| e.yung().is_some_and(|r| r.priority)) + { + return i; + } + let mut chosen = random.next_int_bound(total).unwrap_or(0) + 1; + for (i, (_, weight)) in candidates.iter().enumerate() { + chosen -= weight; + if chosen <= 0 { + return i; + } + } + candidates.len() - 1 +} + +/// JigsawManager.assembleJigsawStructure: the start position and the +/// pieces, or None when no start piece fits. +#[allow(clippy::too_many_arguments)] +pub fn assemble( + config: &JigsawConfig<'_>, + yung: &Config, + context: &mut impl JigsawContext, + pools: &Pools, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + random: &mut impl RandomSource, + position: [i32; 3], +) -> Option<([i32; 3], Vec<PoolPiece>)> { + let pool = pools.get(config.start_pool, resources, bindings)?; + let mut candidates = pool.raw.clone(); + shuffle(&mut candidates, random); + let rotation = Rotation::random(random); + let mut total: i32 = candidates.iter().map(|c| c.1).sum(); + let (element, adjusted, local) = loop { + if candidates.is_empty() || total <= 0 { + return None; + } + let index = pick(&candidates, total, random); + let (element, weight) = candidates[index].clone(); + if matches!(element.as_ref(), PoolElement::Empty) { + return None; + } + let anchored = match config.start_jigsaw { + Some(name) => { + element + .shuffled_jigsaws(resources, position, rotation, random) + .into_iter() + .find(|j| j.name.as_deref() == Some(name))? + .pos + } + None => position, + }; + let local: [i32; 3] = std::array::from_fn(|i| anchored[i] - position[i]); + let adjusted: [i32; 3] = std::array::from_fn(|i| position[i] - local[i]); + let at = At { + depth: 0, + rotation, + piece: None, + pieces: &[], + }; + if element + .yung() + .is_some_and(|r| !r.condition.passes(&at, random)) + { + total -= weight; + candidates.remove(index); + continue; + } + break (element, adjusted, local); + }; + let mut start = PoolPiece { + bounding_box: element.bounding_box(adjusted, rotation), + ground_level_delta: element.ground_level_delta(), + element, + position: adjusted, + rotation, + junctions: Vec::new(), + waterlogging: config.waterlogging, + }; + let b = start.bounding_box; + let (cx, cz) = ((b.max[0] + b.min[0]) / 2, (b.max[2] + b.min[2]) / 2); + let bottom = match config.project_to { + Some(kind) => position[1] + context.base_height(cx, cz, kind), + None => adjusted[1], + }; + start.moved(bottom - (b.min[1] + start.ground_level_delta)); + let cy = bottom + local[1]; + let d = config.max_distance[0]; + let free = Rc::new(RefCell::new(Free { + container: BoundingBox::new([cx - d, cy - d, cz - d], [cx + d, cy + d, cz + d]), + removed: vec![start.bounding_box], + })); + let mut assembler = Assembler { + config, + yung, + pools, + resources, + bindings, + pieces: vec![start], + states: vec![(free, 0)], + counts: HashMap::new(), + }; + if config.max_depth > 0 { + let mut queue = VecDeque::from([0]); + while let Some(piece) = queue.pop_front() { + assembler.children(piece, &mut queue, context, random); + } + } + Some(([cx, cy, cz], assembler.pieces)) +} + +/// JigsawStructureAssembler. +struct Assembler<'a> { + config: &'a JigsawConfig<'a>, + yung: &'a Config, + pools: &'a Pools, + resources: &'a StructureResources, + bindings: &'a FeatureBlockBindings<'a>, + pieces: Vec<PoolPiece>, + /// Per piece: the free space it was placed in, and its depth. + states: Vec<(Rc<RefCell<Free>>, i32)>, + /// Pieces placed per capped name. + counts: HashMap<String, i32>, +} + +/// Where a child goes: the parent's jigsaw and what it needs. +struct Slot<'s> { + source: usize, + jigsaw: &'s super::jigsaw::Jigsaw, + target_pos: [i32; 3], + free: Rc<RefCell<Free>>, + depth: i32, +} + +impl Assembler<'_> { + fn pool(&self, name: &str) -> Option<Arc<super::jigsaw::Pool>> { + let name = self.config.aliases.get(name).map_or(name, String::as_str); + self.pools.get(name, self.resources, self.bindings) + } + /// JigsawStructureAssembler.Settings.isInBounds. + fn in_bounds(&self, y: i32, context: &impl JigsawContext) -> bool { + self.yung.max_y.is_none_or(|m| y <= m) + && self.yung.min_y.is_none_or(|m| y >= m) + && y >= context.min_y() + self.config.padding[0] + && y <= context.max_y() + 1 - self.config.padding[1] + } + /// addChildrenForPiece: one child per jigsaw where one fits, from the + /// target pool unless the piece is at the last depth, else its fallback. + fn children( + &mut self, + source: usize, + queue: &mut VecDeque<usize>, + context: &mut impl JigsawContext, + random: &mut impl RandomSource, + ) { + let (element, position, rotation, source_box) = { + let s = &self.pieces[source]; + (s.element.clone(), s.position, s.rotation, s.bounding_box) + }; + let (context_free, depth) = self.states[source].clone(); + let mut source_free: Option<Rc<RefCell<Free>>> = None; + for jigsaw in element.shuffled_jigsaws(self.resources, position, rotation, random) { + let Some(target) = self.pool(&jigsaw.pool) else { + continue; + }; + if target.templates.is_empty() && jigsaw.pool != "minecraft:empty" { + continue; + } + let Some(fallback) = self.pool(&target.fallback) else { + continue; + }; + if fallback.templates.is_empty() && target.fallback != "minecraft:empty" { + continue; + } + let s = step(jigsaw.front); + let target_pos: [i32; 3] = std::array::from_fn(|i| jigsaw.pos[i] + s[i]); + let free = if source_box.is_inside(target_pos) { + source_free + .get_or_insert_with(|| { + Rc::new(RefCell::new(Free { + container: source_box, + removed: Vec::new(), + })) + }) + .clone() + } else { + context_free.clone() + }; + let slot = Slot { + source, + jigsaw: &jigsaw, + target_pos, + free, + depth, + }; + let placed = depth != self.config.max_depth + && self.choose(&slot, target.raw.clone(), queue, context, random); + if !placed { + self.choose(&slot, fallback.raw.clone(), queue, context, random); + } + } + } + /// chooseCandidateFromPool: whether a piece was placed. + fn choose( + &mut self, + slot: &Slot<'_>, + mut candidates: Vec<(Arc<PoolElement>, i32)>, + queue: &mut VecDeque<usize>, + context: &mut impl JigsawContext, + random: &mut impl RandomSource, + ) -> bool { + let jigsaw = slot.jigsaw; + let (source_rigid, source_y, source_ground) = { + let s = &self.pieces[slot.source]; + ( + s.element.projection() == Projection::Rigid, + s.bounding_box.min[1], + s.ground_level_delta, + ) + }; + let local_y = jigsaw.pos[1] - source_y; + // The surface at the jigsaw, read once per call. + let mut surface = None; + let (x, z) = (jigsaw.pos[0], jigsaw.pos[2]); + let mut base = |context: &mut dyn JigsawContextDyn| { + *surface.get_or_insert_with(|| context.surface(x, z)) + }; + shuffle(&mut candidates, random); + let mut total: i32 = candidates.iter().map(|c| c.1).sum(); + while !candidates.is_empty() && total > 0 { + let index = pick(&candidates, total, random); + let (target, weight) = candidates[index].clone(); + if matches!(target.as_ref(), PoolElement::Empty) { + return false; + } + let rules = target.yung(); + let capped = rules.and_then(Rules::capped); + let full = capped + .is_some_and(|(name, max)| self.counts.get(name).copied().unwrap_or(0) >= max); + if full || rules.is_some_and(|r| !r.at_valid_depth(slot.depth)) { + total -= weight; + candidates.remove(index); + continue; + } + let mut rotations = Rotation::ALL; + shuffle(&mut rotations, random); + for rotation in rotations { + let target_jigsaws = + target.shuffled_jigsaws(self.resources, [0; 3], rotation, random); + let hack_box = target.bounding_box([0; 3], rotation); + let expand_to = if self.config.use_expansion_hack && hack_box.span()[1] <= 16 { + target_jigsaws + .iter() + .map(|tj| { + let st = step(tj.front); + if !hack_box.is_inside(std::array::from_fn(|i| tj.pos[i] + st[i])) { + return 0; + } + let child = self.pool(&tj.pool); + let child_size = child.as_ref().map_or(0, |p| p.max_size()); + let fallback_size = child + .and_then(|p| self.pool(&p.fallback)) + .map_or(0, |p| p.max_size()); + child_size.max(fallback_size) + }) + .max() + .unwrap_or(0) + } else { + 0 + }; + for target_jigsaw in &target_jigsaws { + if !can_attach(jigsaw, target_jigsaw) { + continue; + } + let target_local = target_jigsaw.pos; + let raw_position: [i32; 3] = + std::array::from_fn(|i| slot.target_pos[i] - target_local[i]); + let raw_box = target.bounding_box(raw_position, rotation); + let target_rigid = target.projection() == Projection::Rigid; + let delta_y = local_y - target_local[1] + step(jigsaw.front)[1]; + let target_y = if source_rigid && target_rigid { + source_y + delta_y + } else { + base(context) - target_local[1] + }; + let offset = target_y - raw_box.min[1]; + let mut target_box = raw_box.moved([0, offset, 0]); + let target_position = + [raw_position[0], raw_position[1] + offset, raw_position[2]]; + if expand_to > 0 { + let size = (expand_to + 1).max(target_box.max[1] - target_box.min[1]); + target_box.max[1] = target_box.min[1] + size; + } + if !self.in_bounds(target_box.max[1], context) + || !self.in_bounds(target_box.min[1], context) + { + continue; + } + if !rules.is_some_and(|r| r.ignore_bounds) + && !slot.free.borrow().fits(&target_box) + { + continue; + } + let target_ground = if target_rigid { + source_ground - delta_y + } else { + target.ground_level_delta() + }; + let junction_y = if source_rigid { + source_y + local_y + } else if target_rigid { + target_y + target_local[1] + } else { + base(context) + delta_y / 2 + }; + let at = At { + depth: slot.depth + 1, + rotation, + piece: Some(target_box), + pieces: &self.pieces, + }; + if rules.is_some_and(|r| !r.condition.passes(&at, random)) { + continue; + } + self.pieces[slot.source].junctions.push(Junction { + source_x: slot.target_pos[0], + source_ground_y: junction_y - local_y + source_ground, + source_z: slot.target_pos[2], + }); + slot.free.borrow_mut().removed.push(target_box); + self.pieces.push(PoolPiece { + element: target.clone(), + position: target_position, + ground_level_delta: target_ground, + rotation, + bounding_box: target_box, + junctions: vec![Junction { + source_x: jigsaw.pos[0], + source_ground_y: junction_y - target_local[1] + target_ground, + source_z: jigsaw.pos[2], + }], + waterlogging: self.config.waterlogging, + }); + self.states.push((slot.free.clone(), slot.depth + 1)); + if slot.depth < self.config.max_depth { + queue.push_back(self.pieces.len() - 1); + } + if let Some((name, _)) = capped { + *self.counts.entry(name.to_owned()).or_default() += 1; + } + return true; + } + } + total -= weight; + candidates.remove(index); + } + false + } +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_core::random::LegacyRandom; + + fn single(template: &Arc<StructureTemplate>, rules: Option<Rules>) -> Arc<PoolElement> { + Arc::new(PoolElement::Single { + template: template.clone(), + processors: Default::default(), + legacy: false, + projection: Projection::Rigid, + waterlogging: None, + yung: rules.map(Box::new), + }) + } + + #[test] + fn picks_priority_pieces_then_by_weight() { + let t = Arc::new(StructureTemplate::empty()); + let plain = single(&t, None); + let first = single( + &t, + Some(Rules { + priority: true, + ..Rules::default() + }), + ); + let mut random = LegacyRandom::new(7); + let list = vec![(plain.clone(), 3), (first, 1)]; + assert_eq!(pick(&list, 4, &mut random), 1); + // By weight: nextInt(total) + 1, counted down; the first entry + // takes draws 1..=3 of 4. + let list = vec![(plain.clone(), 3), (plain, 1)]; + let mut ours = LegacyRandom::new(42); + let mut theirs = LegacyRandom::new(42); + for _ in 0..32 { + let draw = theirs.next_int_bound(4).unwrap() + 1; + assert_eq!(pick(&list, 4, &mut ours), usize::from(draw > 3)); + } + } + + #[test] + fn rules_cap_by_name_and_depth() { + let rules = Rules { + name: Some("room".into()), + max_count: Some(2), + min_depth: Some(1), + max_depth: Some(3), + ..Rules::default() + }; + assert_eq!(rules.capped(), Some(("room", 2))); + assert!(!rules.at_valid_depth(0) && rules.at_valid_depth(1) && !rules.at_valid_depth(4)); + // max_count without a name is ignored, as YUNG's does. + let unnamed = Rules { + max_count: Some(1), + ..Rules::default() + }; + assert_eq!(unnamed.capped(), None); + } + + #[test] + fn conditions() { + let t = Arc::new(StructureTemplate::empty()); + let other = Arc::new(StructureTemplate::empty()); + let neighbour = PoolPiece { + element: single(&t, None), + position: [0; 3], + ground_level_delta: 1, + rotation: Rotation::None, + bounding_box: BoundingBox::new([0, 0, -6], [4, 4, -1]), + junctions: Vec::new(), + waterlogging: true, + }; + let pieces = [neighbour]; + let at = |rotation, depth| At { + depth, + rotation, + piece: Some(BoundingBox::new([0, 10, 0], [4, 14, 4])), + pieces: &pieces, + }; + let mut random = LegacyRandom::new(1); + let depth = Condition::Depth { + min: Some(2), + max: None, + }; + assert!(!depth.passes(&at(Rotation::None, 1), &mut random)); + assert!(depth.passes(&at(Rotation::None, 2), &mut random)); + let altitude = |bottom, top| Condition::Altitude { bottom, top }; + assert!(altitude(Some(10.), Some(14.)).passes(&at(Rotation::None, 0), &mut random)); + assert!(!altitude(Some(10.5), None).passes(&at(Rotation::None, 0), &mut random)); + assert!(!altitude(None, Some(13.9)).passes(&at(Rotation::None, 0), &mut random)); + // North (-Z) of an unrotated piece, within 5 blocks; the neighbour + // stays below it in Y, but only X and Z are searched, and it must + // not overlap the piece itself. + let north = |templates, rotation| Condition::PieceInDirection { + templates, + range: 5, + rotation, + }; + assert!(!north(Vec::new(), Rotation::None).passes(&at(Rotation::None, 1), &mut random)); + let low = At { + piece: Some(BoundingBox::new([0, 0, 0], [4, 4, 4])), + ..at(Rotation::None, 1) + }; + assert!(north(Vec::new(), Rotation::None).passes(&low, &mut random)); + assert!(north(vec![t.clone()], Rotation::None).passes(&low, &mut random)); + assert!(!north(vec![other], Rotation::None).passes(&low, &mut random)); + // The piece turned 180°: its north is south. + let turned = At { + rotation: Rotation::Clockwise180, + ..low + }; + assert!(!north(Vec::new(), Rotation::None).passes(&turned, &mut random)); + assert!(north(Vec::new(), Rotation::Clockwise180).passes(&turned, &mut random)); + let all = Condition::AllOf(vec![ + Condition::True, + Condition::Not(Box::new(Condition::False)), + Condition::Rotation(vec![Rotation::Clockwise180]), + ]); + assert!(all.passes(&turned, &mut random)); + assert!(!Condition::AnyOf(vec![Condition::False]).passes(&turned, &mut random)); + } +} diff --git a/crates/horizon-world/tests/collision_data.rs b/crates/horizon-world/tests/collision_data.rs index 3738edf1a..85b41d98e 100644 --- a/crates/horizon-world/tests/collision_data.rs +++ b/crates/horizon-world/tests/collision_data.rs @@ -267,3 +267,75 @@ fn registry_scan_binding_requires_complete_canonical_metadata() { ); } } + +/// A table read from its bytes checks its state identities while reading and +/// keeps none of them, yet loads the same shapes as the tree; a nested table +/// (`block-properties.nbt`'s `occlusion`) is checked the same way. +#[test] +fn streamed_tables_check_states_while_reading() { + use horizon_world::{ + nbt::{self, Limits, NamedTag}, + registry::{BlockTable, BlockTableFile}, + }; + let (registry_tag, collision_tag) = fixture(); + let registry = BlockRegistry::from_nbt(®istry_tag).unwrap(); + let bytes = |tag: &Tag| { + let root = NamedTag { + name: "".into(), + tag: tag.clone(), + }; + nbt::write_named(&root, Limits::tables()).unwrap() + }; + let file = BlockTableFile::read(&bytes(&collision_tag), ®istry).unwrap(); + let table = file.table("collision").unwrap(); + assert_eq!(table.get("states"), Some(&Tag::List(Vec::new()))); + let streamed = CachedCollisionRegistry::from_table(table).unwrap(); + let tree = CachedCollisionRegistry::from_nbt(&collision_tag, ®istry).unwrap(); + for id in 0..3 { + let id = BlockStateId(id); + assert_eq!( + streamed.cached_shape(id).unwrap().map(|s| s.boxes()), + tree.cached_shape(id).unwrap().map(|s| s.boxes()) + ); + } + + let mut outer = Tag::compound([("occlusion", collision_tag.clone())]); + let Tag::Compound(map) = &mut outer else { + unreachable!() + }; + map.insert( + "states".into(), + collision_tag.get("states").unwrap().clone(), + ); + let file = BlockTableFile::read(&bytes(&outer), ®istry).unwrap(); + let nested = file + .table("outer") + .unwrap() + .nested("occlusion", "occlusion") + .unwrap(); + assert_eq!(nested.get("states"), Some(&Tag::List(Vec::new()))); + CachedCollisionRegistry::from_table(nested).unwrap(); + // Checked only as a tree, an emptied list is refused. + assert!(BlockTable::check(nested.tag(), ®istry, "occlusion").is_err()); + + // Other states, a different count or no states at all are refused. + let with_states = |edit: &dyn Fn(&mut Vec<Tag>)| { + let mut tag = collision_tag.clone(); + let Some(Tag::List(states)) = tag.get_mut("states") else { + unreachable!() + }; + edit(states); + tag + }; + let swapped = with_states(&|s| s.swap(1, 2)); + assert!(BlockTableFile::read(&bytes(&swapped), ®istry).is_err()); + let short = with_states(&|s| drop(s.pop())); + assert!(BlockTableFile::read(&bytes(&short), ®istry).is_err()); + let mut swapped = swapped; + let Tag::Compound(map) = &mut swapped else { + unreachable!() + }; + map.remove(&"states".into()); + let file = BlockTableFile::read(&bytes(&swapped), ®istry).unwrap(); + assert!(file.table("collision").is_err()); +} diff --git a/crates/horizon-world/tests/material_rule_specialization.rs b/crates/horizon-world/tests/material_rule_specialization.rs new file mode 100644 index 000000000..e953e908e --- /dev/null +++ b/crates/horizon-world/tests/material_rule_specialization.rs @@ -0,0 +1,172 @@ +use horizon_core::{ + density::{ConstantSampler, DensitySampler}, + position::BlockPos, + random::{RandomSource, XoroshiroRandom}, +}; +use horizon_world::{ + registry::BlockStateId, + worldgen::{ + DecodeError, + anchor::WorldGenerationContext, + material_condition::{ + MaterialCondition, MaterialConditions, MaterialRule, MaterialRuleError, + MaterialSurfaceQueries, + }, + }, +}; +use std::{collections::BTreeSet, sync::Arc}; + +#[derive(Default)] +struct Queries { + bindings: Vec<bool>, + temperatures: usize, + biomes: usize, + fail_binding: bool, + fail_temperature: bool, +} +impl MaterialSurfaceQueries for Queries { + fn possible_biomes(&self) -> Option<BTreeSet<String>> { + Some(BTreeSet::from(["minecraft:plains".into()])) + } + fn surface_depth(&mut self, _: i32, _: i32) -> i32 { + 1 + } + fn surface_secondary(&mut self, _: i32, _: i32) -> f64 { + 0. + } + fn bind_density( + &mut self, + _: Arc<dyn DensitySampler>, + eager: bool, + ) -> Result<usize, DecodeError> { + self.bindings.push(eager); + if self.fail_binding { + return Err(DecodeError::Field("test binding failure")); + } + Ok(self.bindings.len() - 1) + } + fn biome(&mut self, _: BlockPos) -> Result<Option<Arc<str>>, MaterialRuleError> { + self.biomes += 1; + Ok(Some(Arc::from("minecraft:plains"))) + } + fn cold_enough_to_snow( + &mut self, + _: &str, + _: BlockPos, + _: i32, + ) -> Result<bool, MaterialRuleError> { + self.temperatures += 1; + if self.fail_temperature { + Err(MaterialRuleError::BiomeQueryFailed) + } else { + Ok(true) + } + } +} +fn worker(surface: Queries) -> MaterialConditions<XoroshiroRandom, Queries> { + MaterialConditions::new( + WorldGenerationContext::new(-64, 384, 63), + XoroshiroRandom::new(7).fork_positional(), + surface, + ) +} +fn condition(if_true: MaterialCondition, then_run: MaterialRule) -> MaterialRule { + MaterialRule::Condition { + if_true, + then_run: Box::new(then_run), + } +} +fn biome(name: &str) -> MaterialCondition { + MaterialCondition::Biome(vec![name.into()]) +} +fn ore() -> MaterialRule { + MaterialRule::OreVein { + ore: BlockStateId(1), + raw_ore: BlockStateId(2), + filler: BlockStateId(3), + raw_ore_chance: 0.02, + density: Arc::new(ConstantSampler(1.)), + richness: Arc::new(ConstantSampler(1.)), + filler_gap: Arc::new(ConstantSampler(-1.)), + } +} +#[test] +fn constant_branches_keep_binding_order_and_short_circuit_queries() { + let mut w = worker(Queries::default()); + let rule = w + .add_rule(MaterialRule::Sequence(vec![ + condition(biome("minecraft:desert"), ore()), + condition( + MaterialCondition::Not(Box::new(biome("minecraft:desert"))), + MaterialRule::Block(BlockStateId(9)), + ), + ore(), + ])) + .unwrap(); + w.update_xz(4, 5, 0, 0); + w.update_y(1, 1, i32::MIN, 64); + for _ in 0..2 { + assert_eq!( + w.try_apply(rule, BlockPos::new(4, 64, 5)), + Ok(Some(BlockStateId(9))) + ); + } + let q = w.into_surface(); + assert_eq!(q.bindings, [true, true, false, true, true, false]); + assert_eq!(q.biomes, 0); + assert_eq!(q.temperatures, 0); +} +#[test] +fn unreachable_children_still_fail_compilation_without_adding_a_rule() { + for preceding_block in [false, true] { + let mut w = worker(Queries { + fail_binding: true, + ..Queries::default() + }); + let dead = condition(biome("minecraft:desert"), ore()); + let rule = if preceding_block { + MaterialRule::Sequence(vec![MaterialRule::Block(BlockStateId(9)), dead]) + } else { + dead + }; + assert!(w.add_rule(rule).is_err()); + assert_eq!( + w.try_apply(0, BlockPos::new(0, 0, 0)), + Err(MaterialRuleError::UnknownRule) + ); + assert_eq!(w.into_surface().bindings, [true]); + } +} +#[test] +fn dynamic_predicate_on_empty_child_retains_each_temperature_call_and_error() { + for fail in [false, true] { + let mut w = worker(Queries { + fail_temperature: fail, + ..Queries::default() + }); + let rule = w + .add_rule(condition( + MaterialCondition::Temperature, + condition( + biome("minecraft:desert"), + MaterialRule::Block(BlockStateId(9)), + ), + )) + .unwrap(); + w.update_xz(0, 0, 0, 0); + w.update_y(1, 1, i32::MIN, 64); + for _ in 0..2 { + assert_eq!( + w.try_apply(rule, BlockPos::new(0, 64, 0)), + if fail { + Err(MaterialRuleError::BiomeQueryFailed) + } else { + Ok(None) + } + ); + } + let q = w.into_surface(); + assert_eq!(q.temperatures, 2); + assert_eq!(q.biomes, 1); + } +} diff --git a/crates/horizon-world/tests/rule_test_bounds.rs b/crates/horizon-world/tests/rule_test_bounds.rs index de4862f54..e3f614590 100644 --- a/crates/horizon-world/tests/rule_test_bounds.rs +++ b/crates/horizon-world/tests/rule_test_bounds.rs @@ -67,3 +67,80 @@ fn binding_rejects_unknown_tag_blocks_and_duplicate_canonical_tags() { ]); assert!(FeatureBlockBindings::with_tags(®istry, BTreeSet::new(), &tags).is_err()); } +#[test] +fn matter_phase_matches_what_a_block_is_made_of() { + // air, cave_air, void_air, stone, then water (level 0), rail, iron_chain. + let mut states: Vec<Tag> = [ + "minecraft:air", + "minecraft:cave_air", + "minecraft:void_air", + "minecraft:stone", + ] + .iter() + .map(|name| Tag::compound([("id", Tag::String((*name).into()))])) + .collect(); + states.push(Tag::compound([ + ("id", Tag::String("minecraft:water".into())), + ( + "properties", + Tag::compound([("level", Tag::String("0".into()))]), + ), + ])); + for name in ["minecraft:rail", "minecraft:iron_chain"] { + states.push(Tag::compound([("id", Tag::String(name.into()))])); + } + let names = [ + "minecraft:air", + "minecraft:cave_air", + "minecraft:void_air", + "minecraft:stone", + "minecraft:water", + "minecraft:rail", + "minecraft:iron_chain", + ]; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("states", Tag::List(states)), + ( + "defaults", + Tag::Compound( + names + .iter() + .enumerate() + .map(|(id, name)| ((*name).into(), Tag::Int(id as i32))) + .collect(), + ), + ), + ])) + .unwrap(); + let bindings = FeatureBlockBindings::new(®istry, BTreeSet::new()).unwrap(); + let mut random = horizon_core::random::LegacyRandom::new(0); + let matches = |phase: &str, invert: bool, random: &mut horizon_core::random::LegacyRandom| { + let json = format!( + r#"{{"predicate_type":"horizon:matter_phase","phase_to_test_for":"{phase}","invert_condition":{invert}}}"# + ); + let test = RuleTest::from_json(&json, &bindings).unwrap(); + (0..names.len() as u32) + .filter(|&id| test.test(horizon_world::registry::BlockStateId(id), [0; 3], random)) + .collect::<Vec<_>>() + }; + assert_eq!(matches("AIR", false, &mut random), [0, 1, 2]); + assert_eq!(matches("LIQUID", false, &mut random), [4]); + assert_eq!( + matches("AIR_RAIL_OR_CHAIN", false, &mut random), + [0, 1, 2, 5, 6] + ); + assert_eq!( + matches("LIQUID_RAIL_OR_CHAIN", false, &mut random), + [4, 5, 6] + ); + assert_eq!(matches("AIR", true, &mut random), [3, 4, 5, 6]); + // The phase is the enum's name as written; SOLID needs canOcclude. + for json in [ + r#"{"predicate_type":"horizon:matter_phase","phase_to_test_for":"air"}"#, + r#"{"predicate_type":"horizon:matter_phase","phase_to_test_for":"SOLID"}"#, + r#"{"predicate_type":"horizon:matter_phase"}"#, + ] { + assert!(RuleTest::from_json(json, &bindings).is_err(), "{json}"); + } +} diff --git a/crates/horizon-world/tests/world_io.rs b/crates/horizon-world/tests/world_io.rs index 65b5006a8..3dd897794 100644 --- a/crates/horizon-world/tests/world_io.rs +++ b/crates/horizon-world/tests/world_io.rs @@ -74,6 +74,70 @@ fn external_threshold_negative_coordinates_and_timestamps_roundtrip() { assert!(reader.read(ChunkPos::new(0, 0)).is_err()); } +#[test] +fn in_place_writes_reuse_freed_sectors_and_keep_other_chunks() { + let dir = Directory::new(); + let (a, b, c) = ( + ChunkPos::new(-32, 0), + ChunkPos::new(-31, 0), + ChunkPos::new(-1, 31), + ); + let mut region = RegionFile::open_writable(dir.region(), true).unwrap(); + // RegionBitmap: a at sectors 2..4, b at 4. + region.write(a, &record(2 * 4096 - 5)).unwrap(); + region.write(b, &record(100)).unwrap(); + let sectors = |path: &Path| fs::metadata(path).unwrap().len() / 4096; + assert_eq!(sectors(&dir.region()), 5); + // a grows: it moves past b, and its two old sectors are free again. + region.write(a, &record(3 * 4096 - 5)).unwrap(); + assert_eq!(sectors(&dir.region()), 8); + // c fits in a's old sectors; then an oversized c goes to its .mcc file + // (a one-sector stub, at the end: sector 8) and back inline (sector 2). + region.write(c, &record(2 * 4096 - 5)).unwrap(); + assert_eq!(sectors(&dir.region()), 8); + region.write(c, &record(256 * 4096)).unwrap(); + assert!(dir.0.join("c.-1.31.mcc").exists()); + region.write(c, &record(10)).unwrap(); + assert!(!dir.0.join("c.-1.31.mcc").exists()); + assert!(region.clear(b, 7).unwrap()); + assert!(!region.clear(b, 7).unwrap()); + region.sync().unwrap(); + drop(region); + let mut reader = RegionFile::open(dir.region()).unwrap(); + assert_eq!(reader.chunks().map(|(p, _)| p).collect::<Vec<_>>(), [a, c]); + assert_eq!( + reader.read(a).unwrap().unwrap().compressed, + record(3 * 4096 - 5).compressed + ); + assert_eq!( + reader.read(c).unwrap().unwrap().compressed, + record(10).compressed + ); + assert!(reader.read(b).unwrap().is_none()); + // Reopened, the bitmap holds the chunks' sectors: new chunks take the + // first free runs (sectors 3 and 4), not theirs. + let mut region = RegionFile::open_writable(dir.region(), false).unwrap(); + region.write(b, &record(4096 - 5)).unwrap(); + region + .write(ChunkPos::new(-30, 0), &record(4096 - 5)) + .unwrap(); + drop(region); + let mut reader = RegionFile::open(dir.region()).unwrap(); + assert_eq!( + reader.read(a).unwrap().unwrap().compressed, + record(3 * 4096 - 5).compressed + ); + assert_eq!( + reader.read(c).unwrap().unwrap().compressed, + record(10).compressed + ); + assert_eq!( + reader.read(b).unwrap().unwrap().compressed, + record(4096 - 5).compressed + ); + assert_eq!(sectors(&dir.region()), 9); +} + #[test] fn failed_writer_cannot_commit_and_removes_its_own_external_files() { let dir = Directory::new(); @@ -206,3 +270,57 @@ fn chunk_storage_edit_preserves_unknown_fields_and_other_blocks() { let record = ChunkRecord::from_nbt(&root, Compression::Lz4, 17, Limits::default()).unwrap(); assert_eq!(record.nbt(Limits::default()).unwrap(), root); } + +/// Saving one chunk into a full region: the whole file rewritten (every +/// chunk read and written again, then the new file published), against +/// vanilla's in-place write. Run with --ignored --nocapture. +#[test] +#[ignore = "microbenchmark; run with --ignored --nocapture"] +fn benchmark_saving_into_a_full_region() { + let dir = Directory::new(); + let chunks: Vec<ChunkPos> = (0..1024) + .map(|i| ChunkPos::new(-32 + i % 32, i / 32)) + .collect(); + // About what a compressed overworld chunk weighs: two sectors. + let saved = record(6000); + let mut region = RegionFile::open_writable(dir.region(), true).unwrap(); + for &c in &chunks { + region.write(c, &saved).unwrap(); + } + region.sync().unwrap(); + drop(region); + let rounds = 100; + let start = std::time::Instant::now(); + for round in 0..rounds { + let changed = chunks[round * 7 % 1024]; + let mut existing = RegionFile::open(dir.region()).unwrap(); + let mut records = Vec::new(); + for (p, _) in existing.chunks().collect::<Vec<_>>() { + let r = if p == changed { + saved.clone() + } else { + existing.read(p).unwrap().unwrap() + }; + records.push((p, r)); + } + let staging = dir.0.join("staging"); + fs::create_dir_all(&staging).unwrap(); + let temporary = staging.join("r.-1.0.mca"); + let _ = fs::remove_file(&temporary); + let mut writer = RegionWriter::create(&temporary).unwrap(); + for (p, r) in &records { + writer.write(*p, r).unwrap(); + } + writer.finish().unwrap(); + fs::rename(&temporary, dir.region()).unwrap(); + } + let rewrite = start.elapsed() / rounds as u32; + let mut region = RegionFile::open_writable(dir.region(), false).unwrap(); + let start = std::time::Instant::now(); + for round in 0..rounds { + region.write(chunks[round * 7 % 1024], &saved).unwrap(); + region.sync().unwrap(); + } + let in_place = start.elapsed() / rounds as u32; + println!("one chunk into a full region: rewrite {rewrite:?}, in place {in_place:?}"); +} diff --git a/docs/hosting.md b/docs/hosting.md index f07983484..346eb7c8b 100644 --- a/docs/hosting.md +++ b/docs/hosting.md @@ -20,10 +20,14 @@ plan are in [docs/server.md](https://github.com/ludovic111/horizon/blob/main/doc 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. +- **Secure chat** works as on vanilla's server: in online mode, vanilla clients sign their chat, and with + `enforce-secure-profile=true` (the default) unsigned chat is refused. On an offline server, or for a player + without a chat session (Horizon's own client today), chat stays unsigned and shows as not secure. +- **Nether and End:** each player travels on their own through portals, and operators with `execute in + <dimension> run tp`. The players in the level they leave stop seeing them, and the ones in the level they + arrive in start to, as on vanilla (checked against vanilla with two players, by command and through an End + portal: `tools/test_server_dimension_players_parity.py`). The console can't send another player to a + dimension yet (`execute in ... run tp NAME`). - **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. diff --git a/docs/modpacks.md b/docs/modpacks.md index 23b560633..48e2a28e8 100644 --- a/docs/modpacks.md +++ b/docs/modpacks.md @@ -236,7 +236,15 @@ How the game loads them, without touching vanilla's path: so the same mod set gives the same ids. Saves store block names, so ids never reach the disk. - Loaders that read only `data/minecraft/` (recipes, loot, tags) read every namespace, as vanilla does. With no mods there is only `minecraft`, so nothing changes. -- The overlay is cached like the resource-pack overlay and rebuilt when a mod file changes. +- The overlay is built on the first start with a set of mods and kept for later starts. A stamp + (`horizon-mod-content.stamp`) hashes the game executable, the base tables and every mod file's + size and mtime. Adding, removing or editing a mod, or a new build of Horizon, rebuilds it. For + ATM10's 40 data-tier mods the build takes about a minute of the first start on a busy machine. +- **Worldgen.** Mods' structures, structure sets, template pools, processor lists, configured and + placed features join the `worldgen/*.json` bundles. Their structure templates go under + `worldgen/structure/<ns>/`. Their biome tags are merged into `worldgen/biome_tags.json`, minus + the biomes and tags Horizon does not have. Mod biomes, noise and density functions are not + carried yet. - **Limits.** Chunk sections size their global palette to the registry: 16 bits for vanilla's 35,723 states (the same chunks, saves and packets as before), one more bit each time content mods double it, up to 2^20 states (1,048,576). Past that the content root is refused with the @@ -398,6 +406,155 @@ Mechanical, the same for every mod, and no agent: carries those over. 5. Write `<id>.hmod`. For a data-tier mod, it is now ported. +Two cases the oracle fills in: + +- **Loot registered in code.** Chipped ships 7 loot tables for about 7,000 blocks; the rest + drop themselves through Java code. When a declared block has no table in the jar and the + oracle shows vanilla's drop-self, carry writes that table in 26.3's shape. When only the + states with one property value drop it (a door's lower half), the entry gets vanilla's + `match_block` condition. Chipped: 6,843 tables added. +- **Worldgen carry-over.** Structure libraries give vanilla's types other names. Carry maps + these to vanilla's: + - `lithostitched:jigsaw`, MoogsStructureLib's and Repurposed Structures' generic jigsaws + become `minecraft:jigsaw`; + - their `advanced_random_spread` becomes `minecraft:random_spread`; + - their versioned, legacy and empty pool elements become vanilla's. + + Three more rewrites make the mapped structures decode and start where their mod would: + - **Block states.** 1.21.1 writes a block or fluid state as `{"Name", "Properties"}`, 26.3 + as `{"id", "properties"}` and refuses the old shape, which failed the whole processor + list, feature or pool. Carry rewrites them (#816; 1,005 files in 17 of ATM10's mods). + - **Start and placement rules** (#820 in the game, #821 in carry). Repurposed Structures' + and Moog's jigsaws refuse to start in liquid and check biomes and terrain height in a + radius; their spreads keep a minimum distance from the world origin and away from other + sets (named by a structure set tag). Carry writes these under `horizon:start_checks`, + `horizon:min_distance_from_world_origin` and `horizon:exclusion_zone`; the game runs them + (`horizon-world`'s `structure/start_checks.rs`). Vanilla data has none of the keys. Moog's + also spreads its structures 1.65 times as far apart as its files say, which carry now + applies. MVS went from 829 starts to 90 in a 128×128-chunk square (seed 1234): 294 from the + spacing, the rest from the start checks. + - **Processors written in Java** are taken out of their lists (#822). The game, like + vanilla, refuses a list holding a type it does not know, and with it every pool naming the + list. The structures now generate undecorated (no pillars under them, spawners as the + template has them); 1,427 processors of 146 types in ATM10's mods, the most common + `lithostitched:block_swap`, Formations' `biome_replacements` and Repurposed Structures' + pillar, fluid and void processors. + - **Spawner processors** carried as data (`horizon-port-pack/src/processors.rs`). Most + chests in the mods' templates already name their loot table; what the Java processors add + is the spawners' mobs. Moog's and Repurposed Structures' spawner randomizing processors + become `horizon:spawner_mobs` (a weighted mob per spawner, picked with the placement's + random as theirs do, and the spawner NBT they write; Repurposed's `rs_spawners` lists are + written in). YUNG's Better Dungeons and Better Desert Temples turn a spawner or a + placeholder block (gravel, bone block, yellow wool...) into a spawner of a fixed mob: that + is vanilla's `rule` processor with an `append_static` block entity. Moog's vanilla loot + swap acts only when a "replace vanilla" preset is on, and they ship off. Moog's trial + spawner and vault processors keep the block and change its block entity: one `rule` per + block state, with the game's `horizon:edit` modifier, which takes out the state the + template was saved with (a vault saved with `state_updating_resumes_at` far in the future + never opens; a spawner's saved `spawn_data` blocks its own mobs) and merges in the + spawner's normal and ominous configs (by id: the carry upgrades `trial_spawner/` files' + mobs to 26.3's `equipment`) or the vault's loot table and key. Better Desert Temples' + placeholder blocks (orange, red and white glass, blue and yellow concrete, red wool, + polished diorite, blank pots) become what its processors make of them: the fixed swaps as + vanilla's `rule`, the random ones (suspicious sand, sand and sandstone, upside-down stairs, + cobwebs, sherds on the pots) as the game's `horizon:pick`, on the same `nextFloat` as the + mod. Better Dungeons' small dungeons keep one chest and each other one with a fifth's + chance, two at most (the game's `horizon:count_cap`, counted per placement as the mod's + DungeonContext is): 12 chests in five small dungeons at seed 1234 become 6. + Lithostitched's `block_swap` (137 lists, all in ChoiceTheorem's Overhauled Village) is the + game's `horizon:block_swap`: the same map, with Block.withPropertiesOf's properties kept; + a target block the game does not have (most of them are Nature's Spirit's and Croptopia's) + leaves the block as it is, as the mod does. 273 of the 1,427 processors are carried; 1,154 + are still taken out (Formations' biome replacements, Repurposed's pillars and fluid fixes, + Lithostitched's reference, condition and apply_random, blocks aged or propped up). + In the 128×128-chunk square (seed 1234), every spawner of a mod structure now has its mob: + in the Overworld 83 Better Dungeons spawners held the template's placeholder pig and 17 of + Moog's were empty (763 spawners with a mob, up from 628); in the Nether the 52 empty ones + in Moog's Nether Structures are filled (162, up from 110). Chests are unchanged: 2,777 + and 1,405 with a loot table. + - **Rule tests** written in Java. Repurposed Structures' mineshafts and Nether monument test + blocks with three of the mod's own rule tests inside vanilla `rule` processors: what a + block is made of (solid, liquid, air, with rails and chains), a chance over the distance + from the template's origin along one axis, and a world height range. The game runs them + as `horizon:matter_phase`, `horizon:piece_origin_axis_aligned_linear_pos` and + `horizon:y_value` with the mod's fields, and carry renames them (213 in 75 lists). + - **Renamed ids.** 26.3 calls 1.21.1's chain the iron chain (its datafixers rename it in + worlds). Carry renames it in recipes, loot tables and worldgen files (112 files in 5 mods: + Repurposed's mineshafts, Better Dungeons' processors, Regions Unexplored's hanging sign + recipes...), which otherwise fail to load in 26.3. With both, the 5 Nether mineshaft pools load: 47 of + Repurposed's Nether mineshafts in the 128×128-chunk square (seed 1234), under the lava sea. + - **Big templates** (#838). Vanilla reads structure templates with no limit on their tag + count; Horizon now does too (`nbt::Limits::templates`). Seven of ATM10's 8,962 carried + templates are past the old 1,000,000-tag cap: YUNG's monument start, four When Dungeons + Arise main pieces and two Nullscape pieces. They used to load as empty templates, so their + structures never started. + - **Additions to other sets and pools** (#832 in the game, #833 in carry). A set or pool file + holding `horizon:add_to` appends its entries to the sets or pools it names (docs/mods.md). + Carry writes these from lithostitched's `add_structure_set_entries` and + `add_template_pool_elements` modifiers whose load conditions hold for the mods ported + along, and from CTOV's Java registration: its 21 village types and 11 outposts join + vanilla's `villages` and `pillager_outposts` with the mod's default weights. + - **YUNG's API** (#839, #846 in the game; #840, #847 in carry). `yungsapi:yung_jigsaw` and its + elements become vanilla's jigsaw and single element, with their rules under + `horizon:yungsapi`. The game assembles them as YUNG's `JigsawManager` does: priority + pieces, caps by name, depth ranges, `ignore_bounds` and the conditions tree. YUNG's + placements become `horizon:` keys on a random spread: `horizon:exclusion_zone` for the + enhanced exclusion zone, `horizon:avoid_biomes` for the temples' ocean and river search, + `horizon:ring_sections` for Better Strongholds' rings. `horizon:disables` on a YUNG + structure turns off the vanilla type its mod's mixin turns off. It is written only when + the game can start the replacement, so vanilla mineshafts stay while Better Mineshafts (a + Java type) can't. + - **Repurposed Structures' and Moog's own assembler** (#850 in the game, #851 in carry). Both + lay out their jigsaws with `PieceLimitedJigsawManager`, not vanilla's. Their structures, the + Nether variants too, get `horizon:piece_limited`: `y_allowance`, burying, the pools whose + fallbacks ignore the bounds, liquid, the Nether land search and ledge, and each + structure's piece caps and required pieces from the mod's `*_pieces_spawn_counts` files. + The game assembles them the mods' way and runs their post-layout steps (centring, + burying, the Nether land search). + + + Each mod's `carry-report.json` lists what was mapped, the rules and processors lost by name, + and the types left as they are. NeoForge's convention biome tags (`#c:is_forest`, ...) come + from the loader jar (`<work>/loader/neoforge-<version>-universal.jar`, fetched dev-only and + SHA-1 checked) and are written into the carry. The game skips the structures it cannot + decode. + + On ATM10's 42 data-tier mods with a jar (seed 1234, chunks -64..63, `chunkgen_bench + --starts` over the carried worldgen): 286 starts with 15,097 pieces, 150 of them vanilla's + (unchanged), and no pool that fails to decode (65 before #816 in the 64×64 centre). + - 1,061 files were mapped (MVS 413, MNS 210, MSS 157, MES 110, Repurposed Structures 104, + ChoiceTheorem's Overhauled Village 66), and 103 convention biome tags written. + - When Dungeons Arise, Structory and Towns and Towers use vanilla's types already. + - Still lost, written in Java: + - Formations' structure and element types (179): their placements read block states in the + noise column (solid, water, lava), which the structure context doesn't give yet; + - Repurposed's mineshafts, mansions and monuments, Better Mineshafts and two Better + Dungeons types: Java structure types; + - YUNG's and Moog's enhanced terrain adaptation, YUNG's piece modifiers and dead-end pools, + and the block processors written in Java (YUNG's banners, legs and decorations, Repurposed's + pillars and fluid fixes, Lithostitched's block swaps); + - MO Structures (38; its library is only on CurseForge). + + With every structure PR above, the same square (seed 1234, chunks -64..63) holds 362 + overworld starts with 22,026 pieces. CTOV has 7, Better Dungeons 72 and Better Ocean + Monuments 3, and vanilla's monuments are gone as YUNG's mod has them. In the Nether there + are 512 starts, up from 322: Moog's Nether Structures 147, Repurposed's Nether structures + 40, Better Fortresses 7, with no vanilla fortress. Over chunks -256..255: Better Strongholds 10 + (vanilla 0), Better Jungle Temples 5, Better Witch Huts 11. Vanilla's own worlds are + unchanged: the structure-start oracle still matches 35 of 35. + + Repurposed's Nether city, Nether shipwrecks and End stronghold are its generic jigsaw with + one more start check each, carried as `minecraft:jigsaw` with the check named in + `horizon:start_checks.repurposed`: open air from sea level + 20 to + 45 around the city's + chunk, no solid block in a 33×30×33 grid over a shipwreck, and land 45 blocks up at nine + points 35 and 70 blocks apart for the stronghold. Over chunks -320..319 in the Nether there + are 2 cities and 45 shipwrecks (30 and 865 without the checks); the End stronghold keeps + 8,000 blocks from the centre, and chunks 500..1139 × -320..319 hold 2 (43 without). + + In a world with the 40 mods, seed 1234, `/locate structure mvs:azelea_house` finds one 27 + blocks from spawn and it stands there as the template builds it; When Dungeons Arise's + bandit towers and Structory's chapel locate too. + ### 5. Code: one agent per mod For tiers logic, machines and deep, in dependency order, as many agents at once as the AI @@ -473,12 +630,15 @@ user's jars are, and its facts and results stay in the work folder. The first re | Glassential-renewed 3.4.7 | 105/114 | 5177/5177 | 5177/5177 | 4727/5177 | 6447/6447 | 210/210 | 105/105 | 143/143 | 106/115 | | Factory Blocks 1.4.0 | 42/49 | 42/42 | 0/42 | 42/42 | 294/294 | 84/84 | 42/42 | 1/1 | 42/49 | | Cloud Glass 1.1.0 | 16/16 | 16/16 | 16/16 | 0/16 | 112/112 | 32/32 | – | 31/31 | 16/16 | +| Chipped 4.0.2 | 6857/6981 | 46212/46443 | 46443/46443 | 46396/46443 | 149093/149093 | 13548/13714 | 11984/12378 | 6/13 | 6849/6973 | What fails is what API 0.2 cannot express yet: shapes of their own (Japanese doors, hedges, paths a sixteenth high, glass without collision), sound events of the mod's own (`factory_blocks:metal_sound`), and blocks whose vanilla class has no vanilla block with the same states (garage doors, double gates, engraved and facing paths, fans). Every drop, recipe -and tag of the declared blocks matches. +and tag of the declared blocks matches. Chipped's 124 missing blocks are its own classes (workbenches and +`DirectionBlock`), and its workbench recipes need those blocks. Its drops match since carry writes +the self-drop tables it registers in code (step 4). ### 7. Coverage report @@ -520,9 +680,9 @@ files; `inventory`; `carry` and the harness on the eight mods we downloaded; `re By tier, the 367 not yet: data 57 (carry-over and the harness, no agent: their jars were not downloaded), logic 66 (API 0.3), machines 97 (0.4), deep 92 (0.5), client 35, unclassified 20. Ported: Macaw's Trapdoors. Partial: Macaw's Doors, Fences and Walls, Paths and Pavings, -Glassential, Factory Blocks, Cloud Glass (see the harness table) and MVS, whose 784 worldgen -files are carried but not yet read by the game. Of the 8, 7 are MIT and one LGPL; nothing is -published. +Glassential, Factory Blocks, Cloud Glass, Chipped (see the harness table) and MVS, whose +structures now generate (see step 4). Of the 9, 7 are MIT, one LGPL and Chipped is under the +Terrarium License; nothing is published. ## Measuring "10x" @@ -582,8 +742,9 @@ vanilla's 35,723; the per-state tables are the next thing to measure), while the inside its 2 GB heap. Caveats, so none of this is a "10x" claim yet: other sessions and CI runners kept the machine's load average between 30 and 56 on 14 threads, so the confidence intervals are as wide as the means (`perf_bench.py --table`); Horizon's frames are paced near -the display's 144 Hz at 8 chunks; Horizon's title time includes building the content overlay on -a first start (about 5 s, cached afterwards); and the pack runs 1.21.1 against Horizon's 26.3. +the display's 144 Hz at 8 chunks; Horizon's title time includes building the content overlay +(about 5 s for six mods; it was rebuilt on every start then, and is kept for later starts now); +and the pack runs 1.21.1 against Horizon's 26.3. A quiet rerun with more games is the next measurement. **Where the RAM goes (2026-10-17).** RSS overstates it on macOS. `ps` counts pages the allocator @@ -620,8 +781,46 @@ indexes ids by a hash checked against the states: -22 MB live for vanilla, -124 ATM10's, -30 MB and -140 MB of footprint. The startup peaks are what is left. Each step parses its per-state tables whole: as JSON trees, or as NBT trees of 300-600 MB each for ATM10 (`block-properties.nbt`, the collision, support, occlusion and movement tables). The peak -reaches 3.9 GB during worldgen loading, and the footprint stays near the peak. Typed, streaming -readers for those tables are the next cut. +reaches 3.9 GB during worldgen loading, and the footprint stays near the peak. + +The NBT tables now stream: the readers check each state's identity as it is read, and no +`states` tree is built (#753). That tree was about 240 MB for each table. With the carried +ATM10 mods (153,511 states), the peak of each step falls by about 210 MB: + +| step | before MB | after MB | +|---|---:|---:| +| light | 911 | 699 | +| collision | 945 | 733 | +| motion | 1,427 | 1,215 | +| worldgen, uncached | 3,000 | 2,788 | + +The fluid tables no longer decode the 211 MB `gameplay-facts.json` a second time (#754). The +content root is kept between starts (#756). What is left at startup: + +- `facts.json` went through a JSON tree, then an NBT tree, in both the registry and the assets + step. It now streams (#825): at ATM10's size (214,338 states) each step's peak fell from + 816 MB to 153 MB (registry) and 235 MB (assets), and the RSS after the assets step from + 1,344 MB to 442 MB; +- on a first start, the content-root build and `Behaviours`' decode of `gameplay-facts.json` + (cached afterwards in the behaviour snapshot). + +**Against NeoForge, same 40 mods (2026-10-17).** The 40 data-tier mods carried from ATM10 (the +42 without Regions Unexplored and MO Structures, whose libraries are only on CurseForge), +against their jars on NeoForge 21.1.259 with `-Xmx2G`. `perf_bench.py --port-work`, RD 8, one +game each, load average 80-125 on 14 threads; `--warm` measures a later start: + +| game | title / world s | RSS steady / peak MB | footprint steady / peak MB | +|---|---|---|---| +| Horizon before #756 (every start) | 81.1 / 102.8 | 4,008 / 4,164 | 2,368 / 2,554 | +| Horizon, first start | 105.2 / 128.8 | 3,795 / 3,993 | 2,306 / 2,560 | +| **Horizon, later starts** | **21.6 / 33.7** | **2,629 / 2,935** | **2,445 / 2,731** | +| NeoForge + 40 mods | 53.2 / 119.9 | 3,099 / 3,203 | 3,304 / 3,381 | + +On later starts, Horizon uses 15 % less RSS and 26 % less footprint than NeoForge with the +same mods. It reaches the title 2.5x sooner and the world 3.6x sooner, and its flights ran at +93-233 FPS against NeoForge's 27-62. The first start is slower than NeoForge's to the title, +because it builds the content root once. One game per row on a loaded machine is not a +benchmark; a quiet rerun with repeats is still to do. ## The working version for 2026-10-23 @@ -648,11 +847,9 @@ In scope (each is a PR or a small stack): 6. **Measured:** load time, RAM and FPS of that pack on NeoForge 1.21.1 against Horizon, with the full ATM10 on NeoForge as the reference row. -Out of scope for that date, and next in order: worldgen carry-over (the 30 or so structure and biome mods; -the first one looked at, Moog's Voyager Structures, declares all 130 structures and 116 structure -sets with MoogsStructureLib's own `generic_jigsaw_structure` and `advanced_random_spread` types and -NeoForge's `c:` biome tags, so its carry needs a mapping to vanilla's jigsaw and random spread -types plus the oracle's biome tags, not only bundle merging), +Out of scope for that date, and next in order: the rest of worldgen carry-over (mods' +structures, sets, pools and features generate now, see step 4; mod biomes, noise and density +functions, and the structure types written in Java such as YUNG's and Formations', do not yet), behaviour callbacks and server events (0.3), block entities, menus, capabilities and net (0.4), the first agent-ported logic-tier mod as the pilot of step 5, then machines. Porting all of ATM10 is a campaign. Each step publishes its coverage number; we make no claim beyond what diff --git a/docs/mods.md b/docs/mods.md index d1556abd7..bdf45f620 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -287,6 +287,22 @@ its row. The game reads this content into its block and item tables nobody registers (a block a port left out, another mod's item) is dropped, so the rest of the tag still loads; vanilla would drop the whole tag. +A mod adds to structure sets and template pools that are not its own +(vanilla's villages, another mod's houses) with a set or pool file in its own +namespace holding `horizon:add_to`, a key vanilla data never has. Its entries +are appended to each set or pool named, after every mod's own files, in mod +and file order; the file is no set or pool itself. A name nobody defines is +skipped. + +```json +{ "horizon:add_to": "minecraft:villages", + "structures": [ { "structure": "mymod:village_beach", "weight": 10 } ] } +``` + +A pool addition holds `"elements"` as a pool does. This is what lithostitched's +`add_structure_set_entries` and `add_template_pool_elements` modifiers do on +NeoForge and Fabric, and `horizon-port-pack carry` writes them from those. + ## Versions and compatibility - The API is the WIT package `horizon:mods@0.1.0`. New functions and diff --git a/docs/native-client.md b/docs/native-client.md index 4911c8197..fcf28246a 100644 --- a/docs/native-client.md +++ b/docs/native-client.md @@ -109,7 +109,7 @@ game accepts, test hooks included. - **Observe:** `state` (position, rotation, velocity, health, food, saturation, XP, effects, game mode, dimension, time, weather, the screen and what the crosshair points at), `looking-at`, `entities [RADIUS] [TYPE]` (mobs with - ids and health, dropped items, orbs), `block X Y Z`, `blocks X1 Y1 Z1 X2 Y2 Z2`, + ids and health, dropped items, orbs), `block X Y Z`, `blocks X1 Y1 Z1 X2 Y2 Z2`, `light X1 Y1 Z1 X2 Y2 Z2`, `find-block BLOCK [RADIUS]`, `inventory` (stacks with their components as SNBT), `screen` (the open screen or title menu, its buttons and slots) and `messages` (chat, title, subtitle and action bar). diff --git a/docs/performance/paletted-container-access-results.md b/docs/performance/paletted-container-access-results.md new file mode 100644 index 000000000..08783d290 --- /dev/null +++ b/docs/performance/paletted-container-access-results.md @@ -0,0 +1,73 @@ +# Paletted container access + +The `unpack`/`get` cell reader and `BlockSection::get`/`set` are hot in the +chunk workers: light and mesh workers unpack a section's 4,096 cells before +propagating or meshing, and world-generation workers write one block at a time +through `BlockSection::set`. + +The write path resolved the old cell and probed the palette three times; the +bulk readers dispatched the palette per cell; and the storage layer revalidated +indices and values a section had already checked. All three are addressed. + +## Changes + +`BlockSection::set` (`crates/horizon-world/src/chunk.rs`) previously resolved the +old cell through `get` and then probed the section's palette map three times for +one non-trivial write: once to key the old state by id (`local_ids[&old]`), once +to test the incoming state (`contains_key`), and once to find it (`get`). The +slot at the written index already *is* the old state's id, so the old state is +now read straight from storage, and the incoming state is resolved with a single +map probe. The palette-reuse, free-slot and growth paths are unchanged, so the +encoded palette, counts, free list and NBT output stay identical. + +`BlockSection::get` and `set` validate the section index and the state id once, +then read and write through `PackedStorage::read`/`write` +(`crates/horizon-core/src/storage.rs`). These skip the storage-level bounds and +value checks and the `Result` that `PackedStorage::get`/`set` keep for external +callers: a section index is below 4,096 and a palette id always fits the width +`bits_for_palette` chose. Both new methods `debug_assert` their contract and are +used for the hot read, the hot write and the palette-growth re-encode. + +`PalettedContainer::unpack` and `unpack_u16` +(`crates/horizon-core/src/paletted.rs`) matched on the palette variant inside the +per-cell loop. `Single`, `List` and `Global` are now dispatched once before the +loop, leaving each arm a branch-free indexed loop. + +No allocation, layout or wire format changes. + +## Reproduce + +```sh +cargo test -p horizon-world --lib --profile fast benchmark_section_get_set -- --ignored --nocapture +cargo test -p horizon-core --lib --profile fast benchmark_unpack -- --ignored --nocapture +``` + +The ignored tests compare the new code against copies of the pre-optimization +implementations, kept in the test modules (`baseline_get`/`baseline_set`, +`baseline_unpack`). They check every resulting palette, count, free list, cell +and NBT before timing. Rounds alternate baseline/optimized order with `black_box` +and report the median and best nanosecond- or microsecond-per-operation; the best +round is the estimate of uninterrupted CPU time on a contended machine. + +`benchmark_section_get_set` uses a 32-state registry and 50,000 random writes and +reads per round over a section whose palette grows through the 4- and 5-bit +widths (24 distinct states); 51 rounds. `benchmark_unpack` fills a 4,096-entry +list palette (12 states) and the global palette, 2,000 calls per round, 25 +rounds. + +AMD Ryzen 5 5600X, Linux x86_64, rustc 1.99.0, optimized `fast` profile, +nonincremental, no LTO: + +| Operation | Original main | New | Speedup | +| --- | ---: | ---: | ---: | +| `BlockSection::set` | 13.15 ns/write | 9.12 ns/write | 1.44x | +| `BlockSection::get` | 2.33 ns/read | 1.45 ns/read | 1.61x | +| `unpack`, list palette | 1.910 us/call | 1.834 us/call | 1.04x | +| `unpack`, global palette | 2.270 us/call | 2.179 us/call | 1.04x | + +The distinct-state differential test +`chunk::tests::set_matches_baseline_under_random_edits` drives the optimized +`set` and `get` and the originals over the same 50,000-edit streams for 1, 2, 16, +17, 24 and 64 distinct states, including periodic whole-section collapses that +clear the storage and reclaim palette slots, and asserts equal results, bits, +palette, counts, free list, `local_ids` and NBT throughout. diff --git a/docs/performance/startup-stage-3.md b/docs/performance/startup-stage-3.md new file mode 100644 index 000000000..28013e87c --- /dev/null +++ b/docs/performance/startup-stage-3.md @@ -0,0 +1,39 @@ +# Progressive world resources (#712) + +Stage 3a changes shared resource storage and accessors. Pack resources keep their existing per-game ownership for pack reloads. Stage 3b publishes core before the simulation tail, builds the real renderer using the previous device after releasing its surface, and gates backdrop streaming on that renderer. Stage 3c queues an early Play or Connect action and draws the existing level-loading progress screen while polling the worker each event-loop turn. Close and resize events continue to work. After the worker completes, the queued local/server action resumes; integrated servers receive the resource handle only after that join. The synchronous harness and dedicated path returns only fully loaded resources. + +Startup logs distinguish `core-ready`, `world renderer ready`, `starting title backdrop`, and `rest-ready`. Opt-in performance summaries carry `to_core_ms` and `to_rest_ms` separately from the existing UI-driven `to_title_ms`. Loader failures and panics propagate to the client; a tail taking more than 120 seconds fails rather than waiting indefinitely. + +## Stage 3d: interactive menu before core + +An ordinary launch now owns a `StartupMenu` inside `Loading`. The first menu atlas and panorama message makes the existing title screens interactive; assets, facts, biomes, pack tables, collision and motion continue on the resource worker. Pack-overlay and mod-content preparation also run on that worker. The live landscape still starts only after the core renderer exists. + +World browsing, world creation, server address entry and options use the existing title/options widgets. Play and Connect queue a `PendingWorldEntry`; the progress screen covers both the core and tail waits. Escape cancels the queued entry in either phase. Close and resize continue to work. The handoff transfers the title object, options screen, settings, cursor, clipboard selection, timing session and pending action instead of rebuilding the user's screen. + +Pack changes during core loading request another loader generation. The old core and tail finish before replacement begins so cache writes and tail registry initialization cannot overlap. Each generation has its own message channel and progress counter. Language/GUI metadata publication stays on the event-loop thread, using the current language selection rather than the worker's stale settings snapshot. Pack changes after the core handoff also wait for the tail before touching mob metadata. + +The menu still needs its own artwork and renderer before interaction. The core handoff still builds the full renderer and starts audio on the main thread; menu click sounds and controller navigation start with `Game`. This stage does not change synchronous harness/dedicated startup or introduce a render-facts export. + +Regression coverage publishes menu artwork while a fake core worker is blocked, edits a world draft, replaces fallback artwork without losing it, queues entry and draws progress, and checks that loader failure reaches the app. Additional checks cover server identity and cancelled-entry timing. + +## Render facts assessment + +`MeshTables::new` reads names, registry properties, class membership, collision shape flags, fluid and render properties from `BlockFacts`. `LightTables::new/load` reads emission, dampening, occlusion and shape-occlusion flags; geometry comes from `occlusion.nbt`. Neither table needs recipes, item data, AI or the other tail tables. + +A render subset is possible, but the current facts decoder also validates registry order and builds the gameplay projection from the same document. Meshing additionally depends on class chains from `block-behaviours.json`. Avoiding the 54 MB read requires an exported render-facts artifact (and its prepare/cache/version checks), or another decoder plus a second full read at world entry. This is beyond a cheap startup ownership change. Stage 4 can add that artifact and compare the resulting mesh/light tables against the full loader before moving facts out of core. + +## Measurement + +Measurements on this machine are warm runs with `HORIZON_NO_AUDIO=1`. Other compilation and parity jobs were running, so elapsed times are diagnostic rather than a controlled benchmark. + +Before phasing (3a, `42d65465`), `--offscreen --frames 3 --smoke-report` completed successfully with peak RSS 762,536 KiB. The report contained 3 frames, no chunks, no generated or meshed sections, no player, and no error. This is the synchronous harness path; the progressive path is measured separately after 3c. + +After phasing, the same warm three-frame synchronous smoke completed successfully with peak RSS 774,080 KiB, up 11,544 KiB (1.5%) from the 3a measurement. Both reports had 3 frames, no chunks, no generated or meshed sections, no player, and no error. Elapsed time is intentionally excluded from the comparison because the machine was running concurrent builds. + +The progressive checks used an overlay of the prepared resources with `mob-data.json` replaced by a FIFO. This holds WorldRest without a production delay hook. Core and the real renderer became ready, Options → Video opened, and the backdrop logged `title backdrop ready; world rest ready: false` before the FIFO was released. In an unblocked Horizon launch, core was ready at 4,776 ms, the renderer at 5,260 ms, and rest at 6,282 ms under compilation load. Backdrop generation and fade-in still take their own time; these marks measure bundle readiness separately. + +A direct singleplayer launch while the FIFO was held displayed `Loading items` and handled a window resize. Releasing the FIFO resumed entry; the run exited cleanly with a player, 85 chunks, 529 meshed sections and no error. That delayed-entry run peaked at 1,142,560 KiB, including the loaded world. Integrated-server entry also joined after release and rendered a world. Dedicated startup reached `Done`, handled `list` and `stop`, saved and exited with status 0 without constructing a renderer. + +The full parity selection against `origin/main` also includes the unmerged Stage 2 ancestors (313 harnesses). The local run was bounded at 30 minutes; its log recorded passes for `active_effects`, `active_effect_tick` and `anchor`. The remainder needs CI or a longer dedicated run. The client Rust tests, focused startup probes and memory measurements are separate from that incomplete parity run. + +Progressive-title RSS was measured separately with audio disabled, render distance 4 and a 30 FPS cap, using separate temporary game directories. The first 30-second pair measured 1,055,132 KiB before and 1,721,772 KiB after. A warm 60-second repeat in reverse order measured 1,031,948 KiB before and 1,145,776 KiB after: an increase of 113,828 KiB (about 111 MiB, 11%). These launches ran during compilation and did not advance through startup/streaming identically. They establish a memory cost to investigate, not a claim of RSS parity; a quiet-machine cold/warm comparison remains needed before merging the stack. diff --git a/docs/portal-scan-benchmark.md b/docs/portal-scan-benchmark.md new file mode 100644 index 000000000..b8104ef26 --- /dev/null +++ b/docs/portal-scan-benchmark.md @@ -0,0 +1,81 @@ +# Nether-portal section-scan benchmark + +Run with the pinned prepared client resources: + +```sh +CARGO_BUILD_JOBS=6 cargo run --profile fast -p horizon-client --example portal_scan_bench -- \ + .local/horizon-client/26.3 +``` + +The example keeps the original `Game::may_hold_portal` alongside the resident +cache (`portal_sections`). Both run in the same optimized binary, alternating +measurement order. Each workload has one discarded warmup pair and seven pairs +of 300 ticks. It reports resource loading and fixture construction separately. +This measures the section scan only, not the whole `entity_portals` span, the +sweep that follows a positive answer, or the rest of the tick. + +The fixture is a 17x17 chunk world (289 chunks), each with 24 sections, and 500 +entity reaches spread over it (an item or mob box 0.25 wide and the small move +that produces the swept box). A reach touches 1-4 sections. Four palettes: +sparse (one non-portal state), dense (128 distinct), global (300 distinct, a +global palette whose `maybe_has` walks the whole state range) and dense_portal +(the dense palette with a portal in every fifth section). These are controlled +fixtures, not a claim about typical generated terrain. + +Steady includes the initial cache fill amortized over 300 ticks. Cold recreates +the cache each tick, including allocation and destruction; reload clears it each +tick while retaining capacity. Edit workloads alternate a block value in three +or all 289 chunks before every scan. Timing includes the `Arc::make_mut` move of +the 176-byte chunk wrapper caused by weak cache handles; the baseline holds no +such handles. Both paths keep the original outer reach list. + +The scan is parity-checked in the same run: the cached and per-tick answers must +agree for every reach over every sample, or the example panics. + +Measured on an AMD Ryzen 5 5600X (12 logical CPUs), Linux x86-64, rustc 1.99.0 +(b940084d7), using `fast` (release optimization, LTO off, 16 codegen units). +Resource loading took 705 ms; fixture construction took 66 ms sparse, 360 ms +dense, 392 ms global and 385 ms dense_portal, shared by both implementations. + +Median microseconds per tick (seven paired samples): + +| Palette | Workload | Original | Cached | Speedup | +| --- | --- | ---: | ---: | ---: | +| sparse | steady | 40.058 | 16.836 | 2.38x | +| sparse | cold | 40.203 | 48.619 | 0.83x | +| sparse | reload | 40.828 | 44.552 | 0.92x | +| sparse | edit_1pct | 41.282 | 52.200 | 0.79x | +| sparse | edit_all | 50.119 | 4192.396 | 0.01x | +| dense | steady | 244.610 | 21.869 | 11.19x | +| dense | cold | 292.533 | 1505.691 | 0.19x | +| dense | reload | 250.397 | 1301.608 | 0.19x | +| dense | edit_1pct | 256.522 | 69.132 | 3.71x | +| dense | edit_all | 263.829 | 5904.581 | 0.04x | +| global | steady | 6179.070 | 360.082 | 17.16x | +| global | edit_1pct | 6251.530 | 1565.249 | 3.99x | +| dense_portal | steady | 256.854 | 21.078 | 12.19x | +| dense_portal | cold | 240.498 | 1526.251 | 0.16x | +| dense_portal | reload | 347.879 | 2037.123 | 0.17x | +| dense_portal | edit_1pct | 368.684 | 118.108 | 3.12x | +| dense_portal | edit_all | 282.876 | 7194.112 | 0.04x | + +The global palette's `maybe_has` walks the whole ID range, so rescanning every +chunk each tick (cold, reload, edit_all) is intractable; those rows are not +measured for it. + +Keep: the steady scan improves for every palette (2.4x to 17x), which is the +case that repeats each tick in real play. Under constant edits the cache also +improves the dense and global palettes (edit_1pct 3-4x) because the original +rescans through the per-tick map. Rescanning every chunk every tick (cold, +reload, edit_all) is slower than the original because a miss scans all 24 +sections of a chunk, where the original only touched the sections a reach +overlaps. No whole-game speedup is inferred from this microbenchmark; real +terrain's palette sizes and block-write frequency determine the gain. Lighting +and other chunk changes conservatively invalidate a chunk's mask. + +The cache adds a weak handle and mask per visited resident chunk, retains no +unloaded block data, and is pruned when a chunk unloads (`sync_tick_chunks`) and +cleared on resource reload, like `random_tick_sections`. Editing a cached chunk +can move its 176-byte wrapper (plus Arc bookkeeping) on the first edit after it +is cached; it does not force a deep copy of the block data. The original outer +reach-list allocation remains. diff --git a/docs/release-flow.md b/docs/release-flow.md index f1015a31f..b72d896b8 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -131,6 +131,7 @@ the notes. | Archive | Runs on | Checks | | --- | --- | --- | | `horizon-linux-x86_64.tar.gz` | GitHub `ubuntu-22.04` (an older glibc, so it runs on any recent distribution) | the standard loader and libraries only (`tools/check_imports.py`) | +| `horizon-server-linux-x86_64.tar.gz` | the same Linux job, after the client archive: `horizon-server`, `horizon-prepare` and the game built with `--no-default-features` as `horizon-engine` (docs/server.md) | as above, and neither `libasound.so.2` nor `libudev.so.1` (`tools/check_imports.py --server`) | | `horizon-windows-x64.zip` | GitHub `windows-latest`, C runtime linked in | system DLLs only (`tools/check_imports.py`) | | `horizon-macos-arm64.zip` | The Mac mini's runner (`vars.MAC_RUNNER=macos-latest` sends it to GitHub) | system libraries only (`otool -L`); a 1500-frame offscreen run of a new world (about 12 s; 300 frames end before the world has loaded) with resources prepared from the runner's own Minecraft (`--offscreen --world smoke --frames 1500 --smoke-report`: frames drawn, chunks generated and meshed, a player, no error) | diff --git a/docs/server.md b/docs/server.md index 30b81f64a..3d8eb69c8 100644 --- a/docs/server.md +++ b/docs/server.md @@ -55,9 +55,10 @@ distance 10. The vanilla server was the pinned 26.3 `server.jar` on Java 25 with | What has to be installed | one 46.8 MB binary + 589 MB of prepared resources | Java 25 + the 62 MB jar | | Crates linked | 384 (wgpu, winit, cpal, gilrs, arboard, naga…) | n/a | -On Linux the binary loads `libasound.so.2` (cpal) and `libudev.so.1` (gilrs) at startup, even on a server. -wgpu, winit and the Wayland/X11 libraries are loaded only when a window opens. That makes a minimal -container image need ALSA and udev for a program that never plays a sound or reads a controller. +On Linux the full game loads `libasound.so.2` (cpal) and `libudev.so.1` (gilrs) at startup. wgpu, winit +and the Wayland/X11 libraries are loaded only when a window opens. The server build (`horizon-engine`, +section 3) is the same program built without its `audio` and `controllers` features, so it needs neither +library, and a minimal server image runs it as it is. The two clear losses are RAM and idle CPU. The dedicated server loads everything the client needs to draw (the HUD atlas, item renderer, block-entity models, panorama, fog and music tables, entity models), and it @@ -74,15 +75,20 @@ not tick cost, so it is in scope here (see section 9). headless client built from vanilla's own codecs, pings and joins Horizon's server and vanilla's from the same world copy. It compares every login, configuration and play packet up to the first chunk batch, the chunk bytes, chat, `/list`, failing commands, the console lines and the files left behind. Result on main: - see "Harnesses on main" below. The real vanilla GUI client (`tools/vanilla_client.py`) could not be run - here: the tool only knows Linux natives, and the Mac mini's session was locked, which stalls the client's - rendering. It runs on the desktop under vscreen. + see "Harnesses on main" below. +- **The real vanilla 26.3 client** (`tools/vanilla_client.py`, from the owner's own files, dev-only) joins + too. On 2026-10-18 it joined the server build of the game (`horizon-engine`, section 3) on the Mac mini: + `python3 tools/vanilla_client.py --name Vanilla --join localhost:PORT`. It logged in, drew the terrain + around spawn and stayed connected for four minutes, with no warning or error on the server. The tool + runs on Linux under vscreen and on macOS from the logged-in screen session, even a locked one, with vsync + off. ### What fails or is missing | Area | Status | |---|---| -| `online-mode=true` | **Works** (ServerLoginPacketListenerImpl): a 1024-bit RSA key pair at start ("Generating keypair"), the encryption request, the shared secret and challenge, AES/CFB8, and the session service's `hasJoined` check (with the address when `prevent-proxy-connections` is on), with vanilla's log lines and messages. `test_online_mode_parity.py` runs the same logins against vanilla's server and Horizon's with a mock session service. Not yet: secure chat (chat is unsigned, as on a server that doesn't enforce it). | +| `online-mode=true` | **Works** (ServerLoginPacketListenerImpl): a 1024-bit RSA key pair at start ("Generating keypair"), the encryption request, the shared secret and challenge, AES/CFB8, and the session service's `hasJoined` check (with the address when `prevent-proxy-connections` is on), with vanilla's log lines and messages. `test_online_mode_parity.py` runs the same logins against vanilla's server and Horizon's with a mock session service. | +| Secure chat | **Works** (`SignedMessageChain`, `LastSeenMessagesValidator`, `MessageSignatureCache`): the chat session update and its profile key, checked against the services' `playerCertificateKeys`; signed chat, `say`, `me` and `msg`, relayed with their signatures and last-seen lists; `enforce-secure-profile` (with `online-mode`) refuses unsigned chat; and vanilla's log lines (`[Not Secure]`, the decoder's warnings, the kicks). Offline servers and players without a chat session chat unsigned, as on vanilla. `test_secure_chat_parity.py` runs the same signed and unsigned players against vanilla's server and Horizon's, with test keys and a mock services server. | | Nether and End | **Players can't change dimension.** The engine keeps one dimension loaded (`Game::enter_dimension` moves only the local single-player player), and the hub serves one `dimension` to everyone. | | Refused logins | Logged as vanilla does: `Disconnecting <name> (/address): <reason>`, then `<name> (/address) lost connection: <reason>`, and the session errors (`Username '<name>' tried to join with an invalid session`, `Couldn't verify username because servers are unavailable`). | | Gameplay for remote players | The LAN guest leftovers apply: an item used on a block is used twice, the recipe book doesn't work, status effects don't apply to guests, arrows don't record their owner, team friendly fire is ignored (#484). Block desync and short freezes are reported on a same-machine server (#500). | @@ -144,16 +150,22 @@ game built in `Game::new`, the integrated server on its own thread. On that base 1. The dedicated path skips everything only a window uses: the HUD atlas, item renderer, block-entity and entity models, panorama, fog, music, and mesh tables (perf-ticks-2 already stops server-side meshing). This is the RAM and start-time item. -2. The game moves into a library crate, with the window, audio and controller parts behind a `client` - feature. A `horizon-engine` binary built without that feature links no wgpu, winit, cpal or gilrs, and - needs neither ALSA nor udev. The supervisor finds it beside itself and falls back to `horizon-client`. +2. The game moves into a library crate, with the window parts behind a `client` feature, so + `horizon-engine` links no wgpu or winit either. Sound and controllers are already optional (the + `audio` and `controllers` features, on by default): `horizon-engine` today is the game built without + them (section 3). ## 3. Packaging -**Binaries.** The release archives already hold `horizon-client`, `horizon-ctl` and `horizon-prepare`. -`horizon-server` joins them (PR 3: `xtask package` and `release.yml` build it and check it starts). Once -`horizon-engine` exists (section 2), a separate small archive per platform -(`horizon-server-<os>-<arch>.tar.gz` or `.zip`) holds just the server's binaries. +**Binaries.** The release archives hold `horizon-client`, `horizon-ctl`, `horizon-prepare` and +`horizon-server`. On Linux the release also has `horizon-server-linux-x86_64.tar.gz`: `horizon-server`, +`horizon-prepare` and `horizon-engine`, the game built with `--no-default-features` (no sound, no +controllers), which links neither `libasound.so.2` nor `libudev.so.1`. `release.yml` builds it after the +client archive (`xtask package-server`) and fails if `tools/check_imports.py --server` finds either library; +CI lints the same build. `horizon-server` runs `horizon-engine` when it is beside it or on the PATH, else +`horizon-client`. Build it yourself with `cargo build --release -p horizon-client --no-default-features` +and copy `target/release/horizon-client` as `horizon-engine`. macOS and Windows have no such libraries to +avoid, so they keep the one archive. **Game files: the owner's own copy, as with `prepare`.** Nothing of Mojang's is redistributed and nothing is downloaded on the owner's behalf. `horizon-server` looks for prepared resources in this order: @@ -180,10 +192,16 @@ comes out of the headless-engine work. - Linux and macOS: `curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.sh | sh` - The script picks the release archive for the OS and architecture (Linux x86_64, macOS arm64), downloads - it from GitHub Releases, and checks it against the SHA-256 GitHub publishes for each asset. It never asks - for sudo. Options: `--version vX.Y.Z`, `--dir` (default `~/.local/share/horizon`), `--bin` (default - `~/.local/bin`). + The script picks the release archive for the OS and architecture (on Linux x86_64 the server archive, + on macOS arm64 the game's), downloads it from GitHub Releases, and checks it against the SHA-256 GitHub + publishes for each asset. It never asks for sudo. Options: `--version vX.Y.Z`, `--dir` (default + `~/.local/share/horizon`), `--bin` (default `~/.local/bin`), and `--archive FILE` to install an archive + already on the machine (a build of your own; no download and no checksum). + A Linux release from before the server archive installs the full game, which links ALSA's and udev's + libraries (`libasound.so.2`, `libudev.so.1`); minimal server images often lack them (Debian and Ubuntu: + `sudo apt install libasound2 libudev1`, `libasound2t64` on Ubuntu 24.04 and later). Then the script lists + any that are missing, `init` warns, and `run` stops at once with what to install, rather than restarting + a game that can't load. - Windows: `irm https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.ps1 | iex` The script does the same into `%LOCALAPPDATA%\Horizon` (`-Version`, `-Dir`), with junctions instead of @@ -195,8 +213,8 @@ comes out of the headless-engine work. (`horizon-prepare`, `horizon-server init`). **Docker** (`packaging/server/Dockerfile`, built the same way as the relay's image): a multi-stage build that -ends on `debian:bookworm-slim` as user `horizon`. It adds `libasound2` and `libudev1` until the headless engine -lands. It uses volume `/data` for the server folder, takes the owner's prepared game files as a read-only +ends on `debian:bookworm-slim` as user `horizon`, with the server build as `horizon-engine`, so the image needs +no ALSA or udev. It uses volume `/data` for the server folder, takes the owner's prepared game files as a read-only mount on `/opt/horizon/.local/horizon-client/26.3`, exposes port `25565/tcp`, and keeps the control API (and later the panel) on 127.0.0.1 inside the container: `docker exec <name> horizon-server status|cmd|backup`. On the first start, `HORIZON_EULA=true` and `HORIZON_WORLD`, `HORIZON_SEED`, `HORIZON_PORT`, @@ -479,6 +497,30 @@ reproducible by anyone, and show the same gameplay on both sides. and every packet woke its connection's writer thread (#649). Together they took the 50-bot walking tick from 281 ms to 31 ms. At 25 walking bots most of what remains is the engine's streaming and block entity ticks, both of which grow with players (the README has the profile). +- **Mixed bots, as installed (2026-10-18,** `benchmarks/server-mixed-2026-10-18/`, the first published + run for the working version). It used the v2026.10.18.15 release as `install.sh` installs it, against + vanilla 26.3, with 1, 10, 25 and 50 `mixed` bots and vanilla's default game rules on both (Horizon has + the locator bar now). The servers ran on the ThinkPad and the bots on the Mac mini. Results: + - Both kept 20 TPS in every run. + - Horizon's RSS was 3.7 to 5.2 times smaller (1.0 GB against 4.0 GB at 50). + - Horizon's average tick was shorter with 1, 10 and 25 bots (2.4 against 17.9 ms, 12.4 against 34.5, + 24.0 against 31.6) and longer with 50 (35.2 against 29.7). Its P99 was lower at every count. + - Horizon also did more work: it kept up with the exploring bots, so it generated 1.9 to 2.9 times + the new terrain a second. +- **Mixed bots, equal work (2026-10-18,** `benchmarks/server-equal-mixed-2026-10-18/`). This is the same + run with the load made equal. The explore bots fly at 0.8 blocks a second, so every bot follows the same + path on both servers and none waits for terrain. A 300-second warm-up lets both finish the bots' first + views before the measurement. `server_bench.py` now prints a work table that compares each count's chunks + a second across servers and flags a run that isn't equal. Horizon ran as `horizon-engine`, the server + build, installed from its archive. Results, on the ThinkPad again (the desktop didn't wake): + - The work was equal at 1 and 10 bots. At 25 the chunks sent a second were equal (158.6 against 157.6), + and vanilla still sent 2.5 more first-time chunks a second while it caught up. + - Tick: 1.8 against 11.3 ms at 1 bot, 4.7 against 34.3 at 10, 11.7 against 50.5 at 25 (vanilla 19.8 TPS). + At 50 Horizon ran at 23.8 ms. Vanilla's watchdog stopped its server 30 s after the last bot joined (a + 60-second tick). This is one pass, to repeat on a bigger machine. + - Horizon's RSS was 4.1 to 4.9 times smaller (1.03 GB at 50). + - Served in full, vanilla's walking bots got 5400 to 6100 chunks each, against 640 to 1100 in the first + run. That is why vanilla held 50 bots there and not here. - **Ownership.** perf-server-1 owns making the tick faster. This work only measures it, files what it finds, and fixes startup, RAM and packaging. @@ -497,7 +539,8 @@ vanilla. archive in the release. 3. The web panel MVP: status, live TPS/MSPT/RAM/CPU, players, console, backups and login links. 4. `horizon-bots` and `tools/server_bench.py`, with a first run against vanilla (1/10/25/50 bots, `mixed`) - published in `benchmarks/`. + published in `benchmarks/`: done, `benchmarks/server-mixed-2026-10-18/`, and with equal work + `benchmarks/server-equal-mixed-2026-10-18/` (section 9). 5. Small engine fixes found on the way: logging refused logins (vanilla's lines). **Where it stands (2026-10-16):** items 1 to 4 are built and in review (section 11). What's left for the 23rd: @@ -507,7 +550,6 @@ machine, then published in `benchmarks/`; and item 5. **Out (next):** -- secure chat on the server (online mode itself works); - the Nether and End for remote players; - the headless engine and its RAM win; - a server-only prepare without a JDK; diff --git a/docs/surface-generation-benchmark.md b/docs/surface-generation-benchmark.md new file mode 100644 index 000000000..e40849c19 --- /dev/null +++ b/docs/surface-generation-benchmark.md @@ -0,0 +1,15 @@ +# Constant surface-rule specialization benchmark + +The upstream PR contains only the surface change and tests, reapplied to upstream main. The measurements below were collected with #796 present; they are historical incremental measurements, not new timings for the rebased upstream head. + +This surface-only change is based on the bulk unary density optimization in [upstream PR #796](https://github.com/ludovic111/horizon/pull/796). Measurements compare against `eb3789038e3184c98a1459fe638947200217d360`, which already includes that optimization; its savings are not counted again. + +With one worker, primary initialized Overworld terrain time improved from 10.664 to 10.298 ms/input chunk (3.43%). Terrain plus decoration improved from 12.645 to 12.242 (3.19%). With four workers, terrain improved 2.48% and combined time 2.07%. Nether terrain improved 4.16% / 3.93% with one/four workers; combined improved 3.76% / 3.63%. The second Overworld site improved terrain 2.53% / 2.81%. End improved 2.95% with one worker but regressed 2.93% with four, with substantial paired noise. This meets the revised 3% median gate on selected representative cases, not the original 5% gate or every workload. + +Cases were declared before editing. Each used one discarded pair followed by five alternating baseline/candidate pairs, with identical work and builds. The primary case used seed 12345, center (0,0), 256 terrain chunks and 196 decorated interior chunks, at one/four workers across all three dimensions. The second Overworld case used seed -1 at (32,-32). An offset 9×9 generation pass initialized the same seeded generator without pre-generating the measured region. Wall time is elapsed/input count; combined time includes the complete decoration phase and required borders. Cold startup was measured separately. + +Machine: AMD Ryzen 5 5600X, 32 GiB RAM, Linux, Rust 1.99.0. Optimized `fast` profile: release optimization, LTO off, 16 codegen units. Runs and builds were sequential; background desktop activity was not isolated. Memory use was effectively unchanged. The benchmark used the existing chunkgen benchmark with identical optional initialization and exact timing instrumentation on both revisions. `crates/horizon-world/examples/chunkgen_bench.rs` is the standard workload entry point; its thread-multiplied human-readable ms/chunk display differs from actual elapsed/count. + +Validation passed: 102 targeted Rust tests; 162 world-crate tests; 24 exact complete-field baseline/candidate terrain and decorated comparisons across three dimensions, two sites/seeds, and one/four workers; and six fresh pinned Java 26.3 client/server suites covering material stages, rule library, conditions, temperature, extensions, and surface generation. Differential snapshots included block states/palettes, quart biomes, binary entities/block entities, scheduled ticks, all six heightmaps, ordered postprocessing, non-air counts, and chunk metadata. Compilation/binding errors, dynamic queries, and short-circuit behavior have regression coverage. The final production executable matched the measured candidate byte-for-byte. + +The repository quick PR check also passed public-tree validation, Python tests, formatting, clippy, and world tests. Validation is scoped to the declared corpora and does not establish complete gameplay parity. Generated timing files, diagnostic runners, patches, and validation logs are retained locally outside the repository and are not included in this PR. diff --git a/launcher/src/modpacks.rs b/launcher/src/modpacks.rs index 6ff53e4be..b69ff0976 100644 --- a/launcher/src/modpacks.rs +++ b/launcher/src/modpacks.rs @@ -241,8 +241,14 @@ mod tests { .map(|a| a.to_string_lossy().into_owned()) .collect(); assert_eq!(args.len(), 4); - assert_eq!(Path::new(&args[1]), work.join("mods").join("a").join("carry")); - assert_eq!(Path::new(&args[3]), work.join("mods").join("b").join("carry")); + assert_eq!( + Path::new(&args[1]), + work.join("mods").join("a").join("carry") + ); + assert_eq!( + Path::new(&args[3]), + work.join("mods").join("b").join("carry") + ); assert_eq!(cmd.get_current_dir(), Some(profile_home(&work).as_path())); assert!(profile_home(&work).is_dir()); fs::remove_dir_all(&root).unwrap(); diff --git a/launcher/src/sources_tests.rs b/launcher/src/sources_tests.rs index b273fa4ba..6d882f032 100644 --- a/launcher/src/sources_tests.rs +++ b/launcher/src/sources_tests.rs @@ -203,6 +203,35 @@ fn prism_launcher_and_multimc_are_read_through_their_metadata() { assert_eq!(mojang.urls.lock().unwrap().len(), 1); } +/// famescare's Prism Launcher 26.3 install on Windows (#849): Prism keeps a native jar under +/// the name its metadata gives it, not at the version JSON's path, and preparing found it. +#[test] +fn prism_native_jars_are_found_through_the_linked_folder() { + let s = Scratch::new("prism-natives"); + let jar = "libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar"; + let dir = s.launcher("PrismLauncher", "", jar); + s.write( + "PrismLauncher/meta/net.minecraft/26.3.json", + br#"{"mainJar": {"name": "com.mojang:minecraft:26.3:client"}}"#, + ); + let prism = + "libraries/com/mojang/jtracy-natives-windows/1.14.38/jtracy-natives-windows-1.14.38.jar"; + s.write(&format!("PrismLauncher/{prism}"), b"jtracy natives"); + let linked = s.0.join("linked"); + assert_eq!( + resolve_with(&dir, &[], &linked, &Mojang::new(MANIFEST)).unwrap(), + linked + ); + let official = Path::new("com/mojang/jtracy/1.14.38/jtracy-1.14.38-natives-windows.jar"); + assert!(!linked.join("libraries").join(official).exists()); + let found = horizon_prepare::artifacts::launcher_library( + &linked, + "com.mojang:jtracy:1.14.38:natives-windows", + official, + ); + assert!(same_file(&found, &dir.join(prism))); +} + #[test] fn a_main_jar_elsewhere_is_found_from_the_metadata() { let s = Scratch::new("meta-jar"); @@ -388,7 +417,10 @@ fn relinking_follows_the_launcher_the_files_now_come_from() { s.write("ModrinthApp/meta/versions/26.3/26.3.jar", CLIENT); resolve_with(&modrinth, &[], &linked, &mojang).unwrap(); let jar = linked.join("versions/26.3/26.3.jar"); - assert!(same_file(&jar, &modrinth.join("meta/versions/26.3/26.3.jar"))); + assert!(same_file( + &jar, + &modrinth.join("meta/versions/26.3/26.3.jar") + )); assert!(!same_file(&jar, &prism.join(prism_jar))); // The Modrinth App folder has no libraries or assets: the old links are gone, and the // folders they pointed at are untouched. diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/EntityTranscript.java b/mods/horizon/src/test/java/dev/horizonlab/parity/EntityTranscript.java new file mode 100644 index 000000000..09c343f16 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/EntityTranscript.java @@ -0,0 +1,181 @@ +package dev.horizonlab.parity; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket; +import net.minecraft.network.protocol.game.ClientboundProjectilePowerPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; +import net.minecraft.network.protocol.game.VecDeltaCodec; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.phys.Vec3; + +/** + * What a vanilla client knows about the entities a server tracks to it, as + * ClientPacketListener would apply the packets: each entity's spawn packet, + * the entity data it was paired with and all it was sent since, its + * equipment, attributes and passengers, and where the position syncs leave + * it (VecDeltaCodec, as handleMoveEntity and handleEntityPositionSync). + * Entity ids differ between servers: an entity is named by its type and the + * block it was added in, passengers by those names. Players are left out, but + * for the attributes the player itself is sent from its login on. + */ +final class EntityTranscript { + private static final class Tracked { + final String type; + final String add; + final VecDeltaCodec codec = new VecDeltaCodec(); + String name; + String pairing; + final Map<Integer, String> data = new TreeMap<>(); + final Map<String, String> equipment = new TreeMap<>(); + final Map<String, String> attributes = new TreeMap<>(); + int[] passengers = new int[0]; + float yRot; + float xRot; + float headRot; + boolean onGround; + String motion; + String power = ""; + boolean removed; + + Tracked(ClientboundAddEntityPacket p) { + type = BuiltInRegistries.ENTITY_TYPE.getKey(p.getType()).toString(); + Vec3 at = new Vec3(p.getX(), p.getY(), p.getZ()); + codec.setBase(at); + name = type + " " + (int) Math.floor(at.x) + "," + (int) Math.floor(at.y) + "," + (int) Math.floor(at.z); + add = "at " + at + " rot " + p.getXRot() + "," + p.getYRot() + " head " + p.getYHeadRot() + " data " + p.getData() + + " motion " + p.getMovement(); + yRot = p.getYRot(); + xRot = p.getXRot(); + headRot = p.getYHeadRot(); + motion = String.valueOf(p.getMovement()); + } + } + + private final Map<Integer, Tracked> byId = new HashMap<>(); + private final List<Tracked> all = new ArrayList<>(); + private int self = Integer.MIN_VALUE; + private final Map<String, String> selfAttributes = new TreeMap<>(); + + /** The player's own id (login) and attribute instances; false for any other packet. */ + boolean acceptSelf(Packet<?> packet) { + if (packet instanceof net.minecraft.network.protocol.game.ClientboundLoginPacket p) { + self = p.playerId(); + return true; + } + if (packet instanceof ClientboundUpdateAttributesPacket p && p.getEntityId() == self) { + p.getValues().forEach(a -> selfAttributes.put(a.attribute().getRegisteredName(), a.base() + " " + a.modifiers())); + return true; + } + return false; + } + private int unknown; + + /** Applies one packet; false when it isn't about a tracked entity. */ + boolean accept(Packet<?> packet) { + if (packet instanceof ClientboundAddEntityPacket p) { + if (p.getType() == EntityTypes.PLAYER) return true; + Tracked t = new Tracked(p); + byId.put(p.getId(), t); + all.add(t); + return true; + } + if (packet instanceof ClientboundRemoveEntitiesPacket p) { + p.entityIds().forEach(id -> { + Tracked t = byId.remove(id); + if (t != null) t.removed = true; + }); + return true; + } + Tracked t = switch (packet) { + case ClientboundSetEntityDataPacket p -> byId.get(p.id()); + case ClientboundSetEquipmentPacket p -> byId.get(p.getEntity()); + case ClientboundUpdateAttributesPacket p -> byId.get(p.getEntityId()); + case ClientboundSetPassengersPacket p -> byId.get(p.getVehicle()); + case ClientboundEntityPositionSyncPacket p -> byId.get(p.id()); + case ClientboundSetEntityMotionPacket p -> byId.get(p.id()); + case ClientboundTeleportEntityPacket p -> byId.get(p.id()); + case ClientboundProjectilePowerPacket p -> byId.get(p.getId()); + case ClientboundMoveEntityPacket p -> byId.get(VanillaProtocolClient.moveEntityId(p)); + case ClientboundRotateHeadPacket p -> byId.get(VanillaProtocolClient.rotateHeadId(p)); + default -> null; + }; + if (t == null) { + return false; + } + switch (packet) { + case ClientboundSetEntityDataPacket p -> { + for (var v : p.packedItems()) t.data.put(v.id(), net.minecraft.network.syncher.EntityDataSerializers.getSerializedId(v.serializer()) + " " + v.value()); + if (t.pairing == null) { + StringBuilder b = new StringBuilder(); + for (var v : p.packedItems()) b.append(v.id()).append('=').append(v.value()).append(' '); + t.pairing = b.toString().trim(); + } + } + case ClientboundSetEquipmentPacket p -> p.getSlots().forEach(s -> t.equipment.put(s.getFirst().getName(), String.valueOf(s.getSecond()))); + case ClientboundUpdateAttributesPacket p -> p.getValues().forEach(a -> t.attributes.put(a.attribute().getRegisteredName(), + a.base() + " " + a.modifiers())); + case ClientboundSetPassengersPacket p -> t.passengers = p.getPassengers(); + case ClientboundEntityPositionSyncPacket p -> { + t.codec.setBase(p.position().endPosition()); + t.yRot = p.yRot(); + t.xRot = p.xRot(); + t.onGround = p.onGround(); + } + case ClientboundMoveEntityPacket p -> { + if (p.hasPosition()) t.codec.setBase(p.getPositionDelta().decode(t.codec).endPosition()); + if (p.hasRotation()) { + t.yRot = p.getYRot(); + t.xRot = p.getXRot(); + } + t.onGround = p.isOnGround(); + } + case ClientboundSetEntityMotionPacket p -> t.motion = String.valueOf(p.movement()); + case ClientboundTeleportEntityPacket p -> { + t.codec.setBase(p.change().position()); + t.onGround = p.onGround(); + } + case ClientboundRotateHeadPacket p -> t.headRot = p.getYHeadRot(); + case ClientboundProjectilePowerPacket p -> t.power = " power " + p.getAccelerationPower(); + default -> { + } + } + return true; + } + + /** One line per entity, sorted, each field named. */ + List<String> lines() { + Map<String, Integer> seen = new HashMap<>(); + for (Tracked t : all) { + int n = seen.merge(t.name, 1, Integer::sum); + if (n > 1) t.name += " #" + n; + } + Map<Integer, String> names = new HashMap<>(); + byId.forEach((id, t) -> names.put(id, t.name)); + List<String> out = new ArrayList<>(); + for (Tracked t : all) { + List<String> riders = new ArrayList<>(); + for (int id : t.passengers) riders.add(names.getOrDefault(id, "player or unknown")); + out.add("entity " + t.name + " | add " + t.add + " | pairing " + t.pairing + " | data " + t.data + " | equipment " + t.equipment + + " | attributes " + t.attributes + " | passengers " + riders + " | now " + t.codec.getBase() + " rot " + t.xRot + "," + + t.yRot + " head " + t.headRot + " ground " + t.onGround + " motion " + t.motion + t.power + (t.removed ? " | removed" : "")); + } + out.add("self attributes " + selfAttributes); + out.sort(null); + return out; + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java index e41c693ee..3eb241d5e 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java @@ -76,11 +76,22 @@ import net.minecraft.world.phys.Vec3; * line at a time: {@code step LABEL} (the label the next packets are recorded * under), {@code join NAME}, {@code cmd NAME COMMAND...}, {@code shift NAME * on|off} (the shift key, as ServerboundPlayerInputPacket), {@code fly NAME - * on|off} (ServerboundPlayerAbilitiesPacket), {@code quit NAME} and {@code - * end}, which writes each player's lines to OUT. + * on|off} (ServerboundPlayerAbilitiesPacket), {@code still NAME} (the + * position reminder LocalPlayer.sendPosition sends every 20 ticks standing + * still), {@code quit NAME}, {@code + * players on|off} (whether each player also records the other players added + * to and removed from its level, and its own respawns into a dimension), + * {@code chat on|off} (whether the system chat each player receives is + * recorded too, as component JSON), {@code state on|off} (whether each player + * also records what the server changes about it: its game mode, teleports, + * inventory slots, effects and death) and {@code end}, which writes each + * player's lines to OUT. */ public final class LocatorBarClient { private static volatile String step = "start"; + private static volatile boolean players; + private static volatile boolean chat; + private static volatile boolean state; private static final Map<UUID, String> NAMES = new LinkedHashMap<>(); public static void main(String[] args) throws Exception { @@ -110,7 +121,11 @@ public final class LocatorBarClient { abilities.flying = w[2].equals("on"); players.get(w[1]).send(new net.minecraft.network.protocol.game.ServerboundPlayerAbilitiesPacket(abilities)); } + case "still" -> players.get(w[1]).still(); case "quit" -> players.get(w[1]).close(); + case "players" -> LocatorBarClient.players = w[1].equals("on"); + case "chat" -> chat = w[1].equals("on"); + case "state" -> state = w[1].equals("on"); case "end" -> { try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(output, StandardCharsets.UTF_8))) { for (Player p : players.values()) { @@ -166,8 +181,12 @@ public final class LocatorBarClient { private int threshold = -1; private ProtocolInfo<?> inbound; private ProtocolInfo<?> outbound; - private PositionMoveRotation position = new PositionMoveRotation(Vec3.ZERO, Vec3.ZERO, 0, 0); + private volatile PositionMoveRotation position = new PositionMoveRotation(Vec3.ZERO, Vec3.ZERO, 0, 0); private boolean loaded; + /** This player's own entity id (ClientboundLoginPacket). */ + private volatile int id = -1; + /** The other players this one was sent, by entity id. */ + private final Map<Integer, String> seen = new java.util.HashMap<>(); private final Object replyLock = new Object(); private int replies; @@ -198,6 +217,14 @@ public final class LocatorBarClient { } } + void still() throws Exception { + PositionMoveRotation at = position; + // A tick of its own: the server takes one position per client tick (receivedPositionThisTick). + send(net.minecraft.network.protocol.game.ServerboundClientTickEndPacket.INSTANCE); + send(new ServerboundMovePlayerPacket.PosRot(at.position(), at.yRot(), at.xRot(), false, false)); + send(net.minecraft.network.protocol.game.ServerboundClientTickEndPacket.INSTANCE); + } + void close() throws Exception { if (socket != null) socket.close(); } @@ -266,9 +293,31 @@ public final class LocatorBarClient { while (true) { Received r = read(); Packet<?> p = r.packet; - if (p instanceof ClientboundTrackedWaypointPacket) { + if (p instanceof net.minecraft.network.protocol.game.ClientboundLoginPacket l) { + id = l.playerId(); + } + if (state) recordState(p); + if (p instanceof net.minecraft.network.protocol.game.ClientboundAddEntityPacket a + && a.getType() == net.minecraft.world.entity.EntityTypes.PLAYER) { + String who = NAMES.getOrDefault(a.getUUID(), "uuid?"); + seen.put(a.getId(), who); + if (players) record("add " + who + " at " + a.getX() + "," + a.getY() + "," + a.getZ()); + } else if (p instanceof net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket rm) { + rm.entityIds().forEach(id -> { + String who = seen.remove(id); + if (who != null && players) record("remove " + who); + }); + } else if (p instanceof net.minecraft.network.protocol.game.ClientboundRespawnPacket rs) { + if (players) record("respawn " + rs.commonPlayerSpawnInfo().dimension().identifier()); + seen.clear(); + } else if (p instanceof ClientboundTrackedWaypointPacket) { record(waypoint(r.payload)); - } else if (p instanceof ClientboundSystemChatPacket) { + } else if (p instanceof ClientboundSystemChatPacket c) { + if (chat) { + record("chat " + (c.overlay() ? "overlay " : "") + net.minecraft.network.chat.ComponentSerialization.CODEC + .encodeStart(ParityData.access.createSerializationContext(com.mojang.serialization.JsonOps.INSTANCE), c.content()) + .getOrThrow()); + } synchronized (replyLock) { replies++; replyLock.notifyAll(); @@ -280,6 +329,10 @@ public final class LocatorBarClient { } else if (p instanceof ClientboundPlayerPositionPacket t) { position = PositionMoveRotation.calculateAbsolute(position, t.change(), t.relatives()); Vec3 at = position.position(); + if (state) { + record(String.format(java.util.Locale.ROOT, "teleport %.3f %.3f %.3f %.1f %.1f", + at.x, at.y, at.z, position.yRot(), position.xRot())); + } send(new ServerboundAcceptTeleportationPacket(t.id(), at.x, at.y, at.z, position.yRot(), position.xRot())); // Only the spawn teleport is answered with a position too (VanillaProtocolClient). if (!loaded) { @@ -299,6 +352,31 @@ public final class LocatorBarClient { } } + /** What the server changed about this player ({@code state on}). */ + private void recordState(Packet<?> p) { + if (p instanceof net.minecraft.network.protocol.game.ClientboundGameEventPacket g + && g.getEvent() == net.minecraft.network.protocol.game.ClientboundGameEventPacket.CHANGE_GAME_MODE) { + record("gamemode " + (int) g.getParam()); + } else if (p instanceof net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket c) { + record("slot " + c.getContainerId() + " " + c.getSlot() + " " + item(c.getItem())); + } else if (p instanceof net.minecraft.network.protocol.game.ClientboundSetPlayerInventoryPacket i) { + record("inventory " + i.slot() + " " + item(i.contents())); + } else if (p instanceof net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket e && e.getEntityId() == id) { + record("effect " + e.getEffect().getRegisteredName() + " " + e.getEffectAmplifier() + " " + e.getEffectDurationTicks()); + } else if (p instanceof net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket e && e.entityId() == id) { + record("effect-removed " + e.effect().getRegisteredName()); + } else if (p instanceof net.minecraft.network.protocol.game.ClientboundPlayerCombatKillPacket k) { + record("killed " + net.minecraft.network.chat.ComponentSerialization.CODEC + .encodeStart(ParityData.access.createSerializationContext(com.mojang.serialization.JsonOps.INSTANCE), k.message()) + .getOrThrow()); + } + } + + private static String item(net.minecraft.world.item.ItemStack stack) { + return stack.isEmpty() ? "empty" + : net.minecraft.core.registries.BuiltInRegistries.ITEM.getKey(stack.getItem()) + " x" + stack.getCount(); + } + private record Received(Packet<?> packet, byte[] payload) {} private Received read() throws Exception { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/SecureChatClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/SecureChatClient.java new file mode 100644 index 000000000..4d08dafd2 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/SecureChatClient.java @@ -0,0 +1,625 @@ +package dev.horizonlab.parity; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.mojang.serialization.JsonOps; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.EOFException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.math.BigInteger; +import java.net.HttpURLConnection; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.URI; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.zip.Deflater; +import java.util.zip.Inflater; +import javax.crypto.Cipher; +import javax.crypto.CipherInputStream; +import javax.crypto.CipherOutputStream; +import javax.crypto.SecretKey; +import net.minecraft.SharedConstants; +import net.minecraft.commands.arguments.ArgumentSignatures; +import net.minecraft.core.UUIDUtil; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.ProtocolInfo; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.ComponentSerialization; +import net.minecraft.network.chat.LastSeenMessages; +import net.minecraft.network.chat.LastSeenMessagesTracker; +import net.minecraft.network.chat.LocalChatSession; +import net.minecraft.network.chat.MessageSignature; +import net.minecraft.network.chat.MessageSignatureCache; +import net.minecraft.network.chat.PlayerChatMessage; +import net.minecraft.network.chat.RemoteChatSession; +import net.minecraft.network.chat.SignedMessageBody; +import net.minecraft.network.chat.SignedMessageChain; +import net.minecraft.network.chat.SignedMessageLink; +import net.minecraft.network.chat.SignedMessageValidator; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundDisconnectPacket; +import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; +import net.minecraft.network.protocol.common.ClientboundPingPacket; +import net.minecraft.network.protocol.common.ServerboundClientInformationPacket; +import net.minecraft.network.protocol.common.ServerboundKeepAlivePacket; +import net.minecraft.network.protocol.common.ServerboundPongPacket; +import net.minecraft.network.protocol.configuration.ClientboundFinishConfigurationPacket; +import net.minecraft.network.protocol.configuration.ClientboundSelectKnownPacks; +import net.minecraft.network.protocol.configuration.ConfigurationProtocols; +import net.minecraft.network.protocol.configuration.ServerboundFinishConfigurationPacket; +import net.minecraft.network.protocol.configuration.ServerboundSelectKnownPacks; +import net.minecraft.network.protocol.game.ClientboundChunkBatchFinishedPacket; +import net.minecraft.network.protocol.game.ClientboundDisguisedChatPacket; +import net.minecraft.network.protocol.game.ClientboundLoginPacket; +import net.minecraft.network.protocol.game.ClientboundPlayerChatPacket; +import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket; +import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket; +import net.minecraft.network.protocol.game.ClientboundSystemChatPacket; +import net.minecraft.network.protocol.game.GameProtocols; +import net.minecraft.network.protocol.game.ServerboundAcceptTeleportationPacket; +import net.minecraft.network.protocol.game.ServerboundChatAckPacket; +import net.minecraft.network.protocol.game.ServerboundChatCommandPacket; +import net.minecraft.network.protocol.game.ServerboundChatCommandSignedPacket; +import net.minecraft.network.protocol.game.ServerboundChatPacket; +import net.minecraft.network.protocol.game.ServerboundChatSessionUpdatePacket; +import net.minecraft.network.protocol.game.ServerboundChunkBatchReceivedPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerLoadedPacket; +import net.minecraft.network.protocol.handshake.ClientIntent; +import net.minecraft.network.protocol.handshake.ClientIntentionPacket; +import net.minecraft.network.protocol.handshake.HandshakeProtocols; +import net.minecraft.network.protocol.login.ClientboundHelloPacket; +import net.minecraft.network.protocol.login.ClientboundLoginCompressionPacket; +import net.minecraft.network.protocol.login.ClientboundLoginDisconnectPacket; +import net.minecraft.network.protocol.login.ClientboundLoginFinishedPacket; +import net.minecraft.network.protocol.login.LoginProtocols; +import net.minecraft.network.protocol.login.ServerboundHelloPacket; +import net.minecraft.network.protocol.login.ServerboundKeyPacket; +import net.minecraft.network.protocol.login.ServerboundLoginAcknowledgedPacket; +import net.minecraft.server.level.ClientInformation; +import net.minecraft.util.Crypt; +import net.minecraft.util.Signer; +import net.minecraft.world.entity.player.ProfileKeyPair; +import net.minecraft.world.entity.player.ProfilePublicKey; + +/** + * Secure chat seen by vanilla-codec clients: several players on one server, + * signing their chat with profile keys that a mock of the Minecraft services + * signed (the harness serves its public key as the services' key set). + * + * <p>{@code keys <dir>} writes the mock services' key pair: the private key + * (PKCS#8) and {@code publickeys.json} as the services answer it. With a + * host, a port, the private key, an output file and a scenario, it plays the + * scenario. Each client signs and acknowledges exactly as + * ClientPacketListener does (LocalChatSession, SignedMessageChain's encoder, + * LastSeenMessagesTracker, MessageSignatureCache), and checks every player + * chat it receives with SignedMessageValidator against the sender's session + * from the player list. The transcript holds what each player received and + * whether its signature checked out; keys, salts, times and signatures + * differ between runs and are left out. + */ +public final class SecureChatClient { + private static final List<String> LINES = new ArrayList<>(); + private static PrivateKey services; + private static String sessionUrl; + + public static void main(String[] args) throws Exception { + ParityData.init(); + if (args[0].equals("keys")) { + keys(Path.of(args[1])); + return; + } + String host = args[0]; + int port = Integer.parseInt(args[1]); + services = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(Files.readAllBytes(Path.of(args[2])))); + Path output = Path.of(args[3]); + String scenario = args[4]; + sessionUrl = args.length > 5 ? args[5] : null; + try { + if (scenario.equals("offline")) offline(host, port); + else online(host, port); + } catch (Exception e) { + StringBuilder line = new StringBuilder("error " + e); + for (Throwable c = e.getCause(); c != null; c = c.getCause()) line.append(" / caused by ").append(c); + LINES.add(line.toString()); + } + try (PrintWriter w = new PrintWriter(Files.newBufferedWriter(output, StandardCharsets.UTF_8))) { + for (String line : LINES) w.println(line); + } + System.exit(0); + } + + private static void keys(Path dir) throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + KeyPair pair = generator.generateKeyPair(); + Files.write(dir.resolve("services-private.der"), pair.getPrivate().getEncoded()); + JsonObject key = new JsonObject(); + key.addProperty("publicKey", Base64.getEncoder().encodeToString(pair.getPublic().getEncoded())); + JsonArray list = new JsonArray(); + list.add(key); + JsonObject set = new JsonObject(); + set.add("profilePropertyKeys", list); + set.add("playerCertificateKeys", list); + Files.writeString(dir.resolve("publickeys.json"), set.toString()); + } + + // ---- scenarios ---------------------------------------------------- + + /** Offline mode: the server checks chat sessions but enforces nothing. */ + private static void offline(String host, int port) throws Exception { + Client alice = Client.join(host, port, "Alice", true, null); + Client bob = Client.join(host, port, "Bob", true, null); + Client carol = Client.join(host, port, "Carol", false, null); + List<Client> all = List.of(alice, bob, carol); + settle(all, "joined"); + alice.chat("hello, signed"); + settle(all, "alice chats"); + bob.chat("seen it"); + settle(all, "bob chats with alice's message seen"); + carol.chat("no key here"); + settle(all, "carol chats unsigned"); + alice.signedCommand("say signed announcement", "message", "signed announcement"); + settle(all, "alice says"); + alice.signedCommand("me waves", "action", "waves"); + settle(all, "alice emotes"); + alice.signedCommand("msg Bob just between us", "message", "just between us"); + settle(all, "alice whispers to bob"); + carol.signedCommand("me shrugs", null, null); + settle(all, "carol emotes, unsigned arguments"); + carol.command("say plain announcement"); + settle(all, "carol says through the unsigned packet"); + bob.signedCommand("say mismatch", "nothing", "mismatch"); + settle(all, "bob signs the wrong argument"); + bob.chat("after the mismatch"); + settle(all, "bob's chain after the mismatch"); + alice.tamperedChat("forged"); + settle(all, "alice's signature fails"); + alice.chat("after the forgery"); + settle(all, "alice's chain is broken"); + bob.send(new ServerboundChatAckPacket(50)); + settle(all, "bob acknowledges too much"); + for (Client c : all) c.close(); + } + + /** Online mode with enforce-secure-profile: unsigned chat is refused. */ + private static void online(String host, int port) throws Exception { + Client alice = Client.join(host, port, "Alice", true, null); + Client carol = Client.join(host, port, "Carol", false, null); + List<Client> all = List.of(alice, carol); + settle(all, "joined"); + alice.chat("signed and enforced"); + settle(all, "alice chats"); + carol.chat("unsigned under enforcement"); + settle(all, "carol chats without a key"); + carol.command("me tries the unsigned packet"); + settle(all, "carol's unsigned command"); + carol.signedCommand("me tries without signatures", null, null); + settle(all, "carol's command without signatures"); + // A key the services signed for another player. + Client mallory = Client.join(host, port, "Mallory", true, UUID.nameUUIDFromBytes("someone else".getBytes())); + settle(List.of(alice, carol, mallory), "mallory's borrowed key"); + for (Client c : all) c.close(); + mallory.close(); + } + + /** Lets the server answer, then records what each player received, in player order. */ + private static void settle(List<Client> clients, String step) throws Exception { + Thread.sleep(1500); + LINES.add("step " + step); + for (Client c : clients) c.drain(); + } + + private static String json(Component c) { + return ComponentSerialization.CODEC.encodeStart(ParityData.access.createSerializationContext(JsonOps.INSTANCE), c).getOrThrow().toString(); + } + + /** A player: one connection, its chat session and what its client tracks. */ + private static final class Client { + final String name; + UUID id; + Socket socket; + DataInputStream in; + OutputStream out; + int threshold = -1; + ProtocolInfo<?> inbound; + ProtocolInfo<?> outbound; + final BlockingQueue<Packet<?>> queue = new LinkedBlockingQueue<>(); + volatile boolean closed; + LocalChatSession session; + SignedMessageChain.Encoder encoder = SignedMessageChain.Encoder.UNSIGNED; + final LastSeenMessagesTracker lastSeen = new LastSeenMessagesTracker(20); + final MessageSignatureCache cache = MessageSignatureCache.createDefault(); + int nextChatIndex; + final Map<UUID, String> names = new LinkedHashMap<>(); + final Map<UUID, SignedMessageValidator> validators = new HashMap<>(); + boolean enforced; + boolean loaded; + net.minecraft.world.entity.PositionMoveRotation position = new net.minecraft.world.entity.PositionMoveRotation( + net.minecraft.world.phys.Vec3.ZERO, net.minecraft.world.phys.Vec3.ZERO, 0, 0); + + Client(String name) { + this.name = name; + } + + void record(String line) { + LINES.add(name + " " + line); + } + + static Client join(String host, int port, String name, boolean signs, UUID keyOwner) throws Exception { + Client c = new Client(name); + c.connect(host, port, signs, keyOwner); + return c; + } + + void connect(String host, int port, boolean signs, UUID keyOwner) throws Exception { + socket = new Socket(); + socket.connect(new InetSocketAddress(host, port), 10_000); + socket.setSoTimeout(30_000); + socket.setTcpNoDelay(true); + in = new DataInputStream(socket.getInputStream()); + out = socket.getOutputStream(); + outbound = HandshakeProtocols.SERVERBOUND; + send(new ClientIntentionPacket(SharedConstants.getProtocolVersion(), host, port, ClientIntent.LOGIN)); + outbound = LoginProtocols.SERVERBOUND; + inbound = LoginProtocols.CLIENTBOUND; + send(new ServerboundHelloPacket(name, UUIDUtil.createOfflinePlayerUUID(name))); + while (true) { + Packet<?> p = read(); + if (p instanceof ClientboundHelloPacket hello) { + // ClientHandshakePacketListenerImpl.handleHello: join through the session service. + SecretKey secret = Crypt.generateSecretKey(); + String hash = new BigInteger(Crypt.digestData(hello.getServerId(), hello.getPublicKey(), secret)).toString(16); + joinSession(hash); + send(new ServerboundKeyPacket(secret, hello.getPublicKey(), hello.getChallenge())); + in = new DataInputStream(new CipherInputStream(socket.getInputStream(), Crypt.getCipher(Cipher.DECRYPT_MODE, secret))); + out = new CipherOutputStream(socket.getOutputStream(), Crypt.getCipher(Cipher.ENCRYPT_MODE, secret)); + } else if (p instanceof ClientboundLoginCompressionPacket compression) { + threshold = compression.getCompressionThreshold(); + } else if (p instanceof ClientboundLoginFinishedPacket finished) { + id = finished.gameProfile().id(); + record("logged in"); + send(ServerboundLoginAcknowledgedPacket.INSTANCE); + break; + } else if (p instanceof ClientboundLoginDisconnectPacket d) { + record("refused " + json(d.reason())); + closed = true; + return; + } + } + outbound = ConfigurationProtocols.SERVERBOUND; + inbound = ConfigurationProtocols.CLIENTBOUND; + send(new ServerboundClientInformationPacket(ClientInformation.createDefault())); + while (true) { + Packet<?> p = read(); + if (p instanceof ClientboundSelectKnownPacks packs) { + send(new ServerboundSelectKnownPacks(packs.knownPacks())); + } else if (p instanceof ClientboundKeepAlivePacket k) { + send(new ServerboundKeepAlivePacket(k.getId())); + } else if (p instanceof ClientboundPingPacket ping) { + send(new ServerboundPongPacket(ping.getId())); + } else if (p instanceof ClientboundFinishConfigurationPacket) { + send(ServerboundFinishConfigurationPacket.INSTANCE); + break; + } else if (p instanceof ClientboundDisconnectPacket d) { + record("disconnected " + json(d.reason())); + closed = true; + return; + } + } + GameProtocols.Context context = new GameProtocols.Context() { + @Override + public boolean hasInfiniteMaterials() { + return false; + } + + @Override + public boolean canUseCommandBlocks() { + return false; + } + }; + outbound = GameProtocols.SERVERBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(ParityData.access), context); + inbound = GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(ParityData.access)); + // ClientPacketListener.handleLogin: the session goes out once the + // login packet is in (prepareKeyPair, setKeyPair). + while (true) { + Packet<?> p = read(); + if (p instanceof ClientboundLoginPacket login) { + enforced = login.enforcesSecureChat(); + record("login online " + login.onlineMode() + " enforces " + login.enforcesSecureChat()); + if (signs) startSession(keyOwner == null ? id : keyOwner); + break; + } + } + Thread reader = new Thread(() -> { + try { + while (!closed) { + Packet<?> p = read(); + queue.put(p); + // Nothing follows a disconnect but the closed socket. + if (p instanceof ClientboundDisconnectPacket) return; + } + } catch (Exception e) { + if (!closed) queue.add(new ClientboundDisconnectPacket(Component.literal("connection lost: " + e))); + } + }, name + " reader"); + reader.setDaemon(true); + reader.start(); + } + + /** The session service's join, as the launcher's account would. */ + void joinSession(String serverHash) throws Exception { + HttpURLConnection http = (HttpURLConnection) URI.create(sessionUrl + "/session/minecraft/join").toURL().openConnection(); + http.setRequestMethod("POST"); + http.setDoOutput(true); + http.setRequestProperty("Content-Type", "application/json"); + JsonObject body = new JsonObject(); + body.addProperty("accessToken", "mock-token"); + body.addProperty("selectedProfile", name); + body.addProperty("serverId", serverHash); + http.getOutputStream().write(body.toString().getBytes(StandardCharsets.UTF_8)); + http.getResponseCode(); + http.disconnect(); + } + + /** A profile key pair the mock services signed for {@code owner}, and its session. */ + void startSession(UUID owner) throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + KeyPair pair = generator.generateKeyPair(); + Instant expires = Instant.now().plusSeconds(3600).truncatedTo(java.time.temporal.ChronoUnit.MILLIS); + byte[] key = pair.getPublic().getEncoded(); + byte[] payload = ByteBuffer.allocate(24 + key.length).putLong(owner.getMostSignificantBits()) + .putLong(owner.getLeastSignificantBits()).putLong(expires.toEpochMilli()).put(key).array(); + byte[] signature = Signer.from(services, "SHA1withRSA").sign(payload); + ProfilePublicKey publicKey = new ProfilePublicKey(new ProfilePublicKey.Data(expires, pair.getPublic(), signature)); + session = LocalChatSession.create(new ProfileKeyPair(pair.getPrivate(), publicKey, expires)); + encoder = session.createMessageEncoder(id); + send(new ServerboundChatSessionUpdatePacket(session.asRemote().asData())); + } + + /** ClientPacketListener.sendChat. */ + void chat(String content) throws Exception { + Instant now = Instant.now(); + long salt = Crypt.SaltSupplier.getLong(); + LastSeenMessagesTracker.Update update = lastSeen.generateAndApplyUpdate(); + MessageSignature signature = encoder.pack(new SignedMessageBody(content, now, salt, update.lastSeen())); + send(new ServerboundChatPacket(content, now, salt, Optional.ofNullable(signature), update.update())); + } + + /** A chat whose signature doesn't match its text. */ + void tamperedChat(String content) throws Exception { + Instant now = Instant.now(); + long salt = Crypt.SaltSupplier.getLong(); + LastSeenMessagesTracker.Update update = lastSeen.generateAndApplyUpdate(); + MessageSignature signature = encoder.pack(new SignedMessageBody(content + "!", now, salt, update.lastSeen())); + send(new ServerboundChatPacket(content, now, salt, Optional.ofNullable(signature), update.update())); + } + + /** ClientPacketListener.sendCommand for a command with one message argument (none: no signatures). */ + void signedCommand(String command, String argument, String value) throws Exception { + Instant now = Instant.now(); + long salt = Crypt.SaltSupplier.getLong(); + LastSeenMessagesTracker.Update update = lastSeen.generateAndApplyUpdate(); + List<ArgumentSignatures.Entry> entries = new ArrayList<>(); + if (argument != null) { + MessageSignature signature = encoder.pack(new SignedMessageBody(value, now, salt, update.lastSeen())); + if (signature != null) entries.add(new ArgumentSignatures.Entry(argument, signature)); + } + send(new ServerboundChatCommandSignedPacket(command, now, salt, new ArgumentSignatures(entries), update.update())); + } + + void command(String command) throws Exception { + send(new ServerboundChatCommandPacket(command)); + } + + /** Handles and records what arrived. */ + void drain() throws Exception { + Packet<?> p; + while ((p = queue.poll(50, TimeUnit.MILLISECONDS)) != null) handle(p); + } + + void handle(Packet<?> packet) throws Exception { + if (packet instanceof ClientboundKeepAlivePacket k) { + send(new ServerboundKeepAlivePacket(k.getId())); + } else if (packet instanceof ClientboundPingPacket ping) { + send(new ServerboundPongPacket(ping.getId())); + } else if (packet instanceof ClientboundPlayerPositionPacket pos) { + position = net.minecraft.world.entity.PositionMoveRotation.calculateAbsolute(position, pos.change(), pos.relatives()); + send(new ServerboundAcceptTeleportationPacket(pos.id(), position.position().x, position.position().y, + position.position().z, position.yRot(), position.xRot())); + if (!loaded) { + send(new ServerboundPlayerLoadedPacket()); + loaded = true; + } + } else if (packet instanceof ClientboundChunkBatchFinishedPacket) { + send(new ServerboundChunkBatchReceivedPacket(64.0F)); + } else if (packet instanceof ClientboundPlayerInfoUpdatePacket info) { + for (ClientboundPlayerInfoUpdatePacket.Entry e : info.entries()) { + if (info.actions().contains(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER)) { + names.put(e.profileId(), e.profile().name()); + } + if (info.actions().contains(ClientboundPlayerInfoUpdatePacket.Action.INITIALIZE_CHAT)) { + RemoteChatSession.Data data = e.chatSession(); + String who = names.getOrDefault(e.profileId(), "?"); + if (data != null) { + RemoteChatSession remote = new RemoteChatSession(data.sessionId(), new ProfilePublicKey(data.profilePublicKey())); + validators.put(e.profileId(), remote.createMessageValidator(ProfilePublicKey.EXPIRY_GRACE_PERIOD)); + sessions.put(e.profileId(), data.sessionId()); + record("session of " + who); + } else if (!info.actions().contains(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER)) { + record("session cleared for " + who); + } + } + } + } else if (packet instanceof ClientboundPlayerChatPacket chat) { + playerChat(chat); + } else if (packet instanceof ClientboundDisguisedChatPacket d) { + record("disguised " + d.chatType().chatType().getRegisteredName() + " " + json(d.chatType().name()) + " " + + d.chatType().targetName().map(SecureChatClient::json) + " " + json(d.message())); + } else if (packet instanceof ClientboundSystemChatPacket s) { + record("system " + json(s.content())); + } else if (packet instanceof ClientboundDisconnectPacket d) { + record("disconnected " + json(d.reason())); + closed = true; + } + } + + /** ClientPacketListener.handlePlayerChat, then markMessageAsProcessed. */ + void playerChat(ClientboundPlayerChatPacket p) { + int expected = nextChatIndex++; + String sender = names.getOrDefault(p.sender(), p.sender().toString()); + StringBuilder lastSeenPacked = new StringBuilder(); + for (MessageSignature.Packed packed : p.body().lastSeen().entries()) { + lastSeenPacked.append(packed.fullSignature() != null ? "full" : "cached:" + packed.id()).append(','); + } + Optional<SignedMessageBody> body = p.body().unpack(cache); + if (p.globalIndex() != expected || body.isEmpty()) { + record("chat out of order or unknown signature: index " + p.globalIndex() + " expected " + expected); + return; + } + MessageSignature signature = p.signature().orElse(null); + cache.push(body.get(), signature); + SignedMessageValidator validator = validators.get(p.sender()); + String verdict; + if (validator != null) { + PlayerChatMessage message = new PlayerChatMessage( + new SignedMessageLink(p.index(), p.sender(), sessionId(p.sender())), signature, body.get(), + p.unsignedContent().orElse(null), p.filterMask()); + verdict = validator.updateAndValidate(message) != null ? "verified" : "rejected"; + } else { + verdict = signature == null ? (enforced ? "unsigned-rejected" : "unsigned") : "no-session"; + } + record("chat #" + p.globalIndex() + " from " + sender + " link " + p.index() + " " + verdict + " '" + body.get().content() + + "' seen [" + lastSeenPacked + "] " + body.get().lastSeen().entries().size() + " unsigned " + + p.unsignedContent().map(SecureChatClient::json) + " " + p.chatType().chatType().getRegisteredName() + " " + + json(p.chatType().name()) + " " + p.chatType().targetName().map(SecureChatClient::json)); + if (signature != null) lastSeen.addPending(signature, true); + } + + private final Map<UUID, UUID> sessions = new HashMap<>(); + + UUID sessionId(UUID sender) { + return sessions.getOrDefault(sender, new UUID(0, 0)); + } + + // ---- framing ------------------------------------------------------ + + synchronized void send(Packet<?> packet) throws Exception { + ByteBuf body = Unpooled.buffer(); + encode(body, packet); + byte[] raw = new byte[body.readableBytes()]; + body.readBytes(raw); + ByteBuf frame = Unpooled.buffer(); + if (threshold >= 0) { + ByteBuf inner = Unpooled.buffer(); + if (raw.length >= threshold) { + writeVarInt(inner, raw.length); + Deflater d = new Deflater(); + d.setInput(raw); + d.finish(); + byte[] tmp = new byte[raw.length + 64]; + while (!d.finished()) inner.writeBytes(tmp, 0, d.deflate(tmp)); + d.end(); + } else { + writeVarInt(inner, 0); + inner.writeBytes(raw); + } + writeVarInt(frame, inner.readableBytes()); + frame.writeBytes(inner); + } else { + writeVarInt(frame, raw.length); + frame.writeBytes(raw); + } + byte[] bytes = new byte[frame.readableBytes()]; + frame.readBytes(bytes); + // A server that disconnected the player may close before this + // write: what it sent last is the disconnect, which the reader + // records, not the broken pipe. + if (broken) return; + try { + out.write(bytes); + out.flush(); + } catch (java.io.IOException e) { + broken = true; + } + } + + private boolean broken; + + @SuppressWarnings({"unchecked", "rawtypes"}) + private void encode(ByteBuf body, Packet<?> packet) { + ((ProtocolInfo) outbound).codec().encode(body, packet); + } + + Packet<?> read() throws Exception { + int length = readVarInt(in); + byte[] frame = new byte[length]; + in.readFully(frame); + byte[] raw = frame; + if (threshold >= 0) { + DataInputStream f = new DataInputStream(new ByteArrayInputStream(frame)); + int dataLength = readVarInt(f); + byte[] rest = f.readAllBytes(); + if (dataLength == 0) { + raw = rest; + } else { + Inflater inflater = new Inflater(); + inflater.setInput(rest); + raw = new byte[dataLength]; + inflater.inflate(raw); + inflater.end(); + } + } + return inbound.codec().decode(Unpooled.wrappedBuffer(raw)); + } + + void close() throws Exception { + closed = true; + socket.close(); + } + } + + private static int readVarInt(InputStream in) throws Exception { + int value = 0; + for (int i = 0; i < 5; i++) { + int b = in.read(); + if (b < 0) throw new EOFException(); + value |= (b & 0x7F) << (7 * i); + if ((b & 0x80) == 0) return value; + } + throw new IllegalStateException("VarInt too big"); + } + + private static void writeVarInt(ByteBuf buf, int value) { + while ((value & ~0x7F) != 0) { + buf.writeByte((value & 0x7F) | 0x80); + value >>>= 7; + } + buf.writeByte(value); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityTickerOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityTickerOracle.java new file mode 100644 index 000000000..75330c4fe --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityTickerOracle.java @@ -0,0 +1,217 @@ +package dev.horizonlab.parity; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.util.debug.LevelDebugSynchronizers; +import net.minecraft.world.TickRateManager; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.EntityBlock; +import net.minecraft.world.level.block.JukeboxBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.TickingBlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.LevelChunk; + +/** + * The order of vanilla's `Level.blockEntityTickers`: real `LevelChunk`s of a + * server level register, rebind and drop the tickers of real block entities + * (`addAndRegisterBlockEntity`, `setBlockEntity`, `removeBlockEntity`, + * `updateBlockEntityTicker` after a state change, `registerAllBlockEntitiesAfterLevelLoad` + * after a chunk load, `clearAllBlockEntities` when it unloads), and + * `Level.tickBlockEntities` runs with the tick rate frozen, so it only + * promotes pending tickers and drops removed ones. After each `tick` the + * positions of the live tickers are printed in list order. + * + * Input lines: `reset`, `load CX CZ BLOCK X Y Z ...` (a chunk's block entities in + * its save order), `place BLOCK X Y Z`, `replace X Y Z`, `remove X Y Z`, + * `record X Y Z 0|1` (a jukebox's has_record), `unload CX CZ`, `tick`. + */ +public final class VanillaBlockEntityTickerOracle { + static Object unsafe; + static Method allocate; + + static <T> T alloc(Class<T> c) throws Exception { + return c.cast(allocate.invoke(unsafe, c)); + } + + static void set(Class<?> owner, Object target, String name, Object value) throws Exception { + Field f = owner.getDeclaredField(name); + f.setAccessible(true); + f.set(target, value); + } + + static Object get(Class<?> owner, Object target, String name) throws Exception { + Field f = owner.getDeclaredField(name); + f.setAccessible(true); + return f.get(target); + } + + static Map<BlockPos, BlockState> cells = new HashMap<>(); + static Map<Long, Chunk> chunks = new HashMap<>(); + static World world; + + static final class World extends net.minecraft.server.level.ServerLevel { + TickRateManager rate; + LevelDebugSynchronizers debug; + World() { + super(null, null, null, null, null, null, false, 0L, List.of(), false); + } + @Override public boolean isClientSide() { return false; } + @Override public TickRateManager tickRateManager() { return rate; } + @Override public LevelDebugSynchronizers debugSynchronizers() { return debug; } + @Override public void onBlockEntityAdded(BlockEntity blockEntity) { } + @Override public void levelEvent(net.minecraft.world.entity.Entity source, int type, BlockPos at, int data) { } + @Override public void gameEvent(net.minecraft.core.Holder<net.minecraft.world.level.gameevent.GameEvent> event, + net.minecraft.world.phys.Vec3 at, net.minecraft.world.level.gameevent.GameEvent.Context context) { } + @Override public BlockState getBlockState(BlockPos p) { return cells.getOrDefault(p, Blocks.AIR.defaultBlockState()); } + @Override public void playSeededSound(net.minecraft.world.entity.Entity except, double x, double y, double z, + net.minecraft.core.Holder<net.minecraft.sounds.SoundEvent> sound, net.minecraft.sounds.SoundSource source, + float volume, float pitch, long seed) { } + @Override public int getMinY() { return -64; } + @Override public int getHeight() { return 384; } + } + + static final class Chunk extends LevelChunk { + Chunk() { + super(null, null); + } + @Override public BlockState getBlockState(BlockPos p) { return cells.getOrDefault(p, Blocks.AIR.defaultBlockState()); } + @Override public void markUnsaved() { } + } + + static void reset() throws Exception { + cells = new HashMap<>(); + chunks = new HashMap<>(); + world = alloc(World.class); + set(Level.class, world, "blockEntityTickers", new ArrayList<TickingBlockEntity>()); + set(Level.class, world, "pendingBlockEntityTickers", new ArrayList<TickingBlockEntity>()); + set(Level.class, world, "soundSeedGenerator", net.minecraft.util.RandomSource.create(0)); + TickRateManager rate = new TickRateManager(); + set(TickRateManager.class, rate, "runGameElements", false); + world.rate = rate; + LevelDebugSynchronizers debug = alloc(LevelDebugSynchronizers.class); + set(LevelDebugSynchronizers.class, debug, "sleeping", true); + world.debug = debug; + } + + static Chunk chunk(int cx, int cz) throws Exception { + Chunk c = chunks.get(ChunkPos.pack(cx, cz)); + if (c != null) return c; + c = alloc(Chunk.class); + set(ChunkAccess.class, c, "blockEntities", new it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap<BlockPos, BlockEntity>()); + set(ChunkAccess.class, c, "pendingBlockEntities", new HashMap<BlockPos, net.minecraft.nbt.CompoundTag>()); + set(ChunkAccess.class, c, "chunkPos", new ChunkPos(cx, cz)); + set(LevelChunk.class, c, "level", world); + set(LevelChunk.class, c, "tickersInLevel", new HashMap<>()); + chunks.put(ChunkPos.pack(cx, cz), c); + return c; + } + + /** The chunk at `p`, in the level (a chunk first seen here was already loaded). */ + static Chunk at(BlockPos p) throws Exception { + Chunk c = chunk(p.getX() >> 4, p.getZ() >> 4); + c.setLoaded(true); + return c; + } + + /** The block's state: a jukebox's has_record from the name (`jukebox_record`). */ + static BlockState state(String name) { + boolean record = name.equals("jukebox_record"); + Block block = BuiltInRegistries.BLOCK.getValue(Identifier.withDefaultNamespace(record ? "jukebox" : name)); + BlockState s = block.defaultBlockState(); + return block instanceof JukeboxBlock ? s.setValue(JukeboxBlock.HAS_RECORD, record) : s; + } + + static BlockEntity make(BlockPos p) { + BlockState s = cells.get(p); + return ((EntityBlock) s.getBlock()).newBlockEntity(p, s); + } + + static BlockPos pos(String[] w, int i) { + return new BlockPos(Integer.parseInt(w[i]), Integer.parseInt(w[i + 1]), Integer.parseInt(w[i + 2])); + } + + public static void main(String[] args) throws Exception { + // Registries with item components bound (vaults hold item stacks). + ParityData.init(); + var allocator = Class.forName("sun.misc.Unsafe"); + var field = allocator.getDeclaredField("theUnsafe"); + field.setAccessible(true); + unsafe = field.get(null); + allocate = allocator.getMethod("allocateInstance", Class.class); + Method update = LevelChunk.class.getDeclaredMethod("updateBlockEntityTicker", BlockEntity.class); + update.setAccessible(true); + StringBuilder out = new StringBuilder(); + for (String line : Files.readAllLines(Path.of(args[0]))) { + String[] w = line.trim().split(" "); + switch (w[0]) { + case "reset" -> reset(); + case "load" -> { + // SerializableChunkData.postLoadChunk, then ChunkStatusTasks.full. + Chunk c = chunk(Integer.parseInt(w[1]), Integer.parseInt(w[2])); + for (int i = 3; i + 3 < w.length; i += 4) { + BlockPos p = pos(w, i + 1); + cells.put(p, state(w[i])); + c.setBlockEntity(make(p)); + } + c.setLoaded(true); + c.registerAllBlockEntitiesAfterLevelLoad(); + } + case "place" -> { + // LevelChunk.setBlockState: a new block entity block. + BlockPos p = pos(w, 2); + cells.put(p, state(w[1])); + at(p).addAndRegisterBlockEntity(make(p)); + } + case "replace" -> { + BlockPos p = pos(w, 1); + at(p).addAndRegisterBlockEntity(make(p)); + } + case "remove" -> { + BlockPos p = pos(w, 1); + at(p).removeBlockEntity(p); + cells.remove(p); + } + case "record" -> { + // LevelChunk.setBlockState: the same block, another state. + BlockPos p = pos(w, 1); + BlockState s = state(w[4].equals("1") ? "jukebox_record" : "jukebox"); + cells.put(p, s); + BlockEntity be = at(p).getBlockEntity(p); + be.setBlockState(s); + update.invoke(at(p), be); + } + case "unload" -> { + Chunk c = chunks.remove(ChunkPos.pack(Integer.parseInt(w[1]), Integer.parseInt(w[2]))); + if (c != null) c.clearAllBlockEntities(); + } + case "tick" -> { + world.tickBlockEntities(); + @SuppressWarnings("unchecked") + List<TickingBlockEntity> list = (List<TickingBlockEntity>) get(Level.class, world, "blockEntityTickers"); + out.append("tick"); + for (TickingBlockEntity t : list) { + BlockPos p = t.getPos(); + out.append(' ').append(p.getX()).append(',').append(p.getY()).append(',').append(p.getZ()); + } + out.append('\n'); + } + default -> throw new IllegalArgumentException(line); + } + } + Files.writeString(Path.of(args[1]), out); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java index 19779739b..2002285e3 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java @@ -170,14 +170,82 @@ public final class VanillaDispenserOracle { throw new IllegalStateException("no slots in " + be); } - /** The removal a "remove" case runs on the block at its origin. */ - static void remove(VanillaBlockUpdateOracle.World w, BlockPos origin, JsonObject op) { + /** The removal a "remove" case runs on the block at its origin; a player's mining prints its statistics and held stack. */ + static List<String> remove(VanillaBlockUpdateOracle.World w, BlockPos origin, JsonObject op) throws Exception { switch (op.get("op").getAsString()) { case "set" -> w.setBlock(origin, Block.stateById(op.get("state").getAsInt()), op.get("flags").getAsInt()); case "destroy" -> w.destroyBlock(origin, op.get("drop").getAsBoolean()); case "remove" -> w.removeBlock(origin, false); + case "mine" -> { + return mine(w, origin, op); + } default -> throw new IllegalStateException(op.toString()); } + return new ArrayList<>(); + } + + /** + * A survival player three blocks south of `pos` mines it holding the case's + * item: the real `ServerPlayerGameMode.destroyBlock` (playerWillDestroy, + * removeBlock with the block entity's side effects, mineBlock, playerDestroy's + * statistic, exhaustion and drops). The statistics and the held stack follow. + */ + static List<String> mine(VanillaBlockUpdateOracle.World w, BlockPos pos, JsonObject op) throws Exception { + Miner player = (Miner) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Miner.class); + player.world = w; + player.hand = stack(op.get("item").getAsString()); + player.offhand = ItemStack.EMPTY; + player.stats = new ArrayList<>(); + VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "abilities", new net.minecraft.world.entity.player.Abilities()); + VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "foodData", new net.minecraft.world.food.FoodData()); + var advancements = (net.minecraft.server.PlayerAdvancements) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, net.minecraft.server.PlayerAdvancements.class); + VanillaBlockUpdateOracle.set(net.minecraft.server.PlayerAdvancements.class, advancements, "activeTriggers", new HashMap<>()); + VanillaBlockUpdateOracle.set(net.minecraft.server.level.ServerPlayer.class, player, "advancements", advancements); + var at = net.minecraft.world.phys.Vec3.atBottomCenterOf(pos).add(0, 1, 3); + VanillaBlockUpdateOracle.set(Entity.class, player, "position", at); + VanillaBlockUpdateOracle.set(Entity.class, player, "blockPosition", BlockPos.containing(at)); + // PiglinAi.angerNearbyPiglins looks around the player's box (gold, chests, barrels...). + player.setBoundingBox(EntityTypes.PLAYER.getDimensions().makeBoundingBox(at)); + var gameMode = new net.minecraft.server.level.ServerPlayerGameMode(player); + VanillaBlockUpdateOracle.set(net.minecraft.server.level.ServerPlayerGameMode.class, gameMode, "gameModeForPlayer", + net.minecraft.world.level.GameType.SURVIVAL); + gameMode.destroyBlock(pos); + List<String> out = new ArrayList<>(player.stats); + out.add("mine held " + ParityData.canon(player.hand)); + return out; + } + + /** The player of a "mine" case: a survival `Clicker` whose selected inventory slot is its main hand. */ + static final class Miner extends net.minecraft.server.level.ServerPlayer { + VanillaBlockUpdateOracle.World world; + ItemStack hand, offhand; + List<String> stats; + Miner() { + super(null, null, null, null); + } + @Override public ServerLevel level() { return world; } + @Override public boolean hasInfiniteMaterials() { return false; } + @Override public boolean isCreative() { return false; } + @Override public boolean isSpectator() { return false; } + @Override public EntityType<?> getType() { return EntityTypes.PLAYER; } + @Override public net.minecraft.core.Holder<EntityType<?>> typeHolder() { return EntityTypes.PLAYER.builtInRegistryHolder(); } + @Override public ItemStack getItemBySlot(EquipmentSlot slot) { + return slot == EquipmentSlot.MAINHAND ? hand : slot == EquipmentSlot.OFFHAND ? offhand : ItemStack.EMPTY; + } + @Override public void setItemSlot(EquipmentSlot slot, ItemStack stack) { + if (slot == EquipmentSlot.MAINHAND) hand = stack; else if (slot == EquipmentSlot.OFFHAND) offhand = stack; + } + @Override public ItemStack getItemInHand(net.minecraft.world.InteractionHand h) { + return h == net.minecraft.world.InteractionHand.MAIN_HAND ? hand : offhand; + } + // Player.hasCorrectToolForDrops asks the inventory's selected slot: the main hand. + @Override public boolean hasCorrectToolForDrops(BlockState state) { + return !state.requiresCorrectToolForDrops() || hand.isCorrectToolForDrops(state); + } + @Override public void awardStat(net.minecraft.stats.Stat<?> stat, int count) { + stats.add("stat " + User.key(stat) + " " + BuiltInRegistries.STAT_TYPE.getKey(stat.getType()) + " " + count); + } + @Override public net.minecraft.server.players.NameAndId nameAndId() { return new net.minecraft.server.players.NameAndId(new UUID(0L, 0L), "Player"); } } static boolean hasList(Object be) { @@ -324,7 +392,7 @@ public final class VanillaDispenserOracle { BlockState state = w.getBlockState(origin); List<String> used = new ArrayList<>(); if (f.has("remove")) { - remove(w, origin, f.getAsJsonObject("remove")); + used = remove(w, origin, f.getAsJsonObject("remove")); } else if (f.has("use")) { used = use(w, origin, f.getAsJsonObject("use")); } else if (f.has("use_item")) { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInteractionInputOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInteractionInputOracle.java new file mode 100644 index 000000000..884e5042a --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInteractionInputOracle.java @@ -0,0 +1,161 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.io.PrintWriter; +import java.lang.reflect.*; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.*; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.multiplayer.*; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.*; +import net.minecraft.network.protocol.Packet; +import net.minecraft.world.*; +import net.minecraft.world.entity.*; +import net.minecraft.world.entity.player.*; +import net.minecraft.world.flag.*; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.SwingAnimation; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.border.WorldBorder; +import net.minecraft.world.phys.*; + +/** Runs the shipped handleKeybinds; only game-mode effects and UI are shells. */ +public final class VanillaInteractionInputOracle { + static Object unsafe; + static Method allocate; + static List<String> events = new ArrayList<>(); + static Field field(Class<?> type, String name) throws Exception { + var f = type.getDeclaredField(name); f.setAccessible(true); return f; + } + static <T> T make(Class<T> type) throws Exception { return type.cast(allocate.invoke(unsafe, type)); } + public static class MC extends Minecraft { + public MC() { super(null); } + @Override public boolean hasControlDown() { return false; } + } + public static class UI extends Gui { + public UI() { super(null, null, null); } + @Override public void handleKeybinds() {} + } + public static class Mouse extends MouseHandler { + public Mouse() { super(null); } + @Override public boolean isMouseGrabbed() { return true; } + } + public static class Level extends ClientLevel { + public Level() { super(null, null, null, null, 0, 0, null, false, 0L, 0); } + @Override public BlockState getBlockState(BlockPos pos) { return Blocks.STONE.defaultBlockState(); } + @Override public FeatureFlagSet enabledFeatures() { return FeatureFlags.REGISTRY.allFlags(); } + } + public static class Connection extends ClientPacketListener { + public Connection() { super(null, null, null); } + @Override public void send(Packet<?> packet) {} + } + public static class Human extends LocalPlayer { + boolean using; + ItemStack held = ItemStack.EMPTY; + public Human() { super(null, null, null, null, null, null, false, null, null); } + @Override public boolean isUsingItem() { return using; } + @Override public boolean isSpectator() { return false; } + @Override public boolean isCreative() { return false; } + @Override public boolean isHandsBusy() { return false; } + @Override public ItemStack getItemInHand(InteractionHand hand) { + return hand == InteractionHand.MAIN_HAND ? held : ItemStack.EMPTY; + } + @Override public void itemUsed(InteractionHand hand) {} + @Override public boolean cannotAttackWithItem(ItemStack item, int slot) { return false; } + @Override public boolean isWithinEntityInteractionRange(Entity e, double buffer) { return true; } + @Override public boolean swing(InteractionHand hand, SwingAnimation animation, boolean send) { return false; } + } + public static class Mode extends MultiPlayerGameMode { + boolean destroying, digOnAttack, beginUsing, passing; + Human player; + public Mode() { super(null, null); } + @Override public boolean isDestroying() { return destroying; } + @Override public boolean isSpectator() { return false; } + @Override public boolean startDestroyBlock(BlockPos pos, Direction face) { + events.add("attack"); destroying = digOnAttack; return true; + } + @Override public boolean continueDestroyBlock(BlockPos pos, Direction face) { + events.add("continue true"); return true; + } + @Override public void stopDestroyBlock() { events.add("continue false"); destroying = false; } + @Override public void attack(Player p, Entity e) { events.add("attack"); } + @Override public void releaseUsingItem(Player p) { events.add("release"); player.using = false; } + InteractionResult use() { events.add("use"); player.using = beginUsing; return InteractionResult.SUCCESS_SERVER; } + @Override public InteractionResult useItemOn(LocalPlayer p, InteractionHand h, BlockHitResult hit) { + if (passing) { events.add("block"); return InteractionResult.PASS; } + return use(); + } + @Override public InteractionResult interact(Player p, Entity e, EntityHitResult hit, InteractionHand h) { + if (passing) { events.add("entity"); return InteractionResult.PASS; } + return use(); + } + @Override public InteractionResult useItem(Player p, InteractionHand h) { + events.add("item"); player.using = beginUsing; return InteractionResult.SUCCESS_SERVER; + } + @Override public void handlePickItemFromBlock(BlockPos pos, boolean data) { events.add("pick"); } + @Override public void handlePickItemFromEntity(Entity entity, boolean data) { events.add("pick"); } + } + static boolean flag(JsonObject row, String name) { return row.get(name).getAsBoolean(); } + public static void main(String[] args) throws Exception { + ParityData.init(); + var u = Class.forName("sun.misc.Unsafe"); unsafe = field(u, "theUnsafe").get(null); + allocate = u.getMethod("allocateInstance", Class.class); + var handle = Minecraft.class.getDeclaredMethod("handleKeybinds"); handle.setAccessible(true); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]))); + var lines = Files.lines(Path.of(args[0]))) { + int i = 0; + for (String line : (Iterable<String>) lines::iterator) { + var row = JsonParser.parseString(line).getAsJsonObject(); + var mc = make(MC.class); var options = make(Options.class); + for (var f : Options.class.getDeclaredFields()) { + if (Modifier.isStatic(f.getModifiers())) continue; + f.setAccessible(true); + if (f.getType() == KeyMapping.class) f.set(options, make(KeyMapping.class)); + if (f.getType() == KeyMapping[].class) { + var keys = new KeyMapping[9]; + for (int n = 0; n < keys.length; n++) keys[n] = make(KeyMapping.class); + f.set(options, keys); + } + } + var player = make(Human.class); player.using = flag(row, "using"); + boolean passing = row.has("passing") && flag(row, "passing"); + player.held = passing ? new ItemStack(Blocks.STONE.asItem()) : ItemStack.EMPTY; + var level = make(Level.class); + field(ClientLevel.class, "worldBorder").set(level, new WorldBorder()); + field(Player.class, "abilities").set(player, new Abilities()); + field(LocalPlayer.class, "connection").set(player, make(Connection.class)); + var mode = make(Mode.class); mode.player = player; + mode.destroying = flag(row, "destroying"); mode.digOnAttack = flag(row, "dig_on_attack"); + mode.beginUsing = flag(row, "begin_using"); + mode.passing = passing; + field(Minecraft.class, "options").set(mc, options); + field(Minecraft.class, "gui").set(mc, make(UI.class)); + field(Minecraft.class, "mouseHandler").set(mc, make(Mouse.class)); + field(Minecraft.class, "player").set(mc, player); + field(Minecraft.class, "level").set(mc, level); + field(Minecraft.class, "gameMode").set(mc, mode); + var entity = make(net.minecraft.world.entity.item.ItemEntity.class); + field(Entity.class, "blockPosition").set(entity, BlockPos.ZERO); + field(Minecraft.class, "hitResult").set(mc, flag(row, "entity") + ? new EntityHitResult(entity, Vec3.ZERO) + : new BlockHitResult(Vec3.ZERO, Direction.UP, BlockPos.ZERO, false)); + String[] names = {"keyAttack", "keyUse", "keyPickItem"}; + for (var click : row.getAsJsonArray("clicks")) { + var key = (KeyMapping)field(Options.class, names[click.getAsInt()]).get(options); + var count = field(KeyMapping.class, "clickCount"); + count.setInt(key, count.getInt(key) + 1); + } + field(KeyMapping.class, "isDown").setBoolean(options.keyAttack, flag(row, "attack_down")); + field(KeyMapping.class, "isDown").setBoolean(options.keyUse, flag(row, "use_down")); + field(Minecraft.class, "rightClickDelay").setInt(mc, row.get("delay").getAsInt()); + events.clear(); handle.invoke(mc); + out.println("== " + i++); + for (String event : events) out.println(event); + out.println("state " + player.using + " " + mode.destroying + " " + field(Minecraft.class, "rightClickDelay").getInt(mc)); + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerSyncOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerSyncOracle.java new file mode 100644 index 000000000..056240bb8 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerSyncOracle.java @@ -0,0 +1,109 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import io.netty.buffer.Unpooled; +import java.io.PrintWriter; +import java.lang.reflect.*; +import java.nio.file.*; +import java.util.HexFormat; +import net.minecraft.client.*; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.world.entity.*; +import net.minecraft.world.phys.Vec3; + +/** Runs shipped methods; only the world lifecycle and packet sink are fixtures. */ +public final class VanillaPlayerSyncOracle { + static Object unsafe; + static Method allocate; + static PrintWriter out; + static Field field(Class<?> type, String name) throws Exception { + var f = type.getDeclaredField(name); f.setAccessible(true); return f; + } + static <T> T make(Class<T> type) throws Exception { + return type.cast(allocate.invoke(unsafe, type)); + } + public static final class Player extends LocalPlayer { + boolean ground; + public Player() { super(null, null, null, null, null, null, false, null, null); } + @Override protected boolean isControlledCamera() { return true; } + @Override public boolean isSprinting() { return false; } + @Override public boolean onGround() { return ground; } + } + public static final class Sink extends ClientPacketListener { + boolean sent; + public Sink() { super(null, null, null); } + @Override public void send(Packet<?> packet) { + sent = true; + var buf = new FriendlyByteBuf(Unpooled.buffer()); + String name; + try { + if (packet instanceof ServerboundMovePlayerPacket.PosRot p) { + name = "posrot"; ServerboundMovePlayerPacket.PosRot.STREAM_CODEC.encode(buf, p); + } else if (packet instanceof ServerboundMovePlayerPacket.Pos p) { + name = "pos"; ServerboundMovePlayerPacket.Pos.STREAM_CODEC.encode(buf, p); + } else if (packet instanceof ServerboundMovePlayerPacket.Rot p) { + name = "rot"; ServerboundMovePlayerPacket.Rot.STREAM_CODEC.encode(buf, p); + } else if (packet instanceof ServerboundMovePlayerPacket.StatusOnly p) { + name = "status"; ServerboundMovePlayerPacket.StatusOnly.STREAM_CODEC.encode(buf, p); + } else { throw new AssertionError(packet); } + byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); + out.println(name + " " + HexFormat.of().formatHex(bytes)); + } finally { buf.release(); } + } + } + static double number(JsonElement value) { + return Double.longBitsToDouble(Long.parseUnsignedLong(value.getAsString(), 16)); + } + static Vec3 vector(JsonObject row, String key) { + var a = row.getAsJsonArray(key); + return new Vec3(number(a.get(0)), number(a.get(1)), number(a.get(2))); + } + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var u = Class.forName("sun.misc.Unsafe"); + unsafe = field(u, "theUnsafe").get(null); + allocate = u.getMethod("allocateInstance", Class.class); + var sendPosition = LocalPlayer.class.getDeclaredMethod("sendPosition"); + sendPosition.setAccessible(true); + var minecraft = make(Minecraft.class); + var options = make(Options.class); + field(Options.class, "autoJump").set(options, OptionInstance.createBoolean("test", false)); + field(Minecraft.class, "options").set(minecraft, options); + try (var output = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]))); + var lines = Files.lines(Path.of(args[0]))) { + out = output; + for (String line : (Iterable<String>) lines::iterator) { + var row = JsonParser.parseString(line).getAsJsonObject(); + if (row.get("kind").getAsString().equals("movement")) { + var p = make(Player.class); + var sink = make(Sink.class); + field(LocalPlayer.class, "connection").set(p, sink); + field(LocalPlayer.class, "minecraft").set(p, minecraft); + for (var value : row.getAsJsonArray("ops")) { + var op = value.getAsJsonArray(); + field(Entity.class, "position").set(p, new Vec3(number(op.get(0)), number(op.get(1)), number(op.get(2)))); + field(Entity.class, "yRot").setFloat(p, (float)number(op.get(3))); + field(Entity.class, "xRot").setFloat(p, (float)number(op.get(4))); + p.ground = op.get(5).getAsBoolean(); + p.horizontalCollision = op.get(6).getAsBoolean(); + sink.sent = false; + sendPosition.invoke(p); + if (!sink.sent) out.println("-"); + } + } else { + var old = row.getAsJsonArray("old"); + var next = row.getAsJsonArray("new"); + var base = new PositionMoveRotation(Vec3.ZERO, vector(row, "velocity"), (float)number(old.get(0)), (float)number(old.get(1))); + var change = new PositionMoveRotation(Vec3.ZERO, vector(row, "delta"), (float)number(next.get(0)), (float)number(next.get(1))); + var v = PositionMoveRotation.calculateAbsolute(base, change, Relative.unpack(row.get("flags").getAsInt())).deltaMovement(); + out.printf("%016x %016x %016x%n", Double.doubleToRawLongBits(v.x), Double.doubleToRawLongBits(v.y), Double.doubleToRawLongBits(v.z)); + } + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java index f87e9cf0f..b15720848 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java @@ -113,6 +113,8 @@ public final class VanillaProtocolClient { private ProtocolInfo<?> inbound; private ProtocolInfo<?> outbound; private String state; + /** With a fifth argument {@code entities}: the entity transcript mode (EntityTranscript). */ + private EntityTranscript entities; public static void main(String[] args) throws Exception { ParityData.init(); @@ -121,6 +123,7 @@ public final class VanillaProtocolClient { String name = args[2]; Path output = Path.of(args[3]); VanillaProtocolClient client = new VanillaProtocolClient(); + if (args.length > 4 && args[4].equals("entities")) client.entities = new EntityTranscript(); try { client.status(host, port); client.join(host, port, name); @@ -405,6 +408,18 @@ public final class VanillaProtocolClient { play(); } + /** The entity mode's step, and how long it records the entities for (ms). */ + private static final int ENTITIES = 1000; + private static final long ENTITY_WAIT = 20_000; + + static int moveEntityId(net.minecraft.network.protocol.game.ClientboundMoveEntityPacket p) { + return (int) field(p, net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.class, "entityId"); + } + + static int rotateHeadId(net.minecraft.network.protocol.game.ClientboundRotateHeadPacket p) { + return (int) field(p, p.getClass(), "entityId"); + } + private static final String[] REPLIES = {"random value 7..7", "random value x", "trigger nope"}; private void play() throws Exception { @@ -461,6 +476,7 @@ public final class VanillaProtocolClient { if (r != null) { Packet<?> packet = r.packet; counts.merge(r.type, 1, Integer::sum); + if (entities != null && !entities.acceptSelf(packet) && step >= ENTITIES) entities.accept(packet); if (r.type.equals("minecraft:chunk_batch_start")) ordered = false; if (respawning && !respawned) { String line = respawnLine(r); @@ -581,8 +597,20 @@ public final class VanillaProtocolClient { commandTree(p); } } + if (entities != null && loaded && lastChunk > 0 && now - lastChunk > 3000 && step == 0) { + // Entity mode: the harness's console summons the scene once it reads this + // line; everything tracked from then on is recorded until the client leaves. + record("play-chunks", String.valueOf(chunks.size())); + send(new ServerboundChatPacket("summon the entities", Instant.now(), 0L, Optional.empty(), + new LastSeenMessages.Update(0, new BitSet(), (byte) 0))); + step = ENTITIES; + stepAt = now; + } else if (step == ENTITIES && now - stepAt > ENTITY_WAIT) { + for (String line : entities.lines()) record("play-entities", line); + return; + } // Once the chunks stop coming: chat, then /list, then leave. - if (loaded && lastChunk > 0 && now - lastChunk > 3000 && step == 0) { + if (entities == null && loaded && lastChunk > 0 && now - lastChunk > 3000 && step == 0) { record("play-chunks", chunks.size() + " " + chunks); BLOCK_ENTITIES.forEach((k, v) -> record("play-block-entities", k + " " + v)); // Which light layers exist depends on the neighbouring @@ -910,8 +938,12 @@ public final class VanillaProtocolClient { } private static Object field(Object owner, String name) { + return field(owner, owner.getClass(), name); + } + + private static Object field(Object owner, Class<?> declaring, String name) { try { - var f = owner.getClass().getDeclaredField(name); + var f = declaring.getDeclaredField(name); f.setAccessible(true); return f.get(owner); } catch (ReflectiveOperationException e) { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTooltipDisplayOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTooltipDisplayOracle.java new file mode 100644 index 000000000..c31dce98c --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTooltipDisplayOracle.java @@ -0,0 +1,36 @@ +package dev.horizonlab.parity; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import net.minecraft.core.component.DataComponentType; +import net.minecraft.core.component.DataComponents; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.item.component.TooltipDisplay; + +/** The name and attribute lines returned for a diamond sword's tooltip. */ +public final class VanillaTooltipDisplayOracle { + public static void main(String[] args) throws Exception { + ParityData.init(); + var context = Item.TooltipContext.of(ParityData.lookup); + var output = new ArrayList<String>(); + for (String line : Files.readAllLines(Path.of(args[0]))) { + String[] fields = line.split("\t"); + boolean hideTooltip = Boolean.parseBoolean(fields[0]); + boolean creative = Boolean.parseBoolean(fields[1]); + boolean hideAttributes = Boolean.parseBoolean(fields[2]); + var hidden = new LinkedHashSet<DataComponentType<?>>(); + if (hideAttributes) hidden.add(DataComponents.ATTRIBUTE_MODIFIERS); + var stack = new ItemStack(Items.DIAMOND_SWORD, 1); + stack.set(DataComponents.TOOLTIP_DISPLAY, new TooltipDisplay(hideTooltip, hidden)); + TooltipFlag flag = creative ? TooltipFlag.Default.NORMAL.asCreative() : TooltipFlag.Default.NORMAL; + var tooltip = stack.getTooltipLines(context, null, flag); + output.add((!tooltip.isEmpty()) + "\t" + (tooltip.size() > 1)); + } + Files.write(Path.of(args[1]), output); + } +} diff --git a/packaging/server/Dockerfile b/packaging/server/Dockerfile index bbb74ba26..5ae395205 100644 --- a/packaging/server/Dockerfile +++ b/packaging/server/Dockerfile @@ -13,20 +13,15 @@ # start writes /data/server.toml from HORIZON_* (EULA, WORLD, SEED, PORT, WHITELIST, PLAYERS, OP); later # starts use the file. Manage it with `docker exec horizon horizon-server status|cmd|backup|logs ...`. FROM rust:1-slim-bookworm AS build -RUN apt-get update \ - && apt-get install -y --no-install-recommends pkg-config libasound2-dev libudev-dev \ - && rm -rf /var/lib/apt/lists/* WORKDIR /src COPY . . -RUN cargo build --release --locked -p horizon-client --bin horizon-client -p horizon-server --bin horizon-server \ - && mkdir /out && cp target/release/horizon-client target/release/horizon-server /out/ +# The server build of the game (no sound, no controllers: it needs neither ALSA nor udev) as horizon-engine. +RUN cargo build --release --locked -p horizon-client --no-default-features --bin horizon-client \ + && cargo build --release --locked -p horizon-server --bin horizon-server \ + && mkdir /out && cp target/release/horizon-client /out/horizon-engine && cp target/release/horizon-server /out/ FROM debian:bookworm-slim -# The game links ALSA and udev even when it runs headless with no sound. -RUN apt-get update \ - && apt-get install -y --no-install-recommends libasound2 libudev1 \ - && rm -rf /var/lib/apt/lists/* \ - && useradd --system --home-dir /data --shell /usr/sbin/nologin horizon \ +RUN useradd --system --home-dir /data --shell /usr/sbin/nologin horizon \ && mkdir -p /data /opt/horizon/.local/horizon-client \ && chown horizon:horizon /data COPY --from=build /out/ /opt/horizon/ diff --git a/packaging/server/install.sh b/packaging/server/install.sh index 221fcf0a8..eed312c74 100755 --- a/packaging/server/install.sh +++ b/packaging/server/install.sh @@ -1,9 +1,11 @@ #!/bin/sh # Installs horizon-server (docs/server.md) on Linux or macOS: the latest Horizon release for this computer, -# downloaded from GitHub Releases and checked against the SHA-256 GitHub publishes for it. +# downloaded from GitHub Releases and checked against the SHA-256 GitHub publishes for it. On Linux that is +# the server build (horizon-server-linux-x86_64.tar.gz), which needs neither ALSA nor udev. # # curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.sh | sh # curl -fsSL .../install.sh | sh -s -- --version v0.5.0 --dir /opt/horizon --bin /usr/local/bin +# sh install.sh --archive horizon-server-linux-x86_64.tar.gz --version mybuild (an archive you have) # # It needs curl, tar or unzip, and sha256sum or shasum; it never asks for sudo (pick folders you can write). # Releases go to <dir>/releases/<version>, <dir>/current points at the one in use, and <bin>/horizon-server @@ -15,6 +17,7 @@ REPO=ludovic111/horizon VERSION=latest DIR="${XDG_DATA_HOME:-$HOME/.local/share}/horizon" BIN="$HOME/.local/bin" +ARCHIVE= die() { echo "horizon install: $*" >&2; exit 1; } @@ -23,45 +26,58 @@ while [ $# -gt 0 ]; do --version) [ $# -ge 2 ] || die "--version needs a tag"; VERSION=$2; shift 2 ;; --dir) [ $# -ge 2 ] || die "--dir needs a folder"; DIR=$2; shift 2 ;; --bin) [ $# -ge 2 ] || die "--bin needs a folder"; BIN=$2; shift 2 ;; - -h|--help) sed -n '2,12p' "$0" 2>/dev/null || true; exit 0 ;; + --archive) [ $# -ge 2 ] || die "--archive needs a file"; ARCHIVE=$2; shift 2 ;; + -h|--help) sed -n '2,14p' "$0" 2>/dev/null || true; exit 0 ;; *) die "unknown option $1" ;; esac done +# The archives to look for, in order: on Linux the server build, else (releases before it) the full game. case "$(uname -s)-$(uname -m)" in - Linux-x86_64) ASSET=horizon-linux-x86_64.tar.gz ;; - Darwin-arm64) ASSET=horizon-macos-arm64.zip ;; + Linux-x86_64) ASSETS="horizon-server-linux-x86_64.tar.gz horizon-linux-x86_64.tar.gz" ;; + Darwin-arm64) ASSETS=horizon-macos-arm64.zip ;; *) die "no Horizon release for $(uname -s) $(uname -m) yet: build it from source (docs/server.md)" ;; esac -command -v curl >/dev/null || die "curl is needed" -if command -v sha256sum >/dev/null; then SHA="sha256sum" -elif command -v shasum >/dev/null; then SHA="shasum -a 256" -else die "sha256sum or shasum is needed"; fi - -if [ "$VERSION" = latest ]; then API="https://api.github.com/repos/$REPO/releases/latest" -else API="https://api.github.com/repos/$REPO/releases/tags/$VERSION"; fi -JSON=$(curl -fsSL -H "Accept: application/vnd.github+json" "$API") || die "no release $VERSION on GitHub" - -TAG=$(printf '%s\n' "$JSON" | sed -n 's/^ "tag_name": "\([^"]*\)".*/\1/p' | head -n 1) -[ -n "$TAG" ] || die "could not read the release's tag" -# The asset's download address and digest, from its block in the release's JSON. -FIELDS=$(printf '%s\n' "$JSON" | awk -v asset="$ASSET" ' - /"name": / { line = $0; sub(/.*"name": "/, "", line); sub(/".*/, "", line); current = line } - current == asset && /"digest": / { line = $0; sub(/.*"digest": "sha256:/, "", line); sub(/".*/, "", line); digest = line } - current == asset && /"browser_download_url": / { line = $0; sub(/.*"browser_download_url": "/, "", line); sub(/".*/, "", line); url = line } - END { print url; print digest }') -URL=$(printf '%s\n' "$FIELDS" | sed -n 1p) -DIGEST=$(printf '%s\n' "$FIELDS" | sed -n 2p) -[ -n "$URL" ] || die "release $TAG has no $ASSET" -[ -n "$DIGEST" ] || die "release $TAG publishes no SHA-256 for $ASSET" - TMP=$(mktemp -d) trap 'rm -rf "$TMP"' EXIT -echo "Downloading Horizon $TAG ($ASSET)..." -curl -fL --progress-bar -o "$TMP/$ASSET" "$URL" -GOT=$($SHA "$TMP/$ASSET" | cut -d' ' -f1) -[ "$GOT" = "$DIGEST" ] || die "$ASSET doesn't match its SHA-256 (got $GOT, expected $DIGEST): not installed" +if [ -n "$ARCHIVE" ]; then + # An archive already here (a build of your own, or one fetched by hand): checking it is up to you. + [ -f "$ARCHIVE" ] || die "no archive $ARCHIVE" + if [ "$VERSION" = latest ]; then TAG=local; else TAG=$VERSION; fi + ASSET=$(basename "$ARCHIVE") + cp "$ARCHIVE" "$TMP/$ASSET" +else + command -v curl >/dev/null || die "curl is needed" + if command -v sha256sum >/dev/null; then SHA="sha256sum" + elif command -v shasum >/dev/null; then SHA="shasum -a 256" + else die "sha256sum or shasum is needed"; fi + + if [ "$VERSION" = latest ]; then API="https://api.github.com/repos/$REPO/releases/latest" + else API="https://api.github.com/repos/$REPO/releases/tags/$VERSION"; fi + JSON=$(curl -fsSL -H "Accept: application/vnd.github+json" "$API") || die "no release $VERSION on GitHub" + + TAG=$(printf '%s\n' "$JSON" | sed -n 's/^ "tag_name": "\([^"]*\)".*/\1/p' | head -n 1) + [ -n "$TAG" ] || die "could not read the release's tag" + # The first asset the release has: its download address and digest, from its block in the release's JSON. + for ASSET in $ASSETS; do + FIELDS=$(printf '%s\n' "$JSON" | awk -v asset="$ASSET" ' + /"name": / { line = $0; sub(/.*"name": "/, "", line); sub(/".*/, "", line); current = line } + current == asset && /"digest": / { line = $0; sub(/.*"digest": "sha256:/, "", line); sub(/".*/, "", line); digest = line } + current == asset && /"browser_download_url": / { line = $0; sub(/.*"browser_download_url": "/, "", line); sub(/".*/, "", line); url = line } + END { print url; print digest }') + URL=$(printf '%s\n' "$FIELDS" | sed -n 1p) + DIGEST=$(printf '%s\n' "$FIELDS" | sed -n 2p) + [ -z "$URL" ] || break + done + [ -n "$URL" ] || die "release $TAG has none of $ASSETS" + [ -n "$DIGEST" ] || die "release $TAG publishes no SHA-256 for $ASSET" + + echo "Downloading Horizon $TAG ($ASSET)..." + curl -fL --progress-bar -o "$TMP/$ASSET" "$URL" + GOT=$($SHA "$TMP/$ASSET" | cut -d' ' -f1) + [ "$GOT" = "$DIGEST" ] || die "$ASSET doesn't match its SHA-256 (got $GOT, expected $DIGEST): not installed" +fi mkdir -p "$TMP/x" case "$ASSET" in @@ -86,6 +102,18 @@ for tool in horizon-server horizon-prepare; do done echo "Installed Horizon $TAG in $RELEASE; horizon-server and horizon-prepare are in $BIN." +# The full game (releases before the server build) links ALSA and udev; minimal Linux images often lack them. +if [ "$(uname -s)" = Linux ] && [ ! -e "$RELEASE/horizon-engine" ] && command -v ldd >/dev/null; then + MISSING=$(ldd "$RELEASE/horizon-client" 2>/dev/null | awk '/not found/ { printf "%s ", $1 }') + if [ -n "$MISSING" ]; then + echo "The game needs libraries this system doesn't have: $MISSING" + echo "Install them before starting a server:" + echo " Debian, Ubuntu: sudo apt install libasound2 libudev1 (Ubuntu 24.04 and later: libasound2t64)" + echo " Fedora, RHEL: sudo dnf install alsa-lib systemd-libs" + echo " Arch: sudo pacman -S alsa-lib systemd-libs" + echo " NixOS: enable programs.nix-ld with alsa-lib and udev in its libraries" + fi +fi case ":$PATH:" in *":$BIN:"*) ;; *) echo "Add $BIN to your PATH, for example: echo 'export PATH=\"$BIN:\$PATH\"' >> ~/.profile" ;; diff --git a/tests/test_parity_runner.py b/tests/test_parity_runner.py index 78716787a..ffec8d3d5 100644 --- a/tests/test_parity_runner.py +++ b/tests/test_parity_runner.py @@ -1,4 +1,5 @@ from pathlib import Path +import os import tempfile import unittest from unittest import mock @@ -151,6 +152,7 @@ class ShardTests(unittest.TestCase): self.assertEqual(parity.base_name("x#2"), "x") +@unittest.skipIf(os.name == "nt", "oracle PATH shimming uses Unix executable symlink semantics") class OracleReuseTests(unittest.TestCase): """tools/parity_shim.py replays a run only when its inputs and outputs are as recorded.""" diff --git a/tests/test_server_bench.py b/tests/test_server_bench.py new file mode 100644 index 000000000..f392297bc --- /dev/null +++ b/tests/test_server_bench.py @@ -0,0 +1,32 @@ +import unittest + +from tools.server_bench import work + + +def run(server, bots, sent, new, waited=0.0, behaviour="mixed"): + return {"server": server, "behaviour": behaviour, "bots": bots, "chunks_per_second": sent, + "unique_per_second": new, "waited_ticks_per_second": waited} + + +class ServerBenchWorkTests(unittest.TestCase): + def test_shares_of_the_busiest_server(self): + [row] = work([run("horizon", 10, 98.2, 36.5), run("vanilla", 10, 24.3, 19.1, 12.0)]) + self.assertFalse(row["equal"]) + self.assertEqual(row["servers"]["horizon"]["chunks_per_second"], {"value": 98.2, "share": 1.0}) + self.assertEqual(row["servers"]["vanilla"]["chunks_per_second"]["share"], 0.247) + self.assertEqual(row["servers"]["vanilla"]["waited_ticks_per_second"], 12.0) + + def test_equal_within_ten_percent_or_a_chunk(self): + [row] = work([run("horizon", 25, 236, 28.9), run("vanilla", 25, 252, 28.9)]) + self.assertTrue(row["equal"]) + # One bot: 0.3 against 1.1 new chunks a second is within a chunk. + [row] = work([run("horizon", 1, 9.9, 0.3), run("vanilla", 1, 9.9, 1.1)]) + self.assertTrue(row["equal"]) + + def test_only_counts_run_on_several_servers(self): + failed = dict(run("vanilla", 50, 0, 0), error="watchdog") + self.assertEqual(work([run("horizon", 50, 450, 10), failed, run("horizon", 1, 9, 0.3)]), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/agent_control_e2e.py b/tools/agent_control_e2e.py index ab408b2b2..53296669a 100644 --- a/tools/agent_control_e2e.py +++ b/tools/agent_control_e2e.py @@ -7,7 +7,8 @@ runs through the CLI (one horizon-ctl process per command) and through `horizon- small JSON-RPC client, and saves a screenshot of each run. The ui scenario drives the menus by widget id instead: the title screen, the options (a slider set by id) and the inventory's slots; the options scenario reads and sets options.txt values by key; the events scenario waits for -states (wait-for) and reads the event log. +states (wait-for) and reads the event log; the consume scenario eats and drinks consumables (a +golden apple, milk, honey, chorus fruit) and checks their effects, remainders and teleport. python3 tools/agent_control_e2e.py # both modes python3 tools/agent_control_e2e.py --mode mcp # one of them @@ -378,7 +379,52 @@ def events_scenario(d, out): return {'events': len(events)} -SCENARIOS = {'survival': scenario, 'ui': ui_scenario, 'options': options_scenario, 'events': events_scenario} +def consume_scenario(d, out): + # Consumables finish as vanilla's Consumable.onConsume: always-edible food at full hunger with its + # effects, milk and honey (no food or drink sounds) with their effects and use remainders, and + # chorus fruit's random teleport. + d('click', id='singleplayer') + if 'game' not in widgets(d): + d('click', id='create-new-world') + d('type', field='name', replace=True, text='Consume') + d('click', id='create-new-world') + d('wait_for', condition='loaded', timeout=400) + + def consume(item, seconds): + d('command', command='clear @s') + d('give', item=item, count=1) + d('use_item', hold=seconds) + d('wait', ticks=5) + state = d('state') + return state, {e['id'] for e in state['player']['effects']} + + def held(state): + return state['held'] and state['held']['item'] + + state, effects = consume('golden_apple', 2.2) + assert state['player']['food'] == 20 and {'regeneration', 'absorption'} <= effects, effects + assert held(state) is None, state['held'] + d('command', command='effect give @s minecraft:speed 60') + state, effects = consume('milk_bucket', 2.2) + assert effects == set(), effects + assert held(state) == 'minecraft:bucket', state['held'] + d('command', command='effect give @s minecraft:poison 60') + d('command', command='effect give @s minecraft:speed 60') + state, effects = consume('honey_bottle', 2.6) + assert effects == {'speed'}, effects + assert held(state) == 'minecraft:glass_bottle', state['held'] + before = d('state')['player']['position'] + state, _ = consume('chorus_fruit', 2.2) + after = state['player']['position'] + moved = [b - a for a, b in zip(before, after)] + assert held(state) is None, state['held'] + assert moved != [0, 0, 0] and abs(moved[0]) <= 8 and abs(moved[2]) <= 8, moved + d('screenshot', path=str(out / f'consume-{d.name}.png')) + return {'teleported': [round(m, 2) for m in moved]} + + +SCENARIOS = {'survival': scenario, 'ui': ui_scenario, 'options': options_scenario, 'events': events_scenario, + 'consume': consume_scenario} def run(mode, ctl, out, resources, which='survival'): diff --git a/tools/check_imports.py b/tools/check_imports.py index 8cdabe45b..85afb541d 100644 --- a/tools/check_imports.py +++ b/tools/check_imports.py @@ -5,7 +5,8 @@ Windows .exe: every DLL in the import and delay-import tables must ship with Windows (no VCRUNTIME140.dll, vulkan-1.dll, ...): Vulkan and the like are loaded at run time, so a missing driver is an error message, not a dialog. Linux ELF: the loader must be the standard one (not a /nix/store path) and the -needed libraries the ones every desktop distribution has. +needed libraries the ones every desktop distribution has. `--server`: a server +build, which may not need ALSA or udev either (minimal server images lack them). """ import argparse @@ -30,6 +31,8 @@ LINUX_SYSTEM = { "libc.so.6", "libm.so.6", "libgcc_s.so.1", "libdl.so.2", "libpthread.so.0", "librt.so.1", "ld-linux-x86-64.so.2", "libasound.so.2", "libudev.so.1", } +# The game's sound (cpal) and controllers (gilrs): a desktop has them, a server image may not. +LINUX_DESKTOP_ONLY = {"libasound.so.2", "libudev.so.1"} def windows_allowed(name): @@ -111,7 +114,7 @@ def elf_needs(data): return interpreter, needed, runpath -def check(path): +def check(path, server=False): data = Path(path).read_bytes() problems = [] if data[:2] == b"MZ": @@ -123,6 +126,8 @@ def check(path): if interpreter not in (None, LINUX_LOADER): problems.append(f"loader is {interpreter}, not {LINUX_LOADER}") problems += [f"needs {n}, which not every distribution has" for n in needed if n not in LINUX_SYSTEM] + if server: + problems += [f"needs {n}, which a server may not have" for n in needed if n in LINUX_DESKTOP_ONLY] problems += [f"has a run path to {p}" for p in runpath if "/nix/store" in p] summary = f"{interpreter}; " + ", ".join(needed) print(f"{path}: {summary}") @@ -134,8 +139,10 @@ def check(path): def main(): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("binaries", nargs="+") + parser.add_argument("--server", action="store_true", + help="a server build: not even ALSA or udev (the game's sound and controllers)") args = parser.parse_args() - ok = all([check(path) for path in args.binaries]) + ok = all([check(path, args.server) for path in args.binaries]) sys.exit(0 if ok else 1) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 2d64c216f..144ed6961 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -19,10 +19,24 @@ address. The script then checks, from both sides, what a guest's game used to ge - hazards: a guest in survival gets hungry sprint-jumping and is hurt by lava, a block at the eyes, drowning and the void (then respawns); - pvp: the guest and the host hit each other with a sword; with the pvp game rule off, nothing; +- respawn: a player killed is drawn dead by the other side, and alive again once it respawns (the + respawned player is a new entity to the others); the host dies, and on the server thread + the guest too; +- hurt: a pig the guest hits, and one the host hits, flashes red on the other side too (the + server's damage event) (#848); - containers: the guest's ender chest holds the guest's items, not the host's, and a double chest opens as 9x6 with the right half first; +- machines: a hopper, a dispenser and a dropper open on the guest's screen with their 5 and 9 + slots, and keep what the guest shift-clicks into them (#848); +- brewing: a brewing stand opens on the guest's screen; blaze powder, nether wart and a bottle the + guest shift-clicks go to the fuel, ingredient and bottle slots, and the stand's fuel shows + (#848); - feedback: the guest's command feedback names the guest and shows the numbers; +- chat: a line the host sends reaches the guest's event log (`wait-for chat`), and on the + server thread the host window's too; - effects: a beacon's power reaches every player in range, the host and the guest; +- distance: (--server-thread) the server follows the host's render distance, past vanilla's 32 too + (IntegratedServer.tickServer), and the guest's chunks follow the server's (#804) - portals: (--server-thread) the server holds a level per dimension: the guest goes to the Nether through a portal while the host stays, then the host goes to the End while the guest is in the Nether, and both come back. @@ -30,6 +44,36 @@ address. The script then checks, from both sides, what a guest's game used to ge tree (Tab), and runs what it completed; - recipes: the guest's recipe book lists the planks recipe the logs unlock, and clicking it places a log in the inventory's crafting grid (the server places it). +- feedback: the guest's command feedback names the guest and shows the numbers, and the host (an + operator) is told of it as `[Guest: ...]`. +- clicks: with real mouse presses (not click-slot, which skips the screen's press and drag + handling), the guest puts a stack into a chest and a furnace, drags planks across + its crafting grid and gathers a stack with a double click; the server has each. +- sleep: at night the guest lies down in its own bed (not the host); alone it stays night, it + gets up with Escape, and once the host sleeps too the night ends and both wake. +- push: a cow standing in the guest pushes it just clear of the cow (the guest's own client + pushes it, as in vanilla), not ever faster across the ground. +- eat: holding right click with bread, the guest's own screen plays the eating (the item in use + counts up) and the server eats one loaf and feeds the guest. +- eating: each side sees the other player eat: the item in use (LivingEntity's flags) on the + player it draws, and no longer once the bread is eaten (#803); +- xp: experience orbs 4 blocks away fly to the guest, show on the guest's screen and give the + guest their points (not the host). +- objects: boats, minecarts, armor stands, item frames and paintings the host summons reach the + guest as the host has them (kind, place, rotation, what they hold or wear, the variant). +- projectiles: primed TNT (one falling), an end crystal and an arrow that lands reach the guest where + the host has them; a falling block lands on both sides. +- plates: a stone pressure plate the guest steps on is pressed on both sides, and comes up once + the guest steps off (#848). +- swings: each side sees the other's arm swing while it mines a block, and the guest sees its own + swing when its hoe tills dirt (the server's use) (#848). +- time: the guest's clock is the host's: it stops with `/time pause`, and catches up with the + server's game time after the guest's game stalls for a few seconds (#848). +- growth: far from the host, the chunks around the guest tick (#890): water placed there flows + and wheat on farmland grows (random ticks), however the host runs its world. +- light: the guest's light matches the host's: around a torch placed near it, under a roof and + once a block of the roof is removed under the sky, and in the last chunk it tracks next to + glowstone in a chunk it doesn't (only the server's light updates bring that one). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -47,9 +91,11 @@ import json import os import re import shutil +import signal import subprocess import sys import tempfile +import threading import time import zlib from pathlib import Path @@ -61,7 +107,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'commands', 'recipes', 'trials', 'effects', 'portals'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'plates', 'effects', 'portals', 'distance', 'growth'] class Game: @@ -174,7 +220,7 @@ def check_armour(host, guest, out): face_each_other(host, guest) host.shot(out, 'armour') guest.shot(out, 'armour') - seen = host.raw('lan', 'status')['guests'][0].get('model_armor') + seen = lan_guest(host).get('model_armor') assert seen == [None, 'minecraft:diamond_chestplate', 'minecraft:diamond_leggings', None], \ f'the host draws the guest in {seen}' host_gear = [e for e in remote(guest).get('player_equipment', [])] @@ -337,6 +383,33 @@ def nether_portal(game, x, y, z): game('command', command=f'fill {x} {y} {z} {x + 1} {y + 2} {z} minecraft:nether_portal[axis=x]') +def lan_guest(host): + """The guest's entry in the host's `lan status` (on the server thread the owner is listed too).""" + guests = host.raw('lan', 'status')['guests'] + return next(g for g in guests if g['name'] == GUEST_NAME) + +def check_distance(host, guest, out): + """IntegratedServer.tickServer: the server takes the host's render distance as its view distance + (past 32, which Horizon's options allow) and sends it to every player (SetChunkCacheRadius).""" + if not SERVER_THREAD: + return 'skipped (needs --server-thread)' + seen = {} + try: + for distance in (48, 6): + host.raw('render-distance', distance) + # The pause screen doesn't hold the server here: it follows on its next tick. + host.wait(20) + guest.wait(20) + seen[distance] = (host('status').get('render_distance'), guest('status').get('render_distance')) + finally: + host.raw('render-distance', 12) + # A client streams out to min(its render distance, the server's view distance + 1). + assert seen[48][0] == 48, f'the host at 48 streams {seen[48][0]} chunks out (all: {seen})' + assert seen[6][0] == 6, f'the host at 6 streams {seen[6][0]} chunks out (all: {seen})' + assert seen[6][1] == 7, f'the guest streams {seen[6][1]} with the server at 6 (all: {seen})' + return seen + + def check_portals(host, guest, out): if not SERVER_THREAD: return 'skipped (needs --server-thread)' @@ -441,6 +514,9 @@ def check_hazards(host, guest, out): # A fresh life: full health, so no regeneration eats food while the guest runs. guest('command', command='kill @s') guest.wait(20) + # ServerPlayer.doTick sends the dead player's health of 0 too. + died = {'screen': guest('state').get('screen'), 'health': remote(guest)['health']} + assert died == {'screen': 'dead', 'health': 0.0}, f'the guest was killed: {died}' guest.raw('respawn') guest.wait(40) # Sprint-jumping down a stone lane: ServerPlayer.jumpFromGround and checkMovementStatistics. @@ -449,14 +525,14 @@ def check_hazards(host, guest, out): guest.wait(10) x, y, z = pos_of(guest) guest.raw('look-at', f'{x + 60:.2f}', f'{y + 1.6:.2f}', f'{z:.2f}') - food = host.raw('lan', 'status')['guests'][0]['food'] + food = lan_guest(host)['food'] for k in ('w', 'ctrl', 'space'): guest.raw('key', k, 'down') guest.wait(160) for k in ('space', 'ctrl', 'w'): guest.raw('key', k, 'up') guest.wait(10) - fed = host.raw('lan', 'status')['guests'][0]['food'] + fed = lan_guest(host)['food'] hunger = {'before': food, 'after': fed} hurt = {} hx, hy, hz = (int(v // 1) for v in pos_of(host)) @@ -493,7 +569,7 @@ def check_hazards(host, guest, out): assert spent > 1.0, f'no hunger from moving: {hunger} ({spent:.2f} spent)' for name, (before, after) in hurt.items(): assert after < before, f'{name} never hurt the guest: health {before} -> {after} (all: {hurt})' - return {'hunger': hunger, **hurt} + return {'died': died, 'hunger': hunger, **hurt} def check_pvp(host, guest, out): @@ -522,6 +598,72 @@ def check_pvp(host, guest, out): return hits +def dead_players(game, want, ticks=60): + """The other players `game`'s client draws dead, once that is `want` (empty or not) or after `ticks`.""" + for _ in range(ticks // 5): + dead = remote(game)['dead_players'] + if bool(dead) == want: + return dead + game.wait(5) + return dead + + +def check_respawn(host, guest, out): + # ServerLevel.removePlayerImmediately and addRespawnedPlayer: a respawned player is removed + # from the other players and paired again as a new entity, so their clients drop the body. + # The host window only has a client's view of the guest on the server thread. + for g in (host, guest): + back_to_game(g) + results = {} + sides = [('host', host, guest)] + ([('guest', guest, host)] if SERVER_THREAD else []) + for name, dying, watching in sides: + face_each_other(host, guest) + dying('command', command='kill @s') + dying.wait(30) + dead = dead_players(watching, True) + watching.shot(out, f'respawn-{name}-dead') + dying.raw('respawn') + dying.wait(40) + back_to_game(dying) + # Back within tracking range of the other player, wherever the respawn point is. + x, y, z = pos_of(dying) + watching('command', command=f'tp @s {x + 3:.2f} {y:.2f} {z:.2f}') + watching.wait(40) + alive = dead_players(watching, False) + watching.shot(out, f'respawn-{name}-alive') + results[name] = {'dead': dead, 'after_respawn': alive} + assert dead, f'the {name} was not drawn dead: {results}' + assert not alive, f'the {name} still lies dead after respawning: {results}' + return results + + +def check_hurt(host, guest, out): + for g in (host, guest): + g('command', command='gamemode survival') + g('command', command='clear @s') + face_each_other(host, guest) + hx, hy, hz = pos_of(host) + # Between the two, within both players' reach; bare hands leave it alive. + host('command', command=f'summon minecraft:pig {hx + 1.5:.2f} {hy:.2f} {hz + 0.8:.2f} {{NoAI:1b}}') + host.wait(30) + + def pig(game): + return game.raw('entities', 6, 'pig')['entities'][0] + seen = {} + for name, attacker, watcher in (('guest hits', guest, host), ('host hits', host, guest)): + attacker.wait(30) # a full attack charge + attacker.raw('attack', pig(attacker)['id']) + seen[name] = {'attacker': pig(attacker)['hurt_time'], 'watcher': pig(watcher)['hurt_time']} + attacker.shot(out, 'hurt-' + name.replace(' ', '-')) + watcher.shot(out, 'hurt-' + name.replace(' ', '-') + '-seen') + attacker.wait(20) + host('command', command='kill @e[type=minecraft:pig]') + # LivingEntity.hurtTime: 10 when hurt, one less each tick; the reads come a few ticks later. + for name, sides in seen.items(): + assert all(t > 0 for t in sides.values()), f'{name}: the pig\'s hurt flash {seen}' + return seen + + def container_items(game): """The open container's stacks by slot (Horizon's container slots are 300 and up) and its size.""" slots = [s for s in game('screen').get('slots', []) if s.get('slot', 0) >= 300] @@ -584,12 +726,162 @@ def check_containers(host, guest, out): return {'ender': ender, 'double': double, 'taken': taken} +def check_machines(host, guest, out): + # After `recipes`: the stacks given here unlock recipes, which would move the book's first one. + guest('command', command='gamemode survival') + x, y, z = (int(v // 1) for v in pos_of(guest)) + at = (x, y, z + 2) + seen = {} + for block in ('hopper', 'dispenser', 'dropper'): + guest('command', command='clear @s') + guest('command', command='give @s minecraft:cobblestone 4') + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:{block}') + guest.wait(10) + guest.raw('interact', *at) + guest.raw('wait-for', 'screen', 'container', '--timeout', 10) + guest.wait(10) + size = container_items(guest)[1] + guest.shot(out, f'machines-{block}') + guest.raw('click-slot', hotbar_slot(guest, 'minecraft:cobblestone'), 'shift') + guest.wait(10) + guest.raw('key', 'esc', 'tap') + guest.wait(10) + # Opened again, the menu holds what the server has. + seen[block] = (size, open_container(guest, at, out, f'machines-{block}-after')[0]) + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air') + want = {'hopper': (5, {0: 'minecraft:cobblestone'}), 'dispenser': (9, {0: 'minecraft:cobblestone'}), + 'dropper': (9, {0: 'minecraft:cobblestone'})} + assert seen == want, f'the machines on the guest: {seen}' + return seen + + +def check_brewing(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + loads = ('blaze_powder', 'nether_wart', 'glass_bottle') + for item in loads: + guest('command', command=f'give @s minecraft:{item}') + x, y, z = (int(v // 1) for v in pos_of(guest)) + at = (x, y, z + 2) + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:brewing_stand') + guest.wait(10) + guest.raw('interact', *at) + guest.raw('wait-for', 'screen', 'container', '--timeout', 10) + guest.wait(10) + size = container_items(guest)[1] + # BrewingStandMenu.quickMoveStack: blaze powder to the fuel slot, an ingredient to its slot, + # a bottle to the bottle slots. + for item in loads: + guest.raw('click-slot', hotbar_slot(guest, f'minecraft:{item}'), 'shift') + guest.wait(5) + # BrewingStandBlockEntity.serverTick burns the blaze powder into 20 uses; the guest sees them + # through the menu's data slots. + guest.wait(10) + info = guest.raw('menu')['info'] + guest.shot(out, 'brewing') + guest.raw('key', 'esc', 'tap') + guest.wait(10) + items = open_container(guest, at, out, 'brewing-after')[0] + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air') + seen = {'size': size, 'items': items, 'fuel': info and info.get('fuel')} + want = {'size': 5, 'items': {0: 'minecraft:glass_bottle', 3: 'minecraft:nether_wart'}, 'fuel': 20} + assert seen == want, f'the brewing stand on the guest: {seen}' + return seen + + +def slot_point(game, slot): + """The GUI point in the middle of slot `slot` of the open screen (`ui`'s slot-N).""" + for w in game.raw('ui')['widgets']: + if w.get('id') == f'slot-{slot}': + x, y, width, height = w['bounds'] + return x + width / 2, y + height / 2 + raise Failed(f'no slot {slot} on the screen') + + +def mouse(game, *slots, right=False): + """Press over the first slot, move over the others and release: one click, or a drag.""" + points = [f'{v:.1f}' for s in slots for v in slot_point(game, s)] + game.raw('drag-at', *(['right'] if right else []), *points) + game.wait(4) + + +def hotbar_slot(game, item): + return next(s['slot'] for s in game('inventory')['hotbar'] if s and s.get('item') == item) + + +def check_clicks(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + guest('command', command='give @s minecraft:cobblestone 10') + guest('command', command='give @s minecraft:coal 3') + guest('command', command='give @s minecraft:raw_iron 2') + guest('command', command='give @s minecraft:oak_planks 2') + guest.wait(10) + x, y, z = (int(v // 1) for v in pos_of(guest)) + chest, furnace = (x, y, z + 2), (x, y, z - 2) + guest('command', command=f'setblock {chest[0]} {chest[1]} {chest[2]} minecraft:chest') + guest('command', command=f'setblock {furnace[0]} {furnace[1]} {furnace[2]} minecraft:furnace') + guest.wait(10) + # Pick the cobblestone up and put it down in the chest's first slot. + guest.raw('interact', *chest) + guest.raw('wait-for', 'screen', 'container', '--timeout', 10) + guest.wait(10) + mouse(guest, hotbar_slot(guest, 'minecraft:cobblestone')) + mouse(guest, 300) + guest.wait(10) + guest.shot(out, 'clicks-chest') + guest.raw('key', 'esc', 'tap') + guest.wait(10) + in_chest, _ = open_container(guest, chest, out, 'clicks-chest-after') + # Coal into the fuel slot, raw iron into the input. + guest.raw('interact', *furnace) + guest.raw('wait-for', 'screen', 'container', '--timeout', 10) + guest.wait(10) + mouse(guest, hotbar_slot(guest, 'minecraft:coal')) + mouse(guest, 301) + mouse(guest, hotbar_slot(guest, 'minecraft:raw_iron')) + mouse(guest, 300) + guest.wait(10) + guest.shot(out, 'clicks-furnace') + guest.raw('key', 'esc', 'tap') + guest.wait(10) + # Opening the furnace again resends the whole menu: the server's own view. + in_furnace, _ = open_container(guest, furnace, out, 'clicks-furnace-after') + # Two planks dragged over the 2x2 grid's left column: one each, four sticks. + guest.raw('key', 'e', 'tap') + guest.raw('wait-for', 'screen', 'inventory') + guest.wait(5) + mouse(guest, hotbar_slot(guest, 'minecraft:oak_planks')) + mouse(guest, 100, 102) + guest.wait(10) + grid = {s['slot']: (s.get('item'), s.get('count')) for s in guest('screen').get('slots', []) + if s.get('slot') in (100, 102, 200) and s.get('item')} + guest.shot(out, 'clicks-drag') + guest.raw('click-slot', 200, 'shift') + guest.wait(10) + guest.raw('key', 'esc', 'tap') + guest.wait(10) + # The chest's menu brings the whole inventory as the server has it. + open_container(guest, chest, out, 'clicks-inventory') + counts = guest('inventory')['counts'] + for at in (chest, furnace): + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air') + assert in_chest == {0: 'minecraft:cobblestone'}, f'the chest holds {in_chest} after the guest put cobblestone in' + assert in_furnace == {0: 'minecraft:raw_iron', 1: 'minecraft:coal'}, f'the furnace holds {in_furnace}' + assert grid.get(100) == ('minecraft:oak_planks', 1) and grid.get(102) == ('minecraft:oak_planks', 1), \ + f'the drag left the grid as {grid}' + assert counts.get('minecraft:stick') == 4 and 'minecraft:cobblestone' not in counts, f'inventory after: {counts}' + return {'chest': in_chest, 'furnace': in_furnace, 'grid': grid, 'inventory': counts} + + def check_feedback(host, guest, out): x, y, z = (round(v, 1) for v in pos_of(guest)) guest('command', command='item replace entity @s weapon.mainhand with minecraft:stick') guest('command', command=f'tp @s {x:.1f} {y:.1f} {z:.1f}') guest.wait(10) chat = guest.raw('messages', 5)['chat'] + # The host is an operator: broadcastToAdmins tells it, as `[Guest: ...]`. + host_chat = host.raw('messages', 5)['chat'] guest.raw('key', 't', 'tap') guest.wait(5) guest.shot(out, 'feedback') @@ -600,7 +892,9 @@ def check_feedback(host, guest, out): assert any(replaced in line for line in chat), f'no "{replaced}" in {chat}' assert any(line.startswith(f'Teleported {GUEST_NAME} to {x:.6f}') for line in chat), f'teleport feedback: {chat}' assert screen in (None, 'playing'), f'the chat did not close: {screen}' - return chat + told = f'[{GUEST_NAME}: Teleported {GUEST_NAME} to {x:.6f}' + assert any(line.startswith(told) for line in host_chat), f'no "{told}" for the host: {host_chat}' + return chat + host_chat def chat_input(game): @@ -634,11 +928,29 @@ def check_commands(host, guest, out): screen = guest('state').get('screen') guest('command', command='gamemode survival') guest.wait(10) + # A node the tree marks ask_server (a bossbar id): the guest asks the + # server, which completes it from its own bossbars. + host('command', command='bossbar add pt6:check "Check"') + host.wait(5) + guest.raw('key', 'slash', 'tap') + guest.wait(3) + guest.raw('type', 'bossbar get pt') + guest.wait(10) + guest.raw('key', 'tab', 'tap') + guest.wait(2) + asked = chat_input(guest) + for _ in range(3): + if guest('screen').get('screen') != 'chat': + break + guest.raw('key', 'esc', 'tap') + guest.wait(3) + host('command', command='bossbar remove pt6:check') assert literal == '/gamemode', f'Tab after /gamem: {literal!r}' assert argument == '/gamemode creative', f'Tab after /gamemode cr: {argument!r}' assert mode == 'creative', f'the completed command did not run: {mode}' assert screen in (None, 'playing'), f'the chat did not close: {screen}' - return {'literal': literal, 'argument': argument, 'mode': mode} + assert asked == '/bossbar get pt6:check', f'Tab after /bossbar get pt: {asked!r}' + return {'literal': literal, 'argument': argument, 'mode': mode, 'ask_server': asked} def centre(rect): @@ -677,6 +989,33 @@ def check_recipes(host, guest, out): return {'known': known, 'grid': grid} +def check_titles(host, guest, out): + # TitleCommand sends the guest its title packets; its HUD shows and clears them. + for command in ('title @s times 10 400 10', 'title @s subtitle "Under"', 'title @s title "Over"', + 'title @s actionbar "Bar"'): + guest('command', command=command) + guest.wait(5) + shown = {k: guest.raw('messages', 1)[k] for k in ('title', 'subtitle', 'actionbar')} + guest.shot(out, 'titles') + guest('command', command='title @s clear') + guest.wait(5) + cleared = {k: guest.raw('messages', 1)[k] for k in ('title', 'subtitle')} + assert shown == {'title': 'Over', 'subtitle': 'Under', 'actionbar': 'Bar'}, f'titles shown: {shown}' + assert cleared == {'title': None, 'subtitle': None}, f'titles cleared: {cleared}' + return {'shown': shown, 'cleared': cleared} + + +def check_chat(host, guest, out): + # The agent's event log follows a remote client's chat: `wait-for chat` sees the line another + # player sends (and on the server thread the host window's own line, back from the server). + line = f'chat check {int(time.time())}' + host.raw('chat', line) + seen = {g.name: g.raw('wait-for', 'chat', line, '--timeout', 10, '--since', 0).get('ok') + for g in ((guest, host) if SERVER_THREAD else (guest,))} + guest.shot(out, 'chat') + return seen + + def png_rows(path): """The rows of an 8-bit RGB or RGBA PNG, unfiltered, as bytes of 4 (or 3) per pixel.""" data = Path(path).read_bytes() @@ -721,7 +1060,7 @@ def changed_pixels(a, b): def sneaking_on_host(host, want, ticks=40): """Whether the host sees the guest crouching, once it matches `want` or after `ticks`.""" for _ in range(ticks // 5): - sneaking = host.raw('lan', 'status')['guests'][0]['sneaking'] + sneaking = lan_guest(host)['sneaking'] if sneaking == want: return sneaking host.wait(5) @@ -782,6 +1121,27 @@ def wait_state(game, pos, key, want, ticks): return state_of(game, pos, key) +def check_plates(host, guest, out): + guest('command', command='gamemode survival') + x, y, z = (int(v // 1) for v in pos_of(guest)) + plate = (x + 2, y, z) + guest('command', command=f'setblock {plate[0]} {plate[1]} {plate[2]} minecraft:stone_pressure_plate') + guest.wait(10) + guest('command', command=f'tp @s {plate[0] + 0.5} {plate[1]} {plate[2] + 0.5}') + pressed = {'host': wait_state(host, plate, 'powered', 'true', 40), + 'guest': wait_state(guest, plate, 'powered', 'true', 40)} + guest.shot(out, 'plate-pressed') + guest('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + # PressurePlateBlock.getPressedTime: a stone plate checks again every 20 ticks. + released = {'host': wait_state(host, plate, 'powered', 'false', 60), + 'guest': wait_state(guest, plate, 'powered', 'false', 60)} + guest('command', command=f'setblock {plate[0]} {plate[1]} {plate[2]} minecraft:air') + detail = {'pressed': pressed, 'released': released} + assert pressed == {'host': 'true', 'guest': 'true'}, f'the plate under the guest: {detail}' + assert released == {'host': 'false', 'guest': 'false'}, f'the plate after the guest left: {detail}' + return detail + + def check_trials(host, guest, out): # The host watches as a spectator, whom neither block detects: only the guest can wake them. hx, hy, hz = pos_of(host) @@ -824,13 +1184,458 @@ def check_trials(host, guest, out): return {'spawner': trial, 'vault': active, 'rewarded': uuid(rewarded), 'host': uuid(host_uuid)} +def bed_at(game, foot): + """A bed whose foot is at `foot`, its head one block east.""" + x, y, z = foot + game('command', command=f'setblock {x} {y} {z} minecraft:red_bed[facing=east,part=foot]') + game('command', command=f'setblock {x + 1} {y} {z} minecraft:red_bed[facing=east,part=head]') + return [x + 1, y, z] + + +def check_sleep(host, guest, out): + for g in (host, guest): + g('command', command='gamemode survival') + host('command', command='time set midnight') + gx, gy, gz = (int(v // 1) for v in pos_of(guest)) + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + guest_bed = bed_at(guest, (gx, gy, gz + 2)) + host_bed = bed_at(host, (hx, hy, hz + 2)) + guest.wait(10) + guest.raw('interact', *guest_bed) + guest.wait(10) + asleep = {'guest': guest('state').get('sleeping'), 'host': host('state').get('sleeping'), + 'server': lan_guest(host).get('sleeping')} + guest.shot(out, 'sleep-guest') + # Alone in bed: still night 120 ticks later (everyone must sleep). + guest.wait(120) + night = host('state')['time']['time_of_day'] + # Escape gets the guest up (InBedChatScreen), then back to bed. + guest.raw('key', 'esc', 'tap') + guest.wait(10) + up = guest('state').get('sleeping') + guest.raw('interact', *guest_bed) + host.raw('interact', *host_bed) + host.wait(130) + after = {'guest': guest('state').get('sleeping'), 'host': host('state').get('sleeping'), + 'time': host('state')['time']['time_of_day']} + guest.shot(out, 'sleep-morning') + for at in (guest_bed, host_bed): + guest('command', command=f'fill {at[0] - 1} {at[1]} {at[2]} {at[0]} {at[1]} {at[2]} minecraft:air') + host('command', command='time set day') + detail = {'asleep': asleep, 'night': night, 'up': up, 'after': after} + assert asleep['guest'] == guest_bed and asleep['server'] == guest_bed, f'the guest is not in its bed: {detail}' + assert asleep['host'] is None, f'the guest\'s bed put the host to sleep: {detail}' + assert 13000 < night < 23000, f'one of two players asleep ended the night: {detail}' + assert up is None, f'Escape did not get the guest up: {detail}' + assert after['guest'] is None and after['host'] is None and after['time'] < 1000, f'no morning: {detail}' + return detail +def check_push(host, guest, out): + guest('command', command='gamemode survival') + x, y, z = (int(v // 1) + 0.5 for v in pos_of(guest)) + guest('command', command=f'tp @s {x} {y - 0.5} {z}') + guest.wait(20) + x, y, z = pos_of(guest) + # A cow that doesn't walk, 0.3 east of the guest: the two boxes overlap until their centres are + # 0.75 apart, so the push stops a fraction of a block away. + guest('command', command=f'summon minecraft:cow {x + 0.3:.2f} {y:.2f} {z:.2f} {{NoAI:1b}}') + guest.wait(60) + nx, _, nz = pos_of(guest) + guest.shot(out, 'push') + guest('command', command='kill @e[type=minecraft:cow]') + moved = ((nx - x) ** 2 + (nz - z) ** 2) ** 0.5 + detail = {'from': [round(x, 3), round(z, 3)], 'to': [round(nx, 3), round(nz, 3)], 'moved': round(moved, 3)} + assert nx < x, f'the cow did not push the guest west: {detail}' + assert moved < 1.5, f'the cow pushed the guest too far: {detail}' + return detail +def check_eat(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + # Hungry: the eating needs food below 20 (Player.canEat). + guest('command', command='effect give @s minecraft:hunger 3 255') + guest.wait(70) + guest('command', command='effect clear @s') + guest('command', command='give @s minecraft:bread 3') + guest.wait(5) + guest.raw('select', 'minecraft:bread') + hungry = guest('state')['player']['food'] + # use-item --hold returns once released: watch the guest's screen meanwhile. + hold = threading.Thread(target=guest.raw, args=('use-item', '--hold', 2.2)) + hold.start() + using = [] + for _ in range(4): + time.sleep(0.2) + using.append(guest('state').get('using')) + guest.shot(out, 'eat') + hold.join() + guest.wait(10) + fed = guest('state')['player']['food'] + left = guest('inventory')['counts'].get('minecraft:bread', 0) + detail = {'hungry': hungry, 'fed': fed, 'bread': left, 'using': using, 'after': guest('state').get('using')} + assert hungry < 20, f'the guest is not hungry: {detail}' + ticks = [u['ticks'] for u in using if u] + assert len(ticks) >= 3 and ticks == sorted(ticks) and ticks[-1] > ticks[0], f'no eating on the guest\'s screen: {detail}' + assert left == 2 and fed > hungry, f'the server did not eat one loaf: {detail}' + assert detail['after'] is None, f'still eating after the release: {detail}' + return detail + + +def watch_mining(miner, pos, seen): + """Mine the block at `pos` (by hand, for seconds) and sample `seen()` meanwhile.""" + dig = threading.Thread(target=miner.raw, args=('break', *pos)) + dig.start() + samples = [] + for _ in range(8): + time.sleep(0.25) + samples.append(seen()) + dig.join() + return samples + + +def check_swings(host, guest, out): + for g in (host, guest): + g('command', command='gamemode survival') + g('command', command='clear @s') + face_each_other(host, guest) + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + gx, gy, gz = (int(v // 1) for v in pos_of(guest)) + # Stone by hand takes 7.5 seconds: ServerboundPunchPacket every tick keeps the arm swinging. + guest('command', command=f'setblock {gx} {gy} {gz + 1} minecraft:stone') + host('command', command=f'setblock {hx} {hy} {hz + 1} minecraft:stone') + host.wait(10) + def swinging(game): + # On its server thread the host's window is a client of its server too. + if game is host and not SERVER_THREAD: + return lan_guest(host).get('model_swinging') + return any(e.get('swinging') for e in remote(game).get('player_equipment', [])) + # Most samples: a swing restarts only past its first half (SwingState.startIfAble), so a sample can + # fall between two. + host_sees = watch_mining(guest, (gx, gy, gz + 1), lambda: swinging(host)) + guest_sees = watch_mining(host, (hx, hy, hz + 1), lambda: swinging(guest)) + # A hoe on dirt: the server tills it and swings the guest's hand, on the guest's screen too. + # Where the guest stands now (an earlier check can leave it on a ledge it then drops from). + gx, gy, gz = (int(v // 1) for v in pos_of(guest)) + soil = (gx, gy - 1, gz + 1) + guest('command', command=f'setblock {soil[0]} {soil[1]} {soil[2]} minecraft:dirt') + # HoeItem.useOn tills only under air. + guest('command', command=f'setblock {soil[0]} {soil[1] + 1} {soil[2]} minecraft:air') + guest('command', command='give @s minecraft:wooden_hoe') + guest.wait(10) + guest.raw('select', 'minecraft:wooden_hoe') + before = guest('state')['swings'] + guest.raw('interact', *soil) + guest.wait(10) + hoe = {'swings': guest('state')['swings'] - before, 'soil': host.raw('block', *soil)['block']} + guest('command', command=f'setblock {soil[0]} {soil[1]} {soil[2]} minecraft:stone') + detail = {'host_sees_guest': host_sees, 'guest_sees_host': guest_sees, 'hoe': hoe} + assert sum(map(bool, host_sees)) >= 4, f'the host does not see the guest mine: {detail}' + assert sum(map(bool, guest_sees)) >= 4, f'the guest does not see the host mine: {detail}' + assert hoe == {'swings': 1, 'soil': 'minecraft:farmland'}, f'the guest\'s hoe: {detail}' + return detail + + +def check_eating(host, guest, out): + for g in (host, guest): + g('command', command='gamemode survival') + g('command', command='clear @s') + # Hungry: Player.canEat. + g('command', command='effect give @s minecraft:hunger 3 255') + host.wait(70) + for g in (host, guest): + g('command', command='effect clear @s') + g('command', command='give @s minecraft:bread 2') + host.wait(5) + face_each_other(host, guest) + + def using(game): + # On its server thread the host's window is a client of its server too. + if game is host and not SERVER_THREAD: + return lan_guest(host).get('model_using') or 0 + return max((e.get('using') or 0 for e in remote(game).get('player_equipment', [])), default=0) + seen = {} + for name, eater, watcher in (('host eats', host, guest), ('guest eats', guest, host)): + eater.raw('select', 'minecraft:bread') + hold = threading.Thread(target=eater.raw, args=('use-item', '--hold', 2.2)) + hold.start() + samples = [] + for _ in range(4): + time.sleep(0.3) + samples.append(using(watcher)) + watcher.shot(out, 'eating-' + name.replace(' ', '-')) + hold.join() + eater.wait(10) + seen[name] = {'during': samples, 'after': using(watcher)} + for name, s in seen.items(): + assert sum(1 for u in s['during'] if u > 0) >= 3 and s['after'] == 0, f'{name}: {seen}' + return seen + + +def check_xp(host, guest, out): + for g in (host, guest): + g('command', command='gamemode survival') + g('command', command='xp set @s 0 levels') + g('command', command='xp set @s 0 points') + # Out of the orbs' way wherever an earlier check left the host (ExperienceOrb follows the + # nearest player who isn't a spectator). + host('command', command='gamemode spectator') + guest.wait(10) + # `xp set` leaves Player.totalExperience (the score): experience from earlier checks stays in it. + total = guest('state')['player']['xp']['total'] + host_total = host('state')['player']['xp']['total'] + x, y, z = pos_of(guest) + # Three orbs of 7 points 4 blocks east of the guest (out of reach, within the 8 blocks orbs + # follow from): they fly to the guest. + for _ in range(3): + guest('command', command=f'summon minecraft:experience_orb {x + 4:.2f} {y + 0.5:.2f} {z:.2f} {{Value:7s}}') + guest.wait(2) + seen = remote(guest).get('entities', {}).get('minecraft:experience_orb', 0) + guest.shot(out, 'xp-orbs') + guest.wait(60) + xp = guest('state')['player']['xp'] + host_xp = host('state')['player']['xp'] + left = remote(guest).get('entities', {}).get('minecraft:experience_orb', 0) + detail = {'seen': seen, 'guest': xp, 'host': host_xp, 'left': left} + # ExperienceOrb.scanForMerges: orbs of one value side by side can merge into one. + assert 1 <= seen <= 3, f'the guest saw {seen} orbs: {detail}' + assert xp['total'] - total == 21 and xp['level'] == 2, f'the guest\'s experience after three 7-point orbs: {detail}' + assert host_xp['total'] == host_total, f'the host took the orbs: {detail}' + assert left == 0, f'orbs left on the guest\'s screen: {detail}' + return {'seen': seen, 'guest': xp, 'host': host_xp} + + +def check_time(host, guest, out): + def times(): + return host('state')['time']['day_time'], guest('state')['time']['day_time'] + host('command', command='time set 1000') + host('command', command='time pause') + host.wait(60) + paused = times() + host('command', command='time resume') + guest.wait(20) + # A stalled game runs at most 10 missed ticks when it wakes (DeltaTracker); the server's + # game time, sent every second, moves the guest's clock on (ClientClockManager.tick). + os.kill(guest.pid, signal.SIGSTOP) + time.sleep(4) + os.kill(guest.pid, signal.SIGCONT) + guest.wait(60) + stalled = times() + detail = {'paused': paused, 'after_stall': stalled} + assert paused[0] == paused[1] and 1000 <= paused[0] < 1010, f'the clock while paused: {detail}' + # The two reads are a tick or two apart. + assert abs(stalled[0] - stalled[1]) <= 3, f'the guest\'s clock after its game stalled: {detail}' + return detail + + +def objects_near(game, centre, key='objects'): + """`status`'s objects within 8 blocks of centre, without their ids (each side numbers its own).""" + out = [] + for o in game('status')[key]: + if all(abs(o['position'][i] - centre[i]) <= 8 for i in (0, 2)): + o = dict(o) + o.pop('id') + o['position'] = [round(v, 2) for v in o['position']] + if 'yaw' in o: # as the packets carry it, in 256ths of a turn + o['yaw'] = round(o['yaw'] * 256 / 360) % 256 + out.append(o) + return sorted(out, key=json.dumps) + + +def check_objects(host, guest, out): + x, y, z = (int(v // 1) for v in pos_of(host)) + commands = [ + f'fill {x - 6} {y} {z - 6} {x + 6} {y + 3} {z - 6} minecraft:stone', + f'summon minecraft:minecart {x - 4.5} {y} {z + 3.5}', + f'summon minecraft:chest_minecart {x - 2.5} {y} {z + 3.5}', + f'summon minecraft:furnace_minecart {x + 1.5} {y} {z + 3.5}', + f'summon minecraft:tnt_minecart {x + 4.5} {y} {z + 3.5}', + f'summon minecraft:oak_boat {x - 4.5} {y} {z + 6.5} {{Rotation:[45f,0f]}}', + f'summon minecraft:birch_chest_boat {x - 1.5} {y} {z + 6.5}', + f'summon minecraft:bamboo_raft {x + 2.5} {y} {z + 6.5}', + f'summon minecraft:armor_stand {x - 2.5} {y} {z - 2.5} {{Rotation:[90f,0f]}}', + f'summon minecraft:armor_stand {x - 4.5} {y} {z - 2.5} {{ShowArms:1b,Small:1b,NoBasePlate:1b,' + 'equipment:{head:{id:"minecraft:diamond_helmet",count:1}}}', + f'summon minecraft:item_frame {x - 3.5} {y + 1} {z - 4.97} {{block_pos:[I;{x - 4},{y + 1},{z - 5}],Facing:3b,' + 'Item:{id:"minecraft:diamond",count:1},ItemRotation:3b}', + f'summon minecraft:glow_item_frame {x - 1.5} {y + 1} {z - 4.97} {{block_pos:[I;{x - 2},{y + 1},{z - 5}],Facing:3b}}', + f'summon minecraft:painting {x + 1.5} {y + 1} {z - 4.97} {{block_pos:[I;{x + 1},{y + 1},{z - 5}],facing:0b,' + 'variant:"minecraft:kebab"}', + f'summon minecraft:painting {x + 4} {y + 1} {z - 4.97} {{block_pos:[I;{x + 4},{y + 1},{z - 5}],facing:0b,' + 'variant:"minecraft:courbet"}', + ] + try: + for command in commands: + host('command', command=command) + host.wait(60) + guest.raw('look-at', x, y, z - 5) + guest.wait(10) + guest.shot(out, 'objects') + host.shot(out, 'objects') + mine, theirs = objects_near(host, (x, y, z)), objects_near(guest, (x, y, z)) + finally: + host('command', command=f'kill @e[type=!minecraft:player,x={x - 8},y={y - 2},z={z - 8},dx=16,dy=8,dz=16]') + host('command', command=f'fill {x - 6} {y} {z - 6} {x + 6} {y + 3} {z - 6} minecraft:air') + assert len(mine) == len(commands) - 1, f'the host has {len(mine)} objects: {mine}' + assert theirs == mine, f'the guest sees {theirs}\nthe host has {mine}' + return f'{len(theirs)} objects identical' + + +def check_projectiles(host, guest, out): + x, y, z = (int(v // 1) for v in pos_of(host)) + commands = [ + f'summon minecraft:tnt {x + 4.5} {y} {z + 4.5} {{fuse:2000s}}', + f'summon minecraft:end_crystal {x - 4.5} {y} {z + 4.5} {{ShowBottom:0b}}', + f'summon minecraft:tnt {x + 2.5} {y + 5} {z - 3.5} {{fuse:2000s}}', + f'summon minecraft:arrow {x - 2.5} {y + 4} {z - 2.5} {{Motion:[0.2d,0d,0d]}}', + f'summon minecraft:falling_block {x - 0.5} {y + 6} {z - 4.5} {{BlockState:{{Name:"minecraft:sand"}}}}', + ] + try: + for command in commands: + host('command', command=command) + host.wait(80) + guest.raw('look-at', x, y, z) + guest.wait(5) + guest.shot(out, 'projectiles') + mine = objects_near(host, (x, y, z), 'projectiles') + theirs = objects_near(guest, (x, y, z), 'projectiles') + finally: + host('command', command=f'kill @e[type=!minecraft:player,x={x - 8},y={y - 2},z={z - 8},dx=16,dy=10,dz=16]') + host('command', command=f'setblock {x - 1} {y} {z - 5} minecraft:air') + assert len(mine) == len(commands) - 1, f'the host has {len(mine)}: {mine}' + # The fuse counts down every tick: the guest's, read a moment later, may be a tick or two behind. + fuses = [(m.pop('fuse', 0), t.pop('fuse', 0)) for m, t in zip(mine, theirs)] + assert theirs == mine, f'the guest sees {theirs}\nthe host has {mine}' + assert all(abs(a - b) <= 2 for a, b in fuses), f'fuses (host, guest): {fuses}' + return f'{len(theirs)} identical, fuses (host, guest) {fuses}' + + +def light_differences(host, guest, lo, hi): + """Positions of the box loaded on both sides, and those whose sky or block light differ.""" + h, g = host.raw('light', *lo, *hi), guest.raw('light', *lo, *hi) + both = [i for i in range(len(h['sky'])) if h['sky'][i] != '.' and g['sky'][i] != '.'] + differ = [i for i in both if (h['sky'][i], h['block'][i]) != (g['sky'][i], g['block'][i])] + return h, g, both, differ + + +def same_light(host, guest, lo, hi, what, ticks=100): + """Wait until the guest's light over the box is the host's; the number of positions compared.""" + for _ in range(ticks // 10): + h, g, both, differ = light_differences(host, guest, lo, hi) + if not differ: + assert both, f'{what}: no position of the box is loaded on both sides' + return len(both) + host.wait(10) + i = differ[0] + nx, nz = hi[0] - lo[0] + 1, hi[2] - lo[2] + 1 + pos = (lo[0] + i % nx, lo[1] + i // (nx * nz), lo[2] + i // nx % nz) + raise AssertionError(f'{what}: {len(differ)} of {len(both)} positions differ, first {pos}: host sky ' + f'{h["sky"][i]} block {h["block"][i]}, guest sky {g["sky"][i]} block {g["block"][i]}') + + +def check_growth(host, guest, out): + """Block ticks near a guest 1000 blocks from the host: only the guest's tickets tick them.""" + x0, y0, z0 = pos_of(guest) + guest('command', command='gamemode creative') + guest('command', command=f'tp @s {x0 + 1000:.2f} 200 {z0:.2f}') + guest.wait(100) + x, y, z = (int(v // 1) for v in pos_of(guest)) + # A platform in the air over wherever the guest landed: a water source two blocks east of the + # guest, wheat on farmland two blocks west. Vanilla's water spreads only towards the nearest + # drop (FlowingFluid.getSpread), so any of the source's four neighbours may take it. Wheat + # grows only in daylight (raw brightness 9 or more). + top = max(y + 12, 120) + water = (x + 2, top + 1, z) + beside = [(water[0] + dx, water[1], water[2] + dz) for dx, dz in ((1, 0), (-1, 0), (0, 1), (0, -1))] + wheat = (x - 2, top + 1, z) + flowed = [] + try: + host('command', command='time set noon') + guest('command', command=f'fill {x - 4} {top} {z - 2} {x + 4} {top} {z + 2} minecraft:stone') + guest('command', command=f'setblock {wheat[0]} {top} {wheat[2]} minecraft:farmland[moisture=7]') + guest('command', command=f'setblock {wheat[0]} {wheat[1]} {wheat[2]} minecraft:wheat[age=0]') + guest('command', command='gamerule random_tick_speed 1000') + guest('command', command=f'setblock {water[0]} {water[1]} {water[2]} minecraft:water') + for _ in range(40): + guest.wait(10) + flowed = [p for p in beside if guest.raw('block', *p).get('block') == 'minecraft:water'] + if flowed: + break + age = wait_state(guest, wheat, 'age', '7', 2400) + guest.shot(out, 'growth') + finally: + guest('command', command='gamerule random_tick_speed 3') + host('command', command='time set day') + guest('command', command=f'tp @s {x0:.2f} {y0:.2f} {z0:.2f}') + guest('command', command='gamemode survival') + guest.wait(40) + detail = {'flowed': flowed, 'wheat age': age} + assert flowed, f'the water beside the guest did not flow: {detail}' + assert age == '7', f'the wheat beside the guest did not grow: {detail}' + return detail + + +def check_light(host, guest, out): + gx, gy, gz = (int(v // 1) for v in pos_of(guest)) + results = {} + # A torch near the guest: the guest lights it itself, as vanilla's client does. + torch = (gx + 3, gy, gz + 3) + host('command', command=f'setblock {torch[0]} {torch[1]} {torch[2]} minecraft:torch') + try: + results['torch'] = same_light(host, guest, (gx - 12, gy - 1, gz - 12), (gx + 16, gy + 3, gz + 16), 'torch') + finally: + host('command', command=f'setblock {torch[0]} {torch[1]} {torch[2]} minecraft:air') + # A roof over the guest, then a hole in it: sky light falls through. + roof = f'{gx - 3} {gy + 4} {gz - 3} {gx + 3} {gy + 4} {gz + 3}' + box = (gx - 6, gy - 1, gz - 6), (gx + 6, gy + 5, gz + 6) + host('command', command=f'fill {roof} minecraft:stone') + try: + results['roof'] = same_light(host, guest, *box, 'roof') + host('command', command=f'setblock {gx} {gy + 4} {gz} minecraft:air') + results['hole'] = same_light(host, guest, *box, 'hole in the roof') + finally: + host('command', command=f'fill {roof} minecraft:air') + # The last chunk the guest tracks eastwards, and glowstone high up just past it in a chunk it + # doesn't track: the guest never sees that block, only the light updates of its border chunk. + y = 200 + row = guest.raw('light', gx, y, gz, gx + 16 * 24, y, gz)['sky'] + assert '.' in row, 'the guest has every chunk 24 chunks east' + untracked = (gx + row.index('.')) >> 4 + near = untracked * 16 + 1 + # On its server thread the host's own game is a client too, sent the same light updates. + if not SERVER_THREAD: + assert host.raw('light', near, y, gz, near, y, gz)['sky'] != '.', 'the host lacks the chunk past the guest' + host('command', command=f'setblock {near} {y} {gz} minecraft:glowstone') + try: + lo, hi = (untracked * 16 - 16, y - 3, gz - 8), (untracked * 16 - 1, y + 3, gz + 8) + # On the server thread the host's game is a client too, as dark as the guest until the light + # update arrives: wait for it before comparing them. + for _ in range(10): + lit = guest.raw('light', near - 2, y, gz, near - 2, y, gz)['block'] + if lit == 'd': + break + host.wait(10) + assert lit == 'd', f'the border chunk by the glowstone has block light {lit}, not 13, after 100 ticks' + results['border'] = same_light(host, guest, lo, hi, 'border chunk') + finally: + host('command', command=f'setblock {near} {y} {gz} minecraft:air') + results['border_cleared'] = same_light(host, guest, lo, hi, 'border chunk without the glowstone') + return results + + CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags, 'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, - 'containers': check_containers, 'feedback': check_feedback, 'commands': check_commands, - 'recipes': check_recipes, - 'trials': check_trials, - 'walls': check_walls, 'effects': check_effects, 'portals': check_portals} + 'respawn': check_respawn, + 'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles, 'chat': check_chat, + 'machines': check_machines, + 'brewing': check_brewing, + 'hurt': check_hurt, + 'commands': check_commands, + 'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls, + 'effects': check_effects, 'portals': check_portals, 'distance': check_distance, 'clicks': check_clicks, + 'sleep': check_sleep, 'push': check_push, 'eat': check_eat, 'eating': check_eating, + 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, + 'light': check_light, 'plates': check_plates, + 'swings': check_swings, + 'time': check_time, 'growth': check_growth} def run(ctl, out, resources, checks): @@ -853,7 +1658,7 @@ def run(ctl, out, resources, checks): host('command', command='gamerule spawn_mobs false') port = host.raw('lan', 'open', 0, 'commands')['port'] host.player = host.raw('lan', 'status').get('host', 'Player') # the host's profile name - guest('launch', wait=False, offscreen=sys.platform == 'darwin') + guest.pid = guest('launch', wait=False, offscreen=sys.platform == 'darwin')['pid'] guest.raw('connect', f'127.0.0.1:{port}', GUEST_NAME) guest.raw('wait-for', 'loaded', '--timeout', 300) guest.wait(40) diff --git a/tools/parity.py b/tools/parity.py index 5809f913e..6ba4c0d90 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -36,8 +36,9 @@ import argparse import hashlib import json import os -from pathlib import Path +from pathlib import Path, PurePosixPath import re +import socket import subprocess import sys import time @@ -61,14 +62,14 @@ SHIM = STATE_DIR / "shim" # so a harness whose inputs match one that passed elsewhere doesn't run again. SHARED = Path(os.environ.get("PARITY_SHARED") or (LOCAL / "minecraft").resolve().parent / "parity-shared") MACHINE_JOBS = int(os.environ.get("PARITY_MACHINE_JOBS") or max(1, (os.cpu_count() or 4) // 2)) -HOST = os.uname().nodename.split(".")[0] +HOST = socket.gethostname().split(".")[0] DEFAULT_MEMORY = 3 << 30 # assumed peak for a harness that never ran here def harness_settings(path): """PARITY_SHARDS and PARITY_RUST_SCOPE, read from a harness's source without running it.""" import ast - text = Path(path).read_text() + text = Path(path).read_text(encoding="utf-8") settings = {} if "PARITY_" in text: for node in ast.parse(text).body: @@ -102,7 +103,7 @@ def base_name(name): def load_state(): - return json.loads(STATE.read_text()) if STATE.exists() else {"harnesses": {}, "hashes": {}} + return json.loads(STATE.read_text(encoding="utf-8")) if STATE.exists() else {"harnesses": {}, "hashes": {}} def save_state(state): @@ -129,7 +130,7 @@ class Hasher: if cached and cached[0] == stamp: return cached[1] if keep: - digest = hashlib.sha256(crate_root_without_modules(Path(real).read_text(), set(keep.split(","))).encode()).hexdigest() + digest = hashlib.sha256(crate_root_without_modules(Path(real).read_text(encoding="utf-8"), set(keep.split(","))).encode()).hexdigest() else: with open(real, "rb") as stream: digest = hashlib.file_digest(stream, "sha256").hexdigest() @@ -168,7 +169,7 @@ def environment_key(hasher): return (result.stdout + result.stderr).strip() except FileNotFoundError: return "missing" - lock = json.loads((ROOT / "research-lock.json").read_text()) + lock = json.loads((ROOT / "research-lock.json").read_text(encoding="utf-8")) version_dir = LOCAL / "minecraft" / lock["minecraft"]["version"] parts = [version(["rustc", "-V"]), version(["java", "-version"]), version(["javac", "-version"]), json.dumps(PROFILE, sort_keys=True), hasher(ROOT / "research-lock.json"), hasher(ROOT / "Cargo.lock"), @@ -197,7 +198,7 @@ def dep_info(binary): if not info.exists(): return [] sources = [] - for line in info.read_text().splitlines(): + for line in info.read_text(encoding="utf-8").splitlines(): _, separator, rest = line.partition(": ") if separator: sources += [part.replace("\\ ", " ") for part in re.split(r"(?<!\\) ", rest.strip()) if part] @@ -371,17 +372,17 @@ def narrow_rust_sources(sources, scope): for candidate in (crate_dir / "src" / Path(*parts[:count - 1]) / f"{parts[count - 1]}.rs", crate_dir / "src" / Path(*parts[:count]) / "mod.rs"): if candidate.is_file(): - return str(candidate.relative_to(ROOT)), count + return candidate.relative_to(ROOT).as_posix(), count return None, 0 def module_path(path): - parts = list(Path(*Path(path).parts[3:]).with_suffix("").parts) # crates/<crate>/src/... + parts = list(PurePosixPath(path).parts[3:-1] + (PurePosixPath(path).with_suffix("").name,)) return parts[:-1] if parts[-1] in ("mod", "lib") else parts defined_types, used_macros, kept_modules = set(), set(), {} for path in inner + entry: - text = rust_code((ROOT / path).read_text(errors="replace")) - crate_name = Path(path).parts[1].replace("-", "_") + text = rust_code((ROOT / path).read_text(encoding="utf-8", errors="replace")) + crate_name = PurePosixPath(path).parts[1].replace("-", "_") nesting = inline_modules(text) if re.search(r"\binclude!\s*\(", text): return sources, f"{path} includes source" @@ -401,7 +402,7 @@ def narrow_rust_sources(sources, scope): if head in crates: # a workspace crate base, crate_name = [], head elif head.startswith(("crate", "self", "super")) and path in inner: - own, crate_name = module_path(path) + nesting(match.start()), Path(path).parts[1].replace("-", "_") + own, crate_name = module_path(path) + nesting(match.start()), PurePosixPath(path).parts[1].replace("-", "_") ups = head.count("super") if head != "crate" and ups <= len(nesting(match.start())): continue # within this file @@ -415,14 +416,14 @@ def narrow_rust_sources(sources, scope): item = (base + parts)[0] defined_in_root = root.is_file() and re.search( rf"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:const|static|fn|struct|enum|type|trait|union)\s+{item}\b", - root.read_text(), re.MULTILINE) + root.read_text(encoding="utf-8"), re.MULTILINE) if not defined_in_root: return sources, f"{path} names {head}::{rest}, which the crate root doesn't define itself" continue if not scoped(target): return sources, f"{path} names {head}::{rest} ({target})" for path in outside: - text = rust_code((ROOT / path).read_text(errors="replace")) + text = rust_code((ROOT / path).read_text(encoding="utf-8", errors="replace")) defined = set(RUST_MACRO_DEFINITION.findall(text)) & used_macros if defined: return sources, f"the scope uses macro {sorted(defined)[0]}! defined in {path}" @@ -433,7 +434,7 @@ def narrow_rust_sources(sources, scope): kept = [path for path in sources if path not in outside and not path.endswith("/src/lib.rs")] for path in sources: if path.endswith("/src/lib.rs"): - modules = kept_modules.get(Path(path).parts[1].replace("-", "_")) or {"-"} # "-": no module of it is reachable + modules = kept_modules.get(PurePosixPath(path).parts[1].replace("-", "_")) or {"-"} # "-": no module of it is reachable kept.append(f"{path}{KEEP}{','.join(sorted(modules))}") return sorted(kept), None @@ -549,7 +550,7 @@ def clear_large_outputs(name, trace): everything else large under the harness's .local directories is rebuilt on its next run.""" local = LOCAL.resolve() - keep = {os.path.realpath(line) for line in outputs_listing(name).read_text().splitlines() if line} + keep = {os.path.realpath(line) for line in outputs_listing(name).read_text(encoding="utf-8").splitlines() if line} directories = set() for command in trace["commands"]: for argument in command[1:]: @@ -600,7 +601,7 @@ def memory_available(): """Bytes the system can give harnesses now: MemAvailable on Linux, free and reclaimable pages on macOS.""" meminfo = Path("/proc/meminfo") if meminfo.exists(): - for line in meminfo.read_text().splitlines(): + for line in meminfo.read_text(encoding="utf-8").splitlines(): if line.startswith("MemAvailable:"): return int(line.split()[1]) * 1024 try: @@ -634,7 +635,7 @@ def outcome(name, script, passed, elapsed, trace_path, hasher=None): record = {"status": "pass" if passed else "fail", "seconds": round(elapsed, 1), "finished": time.strftime("%Y-%m-%dT%H:%M:%S"), "host": HOST} try: - trace = json.loads(Path(trace_path).read_text()) + trace = json.loads(Path(trace_path).read_text(encoding="utf-8")) except (OSError, ValueError): trace = None # killed before writing it, or the disk was full: the pass can't be keyed if trace: @@ -726,7 +727,7 @@ class LocalExecutor: def host_config(): """tools/parity_hosts.json: the machines harnesses can run on, and the harnesses that must stay local.""" path = ROOT / "tools" / "parity_hosts.json" - return json.loads(path.read_text()) if path.exists() else {"default": [], "hosts": {}, "local_only": {}} + return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {"default": [], "hosts": {}, "local_only": {}} class RemoteExecutor: @@ -1017,11 +1018,11 @@ def stale(name, state, hasher, environment): candidates = [record] if record and record.get("dependencies") else [] template = SHARED / "dependencies" / f"{name}.json" if template.exists(): - candidates.append(json.loads(template.read_text())) + candidates.append(json.loads(template.read_text(encoding="utf-8"))) for candidate in candidates: shared = SHARED / "passes" / name / f"{key(candidate, hasher, environment)}.json" if shared.exists(): - state["harnesses"][name] = dict(json.loads(shared.read_text()), shared=True) + state["harnesses"][name] = dict(json.loads(shared.read_text(encoding="utf-8")), shared=True) return False return True @@ -1088,7 +1089,7 @@ def changed_harnesses(found, records, ref): for name, script in found.items(): specific = [path for path in records.get(name, {}).get("dependencies", []) if path.startswith("mods/horizon/src/test/") or "/examples/" in path or "/src/bin/" in path] - if str(Path(script).relative_to(ROOT)) in changed or any(path in changed for path in specific): + if Path(script).relative_to(ROOT).as_posix() in changed or any(path in changed for path in specific): found_changed.add(name) return found_changed @@ -1103,8 +1104,8 @@ def affected_harnesses(found, records, changed): dependencies = records.get(name, {}).get("dependencies") template = SHARED / "dependencies" / f"{name}.json" if dependencies is None and template.exists(): - dependencies = json.loads(template.read_text()).get("dependencies") - if dependencies is None or str(Path(script).relative_to(ROOT)) in changed or \ + dependencies = json.loads(template.read_text(encoding="utf-8")).get("dependencies") + if dependencies is None or Path(script).relative_to(ROOT).as_posix() in changed or \ any(path.split(KEEP)[0] in changed for path in dependencies): affected.add(name) return affected @@ -1180,7 +1181,7 @@ def main(): chosen = [name for name in found if records.get(name, {}).get("status") == "fail"] elif args.changed or args.changed_files: if args.changed_files: - changed, since = set(Path(args.changed_files).read_text().split("\n")) - {""}, "" + changed, since = set(Path(args.changed_files).read_text(encoding="utf-8").split("\n")) - {""}, "" else: changed, since = changed_files(args.changed), f" since the merge base with {args.changed}" if changed is None: diff --git a/tools/perf_bench.py b/tools/perf_bench.py index bbae4934f..6d0c5571d 100644 --- a/tools/perf_bench.py +++ b/tools/perf_bench.py @@ -364,6 +364,20 @@ def run_horizon(args, distance): for carry in dev_mods(args): command += ["--dev-mod", str(carry)] env = dict(os.environ, HORIZON_NO_AUDIO="1") + if args.warm: + # A first start to the title screen builds what later starts reuse (the content-mod + # root, the block behaviour snapshot). It is not measured: players see it once. + with (WORK / f"horizon-rd{distance}-warm.log").open("w") as log: + proc = subprocess.Popen(command, cwd=game_dir, env=env, stdout=log, stderr=subprocess.STDOUT) + try: + poll(Control(sock), lambda s: s.get("screen") == "title", 600) + try: + Control(sock)("quit", timeout=60) + except (OSError, ValueError, RuntimeError): + pass + finally: + stop(proc) + sock.unlink(missing_ok=True) log = (WORK / f"horizon-rd{distance}.log").open("w") started = time.time() proc = subprocess.Popen(command, cwd=game_dir, env=env, stdout=log, stderr=subprocess.STDOUT) @@ -774,6 +788,8 @@ def main(): p.add_argument("--build", default=str(ROOT / "target/release")) p.add_argument("--repeats", type=int, default=3, help="games per render distance; the report gives means and 95%% CIs") p.add_argument("--port-work", help="horizon: also load the mods carried over in this horizon-port-pack work folder") + p.add_argument("--warm", action="store_true", + help="horizon: measure a later start, after one start to the title screen built the caches") p.add_argument("--mod-jars", help="neoforge: the mod jars to load (the user's own; never committed)") p.add_argument("--deps", help="neoforge: their required libraries") p.add_argument("--table", nargs="+", metavar="LABEL", help="print markdown tables of saved runs, and exit") diff --git a/tools/pr_ready.py b/tools/pr_ready.py index 980080284..9ec216fea 100755 --- a/tools/pr_ready.py +++ b/tools/pr_ready.py @@ -29,6 +29,10 @@ import subprocess import sys import time +if os.name == "nt": + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + sys.stderr.reconfigure(encoding="utf-8", errors="replace") + ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) FLEET_SHARED = Path.home() / "code" / "horizon-parity" / "shared-local" / "parity-shared" @@ -184,7 +188,7 @@ def line_counts(base, changed): for path in git("ls-files", "--others", "--exclude-standard").splitlines(): if path in changed: try: - counts[path] = (len((ROOT / path).read_text().splitlines()), 0) + counts[path] = (len((ROOT / path).read_text(encoding="utf-8").splitlines()), 0) except (UnicodeDecodeError, OSError): pass return counts @@ -303,6 +307,9 @@ def run_script(steps, host, verbose): """Runs the steps in one shell on host (here for "local"), each between markers, reading results as they come.""" if not steps: return + if host == "local" and os.name == "nt": + run_windows(steps, verbose) + return parts = [HOST_SETUP.get(host, ""), "set +e"] for index, step in enumerate(steps): parts.append(f"echo '@@pr_ready:begin:{index}'; started=$(date +%s)\n( {step.command}\n) 2>&1 < /dev/null\n" @@ -338,6 +345,61 @@ def run_script(steps, host, verbose): finish(step, verbose) +def run_windows(steps, verbose): + """Run local checks directly on Windows without requiring a Unix shell.""" + for step in steps: + command = shlex.split(step.command) + cwd = ROOT + env = os.environ.copy() + env["PYTHONUTF8"] = "1" + if step.name == "Public tree": + command = [sys.executable, "tools/check_public_tree.py"] + elif step.name == "Python tests": + command = [sys.executable, "-m", "unittest", "discover", "-s", "tests"] + elif step.name == "rustfmt": + command = ["cargo", "fmt", "--all", "--", "--check"] + elif step.name == "clippy": + command = ["cargo", "clippy", "--workspace", "--all-targets", "--locked", "--", "-D", "warnings"] + elif step.name.startswith("tests"): + command = shlex.split(step.command) + elif step.name == "tokens.css up to date": + command = shlex.split(step.command) + elif step.name == "launcher rustfmt": + command = ["cargo", "fmt", "--check"] + cwd = ROOT / "launcher" + elif step.name == "launcher clippy": + command = ["cargo", "clippy", "--all-targets", "--locked", "--", "-D", "warnings"] + cwd = ROOT / "launcher" + elif step.name == "launcher tests": + command = ["cargo", "test", "--locked", "--lib"] + cwd = ROOT / "launcher" + elif step.name == "Parity": + command = shlex.split(step.command) + if command and command[0] == "PARITY_HOSTS=": + command.pop(0) + if command and command[0] == "python3": + command[0] = sys.executable + env["PARITY_HOSTS"] = "" + elif command and command[0] == "python3": + command[0] = sys.executable + + print(f" {step.name}...", file=sys.stderr, flush=True) + started = time.monotonic() + try: + with subprocess.Popen(command, cwd=cwd, env=env, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, text=True, errors="replace") as process: + for line in process.stdout: + step.output += line + if verbose: + print(" " + line, end="", file=sys.stderr) + status = process.wait() + step.status = "pass" if status == 0 else "fail" + except OSError as error: + step.status, step.detail = "fail", str(error) + step.seconds = int(time.monotonic() - started) + finish(step, verbose) + + def finish(step, verbose): if step.status == "pass" and step.summary: step.detail = step.summary(step.output) diff --git a/tools/server_bench.py b/tools/server_bench.py index c79d6aab1..0ba99617a 100755 --- a/tools/server_bench.py +++ b/tools/server_bench.py @@ -19,7 +19,9 @@ The bots can run on another machine, so they don't take the server's CPU: `--bot `--bots-bin` naming horizon-bots there and `--connect` the address it reaches this machine at. `--nice 19` runs every server at the lowest priority (a shared machine). The explore bots fly as fast as each server sends them chunks, so a faster server gets more terrain to generate; `--explore-speed` slows them to a rate -both servers keep up with, for equal work. +both servers keep up with, for equal work. After the runs, the work table compares the servers at each bot +count: chunks sent and new chunks generated a second, against the busiest server's. A run whose work is more +than 10 % apart isn't a fair comparison of its tick times. The vanilla side runs the pinned server jar from tools/lab.py prepare (your own copy). It needs Java 25. The Horizon side runs target/release/horizon-server with the engine beside it; build both first: @@ -306,6 +308,38 @@ def run_once(kind, bots, behaviour, args, out): return result +# How far apart two servers' chunks a second (sent, and new) may be and still count as the same work: 10 %, +# or a chunk a second when there are few. +EQUAL_WORK = 0.10 + + +def work(runs): + """Each pass and bot count that ran on more than one server: every server's chunks sent and new chunks a + second as a share of the busiest one's, the ticks a second its bots stood waiting for their own chunk, + and whether the work was equal (within EQUAL_WORK on both).""" + groups = {} + for r in runs: + if 'error' not in r: + groups.setdefault((r['behaviour'], r['bots']), []).append(r) + rows = [] + for (behaviour, bots), group in groups.items(): + if len(group) < 2: + continue + row = {'behaviour': behaviour, 'bots': bots, 'servers': {}, 'equal': True} + for key in ('chunks_per_second', 'unique_per_second'): + top = max(r.get(key) or 0 for r in group) + for r in group: + value = r.get(key) or 0 + share = round(value / top, 3) if top else 1.0 + row['servers'].setdefault(r['server'], {})[key] = {'value': value, 'share': share} + if top - value > max(EQUAL_WORK * top, 1.0): + row['equal'] = False + for r in group: + row['servers'][r['server']]['waited_ticks_per_second'] = r.get('waited_ticks_per_second') + rows.append(row) + return rows + + def main(): parser = argparse.ArgumentParser(description=__doc__.split('\n\n')[0]) parser.add_argument('--servers', default='horizon,vanilla') @@ -346,6 +380,7 @@ def main(): 'java': subprocess.run(['java', '--version'], capture_output=True, text=True).stdout.splitlines()[:1], 'settings': {**vars(args), 'out': str(args.out), 'properties': PROPERTIES}, 'runs': runs, + 'work': work(runs), } path = args.out or out / 'report.json' path.parent.mkdir(parents=True, exist_ok=True) @@ -356,11 +391,20 @@ def main(): if 'error' in r: print(f'{r["server"]:8} {r["behaviour"]:8} {r["bots"]:>4} failed: {r["error"].splitlines()[0]}') continue - per_bot = r['chunks_per_bot'].get(r['behaviour']) + # A mixed pass: every bot's. + per_bot = r['chunks_per_bot'].get(r['behaviour']) or round((r['chunks_total'] or 0) / r['bots']) print(f'{r["server"]:8} {r["behaviour"]:8} {r["bots"]:>4} {r["start_seconds"]:>8} {r["mspt"]["average"]!s:>6} ' f'{r["mspt"]["p95"]!s:>6} {r["mspt"]["p99"]!s:>6} {r["rss_mb"]["mean"]!s:>7} {r["cpu_percent"]!s:>6} ' f'{r["chunks_per_second"]!s:>8} {per_bot!s:>6} {r["resent"]!s:>6} {r["pulled_back"]!s:>6} ' f'{r["bots_joined"]!s:>6}') + if report['work']: + print(f'\nWork, against the busiest server (chunks a second sent, new; ticks a second bots waited):') + for row in report['work']: + cells = ' '.join( + f'{server} {w["chunks_per_second"]["value"]} ({w["chunks_per_second"]["share"]:.0%}), ' + f'{w["unique_per_second"]["value"]} ({w["unique_per_second"]["share"]:.0%}), ' + f'{w["waited_ticks_per_second"]}' for server, w in row['servers'].items()) + print(f'{row["behaviour"]:8} {row["bots"]:>4} {"equal" if row["equal"] else "NOT EQUAL"} {cells}') print(f'\nWrote {path}') diff --git a/tools/test_block_entity_tickers_parity.py b/tools/test_block_entity_tickers_parity.py new file mode 100644 index 000000000..459e7a926 --- /dev/null +++ b/tools/test_block_entity_tickers_parity.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Compare the order block entities tick in with vanilla's `Level.blockEntityTickers`. + +Random scenarios load chunks with block entities in a save order (enough in +one chunk to make its block entity map grow), place, replace and remove block +entities, give jukeboxes a record and take it, and unload chunks, with ticks +in between. `VanillaBlockEntityTickerOracle` runs them on real `LevelChunk`s +of a server level and prints, after each tick, the positions of the live +tickers in list order; `examples/block_entity_tickers_fixture` runs the same +on `horizon_client::block_entities::BlockEntities`. The block entities are +the kinds the game ticks in that list (hoppers, furnaces, beacons, spawners, +trial spawners, vaults, hives, crafters, brewing stands, jukebox), with chests and barrels, +which have no ticker, among them. +""" +import argparse +import os +import random +import subprocess +import sys +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + +PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity' +TICKING = ['hopper', 'furnace', 'blast_furnace', 'smoker', 'beacon', 'spawner', 'trial_spawner', 'vault', + 'beehive', 'bee_nest', 'crafter', 'brewing_stand', 'jukebox_record'] +KINDS = TICKING + ['jukebox', 'chest', 'barrel'] + + +def scenario(rng): + """One scenario's lines: a few chunks near the origin and the ops on them.""" + lines = ['reset'] + loaded, blocks = set(), {} + + def free(cx, cz): + while True: + p = (cx * 16 + rng.randrange(16), rng.randrange(-64, 320), cz * 16 + rng.randrange(16)) + if p not in blocks: + return p + + def load(): + options = [(x, z) for x in range(-2, 3) for z in range(-2, 3) if (x, z) not in loaded] + if not options: + return + cx, cz = rng.choice(options) + loaded.add((cx, cz)) + words = ['load', str(cx), str(cz)] + for _ in range(rng.choice([0, 1, 3, 8, 20, 30, 60])): + p, kind = free(cx, cz), rng.choice(KINDS) + blocks[p] = kind + words += [kind, *map(str, p)] + lines.append(' '.join(words)) + for _ in range(rng.randrange(1, 4)): + load() + lines.append('tick') + for _ in range(rng.randrange(10, 60)): + op = rng.random() + mine = sorted(blocks) + if op < 0.25 and loaded: + cx, cz = rng.choice(sorted(loaded)) + p, kind = free(cx, cz), rng.choice(KINDS) + blocks[p] = kind + lines.append(f'place {kind} {p[0]} {p[1]} {p[2]}') + elif op < 0.4 and mine: + p = rng.choice(mine) + lines.append(f'replace {p[0]} {p[1]} {p[2]}') + elif op < 0.6 and mine: + p = rng.choice(mine) + del blocks[p] + lines.append(f'remove {p[0]} {p[1]} {p[2]}') + elif op < 0.72: + jukeboxes = [p for p in mine if blocks[p].startswith('jukebox')] + if jukeboxes: + p = rng.choice(jukeboxes) + record = blocks[p] == 'jukebox' + blocks[p] = 'jukebox_record' if record else 'jukebox' + lines.append(f'record {p[0]} {p[1]} {p[2]} {int(record)}') + elif op < 0.78 and loaded: + cx, cz = rng.choice(sorted(loaded)) + loaded.discard((cx, cz)) + for p in [p for p in blocks if (p[0] >> 4, p[2] >> 4) == (cx, cz)]: + del blocks[p] + lines.append(f'unload {cx} {cz}') + elif op < 0.85: + load() + else: + lines.append('tick') + lines.append('tick') + return lines + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--scenarios', type=int, default=3000) + parser.add_argument('--seed', type=int, default=0x7469636b) + args = parser.parse_args() + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / 'rust-block-entity-tickers-parity' + build.mkdir(parents=True, exist_ok=True) + rng = random.Random(args.seed) + lines = [line for _ in range(args.scenarios) for line in scenario(rng)] + inputs = build / 'inputs.txt' + inputs.write_text('\n'.join(lines) + '\n') + classes = build / 'classes' + classes.mkdir(exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + + def run(command, name): + with (build / (name + '.log')).open('w') as log: + result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, + stderr=subprocess.STDOUT) + if result.returncode: + print((build / (name + '.log')).read_text()[-4000:]) + sys.exit(f'{name} failed') + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, + '-d', classes, *(PARITY / f'{n}.java' for n in ('ParityData', 'VanillaBlockEntityTickerOracle'))], + 'compile-java') + run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, + 'dev.horizonlab.parity.VanillaBlockEntityTickerOracle', inputs, build / 'vanilla.txt'], 'vanilla') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', + 'block_entity_tickers_fixture', '--', inputs, build / 'rust.txt'], 'rust') + matched = base.compare(build / 'vanilla.txt', build / 'rust.txt') + ticks = sum(1 for line in lines if line == 'tick') + listed = sum(len(line.split()) - 1 for line in (build / 'vanilla.txt').read_text().splitlines()) + print(f'block entity tickers: {args.scenarios} scenarios, {matched} of {ticks} ticks match vanilla ' + f'({listed} tickers listed)') + + +if __name__ == '__main__': + main() diff --git a/tools/test_block_removal_parity.py b/tools/test_block_removal_parity.py index 35b0fdd2b..6ebbbf1d3 100755 --- a/tools/test_block_removal_parity.py +++ b/tools/test_block_removal_parity.py @@ -5,8 +5,9 @@ A container, jukebox, lectern, campfire, decorated pot, chiseled bookshelf, shelf, shulker box or another block entity holder at the origin holds random contents; the case then replaces it with `Level.setBlock` (another block, the same block in another state, with or without UPDATE_SKIP_BLOCK_ENTITY_SIDEEFFECTS), -destroys it with `Level.destroyBlock` (with or without drops) or removes it with -`Level.removeBlock`. Vanilla runs over the headless level of the dispenser oracle +destroys it with `Level.destroyBlock` (with or without drops), removes it with +`Level.removeBlock`, or a survival player mines it (`ServerPlayerGameMode.destroyBlock`, +holding a tool or nothing, #844). Vanilla runs over the headless level of the dispenser oracle (`VanillaDispenserOracle`, "remove" cases), which replays `LevelChunk.setBlockState`'s `BlockEntity.preRemoveSideEffects`; Horizon runs its game glue in a headless game (`HORIZON_DISPENSE_FIXTURE`). Both print the block changes, the contents left, @@ -63,6 +64,10 @@ LISTED = {'chest', 'trapped_chest', 'barrel', 'hopper', 'dispenser', 'dropper', REPLACEMENTS = ['air', 'stone', 'glass', 'water', 'oak_planks', 'barrel', 'chest', 'hopper', 'blue_shulker_box', 'dirt', 'tnt', 'copper_chest', 'oxidized_copper_chest', 'lectern', 'jukebox'] FLAGS = [3, 3, 3, 2, 18, 2 | 256, 816, 3 | 64, 1] +# What a mining player holds: the right tool, a tool too weak or of another kind (swords and maces +# wear 2 a block, shears any block but fire), or nothing. +TOOLS = [plain('diamond_pickaxe'), plain('wooden_pickaxe'), plain('stone_axe'), plain('iron_shovel'), plain('iron_sword'), + plain('shears'), plain('mace'), '-'] def contents(rng, name, slots, pool): @@ -135,8 +140,12 @@ def cases(facts, count, seed, only): op = {'op': 'destroy', 'drop': True} elif roll < 0.85: op = {'op': 'destroy', 'drop': False} - else: + elif roll < 0.92: op = {'op': 'remove'} + else: + # ServerPlayerGameMode.destroyBlock: a survival player mines it (#844). The tool comes + # from the roll, not another draw, so the cases after this one stay the same. + op = {'op': 'mine', 'item': TOOLS[int(roll * 1000) % len(TOOLS)]} case = {**h.environment(rng), 'mode': 'remove', 'pos': [0, 0, 0], 'cells': cells, 'items': items, 'remove': op} case.pop('raining', None) case.pop('thundering', None) diff --git a/tools/test_dedicated_server_parity.py b/tools/test_dedicated_server_parity.py index 6ac9aecbe..e8497d7f8 100644 --- a/tools/test_dedicated_server_parity.py +++ b/tools/test_dedicated_server_parity.py @@ -268,6 +268,12 @@ def run_side(label, command, directory, client): # it stays put; experience keeps its profession). server.console('summon minecraft:villager ~1 ~ ~ {NoAI:1b,Xp:1,VillagerData:' '{profession:"minecraft:librarian",level:2,type:"minecraft:plains"}}') + # The saved world still has fluid ticks due in the area the client is sent (a lava fall + # that never settles), and they run once their chunk ticks. When that is, against when the + # chunk is sent, follows how fast the server loads the chunks around the joining player: + # each run, vanilla sends a different set of them already flowed. Frozen until the client + # has its chunks, both servers send the world as saved; blocks tick again from the chat on. + server.console('tick freeze') port = int(PROPERTIES_PORTS[label]) legacy = legacy_ping(port) # The client asks to be made an operator once it has traded, runs /kill and respawns. @@ -282,7 +288,11 @@ def run_side(label, command, directory, client): joined = threading.Thread(target=join) joined.start() deadline = time.time() + 300 + frozen = True while joined.is_alive() and not any('<Tester> ready to respawn' in l for l in server.lines): + if frozen and any('<Tester> hello from the parity client' in l for l in server.lines): + server.console('tick unfreeze') + frozen = False if time.time() > deadline: break time.sleep(0.2) diff --git a/tools/test_interaction_input_parity.py b/tools/test_interaction_input_parity.py new file mode 100644 index 000000000..1aa34a73f --- /dev/null +++ b/tools/test_interaction_input_parity.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +"""Compare queued interaction ordering with the real Minecraft.handleKeybinds.""" +import itertools +import json +import random + +try: + from . import lab, oracle_harness as harness +except ImportError: + import lab, oracle_harness as harness + + +def corpus(): + rng = random.Random(0x434C49434B) + for using, destroying, attack_down, use_down, entity in itertools.product([False, True], repeat=5): + for clicks in [[], [1], [0, 1], [1, 0], [2, 1, 0], [0, 0, 1, 1, 2]]: + for delay in [0, 3]: + yield dict(using=using, destroying=destroying, attack_down=attack_down, + use_down=use_down, entity=entity, clicks=clicks, delay=delay, + dig_on_attack=rng.choice([False, True]), + begin_using=rng.choice([False, True])) + # A player interaction returning PASS must go directly to the held item. + # The level still reports a solid block underneath the entity hit. + for entity in [False, True]: + for clicks in [[1], [1, 1], [0, 1], [1, 2]]: + yield dict(using=False, destroying=False, attack_down=False, use_down=False, + entity=entity, clicks=clicks, delay=0, dig_on_attack=False, + begin_using=False, passing=True) + + +def main(): + def inputs(build): + rows = list(corpus()) + path = build / "inputs.jsonl" + path.write_text("".join(json.dumps(row) + "\n" for row in rows)) + return path, len(rows) + + harness.differential( + "interaction-input-parity", "VanillaInteractionInputOracle", "interaction_input_fixture", inputs, + "Invokes Minecraft.handleKeybinds itself with real KeyMapping click counters. " + "Compares attack/use/pick ordering, release gating, drained clicks during use, " + "held-button repetition and use cooldowns for block/entity targets. " + "Includes passing entity interactions over solid blocks: only the held " + "item may be tried afterward. " + "Game-mode side effects and world simulation are controlled fixtures.", + sources=[lab.ROOT / "crates/horizon-client/src/interaction_input.rs", + lab.ROOT / "crates/horizon-client/src/game/remote.rs", + lab.ROOT / "crates/horizon-client/src/game/hand.rs", + lab.ROOT / "mods/horizon/src/test/java/dev/horizonlab/parity/ParityData.java"]) + + +if __name__ == "__main__": + main() diff --git a/tools/test_player_sync_parity.py b/tools/test_player_sync_parity.py new file mode 100644 index 000000000..4c78b439f --- /dev/null +++ b/tools/test_player_sync_parity.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Compare movement packet selection and teleport velocity with the pinned client.""" +import json +import random +import struct + +try: + from . import lab, oracle_harness as harness +except ImportError: + import lab, oracle_harness as harness + + +def corpus(): + # Stationary heartbeats, rotation-only updates, status changes and corrected + # positions followed by unchanged looks must retain vanilla's packet types. + yield dict(kind="movement", ops=[[0, 0, 0, 0, 0, False, False]] * 61) + yield dict(kind="movement", ops=[ + [0, 64, 0, 90, 0, True, False], + [0, 64, 0, 90, 0, True, False], + [0, 64, 0, 91, 0, True, False], + [100, 80, -20, 180, 20, False, False], + [100, 80, -20, 180, 20, True, False], + [100, 80, -20, 180, 20, True, True], + ]) + rng = random.Random(0x53594E43) + for _ in range(300): + state = [0, 0, 0, 0, 0, False, False] + ops = [] + for _ in range(80): + if rng.random() < 0.5: + axis = rng.randrange(3) + state[axis] += rng.choice([0, 0.0001, 0.0002, 0.0002000001, 0.1, 10]) + if rng.random() < 0.3: + state[3] += rng.choice([-360, -1, 0, 0.001, 1, 360]) + state[4] = rng.choice([-90, 0, 30, 90]) + if rng.random() < 0.2: + state[rng.randrange(5, 7)] = rng.choice([False, True]) + ops.append(state.copy()) + yield dict(kind="movement", ops=ops) + for flags in range(16): + for _ in range(40): + yield dict(kind="velocity", flags=flags << 5, + velocity=[rng.uniform(-4, 4) for _ in range(3)], + delta=[rng.uniform(-4, 4) for _ in range(3)], + old=[rng.uniform(-720, 720), rng.uniform(-90, 90)], + new=[rng.uniform(-720, 720), rng.uniform(-90, 90)]) + + +def main(): + def inputs(build): + rows = list(corpus()) + def bits(v): + return struct.pack(">d", v).hex() + for row in rows: + if row["kind"] == "movement": + row["ops"] = [[*map(bits, op[:5]), *op[5:]] for op in row["ops"]] + else: + for key in ["velocity", "delta", "old", "new"]: + row[key] = list(map(bits, row[key])) + path = build / "inputs.jsonl" + path.write_text("".join(json.dumps(row) + "\n" for row in rows)) + return path, len(rows) + + harness.differential( + "player-sync-parity", "VanillaPlayerSyncOracle", "player_sync_fixture", inputs, + "Actual LocalPlayer.sendPosition packet payloads over persistent movement " + "sequences; PositionMoveRotation.calculateAbsolute velocity with every " + "relative-delta/rotate-delta combination. World simulation, connection " + "scheduling and live anticheat behaviour are outside this harness.", + sources=[lab.ROOT / "crates/horizon-client/src/player_sync.rs", + lab.ROOT / "crates/horizon-client/src/game/remote.rs", + lab.ROOT / "crates/horizon-client/src/net.rs"]) + + +if __name__ == "__main__": + main() diff --git a/tools/test_secure_chat_parity.py b/tools/test_secure_chat_parity.py new file mode 100644 index 000000000..13bf494dd --- /dev/null +++ b/tools/test_secure_chat_parity.py @@ -0,0 +1,317 @@ +#!/usr/bin/env python3 +"""Secure chat on vanilla's dedicated server and Horizon's, with no real account. + +A mock of the Minecraft services stands in for Mojang's: its key set (the +`authentication` / `getPublicKeys` endpoint) holds a key pair the harness +makes, so the profile keys it signs are as good as Mojang's to both servers. +Vanilla finds the mock through authlib's `-Dminecraft.api.discovery.host`, +Horizon through `HORIZON_API_DISCOVERY`. SecureChatClient (vanilla's own +codecs and chat classes) plays several players at once: each signs its chat +with a profile key the mock signed, acknowledges what it saw, and checks the +signature of every chat it receives against the sender's session from the +player list, as vanilla's client does. + +Two servers, each run on vanilla then on Horizon: +- offline mode (enforce-secure-profile is then off): signed chat with the + last-seen window and the signature cache, unsigned chat beside it, /say, + /me and /msg with signed and unsigned arguments, a signed argument under + the wrong name, a forged signature and the broken chain after it, and an + acknowledgement past the window; +- online mode with enforce-secure-profile: the status and the login packet + say so, unsigned chat and unsigned commands with a message are refused, and + a key signed for another player is refused. + +Compared: every player's transcript, the status' `enforcesSecureChat`, and +the servers' log lines about chat. +""" +import hashlib +import json +import os +from pathlib import Path +import platform +import re +import shutil +import socket +import subprocess +import sys +import time +import threading +import urllib.parse +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +try: + from . import lab, oracle_harness as oh, test_rust_parity as base + from .test_dedicated_server_parity import Server, free_port +except ImportError: + import lab + import oracle_harness as oh + import test_rust_parity as base + from test_dedicated_server_parity import Server, free_port + +NAME = 'secure-chat-parity' +SCENARIOS = { + 'offline': {'online-mode': 'false'}, + 'online': {'online-mode': 'true', 'enforce-secure-profile': 'true'}, +} +PROPERTIES = { + 'white-list': 'false', + 'level-seed': '12345', + 'view-distance': '3', + 'simulation-distance': '3', + 'spawn-protection': '0', + 'max-players': '8', + 'pause-when-empty-seconds': '-1', +} + + +def account(name): + """The mock services' account id for a name.""" + return hashlib.md5(f'account:{name}'.encode()).hexdigest() + + +class Services: + """Discovery, the key set, the session service's join and hasJoined, profiles by name.""" + + def __init__(self, key_set): + self.joined = {} + self.lock = threading.Lock() + services = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def reply(self, status, body=None): + data = b'' if body is None else json.dumps(body).encode() + self.send_response(status) + if body is not None: + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_GET(self): + url = urllib.parse.urlparse(self.path) + query = dict(urllib.parse.parse_qsl(url.query)) + if url.path == '/minecraft/client': + return self.reply(200, services.discovery()) + if url.path == '/publickeys': + return self.reply(200, key_set) + if url.path.startswith('/users/profiles/minecraft/'): + name = urllib.parse.unquote(url.path.rsplit('/', 1)[1]) + return self.reply(200, {'id': account(name), 'name': name}) + if url.path == '/session/minecraft/hasJoined': + name = query.get('username') + with services.lock: + ok = services.joined.get(name) == query.get('serverId') + if ok: + return self.reply(200, {'id': account(name), 'name': name, 'properties': []}) + return self.reply(204) + self.reply(404, {'error': 'NotFound'}) + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers.get('Content-Length', 0))) or b'{}') + if self.path != '/session/minecraft/join': + return self.reply(404, {'error': 'NotFound'}) + # The test client names its account instead of its id. + with services.lock: + services.joined[body.get('selectedProfile')] = body.get('serverId') + self.reply(204) + + self.server = ThreadingHTTPServer(('127.0.0.1', 0), Handler) + self.url = f'http://127.0.0.1:{self.server.server_address[1]}' + threading.Thread(target=self.server.serve_forever, daemon=True).start() + + def discovery(self): + def endpoints(**names): + return {'endpoints': {k: {'uri': self.url + v} for k, v in names.items()}} + return {'environment': 'mock', 'product': 'minecraft', 'discovery': { + 'authentication': endpoints(getPublicKeys='/publickeys'), + 'session': endpoints(join='/session/minecraft/join', verify='/session/minecraft/hasJoined', + getProfileById='/session/minecraft/profile/{profileId}'), + 'player': {'endpoints': {}}, + 'profiles': {'endpoints': {'getTexture': {'validUris': [self.url + '/texture/{textureId}']}, + 'getByName': {'uri': self.url + '/users/profiles/minecraft/{name}'}}}, + 'telemetry': {'endpoints': {}}, + }} + + def stop(self): + self.server.shutdown() + + +def player_id(name, scenario): + """The player's id: the account's online, UUIDUtil.createOfflinePlayerUUID offline.""" + if scenario == 'online': + return account(name) + digest = bytearray(hashlib.md5(f'OfflinePlayer:{name}'.encode()).digest()) + digest[6] = digest[6] & 0x0F | 0x30 + digest[8] = digest[8] & 0x3F | 0x80 + return digest.hex() + + +def dashed(u): + return f'{u[:8]}-{u[8:12]}-{u[12:16]}-{u[16:20]}-{u[20:]}' + + +def varint(n): + out = b'' + while True: + b = n & 0x7F + n >>= 7 + out += bytes([b | (0x80 if n else 0)]) + if not n: + return out + + +def status(port): + """The status response's JSON (ServerStatus).""" + def packet(body): + return varint(len(body)) + body + + def read_varint(s): + value = 0 + for i in range(5): + b = s.recv(1)[0] + value |= (b & 0x7F) << (7 * i) + if not b & 0x80: + return value + with socket.create_connection(('127.0.0.1', port), timeout=10) as s: + host = b'127.0.0.1' + s.sendall(packet(b'\x00' + varint(777) + varint(len(host)) + host + port.to_bytes(2, 'big') + b'\x01')) + s.sendall(packet(b'\x00')) + length = read_varint(s) + data = b'' + while len(data) < length: + data += s.recv(length - len(data)) + text = data[1:] + n, shift, i = 0, 0, 0 + while True: + b = text[i] + n |= (b & 0x7F) << shift + shift += 7 + i += 1 + if not b & 0x80: + break + return json.loads(text[i:i + n]) + + +# The servers' lines about chat, with their level. The thread is left out: +# vanilla handles acknowledgements on its network threads, named per platform. +CHAT_LINE = re.compile(r'^\[\d\d:\d\d:\d\d\] \[([^\]]+)\]: (.*(?:<\w+>|\[Not Secure\]|\[\w+\] |\* \w+ |secure chat|' + r'signable|Signed command|acknowledgement|profile key|chat session|expired chat|lost connection|' + r'Disconnecting).*)$') + + +def chat_lines(lines): + out = [] + for line in lines: + if m := CHAT_LINE.match(line): + text = re.sub(r'/127\.0\.0\.1:\d+', '/127.0.0.1:_', m.group(2)) + out.append(f'[{m.group(1).rsplit("/", 1)[-1]}] {text}') + return out + + +def run_side(label, scenario, command, directory, client): + port = free_port() + shutil.rmtree(directory, ignore_errors=True) + directory.mkdir(parents=True) + props = dict(PROPERTIES, **SCENARIOS[scenario], **{'server-port': str(port)}) + (directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items())) + (directory / 'eula.txt').write_text('eula=true\n') + # Alice and Carol are operators (/say needs it), by their ids. + ops = [{'uuid': dashed(player_id(name, scenario)), 'name': name, 'level': 4, 'bypassesPlayerLimit': False} + for name in ('Alice', 'Carol')] + (directory / 'ops.json').write_text(json.dumps(ops, indent=2)) + server = Server(command, directory, f'{label}-{scenario}') + try: + server.wait_for(r'Done \(', timeout=600) + # A server can drop a ping in its first moments (the network thread still starting): try again. + for attempt in range(5): + try: + enforces = status(port).get('enforcesSecureChat', False) + break + except (OSError, IndexError): + if attempt == 4: + raise + time.sleep(2) + out = directory.parent / f'{label}-{scenario}.txt' + client(port, scenario, out) + transcript = [f'status enforcesSecureChat {enforces}'] + out.read_text(encoding='utf-8').splitlines() + finally: + server.stop() + return transcript, chat_lines(server.lines) + + +def main(): + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / NAME + build.mkdir(parents=True, exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + classes = build / 'classes' + shutil.rmtree(classes, ignore_errors=True) + classes.mkdir() + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/SecureChatClient.java' + oh.run_logged(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-sourcepath', + lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], + build, 'compile-java') + oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], build, + 'compile-rust') + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], + cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + java = ['java', '-Xmx1g', '-Duser.timezone=UTC', '-cp', str(classes) + os.pathsep + dependencies, + 'dev.horizonlab.parity.SecureChatClient'] + oh.run_logged([*java, 'keys', build], build, 'keys') + services = Services(json.loads((build / 'publickeys.json').read_text())) + discovery = services.url + '/minecraft/client' + os.environ.update(HORIZON_NO_AUDIO='1', HORIZON_API_DISCOVERY=discovery) + servers = { + 'vanilla': ['java', '-Xmx2g', '-Duser.timezone=UTC', f'-Dminecraft.api.discovery.host={discovery}', + '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'], + 'horizon': [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'], + } + + def client(port, scenario, out): + oh.run_logged([*java, '127.0.0.1', port, build / 'services-private.der', out, scenario, services.url], + build, out.stem, timeout=300) + + differences = [] + try: + for scenario in SCENARIOS: + results = {} + for label, command in servers.items(): + results[label] = run_side(label, scenario, command, build / f'{label}-{scenario}', client) + transcript, log = results[label] + (build / f'{label}-{scenario}-all.txt').write_text('\n'.join(transcript + ['--- log'] + log) + '\n', + encoding='utf-8') + import difflib + for part, index in (('transcript', 0), ('log', 1)): + diff = [l for l in difflib.unified_diff(results['vanilla'][index], results['horizon'][index], + 'vanilla', 'horizon', n=0, lineterm='') + if l[:1] in '+-' and l[:3] not in ('+++', '---')] + if diff: + differences.append(f'{scenario} {part}:\n ' + '\n '.join(diff[:60])) + errors = [l for l in results['vanilla'][0] if l.startswith('error')] + if errors: + differences.append(f'{scenario}: the vanilla run failed: {errors}') + finally: + services.stop() + if differences: + raise AssertionError('\n'.join(differences) + f'\n(transcripts in {build})') + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), + java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], + scope='Secure chat against vanilla\'s dedicated server: chat sessions validated against mock services keys, ' + 'signed chat with last seen and the signature cache, unsigned chat, /say /me /msg with signed and ' + 'unsigned arguments, mismatched and forged signatures, the broken chain, a bad acknowledgement; ' + 'enforce-secure-profile in online mode (status, login, refusals, a borrowed key); the chat log lines.')) + print('secure chat: transcripts and chat log lines identical') + + +if __name__ == '__main__': + try: + main() + except AssertionError as error: + sys.exit(f'{NAME}: {error}') diff --git a/tools/test_server_dimension_players_parity.py b/tools/test_server_dimension_players_parity.py new file mode 100644 index 000000000..77e1428e9 --- /dev/null +++ b/tools/test_server_dimension_players_parity.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Players in different dimensions on a dedicated server, against vanilla's, seen by vanilla clients. + +A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat +world vanilla generated first, with Alice and Bob as operators in creative. LocatorBarClient joins them both +(players made of vanilla's protocol code) and records, step by step, the other players each is sent and loses +(ClientboundAddEntityPacket, ClientboundRemoveEntitiesPacket) and the dimensions it respawns into +(ClientboundRespawnPacket), with the locator bar's waypoints, while they change dimensions (ServerPlayer.teleport +through `execute in ... run tp`, and an End portal): Bob goes to the Nether and back, Alice to the End, Bob +follows her there, both come back to the Overworld, then Bob steps into an End portal and comes back. Between +the steps each client sends its position (the reminder a still client sends every second). Each player's lines in each step are compared exactly. +""" +import os +from pathlib import Path +import platform +import shutil +import subprocess +import sys +import time + +try: + from . import lab, test_rust_parity as base + from .test_dedicated_server_parity import Server + from .test_locator_bar_parity import generate_world, server_dir +except ImportError: + import lab + import test_rust_parity as base + from test_dedicated_server_parity import Server + from test_locator_bar_parity import generate_world, server_dir + +NAME = 'server-dimension-players-parity' +NETHER, END, OVERWORLD = 'minecraft:the_nether', 'minecraft:the_end', 'minecraft:overworld' +# (label, what the players do). +SCRIPT = [ + ('bob-nether', [f'cmd Bob execute in {NETHER} run tp @s 0.5 100 0.5']), + ('bob-back', [f'cmd Bob execute in {OVERWORLD} run tp @s 2.5 100 0.5']), + ('alice-end', [f'cmd Alice execute in {END} run tp @s 0.5 100 0.5']), + ('bob-end', [f'cmd Bob execute in {END} run tp @s 2.5 100 0.5']), + ('alice-back', [f'cmd Alice execute in {OVERWORLD} run tp @s 0.5 100 0.5']), + ('bob-back-again', [f'cmd Bob execute in {OVERWORLD} run tp @s 2.5 100 0.5']), + # Through an End portal (Entity.handlePortal), and back by command. + ('bob-portal', ['cmd Bob setblock 2 101 3 minecraft:end_portal', 'cmd Bob tp @s 2.5 101 3.5']), + ('bob-portal-back', [f'cmd Bob execute in {OVERWORLD} run tp @s 2.5 100 0.5']), +] +STEP_SECONDS = 5.0 + + +def run_side(label, server_command, client_command, build, world): + directory = build / label + port = server_dir(directory, world) + out = build / f'{label}.txt' + out.unlink(missing_ok=True) + server = Server(server_command, directory, label) + try: + server.wait_for(r'Done \(') + with (build / f'{label}-client.log').open('w') as log: + client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)], + cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, + text=True) + + def tell(line): + client.stdin.write(line + '\n') + client.stdin.flush() + try: + tell('players on') + tell('step joins') + for name, x in (('Alice', 0.5), ('Bob', 2.5)): + tell(f'join {name}') + server.wait_for(rf'{name} joined the game', timeout=120) + tell(f'fly {name} on') + tell(f'cmd {name} tp @s {x} 100 0.5') + time.sleep(STEP_SECONDS) + for step, actions in SCRIPT: + tell(f'step {step}') + for action in actions: + tell(action) + # Standing still, a client still sends its position every 20 ticks + # (LocalPlayer.sendPosition): the server then tracks to it what it has sent the + # chunks of since (ChunkMap.move). + time.sleep(STEP_SECONDS / 2) + tell('still Alice') + tell('still Bob') + time.sleep(STEP_SECONDS / 2) + tell('end') + client.wait(timeout=60) + finally: + if client.poll() is None: + client.kill() + finally: + server.stop() + if not out.exists(): + raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)') + return out.read_text(encoding='utf-8').splitlines() + + +def shown(lines): + """Each player's adds, removes and respawns, without the waypoints (the locator bar harness has those).""" + return [l for l in lines if l.split(' ', 2)[2:3] and l.split(' ', 2)[2].split(' ')[0] in ('add', 'remove', 'respawn')] + + +def main(): + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / NAME + build.mkdir(parents=True, exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java' + classes = build / 'classes' + shutil.rmtree(classes, ignore_errors=True) + classes.mkdir() + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', + lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], + cwd=lab.ROOT, check=True, capture_output=True) + subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + check=True, capture_output=True) + import json + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], + cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] + horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] + client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient'] + + world = generate_world(vanilla_server, build) + vanilla_all = run_side('vanilla', vanilla_server, client, build, world) + horizon_all = run_side('horizon', horizon_server, client, build, world) + errors = [l for l in vanilla_all + horizon_all if ' error ' in f' {l} ' or 'disconnected' in l] + vanilla, horizon = shown(vanilla_all), shown(horizon_all) + if errors or vanilla != horizon: + import difflib + diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=1, lineterm='')) + raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n' + + '\n'.join(errors[:10]) + '\n' + diff[:6000]) + if sum(' respawn ' in l for l in vanilla) < 6: + raise AssertionError(f'vanilla sent too few respawns: the script did not run (see {build})') + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), + java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], + lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'), + scope='Two players on a dedicated server changing dimensions (Nether, End, back): the other players each ' + 'is sent and loses, and the dimensions it respawns into.')) + print(f'server dimension players: {len(vanilla)} lines identical') + + +if __name__ == '__main__': + try: + main() + except AssertionError as error: + sys.exit(f'{NAME}: {error}') diff --git a/tools/test_server_entities_parity.py b/tools/test_server_entities_parity.py new file mode 100644 index 000000000..500497275 --- /dev/null +++ b/tools/test_server_entities_parity.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Entities other than mobs and items, tracked to a vanilla client, against vanilla's dedicated server. + +A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat +world vanilla generated first, with the same server.properties (offline, view distance 4). A vanilla-codec +client (VanillaProtocolClient in its entity mode) joins, and once its chunks are in it asks for the scene: the +console freezes the ticks, builds a wall and a rail and summons, around the spawn, every kind of minecart (one +set rolling along the rail), boats and a raft (one falling onto the ground), armor stands (posed, small, with +arms, wearing a helmet, one falling), a chicken jockey, a slime, a pig whose scale `/attribute` sets, item +frames (one holding a turned diamond), paintings, primed TNT (one falling), a floating falling block, an arrow +that lands and an end crystal. The client records for 20 seconds, the ticks running for 200 more after 3, what +ClientPacketListener would make of the packets (EntityTranscript): each entity's spawn +packet (position, rotations, data, motion), the entity data it was paired with and all it was sent since, its +equipment, its attribute instances (ClientboundUpdateAttributesPacket: the ones its first tick creates, the +type's set by finalizeSpawn, the baby speed modifier, effects', equipment's and /attribute's) and passengers, and +where its position syncs leave it; and the attribute instances the player itself is sent from its login on. Both +transcripts must match exactly, entity by entity (named by type and the block it was added in), once the amounts +of vanilla's random spawn modifiers are normalised (only client-syncable attributes are sent, so follow range and +knockback resistance never show). +""" +import os +from pathlib import Path +import platform +import re +import shutil +import subprocess +import sys +import time + +try: + from . import lab, test_rust_parity as base + from .test_dedicated_server_parity import Server + from .test_locator_bar_parity import generate_world, server_dir +except ImportError: + import lab + import test_rust_parity as base + from test_dedicated_server_parity import Server + from test_locator_bar_parity import generate_world, server_dir + +NAME = 'server-entities-parity' +# Ticks the scene runs for once it is summoned: 10 seconds, within the client's 20. +STEPS = 200 +PLAYER = 'Tester' + +# Around the spawn at 0 -60 0 on the flat world's grass: a wall to the north for the frames and paintings, +# a rail to the south. +SCENE = [ + 'fill -7 -60 -6 7 -57 -6 minecraft:stone', + 'fill -7 -60 9 7 -60 9 minecraft:rail', + # Minecarts. + 'summon minecraft:minecart -5.5 -60 3.5', + 'summon minecraft:chest_minecart -3.5 -60 3.5', + 'summon minecraft:furnace_minecart -1.5 -60 3.5', + 'summon minecraft:hopper_minecart 1.5 -60 3.5', + 'summon minecraft:tnt_minecart 3.5 -60 3.5', + 'summon minecraft:command_block_minecart 5.5 -60 1.5 {Command:"say hi"}', + 'summon minecraft:minecart -6.5 -60 9.5 {Motion:[0.5d,0d,0d]}', + # Boats. + 'summon minecraft:oak_boat -5.5 -60 6.5 {Rotation:[45f,0f]}', + 'summon minecraft:birch_chest_boat -2.5 -60 6.5', + 'summon minecraft:bamboo_raft 0.5 -60 6.5', + 'summon minecraft:oak_boat 4.5 -56 6.5', + # Armor stands. + 'summon minecraft:armor_stand -2.5 -60 -2.5 {Rotation:[90f,0f]}', + 'summon minecraft:armor_stand 6.5 -57 -2.5', + 'summon minecraft:armor_stand -4.5 -60 -2.5 {ShowArms:1b,Small:1b,NoBasePlate:1b,' + 'Pose:{Head:[10f,20f,0f],RightArm:[-30f,0f,15f]},equipment:{head:{id:"minecraft:diamond_helmet",count:1}}}', + # A chicken jockey (passengers). + 'summon minecraft:chicken -6.5 -60 -2.5 {NoAI:1b,Passengers:[{id:"minecraft:husk",IsBaby:1b,NoAI:1b}]}', + # Attributes: a slime's size sets its bases, /attribute a pig's scale. + 'summon minecraft:slime 2.5 -60 1.5 {Size:1,NoAI:1b}', + 'summon minecraft:pig -0.5 -60 1.5 {NoAI:1b}', + 'attribute @e[type=minecraft:pig,limit=1,x=-0.5,y=-60,z=1.5,distance=..1] minecraft:scale base set 1.5', + # Frames and paintings on the wall's south face. + 'summon minecraft:item_frame -3.5 -59 -4.97 {block_pos:[I;-4,-59,-5],Facing:3b,' + 'Item:{id:"minecraft:diamond",count:1},ItemRotation:3b}', + 'summon minecraft:glow_item_frame -1.5 -59 -4.97 {block_pos:[I;-2,-59,-5],Facing:3b}', + 'summon minecraft:painting 1.5 -59 -4.97 {block_pos:[I;1,-59,-5],facing:0b,variant:"minecraft:kebab"}', + 'summon minecraft:painting 4 -59 -4.97 {block_pos:[I;4,-59,-5],facing:0b,variant:"minecraft:courbet"}', + # Primed TNT that won't go off (one falling), a floating falling block, an arrow that lands, an end crystal. + 'summon minecraft:tnt 6.5 -60 6.5 {fuse:2000s}', + 'summon minecraft:tnt 6.5 -56 4.5 {fuse:2000s}', + 'summon minecraft:falling_block 2.5 -58 -0.5 {BlockState:{Name:"minecraft:sand"},NoGravity:1b}', + 'summon minecraft:arrow 0.5 -55 -1.5 {Motion:[0.3d,0d,0d]}', + 'summon minecraft:end_crystal -6.5 -60 6.5 {ShowBottom:0b}', +] + + +# finalizeSpawn's random modifiers on client-syncable attributes (a leader zombie's max health); their amounts +# differ from one server to the other. +RANDOM_MODIFIERS = re.compile(r'(id=minecraft:(?:random_spawn_bonus|leader_zombie_bonus), amount=)[^,]+') + + +def scene_lines(lines): + """The transcript's entities in the scene's area (the world's own animals and slimes wander elsewhere), the + amounts of random spawn modifiers normalised.""" + out = [] + for line in lines: + m = re.match(r'play-entities entity \S+ (-?\d+),-?\d+,(-?\d+)', line) + if m and -8 <= int(m.group(1)) <= 8 and -7 <= int(m.group(2)) <= 10 or line.startswith('play-entities self '): + out.append(RANDOM_MODIFIERS.sub(r'\1~', line)) + return out + + +def run_side(label, server_command, client_command, build, world): + directory = build / label + port = server_dir(directory, world) + out = build / f'{label}-client.txt' + out.unlink(missing_ok=True) + server = Server(server_command, directory, label) + try: + server.wait_for(r'Done \(') + with (build / f'{label}-client.log').open('w') as log: + client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), PLAYER, str(out), 'entities'], + cwd=lab.ROOT, stdout=log, stderr=subprocess.STDOUT, text=True) + try: + server.wait_for(rf'<{PLAYER}> summon the entities', timeout=180) + # Frozen, so that every entity is paired as it was summoned whenever each server tracks it in + # its tick; then they fall and roll. + server.console('tick freeze') + for command in SCENE: + server.console(command) + time.sleep(3) + # A fixed number of ticks, so that what still changes (a TNT fuse) ends the same. + server.console(f'tick step {STEPS}') + client.wait(timeout=120) + finally: + if client.poll() is None: + client.kill() + finally: + server.stop() + if not out.exists(): + raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)') + lines = out.read_text(encoding='utf-8').splitlines() + (build / f'{label}.txt').write_text('\n'.join(lines) + '\n', encoding='utf-8') + return lines + + +def main(): + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / NAME + build.mkdir(parents=True, exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java' + classes = build / 'classes' + shutil.rmtree(classes, ignore_errors=True) + classes.mkdir() + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', + lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], + cwd=lab.ROOT, check=True, capture_output=True) + # SERVER_ENTITIES_SIDES=vanilla (or horizon) runs one side and reads the other's last transcript. + sides = [s for s in os.environ.get('SERVER_ENTITIES_SIDES', 'vanilla,horizon').split(',') if s] + if 'horizon' in sides: + subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + check=True, capture_output=True) + import json + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], + cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] + horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] + client = ['java', '-Xmx1g', '-Duser.timezone=UTC', '-cp', str(classes) + os.pathsep + dependencies, + 'dev.horizonlab.parity.VanillaProtocolClient'] + + world = generate_world(vanilla_server, build) + results = {} + for label, command in [('vanilla', vanilla_server), ('horizon', horizon_server)]: + if label in sides: + results[label] = run_side(label, command, client, build, world) + else: + results[label] = (build / f'{label}.txt').read_text(encoding='utf-8').splitlines() + vanilla, horizon = scene_lines(results['vanilla']), scene_lines(results['horizon']) + errors = [l for l in results['vanilla'] + results['horizon'] if l.startswith('error')] + if errors or vanilla != horizon: + import difflib + diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=0, lineterm='')) + raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n' + + '\n'.join(errors[:10]) + '\n' + diff[:8000]) + if len(vanilla) < len(SCENE) - 2: + raise AssertionError(f'only {len(vanilla)} entities tracked: the scene did not run (see {build})') + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), + java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], + entities=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'), + scope='Minecarts (one rolling), boats (one falling), armor stands, a chicken jockey, a slime, a pig with a ' + 'scale, item frames, paintings, primed TNT, a falling block, an arrow and an end crystal ' + 'tracked to a vanilla-codec client by a dedicated server: spawn packets, entity data, equipment, ' + 'attributes, passengers and the positions the syncs leave them at.')) + print(f'server entities: {len(vanilla)} entities identical') + + +if __name__ == '__main__': + try: + main() + except AssertionError as error: + sys.exit(f'{NAME}: {error}') diff --git a/tools/test_server_ops_feedback_parity.py b/tools/test_server_ops_feedback_parity.py new file mode 100644 index 000000000..2dd405517 --- /dev/null +++ b/tools/test_server_ops_feedback_parity.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +"""Command feedback the operators get on a dedicated server (`[Server: ...]`), against vanilla's. + +CommandSourceStack.broadcastToAdmins: a command's success that vanilla sends with `broadcast` goes, gray and +italic as `[name: message]`, to every other operator while `send_command_feedback` is on, including the +console's own commands when `broadcast-console-to-ops` is (DedicatedServer.shouldInformAdmins). + +A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat +world vanilla generated first, with the same server.properties and Alice and Bob as operators. LocatorBarClient +joins them both (players made of vanilla's protocol code) and records the system chat each receives while, step +by step, the console sets the time, asks for the difficulty (a query, told to nobody), whitelists a player, +deops Bob (who stops hearing of it) and ops him again, turns `send_command_feedback` off and on and saves, and +Alice runs a command herself (Bob hears of it as an operator). Then again with `broadcast-console-to-ops=false`. +Each player's chat in each step is compared exactly. +""" +import os +from pathlib import Path +import platform +import shutil +import subprocess +import sys +import time + +try: + from . import lab, test_rust_parity as base + from .test_dedicated_server_parity import Server + from .test_locator_bar_parity import generate_world, server_dir +except ImportError: + import lab + import test_rust_parity as base + from test_dedicated_server_parity import Server + from test_locator_bar_parity import generate_world, server_dir + +NAME = 'server-ops-feedback-parity' +# (label, what the console does, what the players do). +BROADCAST = [ + ('console-time', ['time set 1000'], []), + ('console-query', ['difficulty'], []), + ('console-whitelist', ['whitelist add Alice'], []), + ('console-deop', ['deop Bob'], []), + ('bob-not-op', ['time set 2000'], []), + ('alice-bob-not-op', [], ['cmd Alice time set 3000']), + ('console-op', ['op Bob'], []), + ('alice-bob-op', [], ['cmd Alice time set 4000']), + ('feedback-off', ['gamerule send_command_feedback false'], []), + ('console-feedback-off', ['time set 5000'], []), + ('feedback-on', ['gamerule send_command_feedback true'], []), + ('console-save', ['save-all'], []), +] +QUIET = [ + ('console-time', ['time set 1000'], []), + ('console-whitelist', ['whitelist add Alice'], []), + ('alice', [], ['cmd Alice time set 3000']), +] +CASES = {'broadcast': ({}, BROADCAST), 'quiet': ({'broadcast-console-to-ops': 'false'}, QUIET)} +STEP_SECONDS = 2.0 + + +def run_side(label, case, server_command, client_command, build, world): + properties, script = CASES[case] + directory = build / label / case + directory.parent.mkdir(parents=True, exist_ok=True) + port = server_dir(directory, world) + with (directory / 'server.properties').open('a', encoding='iso-8859-1') as f: + f.writelines(f'{k}={v}\n' for k, v in properties.items()) + out = build / f'{label}-{case}.txt' + out.unlink(missing_ok=True) + server = Server(server_command, directory, f'{label}-{case}') + try: + server.wait_for(r'Done \(') + with (build / f'{label}-{case}-client.log').open('w') as log: + client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)], + cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, + text=True) + + def tell(line): + client.stdin.write(line + '\n') + client.stdin.flush() + try: + for name in ('Alice', 'Bob'): + tell(f'join {name}') + server.wait_for(rf'{name} joined the game', timeout=120) + time.sleep(STEP_SECONDS) + tell('chat on') + for step, console, actions in script: + tell(f'step {step}') + for command in console: + server.console(command) + for action in actions: + tell(action) + time.sleep(STEP_SECONDS) + tell('end') + client.wait(timeout=60) + finally: + if client.poll() is None: + client.kill() + finally: + server.stop() + if not out.exists(): + raise AssertionError(f'{label} {case}: the client wrote no transcript (see {build}/{label}-{case}-client.log)') + lines = out.read_text(encoding='utf-8').splitlines() + errors = [l for l in lines if ' error ' in f' {l} ' or 'disconnected' in l] + return [f'{case} {l}' for l in lines if l.split(' ', 2)[2:3] and l.split(' ', 2)[2].startswith('chat ')], errors + + +def main(): + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / NAME + build.mkdir(parents=True, exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java' + classes = build / 'classes' + shutil.rmtree(classes, ignore_errors=True) + classes.mkdir() + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', + lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], + cwd=lab.ROOT, check=True, capture_output=True) + subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + check=True, capture_output=True) + import json + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], + cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] + horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] + client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient'] + + world = generate_world(vanilla_server, build) + sides = {'vanilla': ([], []), 'horizon': ([], [])} + for case in CASES: + for label, command in [('vanilla', vanilla_server), ('horizon', horizon_server)]: + lines, errors = run_side(label, case, command, client, build, world) + sides[label][0].extend(lines) + sides[label][1].extend(errors) + (vanilla, vanilla_errors), (horizon, horizon_errors) = sides['vanilla'], sides['horizon'] + (build / 'vanilla.txt').write_text('\n'.join(vanilla) + '\n', encoding='utf-8') + (build / 'horizon.txt').write_text('\n'.join(horizon) + '\n', encoding='utf-8') + errors = vanilla_errors + horizon_errors + if errors or vanilla != horizon: + import difflib + diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=1, lineterm='')) + raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n' + + '\n'.join(errors[:10]) + '\n' + diff[:6000]) + if sum('[Server' in l or 'chat.type.admin' in l for l in vanilla) < 5: + raise AssertionError(f'vanilla sent the operators too little: the script did not run (see {build})') + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), + java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], + lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'), + scope='The system chat two operators get on a dedicated server while the console and one of them run ' + 'commands: broadcastToAdmins for the console (broadcast-console-to-ops on and off) and a player, ' + 'queries, deop and op, send_command_feedback off and on, and save-all.')) + print(f'server ops feedback: {len(vanilla)} chat lines identical') + + +if __name__ == '__main__': + try: + main() + except AssertionError as error: + sys.exit(f'{NAME}: {error}') diff --git a/tools/test_server_player_targets_parity.py b/tools/test_server_player_targets_parity.py new file mode 100644 index 000000000..f8f457143 --- /dev/null +++ b/tools/test_server_player_targets_parity.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python3 +"""Commands acting on other players of a dedicated server, against vanilla's, seen by vanilla clients. + +EntitySelector.findPlayers and EntityArgument's player targets: names, UUIDs, `@a`, `@p`, `@r`, `@s` under +`execute as`, from the console and from an operator, with `give`, `gamemode`, `tp` (to a place, to a player, with a +rotation, and into another level by `execute in`, the console's own level or the destination's), `effect give` and +`effect clear`, and `kill`. + +A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat world +vanilla generated first, with Alice and Bob as operators in creative. LocatorBarClient joins them both (players made +of vanilla's protocol code) and records, step by step, the system chat each receives and what the server changes +about it: game mode events, teleports, inventory slots, effects, its death (with the death message), the other +players it is sent or loses and the levels it respawns into. Each player's lines in each step are compared exactly, +in sorted order (the packets of one step may leave in another order within the tick). The locator bar's waypoints +and what a death does besides its messages are left to their own harnesses. +""" +import hashlib +import os +from pathlib import Path +import platform +import shutil +import subprocess +import sys +import time +import uuid as uuidlib + +try: + from . import lab, test_rust_parity as base + from .test_dedicated_server_parity import Server + from .test_locator_bar_parity import generate_world, server_dir +except ImportError: + import lab + import test_rust_parity as base + from test_dedicated_server_parity import Server + from test_locator_bar_parity import generate_world, server_dir + +NAME = 'server-player-targets-parity' +NETHER, OVERWORLD = 'minecraft:the_nether', 'minecraft:overworld' + + +def offline_uuid(name): + """UUIDUtil.createOfflinePlayerUUID.""" + digest = bytearray(hashlib.md5(f'OfflinePlayer:{name}'.encode()).digest()) + digest[6] = (digest[6] & 0x0F) | 0x30 + digest[8] = (digest[8] & 0x3F) | 0x80 + return str(uuidlib.UUID(bytes=bytes(digest))) + + +# (label, what the console does, what the players do). +SCRIPT = [ + ('console-give', ['give Bob minecraft:diamond 3'], []), + ('console-give-all', ['give @a minecraft:apple'], []), + ('alice-give-bob', [], ['cmd Alice give Bob minecraft:stick 2']), + ('console-give-uuid', [f'give {offline_uuid("Bob")} minecraft:iron_ingot'], []), + ('console-give-nearest', ['give @p minecraft:emerald'], []), + ('alice-give-random', [], ['cmd Alice give @r[name=Bob] minecraft:gold_ingot']), + ('console-gamemode', ['gamemode survival Bob'], []), + ('alice-gamemode-bob', [], ['cmd Alice gamemode creative Bob']), + ('alice-gamemode-all', [], ['cmd Alice gamemode adventure @a']), + ('console-gamemode-back', ['gamemode creative @a'], []), + ('console-tp', ['tp Bob 8.5 -60 8.5'], []), + ('alice-tp-bob-to-alice', [], ['cmd Alice tp Bob Alice']), + ('console-tp-rotation', ['tp Bob 4.5 -60 0.5 90 10'], []), + ('bob-tp-self', [], ['cmd Bob tp @s 6.5 -60 0.5']), + ('console-execute-as', ['execute as Bob run tp @s ~ ~ ~2'], []), + ('console-execute-at', ['execute at Bob run tp Alice ~1 ~ ~'], []), + ('alice-execute-as-all', [], ['cmd Alice execute as @a run give @s minecraft:bread']), + ('console-effect', ['effect give Bob minecraft:speed 30 1'], []), + ('alice-effect-all', [], ['cmd Alice effect give @a minecraft:haste infinite']), + ('console-effect-clear', ['effect clear Bob'], []), + ('alice-effect-clear-all', [], ['cmd Alice effect clear @a minecraft:haste']), + ('console-nether', [f'execute in {NETHER} run tp Bob 0.5 100 0.5'], []), + ('console-tp-home', ['tp Bob 4.5 -60 0.5'], []), + ('alice-nether', [], [f'cmd Alice execute in {NETHER} run tp Bob 0.5 100 0.5']), + ('console-tp-to-alice', ['tp Bob Alice'], []), + ('alice-kill-missing', [], ['cmd Alice kill Carol']), + ('console-kill', ['kill Bob'], []), +] +# What the players' locator bars show has its own harness (test_locator_bar_parity), and what a death does +# besides its messages (drops, the body leaving) the player combat ones: here only the messages of `kill`. +WAYPOINTS = ('track ', 'untrack ', 'update ') +DEATH_STEP = 'step=console-kill' +STEP_SECONDS = 2.5 + + +def run_side(label, server_command, client_command, build, world): + directory = build / label + port = server_dir(directory, world) + out = build / f'{label}.txt' + out.unlink(missing_ok=True) + server = Server(server_command, directory, label) + try: + server.wait_for(r'Done \(') + with (build / f'{label}-client.log').open('w') as log: + client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)], + cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, + text=True) + + def tell(line): + client.stdin.write(line + '\n') + client.stdin.flush() + try: + for name, x in (('Alice', 0.5), ('Bob', 4.5)): + tell(f'join {name}') + server.wait_for(rf'{name} joined the game', timeout=120) + tell(f'fly {name} on') + tell(f'cmd {name} tp @s {x} -60 0.5 0 0') + time.sleep(STEP_SECONDS) + for flag in ('chat', 'state', 'players'): + tell(f'{flag} on') + for step, console, actions in SCRIPT: + tell(f'step {step}') + for command in console: + server.console(command) + for action in actions: + tell(action) + time.sleep(STEP_SECONDS) + for name in ('Alice', 'Bob'): + tell(f'still {name}') + tell('end') + client.wait(timeout=60) + finally: + if client.poll() is None: + client.kill() + finally: + server.stop() + if not out.exists(): + raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)') + lines = out.read_text(encoding='utf-8').splitlines() + errors = [l for l in lines if ' error ' in f' {l} ' or 'disconnected' in l] + steps = {} + for line in lines: + who, step, rest = line.split(' ', 2) + # At the death, Alice picks up Bob's drops (and gets their advancements) in vanilla. + death_side = step == DEATH_STEP and (not rest.startswith(('chat ', 'killed ')) + or 'chat.type.advancement' in rest) + if rest.startswith(WAYPOINTS) or death_side: + continue + if step != 'step=start': + steps.setdefault((who, step), []).append(line) + order = {f'step={s}': i for i, (s, _, _) in enumerate(SCRIPT)} + keys = sorted(steps, key=lambda k: (k[0], order.get(k[1], -1))) + return [l for k in keys for l in sorted(steps[k])], errors + + +def main(): + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / NAME + build.mkdir(parents=True, exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java' + classes = build / 'classes' + shutil.rmtree(classes, ignore_errors=True) + classes.mkdir() + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', + lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], + cwd=lab.ROOT, check=True, capture_output=True) + subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + check=True, capture_output=True) + import json + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], + cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] + horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] + client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient'] + + world = generate_world(vanilla_server, build) + vanilla, vanilla_errors = run_side('vanilla', vanilla_server, client, build, world) + horizon, horizon_errors = run_side('horizon', horizon_server, client, build, world) + (build / 'vanilla.txt').write_text('\n'.join(vanilla) + '\n', encoding='utf-8') + (build / 'horizon.txt').write_text('\n'.join(horizon) + '\n', encoding='utf-8') + errors = vanilla_errors + horizon_errors + if errors or vanilla != horizon: + import difflib + diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=1, lineterm='')) + raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n' + + '\n'.join(errors[:10]) + '\n' + diff[:8000]) + for needle in ('gamemode 0', 'minecraft:diamond x3', 'effect minecraft:speed', 'respawn ' + NETHER, + 'death.attack.genericKill'): + if not any(needle in l for l in vanilla): + raise AssertionError(f'vanilla never sent {needle!r}: the script did not run (see {build})') + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), + java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], + lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'), + scope='Commands from the console and an operator acting on another player of a dedicated server: names, ' + 'UUIDs, @a, @p, @r and @s under execute as/at, with give, gamemode, tp (place, player, rotation, ' + 'execute in, across levels), effect give and clear and kill, as the players see them.')) + print(f'server player targets: {len(vanilla)} lines identical') + + +if __name__ == '__main__': + try: + main() + except AssertionError as error: + sys.exit(f'{NAME}: {error}') diff --git a/tools/test_server_world_gen_parity.py b/tools/test_server_world_gen_parity.py index 0ad0ed25e..f55e55809 100644 --- a/tools/test_server_world_gen_parity.py +++ b/tools/test_server_world_gen_parity.py @@ -10,7 +10,10 @@ to the preset's classic ones) and `generate-structures`. Each case starts vanilla's server and Horizon's (`horizon-client --dedicated --nogui`) in a new folder, waits for `Done` and stops them. Compared exactly: the world's `data/minecraft/world_gen_settings.dat`, tag types included, and the warnings and errors logged while the world's settings are read (the `Worker-Main` lines; -the worker's number is left out). +the worker's number is left out). In a world without structures (`generate-structures=false`), also what +`locate structure` answers on the console for a village and a mineshaft (ChunkGenerator.findNearestMapStructure +finds none) and how many of the saved chunks hold structure starts or references (none: +ChunkStatusTasks.generateStructureStarts does nothing). Horizon generates the normal and flat presets only: `large_biomes`, `amplified`, `single_biome_surface` and `debug_all_block_states` aren't tested. @@ -23,6 +26,7 @@ import re import shutil import subprocess import sys +import time try: from . import anvil_dump, lab, test_rust_parity as base @@ -60,6 +64,32 @@ CASES = { 'unknown': {'level-type': 'Some Type', 'level-seed': '42'}, } WORKER = re.compile(r'\[Worker-Main-\d+/(WARN|ERROR)\]: (.*)') +LOCATE = ['locate structure #minecraft:village', 'locate structure minecraft:mineshaft'] +REPLY = re.compile(r'\]: (?:System chat: )?((?:Could not find|The nearest|Unknown|Incorrect).*)') + + +def console_reply(server, command, timeout=300): + """The first command reply the console logs after `command`.""" + start = len(server.lines) + server.console(command) + deadline = time.time() + timeout + while time.time() < deadline: + for line in server.lines[start:]: + if m := REPLY.search(line): + return m.group(1) + time.sleep(0.2) + raise AssertionError(f'no reply to {command!r} in {timeout} s:\n' + '\n'.join(server.lines[-20:])) + + +def structure_chunks(world): + """How many saved overworld chunks hold structure starts, and how many references.""" + starts = references = 0 + for region in sorted((world / 'region').glob('*.mca')): + for chunk in anvil_dump.region_chunks(region).values(): + structures = anvil_dump.plain(chunk, True).get('structures', {}) + starts += bool(structures.get('starts')) + references += bool(structures.get('References')) + return f'chunks with structure starts: {starts}, with references: {references}' def escape(value): @@ -77,11 +107,16 @@ def run_case(label, command, build, case): encoding='iso-8859-1') (directory / 'eula.txt').write_text('eula=true\n') server = Server(command, directory, f'{label}-{case}') + replies = [] try: server.wait_for(r'Done \(') + if CASES[case].get('generate-structures') == 'false': + replies = [f'{c}: {console_reply(server, c)}' for c in LOCATE] finally: server.stop() - out = [f'# {case}'] + out = [f'# {case}', *replies] + if replies: + out.append(structure_chunks(directory / 'world')) out += [f'{m.group(1)}: {m.group(2)}' for l in server.lines if (m := WORKER.search(l))] settings = anvil_dump.plain(anvil_dump.read_dat(directory / 'world/data/minecraft/world_gen_settings.dat'), True, typed=True) @@ -121,7 +156,8 @@ def main(): java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], cases=list(CASES), lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'), scope='a new dedicated-server world: level-type (flat, normal, unknown), a flat world\'s ' - 'generator-settings, generate-structures, as world_gen_settings.dat and the lines logged.')) + 'generator-settings, generate-structures, as world_gen_settings.dat and the lines logged; without ' + 'structures, locate structure\'s replies and the saved chunks\' structure starts and references.')) print(f'server world gen: {len(CASES)} cases, {len(vanilla)} lines identical') diff --git a/tools/test_tooltip_display_parity.py b/tools/test_tooltip_display_parity.py new file mode 100644 index 000000000..22b485320 --- /dev/null +++ b/tools/test_tooltip_display_parity.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +"""Compare item tooltip display visibility with the pinned vanilla client.""" +try: + from . import lab, oracle_harness as harness +except ImportError: + import lab, oracle_harness as harness + + +def cases(build): + values = [ + (False, False, False), + (False, False, True), + (False, True, True), + (True, False, False), + (True, True, False), + (True, True, True), + ] + path = build / 'cases.txt' + # Lowercase: Rust's bool parser takes only true/false (Java's parseBoolean ignores case). + path.write_text('\n'.join('\t'.join(str(v).lower() for v in row) for row in values) + '\n') + return path, len(values) + + +if __name__ == '__main__': + harness.differential( + 'tooltip-display-parity', 'VanillaTooltipDisplayOracle', 'tooltip_display_fixture', cases, + 'Diamond sword name and attribute tooltip visibility for hide_tooltip, hidden_components, and creative flags', + sources=[ + lab.ROOT / 'crates/horizon-client/src/game/stations.rs', + lab.ROOT / 'crates/horizon-client/src/item_tooltip.rs', + ], + expected_lines=6) diff --git a/tools/test_world_movement_parity.py b/tools/test_world_movement_parity.py index 8cffb456c..e01a989f5 100644 --- a/tools/test_world_movement_parity.py +++ b/tools/test_world_movement_parity.py @@ -18,18 +18,28 @@ except ImportError: def corpus(facts): def bits(v):return struct.pack('>d',float(v)).hex() - def row(state,delta=(1,-0.08,0),step=0.6,grounded=True,context=2,offset=0,fail=-1,extra=(),entities=(),border=None): + def row(state,delta=(1,-0.08,0),step=0.6,grounded=True,context=2,offset=0,fail=-1,extra=(),entities=(),border=None,box=None): blocks=[[x+offset,-1,z,facts['defaults']['minecraft:stone']] for x in range(-2,4) for z in range(-2,3)] blocks.append([offset,0,0,state]);blocks.extend(extra) return dict(chunks=[[x,z] for x in range((offset>>4)-1,(offset>>4)+2) for z in range(-1,2)], blocks=blocks,context=context,y=bits(0),entities=[0,0],fail=fail,limit=100000,suffocating=False, - box=list(map(bits,[-0.6+offset,0,0.2,-0.2+offset,1.8,0.8])), + box=list(map(bits,box if box is not None else [-0.6+offset,0,0.2,-0.2+offset,1.8,0.8])), movement=dict(delta=list(map(bits,delta)),step=bits(step),grounded=grounded, entities=[list(map(bits,b)) for b in entities],border=None if border is None else list(map(bits,border)))) states=facts['states'] for state in range(len(states)): yield row(state,context=state%4) defaults=facts['defaults'] + falling_surfaces=[('minecraft:stone_slab',0.5),('minecraft:oak_stairs',1.0),('minecraft:snow',0.125), + ('minecraft:oak_fence',1.5),('minecraft:iron_bars',1.0),('minecraft:soul_sand',0.875), + ('minecraft:farmland',0.9375)] + for block_id,top in falling_surfaces: + state=defaults[block_id] + size=struct.unpack('>f',struct.pack('>f',0.98))[0] + half=size/2 + bottom=top+0.1 + box=[0.5-half,bottom,0.5-half,0.5+half,bottom+size,0.5+half] + yield row(state,delta=(0,-0.25,0),step=0,grounded=False,context=2,box=box) obstacles=[i for i,s in enumerate(states) if s['id'] in ['minecraft:oak_stairs','minecraft:stone_slab', 'minecraft:snow','minecraft:scaffolding','minecraft:powder_snow','minecraft:water', 'minecraft:shulker_box','minecraft:moving_piston','minecraft:piston','minecraft:soul_sand', @@ -114,7 +124,7 @@ def main(): 'definition_counts':dict(collections.Counter(definitions.values())), 'native_chunk_storage':'ProtoChunk', 'rust_chunk_storage':'TerrainChunk', 'fixtures':count, 'sources_sha256':tested, 'fixtures_sha256':fixtures, 'rust_output_sha256':lab.digest(build/'rust.txt', 'sha256'), 'references':references, - 'scope':'Actual native Entity.collide executes initial collision and step-up decisions over BlockCollisions, registered block shapes and resident ProtoChunk sections. Rust combines owned/fallible step resolution with registry-bound TerrainChunk scanning. All registered states are used as obstacles, plus step heights, falling/grounded motion, zero and underflow motion, partial blocks, fluids, dynamic blocks, ceilings, chunk boundaries and query failures. Entity collider lists and world-border proximity/shape are controlled inputs; query order and reuse, shape collection and resulting displacement are compared. Contexts are deliberately supplied empty/position/placement snapshots in both worlds. This does not establish entity broad-phase selection, actual world-border proximity, travel/gravity/velocity or grounded side effects, experimental minecarts or a playable game.'} + 'scope':'Actual native Entity.collide executes initial collision and step-up decisions over BlockCollisions, registered block shapes and resident ProtoChunk sections. Rust combines owned/fallible step resolution with registry-bound TerrainChunk scanning. All registered states are used as obstacles, plus step heights, falling/grounded motion, zero and underflow motion, partial blocks including exact falling-block-sized boxes over slabs, stairs, snow, fences, iron bars, soul sand and farmland, fluids, dynamic blocks, ceilings, chunk boundaries and query failures. Entity collider lists and world-border proximity/shape are controlled inputs; query order and reuse, shape collection and resulting displacement are compared. Contexts are deliberately supplied empty/position/placement snapshots in both worlds. This does not establish entity broad-phase selection, actual world-border proximity, travel/gravity/velocity or grounded side effects, experimental minecarts or a playable game.'} lab.write_json(report_path, report);print(f'Scoped world movement parity passed: {report_path}', flush=True) diff --git a/tools/vanilla_client.py b/tools/vanilla_client.py index 88c6aba5b..41ae38556 100644 --- a/tools/vanilla_client.py +++ b/tools/vanilla_client.py @@ -5,6 +5,10 @@ servers: --offlineDeveloperMode) and optionally join a server straight away vscreen start python3 tools/vanilla_client.py --name Guest --join localhost:25565 +On Linux (x86_64) and on macOS (Apple silicon, from the logged-in screen session), from the files +tools/lab.py prepared on that machine. On macOS vsync is off: with it on, a window nobody can see (a +locked session, or covered) blocks in SDL_GL_SwapWindow and the client stops before it joins. + Sound goes to OpenAL's null backend. The game directory gets an options.txt that skips the first-run screens, keeps the game running unfocused and renders few chunks, so a harness can drive it with vscreen keys. @@ -21,6 +25,9 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[1] GAME = ROOT / ".local/minecraft/26.3" +MAC = sys.platform == "darwin" +# The natives of this machine's platform, and the shared libraries in them. +NATIVES, LIBRARY_SUFFIX = ("natives-macos-arm64.jar", ".dylib") if MAC else ("natives-linux.jar", ".so") OPTIONS = { "onboardAccessibility": "false", @@ -40,6 +47,8 @@ OPTIONS = { "onlyShowSecureChat": "false", "rawMouseInput": "false", } +if sys.platform == "darwin": + OPTIONS["enableVsync"] = "false" def offline_uuid(name): @@ -49,10 +58,12 @@ def offline_uuid(name): return uuid.UUID(bytes=bytes(digest)) -def linux_library(path): +def host_library(path): name = Path(path).name if "natives-" in name: - return name.endswith("natives-linux.jar") + return name.endswith(NATIVES) + if MAC: + return "netty-transport-native" not in name or "linux" not in name if "netty-transport-native" in name and ("osx" in name or "aarch_64" in name): return False return "java-objc-bridge" not in name @@ -60,18 +71,18 @@ def linux_library(path): def classpath(): prepared = json.loads((GAME / "prepared.json").read_text()) - jars = [ROOT / p for p in prepared["libraries"]["client"] if linux_library(p)] + jars = [ROOT / p for p in prepared["libraries"]["client"] if host_library(p)] return [GAME / "jars/client.jar", *jars] def extract_natives(jars, target): target.mkdir(parents=True, exist_ok=True) for jar in jars: - if not jar.name.endswith("natives-linux.jar"): + if not jar.name.endswith(NATIVES): continue with zipfile.ZipFile(jar) as archive: for name in archive.namelist(): - if name.endswith(".so") and "arm" not in name and "aarch" not in name: + if name.endswith(LIBRARY_SUFFIX) and (MAC or ("arm" not in name and "aarch" not in name)): out = target / Path(name).name if not out.exists(): out.write_bytes(archive.read(name)) @@ -105,7 +116,7 @@ def command(args): extract_natives(jars, natives) assets = args.assets or (args.game_dir / "assets") (assets / "indexes").mkdir(parents=True, exist_ok=True) - cmd = ["java", f"-Xmx{args.heap}", "-XX:StackShadowPages=32", + cmd = ["java", f"-Xmx{args.heap}", *(["-XstartOnFirstThread"] if MAC else []), "-XX:StackShadowPages=32", "--enable-native-access=ALL-UNNAMED", "--add-exports", "java.base/jdk.internal.misc=ALL-UNNAMED", f"-Djava.library.path={natives}", f"-Dorg.lwjgl.system.SharedLibraryExtractPath={natives}", diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 05b84553b..28b591626 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -6,6 +6,10 @@ //! them to its own), and PLAY.txt. It holds none of Minecraft's files: players prepare those //! from their own copy. .github/workflows/release.yml makes the release folders with it. //! +//! `package-server ENGINE OUTDIR`: a server folder (docs/server.md): the server build of the game +//! (`cargo build --release -p horizon-client --no-default-features`, without sound or controllers) +//! as horizon-engine, with horizon-prepare and horizon-server from beside it and the same sources. +//! //! `tokens`: writes `website/src/tokens.css`, the design tokens of `crates/horizon-theme` as CSS //! custom properties (a horizon-theme test fails when the file is out of date). //! @@ -17,7 +21,7 @@ use std::fs; use std::path::{Component, Path, PathBuf}; use std::process::{Command, ExitCode}; -const USAGE: &str = "usage: cargo run -p xtask -- package BINARY OUTDIR | tokens | icons"; +const USAGE: &str = "usage: cargo run -p xtask -- package BINARY OUTDIR | package-server ENGINE OUTDIR | tokens | icons"; /// What the release folder takes from the repository at HEAD, as `git archive` writes it. const ARCHIVED: [&str; 5] = [ @@ -34,10 +38,16 @@ const ARCHIVED: [&str; 5] = [ /// (docs/server.md). const TOOLS: [&str; 3] = ["horizon-ctl", "horizon-prepare", "horizon-server"]; +/// The programs beside the engine in a server folder. +const SERVER_TOOLS: [&str; 2] = ["horizon-prepare", "horizon-server"]; + fn main() -> ExitCode { let args: Vec<String> = std::env::args().skip(1).collect(); let result = match args.as_slice() { [task, binary, out] if task == "package" => package(Path::new(binary), Path::new(out)), + [task, engine, out] if task == "package-server" => { + package_server(Path::new(engine), Path::new(out)) + } [task] if task == "tokens" => tokens(), [task] if task == "icons" => icons(), _ => Err(USAGE.to_string()), @@ -209,6 +219,21 @@ fn icons() -> Result<(), String> { } fn package(binary: &Path, out: &Path) -> Result<(), String> { + let repo = new_folder(out)?; + copy_into(binary, out)?; + copy_beside(binary, &TOOLS, out)?; + let play = repo.join("packaging/PLAY.txt"); + copy(&play, &out.join("PLAY.txt")) +} + +fn package_server(engine: &Path, out: &Path) -> Result<(), String> { + new_folder(out)?; + copy(engine, &out.join(program_name(engine, "horizon-engine")))?; + copy_beside(engine, &SERVER_TOOLS, out) +} + +/// `OUT`, emptied, with the sources the release folders take (`ARCHIVED`); the repository's path. +fn new_folder(out: &Path) -> Result<PathBuf, String> { let top = git( Path::new(env!("CARGO_MANIFEST_DIR")), &["rev-parse", "--show-toplevel"], @@ -224,15 +249,25 @@ fn package(binary: &Path, out: &Path) -> Result<(), String> { let mut args = vec!["archive", "--format=tar", "HEAD"]; args.extend(ARCHIVED); extract(&git(&repo, &args)?, out)?; - copy_into(binary, out)?; - let exe = binary.extension().is_some_and(|e| e == "exe"); - for tool in TOOLS { - let name = if exe { - format!("{tool}.exe") - } else { - tool.to_string() - }; - let path = binary.parent().unwrap_or(Path::new("")).join(name); + Ok(repo) +} + +/// `name`, with `.exe` when `program` has it. +fn program_name(program: &Path, name: &str) -> String { + if program.extension().is_some_and(|e| e == "exe") { + format!("{name}.exe") + } else { + name.to_string() + } +} + +/// Copies `tools`, built beside `program`, into `out`. +fn copy_beside(program: &Path, tools: &[&str], out: &Path) -> Result<(), String> { + for tool in tools { + let path = program + .parent() + .unwrap_or(Path::new("")) + .join(program_name(program, tool)); if !path.is_file() { return Err(format!( "{} is missing; build it too: cargo build --release -p horizon-client --bins -p horizon-prepare -p horizon-server", @@ -241,8 +276,7 @@ fn package(binary: &Path, out: &Path) -> Result<(), String> { } copy_into(&path, out)?; } - let play = repo.join("packaging/PLAY.txt"); - copy(&play, &out.join("PLAY.txt")) + Ok(()) } /// `cp FILE DIR/`.