diff --git a/.dockerignore b/.dockerignore index 417a1867c..458330c93 100644 --- a/.dockerignore +++ b/.dockerignore @@ -2,7 +2,6 @@ target/ .local/ **/node_modules/ -website/ benchmarks/ packs/ mods/ diff --git a/.gitattributes b/.gitattributes index 358aeae7a..f9e1922d7 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,5 +2,5 @@ # where Git for Windows' core.autocrlf would check them out with CRLF. docs/launcher-commands.md text eol=lf docs/horizon-ctl-commands.md text eol=lf -website/src/tokens.css text eol=lf +crates/horizon-theme/tokens.css text eol=lf docs/api/*-reference.md text eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eff82fa99..b2fd9fa48 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -73,6 +73,42 @@ jobs: run: | cargo +stable test --workspace --lib --bins --tests --features horizon-client/mods,horizon-mods/pack cargo +stable test --workspace --doc --features horizon-client/mods,horizon-mods/pack + # The launcher is its own workspace (launcher/Cargo.toml), so verify's cargo runs never build it. A pull request that + # changes it or a crate it builds is checked here, and so is every push to main: two pull requests can each pass + # alone and break it together (#2059 and the registry ratings did, 2026-10-26). + launcher: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Does this pull request change the launcher or a crate it builds? + if: github.event_name == 'pull_request' + id: launcher + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: python3 tools/ci/rust_changes.py --launcher "$BASE_SHA" "$HEAD_SHA" >> "$GITHUB_OUTPUT" + - name: Install Rust and the headers GPUI links against + if: steps.launcher.outputs.required != 'false' + run: | + sudo apt-get update && sudo apt-get install -y --no-install-recommends libxkbcommon-x11-dev libwayland-dev \ + libx11-xcb-dev libfontconfig-dev libvulkan-dev libasound2-dev libudev-dev + rustup toolchain install stable --profile minimal --component rustfmt --component clippy + - uses: Swatinem/rust-cache@v2 + if: steps.launcher.outputs.required != 'false' + with: + workspaces: launcher + shared-key: launcher + save-if: ${{ github.ref == 'refs/heads/main' }} + - name: Check the launcher's formatting, lint and tests + if: steps.launcher.outputs.required != 'false' + working-directory: launcher + run: | + cargo +stable fmt --check + cargo +stable clippy --all-targets --locked -- -D warnings + cargo +stable test --locked --lib # Most pull requests leave the harnesses to parity-main, which runs them on main a batch of merges at a time # (.github/workflows/parity-main.yml; releases wait for it). A pull request still runs them itself when it changes # a harness, an oracle, a probe or the runner, or carries the run-parity label (run-parity.yml, when it is added). @@ -108,6 +144,7 @@ jobs: with: base: ${{ github.event.pull_request.base.sha }} head: ${{ github.event.pull_request.head.sha }} + full: ${{ contains(github.event.pull_request.labels.*.name, 'full-parity') }} # Horizon never downloads the game. These jobs need a self-hosted Linux runner # (label horizon-game) holding the maintainer's own copy: the official launcher's # game directory in HORIZON_MINECRAFT_DIR and the pinned server jar in diff --git a/.github/workflows/parity-main.yml b/.github/workflows/parity-main.yml index c47005ab0..4840b98be 100644 --- a/.github/workflows/parity-main.yml +++ b/.github/workflows/parity-main.yml @@ -25,8 +25,8 @@ jobs: parity-main: # A Mac mini runner of its own (ludovics-mac-mini-2 holds only this label since 2026-10-26): behind PR parity jobs # this run waited 2 h while every merge replaced the pending one, and on the release runner a release then waited - # behind the next run. PR parity jobs have ludovics-mac-mini and the desktop. Not the desktop: a job slowed down - # because the maintainer came back could time out, and a failure here bisects and comments on merges. + # behind the next run. PR parity jobs have ludovics-mac-mini and playhorizon. Not playhorizon: its 4 CPUs + # make a core-crate run several times longer, and a failure here bisects and comments on merges. runs-on: [self-hosted, macOS, horizon-parity-main] timeout-minutes: 240 # a core-crate batch reruns ~300 harnesses (~60-90 min), a bisect a few rounds of the failures steps: @@ -48,6 +48,9 @@ jobs: GH_TOKEN: ${{ github.token }} run: echo "sha=$(python3 tools/parity_main.py base)" >> "$GITHUB_OUTPUT" - name: The harnesses the merges since then can affect + id: harnesses + # A failure here is judged by the next step: the run passes when every failed harness passes again at HEAD. + continue-on-error: true env: PARITY_HOSTS: '' BASE_SHA: ${{ steps.base.outputs.sha }} @@ -55,8 +58,8 @@ jobs: echo "Merges since ${BASE_SHA}:" git log --first-parent --format=' %h %s' "$BASE_SHA..HEAD" python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400 - - name: The merge that broke them - if: failure() + - name: A flake, or the merge that broke them + if: steps.harnesses.outcome == 'failure' env: GH_TOKEN: ${{ github.token }} PARITY_HOSTS: '' @@ -65,7 +68,7 @@ jobs: rm -rf .local/parity-main-logs && cp -R .local/parity-runner/logs .local/parity-main-logs 2>/dev/null || true python3 tools/parity_main.py bisect "$BASE_SHA" --comment - name: Logs of the failed harnesses - if: failure() + if: steps.harnesses.outcome == 'failure' uses: actions/upload-artifact@v4 with: name: parity-main-logs diff --git a/.github/workflows/parity.yml b/.github/workflows/parity.yml index 1fc31d8cb..c850c17aa 100644 --- a/.github/workflows/parity.yml +++ b/.github/workflows/parity.yml @@ -1,6 +1,6 @@ name: parity -# The vanilla harnesses a pull request's changes can affect, on the Mac mini's runner, which holds the maintainer's -# own Minecraft files (Horizon never downloads the game). Called by ci.yml for pull requests from this repository +# The vanilla harnesses a pull request's changes can affect, on the Mac mini's runner or playhorizon's, which hold the +# maintainer's own Minecraft files (Horizon never downloads the game). Called by ci.yml for pull requests from this repository # and by run-parity.yml when a maintainer labels a fork's pull request run-parity. See docs/release-flow.md. on: workflow_call: @@ -13,6 +13,13 @@ on: description: The commit to check out and test type: string required: true + full: + description: >- + The pull request carries the full-parity label (a change every harness reaches, such as a crate split): it + runs on playhorizon's runner only, so the Mac mini's runners stay free for the others. While that runner is + busy the job waits for it. + type: boolean + default: false permissions: contents: read env: @@ -21,40 +28,53 @@ env: jobs: parity: - runs-on: [self-hosted, horizon-game] - timeout-minutes: 120 # a change to core crates reruns ~300 harnesses: ~60-90 min on the Mac mini + runs-on: ${{ inputs.full && fromJSON('["self-hosted", "horizon-game", "playhorizon"]') || fromJSON('["self-hosted", "horizon-game"]') }} + # A change to core crates reruns ~350 harnesses: ~60-90 min on the Mac mini; on playhorizon (4 of its 8 vCPUs, 4 + # harnesses at a time) up to a few hours, and any pull request's job may land there. + timeout-minutes: ${{ inputs.full && 360 || 180 }} steps: - uses: actions/checkout@v4 with: - # The commit the event names: a fork's later pushes need another run-parity label. + # The commit the event names: a fork's later pushes need another run-parity label. The next step merges + # main into it. ref: ${{ inputs.head }} fetch-depth: 0 persist-credentials: false # Keeps .local/ (parity state, probe builds, oracle results) and target/ between runs. clean: false + - name: The head merged into main (what merging it would land) + id: merge + env: + BASE_SHA: ${{ inputs.base }} + HEAD_SHA: ${{ inputs.head }} + run: | + # Harness fixes and game fixes that reached main since the branch was made then apply here too: a head + # tested alone failed harnesses already fixed on main (server_knockback before #2114, mob_ai's heap before + # #2270, save_roundtrip before #2212). Selection then compares with this main, so it sees only the pull + # request's own changes. A head that conflicts with main is tested alone. + set -euo pipefail + git merge --abort 2>/dev/null || true + git fetch -q --no-tags origin +refs/heads/main:refs/remotes/origin/main + main=$(git rev-parse origin/main) + if git -c user.name=parity -c user.email=parity@localhost merge -q --no-edit --no-ff "$main" >/dev/null 2>&1; then + echo "base=$main" >> "$GITHUB_OUTPUT" + echo "Tested: head ${HEAD_SHA:0:9} merged into main ${main:0:9}" | tee -a "$GITHUB_STEP_SUMMARY" + else + git merge --abort + echo "base=$BASE_SHA" >> "$GITHUB_OUTPUT" + echo "::warning::head ${HEAD_SHA:0:9} conflicts with main ${main:0:9}: tested alone, without main's fixes" + echo "Tested: head ${HEAD_SHA:0:9} alone (it conflicts with main ${main:0:9})" | tee -a "$GITHUB_STEP_SUMMARY" + fi - uses: dtolnay/rust-toolchain@stable - name: Tools from the runner run: bash tools/ci/runner-env.sh - name: Vanilla data, and resources prepared by this preparer - env: - BASE_SHA: ${{ inputs.base }} - run: | - # main's script: one written before a fix to it left a real .local/horizon-client without sounds.json on - # the runner, and every later job there failed `subtitle`. A branch that changes the script runs its own. - set -euo pipefail - if git rev-parse --verify -q origin/main >/dev/null \ - && git diff --quiet "$(git merge-base "$BASE_SHA" HEAD)" HEAD -- tools/ci/vanilla-data.sh; then - git show origin/main:tools/ci/vanilla-data.sh > "$RUNNER_TEMP/vanilla-data.sh" - bash "$RUNNER_TEMP/vanilla-data.sh" - else - bash tools/ci/vanilla-data.sh - fi + run: bash tools/ci/vanilla-data.sh - name: The prepared output is the one the preparer's OUTPUT_VERSION says env: - BASE_SHA: ${{ inputs.base }} + BASE_SHA: ${{ steps.merge.outputs.base }} run: | - # The job runs main's workflow on the head's files: a head made before OUTPUT_VERSION (#1947) has neither - # the tool nor the number, so there is nothing to check. + # A head made before OUTPUT_VERSION (#1947) that conflicts with main has neither the tool nor the number. if [ ! -f tools/prepare_output.py ] || ! grep -q OUTPUT_VERSION crates/horizon-prepare/src/lib.rs; then echo "This head's preparer has no OUTPUT_VERSION: nothing to check" exit 0 @@ -65,47 +85,8 @@ jobs: - name: The harnesses this change can affect env: PARITY_HOSTS: '' - BASE_SHA: ${{ inputs.base }} - run: | - # main's selection (tools/parity.py --changed --list with main's parity.py and parity_reach.py), so a - # branch made before a better selection landed gets it too; the head's own runner then runs those - # harnesses. A branch that changes the selection itself selects with its own code. - set -euo pipefail - own() { python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400; } # world_spawn takes ~1480 s on a busy runner - fork_point=$(git merge-base "$BASE_SHA" HEAD) - if ! git rev-parse --verify -q origin/main >/dev/null || ! git diff --quiet "$fork_point" HEAD -- tools/parity.py tools/parity_reach.py; then - own - exit - fi - had_reach=$(git ls-files tools/parity_reach.py) - git show origin/main:tools/parity.py > tools/parity.py - git show origin/main:tools/parity_reach.py > tools/parity_reach.py - status=0 - python3 tools/parity.py --changed "$BASE_SHA" --list > .local/parity-selection.txt || status=$? - git checkout -- tools/parity.py - if [ -n "$had_reach" ]; then git checkout -- tools/parity_reach.py; else rm -f tools/parity_reach.py; fi - cat .local/parity-selection.txt - if [ "$status" != 0 ]; then - echo "main's selection failed: the head's own selection runs" - own - exit - fi - names=$(sed '$d' .local/parity-selection.txt | grep -E '^[A-Za-z0-9_#]+$' || true) - # The summary line says how many would run: a count that doesn't match the names read (a format change) - # must not let the job pass untested. - expected=$(tail -1 .local/parity-selection.txt | sed -nE 's/^([0-9]+) of [0-9]+ harnesses would run$/\1/p') - count=$(printf '%s' "$names" | grep -c . || true) - if [ -z "$expected" ] || [ "$expected" != "$count" ]; then - echo "main's selection listed $count names, its summary says '${expected:-?}': the head's own selection runs" - own - exit - fi - if [ "$count" = 0 ]; then - echo "Nothing to run." - exit 0 - fi - # shellcheck disable=SC2086 - python3 tools/parity.py $names --timeout 2400 + BASE_SHA: ${{ steps.merge.outputs.base }} + run: python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400 # world_spawn takes ~1480 s on a busy runner - name: Logs of the failed harnesses if: failure() uses: actions/upload-artifact@v4 diff --git a/.github/workflows/run-parity.yml b/.github/workflows/run-parity.yml index a2b8e3291..9089a9a09 100644 --- a/.github/workflows/run-parity.yml +++ b/.github/workflows/run-parity.yml @@ -22,3 +22,4 @@ jobs: with: base: ${{ github.event.pull_request.base.sha }} head: ${{ github.event.pull_request.head.sha }} + full: ${{ contains(github.event.pull_request.labels.*.name, 'full-parity') }} diff --git a/AGENTS.md b/AGENTS.md index dcd4ca595..489a1466b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,8 @@ Feature → files → harness for the most-changed areas: [docs/architecture.md] `tools/check_public_tree.py` rejects them; `git config core.hooksPath .githooks` runs it on commit. - **Keep your runs away from real player data.** Any game or launcher you start gets fresh `mktemp -d` folders in `HORIZON_HOME` (the game's data), `HORIZON_LAUNCHER_HOME`, `XDG_DATA_HOME` and - `XDG_CONFIG_HOME`, plus `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` and `HORIZON_NO_AUDIO=1`. Never write to + `XDG_CONFIG_HOME`, plus `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` and `HORIZON_NO_AUDIO=1`, and, for the + launcher, `HORIZON_LAUNCHER_TRASH` and `HORIZON_LAUNCHER_CLIPBOARD` pointing into the scratch home. Never write to `~/.local/share/{applications,horizon,horizon-launcher}` or `~/.local/bin`. - **Mark what an agent posts.** A PR body starts with a line naming whose agent opened it and with what. Ludovic's agents write `> 🤖 Opened by Ludovic's AI agent (Claude), not by Ludovic himself.`, and a @@ -34,7 +35,9 @@ Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-se | Crate | Owns | |---|---| -| `horizon-client` | The game: a lib (`src/lib.rs`, ~190 flat modules) and the bin (`src/main.rs` → `game.rs` + `game/`), plus `horizon-ctl` (`src/bin/horizon-ctl/`). Also the dedicated server (`--dedicated`) | +| `horizon-client` | The game: a lib (`src/lib.rs`, ~180 flat modules) and the bin (`src/main.rs` → `game.rs` + `game/`), plus `horizon-ctl` (`src/bin/horizon-ctl/`). Also the dedicated server (`--dedicated`) | +| `horizon-command` | Command parsing (Brigadier): the vanilla tree, argument types, selectors, suggestions, the tree's network form. Re-exported as `horizon_client::command` | +| `horizon-client-core` | The client lib's bottom layer: `text.rs`, `lang.rs`, `snbt.rs`, `nbt_path.rs`, `component.rs`, `scoreboard.rs`, `bossbar.rs`, `gamerules.rs`, `block_entity_nbt.rs`, registry/particle/sound tables. Re-exported under the old paths (`horizon_client::text`...) | | `horizon-world` | Vanilla world data with no gameplay loop: NBT, regions, chunks, `datafix/`, `worldgen/`, `level/` (server-side block behaviour, ticks, redstone), entity physics, items, effects, food, damage | | `horizon-core` | Simulation primitives: Java `Random`s, `jmath` (HotSpot-exact `Math`), positions, noise, density, paletted storage, `version.rs` (the pinned version) | | `horizon-protocol` | Network protocol 777: codecs, framing, encryption, `packets/{handshake,status,login,configuration,play}.rs`, `entity_data.rs` | @@ -54,7 +57,8 @@ Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-se Other top-level folders: `tools/` (harnesses and dev scripts), `tests/` (Python unit tests: `python3 -m unittest discover -s tests`), `mods/horizon/src/test/java/dev/horizonlab/parity/` (Java oracles), -`website/` (playhorizon.dev; its paths are relative to `website/`), `docs/`, `.github/workflows/`. +`docs/`, `.github/workflows/`. The website (playhorizon.dev) is the private ludovic111/horizon-site: its build +reads `README.md`, `launcher/links.json`, `docs/api/`, `roadmap/roadmap.json` and `crates/horizon-theme/tokens.css` from main. ## Build and test fast @@ -117,16 +121,16 @@ python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end | Other entities | L: `entities.rs`, `projectiles.rs`, `arrows.rs`; G: `boats.rs`, `minecarts.rs`, `mounts.rs`, `armor_stands.rs`, `paintings.rs`, `frames.rs`, `fireworks.rs`, `tnt.rs`, `explosion.rs` | | Player actions | game.rs (`fn use_hand`, `fn use_item`, `fn attack`, `fn tick_mining`, `fn break_block`); G: `hand.rs`, `combat.rs`, `consume.rs`, `potions.rs`, `shield.rs`, `crossbow.rs`, `trident.rs`, `fishing.rs`; L: `motion.rs` + `motion/` (movement), `collisions.rs`, `items.rs`, `item_data.rs` | | Inventory and containers | L: `menu.rs` (`AbstractContainerMenu.clicked`), `container_screen.rs`, `containers.rs`, `creative.rs`, `crafting.rs`, `recipe_book*.rs`, `stations.rs`, `merchant.rs`; game.rs `fn menu_ops`, `fn click_inventory`; G: `stations.rs`, `trading.rs`, `recipe_book.rs`, `machines.rs` | -| Commands | parse: L: `command/` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`); run: G: `commands.rs` (dispatch) + `commands/*.rs` (`admin`, `execute`, `items`, `players`, `world_cmds`...); L: `scoreboard_cmd.rs`, `data_cmd.rs`, `nbt_path.rs`; G: `functions.rs`, `command_blocks.rs` | +| Commands | parse: crate `horizon-command` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`); run: G: `commands.rs` (dispatch) + `commands/*.rs` (`admin`, `execute`, `items`, `players`, `world_cmds`...); L: `scoreboard_cmd.rs`, `data_cmd.rs`; `horizon-client-core`: `nbt_path.rs`, `scoreboard.rs`; G: `functions.rs`, `command_blocks.rs` | | UI screens | `Screen` enum in game.rs; L: `title.rs` + `title/`, `options_ui.rs`, `multiplayer.rs`, `pack_screen.rs`, `graphics_ui.rs`, `screen_draw.rs`, `ui.rs` (widgets), `hud.rs`, `hud_layout.rs`, `hud_overlays.rs`, `chat.rs`, `tab_list.rs`; G: `startup_menu.rs`, `screens.rs` (pause, death), `options.rs`, `lan_screen.rs`, `chat.rs`, `sign_edit.rs`, `books.rs` | | Multiplayer client | L: `net.rs` (network thread); G: `remote.rs` (`fn handle_packet`, `fn tick_remote`), `remote_*.rs` (mob data, objects, projectiles, vehicles, stations) | | LAN host / server side | L: `lan/` (`conn.rs` handshake + login threads, `hub.rs` + `hub/` play state, `chunks.rs`, `entity.rs`, `tracking.rs`, `guest.rs`, `playerdata.rs`); G: `lan.rs` (`LanHost`), `lan_actions.rs` (`fn as_guest`, `fn tick_guests`), `lan_*.rs` per feature, `lan_entities.rs` (tracked entities) | | Integrated server | G: `integrated.rs` (the server thread), `levels.rs` (one level per dimension, `fn tick_server`), `server_travel.rs` | | Dedicated server | G: `dedicated.rs`, `dedicated/status.rs`; crates `horizon-server-files`, `horizon-server` | -| Save and load | L: `save.rs` (level.dat, regions, playerdata), `entity_nbt.rs`, `block_entity_nbt.rs`, `options_file.rs`; G: `saving.rs`, `persist.rs` (entities); `crates/horizon-world/src/{region.rs,nbt.rs,datafix/}` | +| Save and load | L: `save.rs` (level.dat, regions, playerdata), `entity_nbt.rs`, `options_file.rs`; `horizon-client-core/src/block_entity_nbt.rs`; G: `saving.rs`, `persist.rs` (entities); `crates/horizon-world/src/{region.rs,nbt.rs,datafix/}` | | Input | game.rs `fn window_event`, `fn key_pressed`, `fn play_mouse`; L: `keybinds.rs`, `keymapping.rs`, `key_names.rs`, `mouse.rs`, `input.rs`, `interaction_input.rs`, `gamepad.rs`, `osk.rs`, `clipboard.rs`; G: `pad.rs`, `pad_menu.rs` | | Audio | L: `audio.rs` (mixer), `sound_engine.rs`, `sound_events.rs`, `music.rs`, `ambience.rs`; G: `music.rs`, `subtitle_hud.rs` | -| Resource packs | L: `packs.rs` + `packs/`, `pack_screen.rs`, `atlas_sources.rs`, `sprites.rs`, `mipmap.rs`, `model_library.rs`, `font.rs`, `lang.rs`; crate `horizon-assets`; G: `packs.rs` | +| Resource packs | L: `packs.rs` + `packs/`, `pack_screen.rs`, `atlas_sources.rs`, `sprites.rs`, `mipmap.rs`, `model_library.rs`, `font.rs`; `horizon-client-core/src/lang.rs`; crate `horizon-assets`; G: `packs.rs` | | Agent control | L: `control.rs` (socket), `bin/horizon-ctl/`; G: `control.rs`, `agent.rs`, `events.rs`, `ui_control.rs` ([docs/agent-control.md](docs/agent-control.md)) | | Mods | crate `horizon-mods`; G: `mods.rs`; L: `mod_content.rs`, `mod_list.rs` | | Horizon extras, settings | L: `extras.rs`, `graphics.rs`, `settings.rs`, `minimap.rs`; G: `extras.rs`, `tweaks.rs`, `options.rs` | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 21951c083..03f3bd97b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,8 +4,8 @@ Thanks for helping. Horizon is Minecraft: Java Edition 26.3 rewritten in Rust, a everything is that **it plays exactly like vanilla**. This page is the short version of how we work; questions are welcome on [Discord](https://discord.gg/HcTeMZxe5E). -This repository holds the game, the launcher and the website, plus the tools, tests and docs that build, check and -release them. Anything else (videos, Discord and other community material) lives elsewhere. +This repository holds the game and the launcher, plus the tools, tests and docs that build, check and release them. +The website (playhorizon.dev) is built in a separate repository from this one's README, `docs/api/` and roadmap. Anything else (videos, Discord and other community material) lives elsewhere. **Where to start: [playhorizon.dev/hub](https://playhorizon.dev/hub).** It shows what is being done now and next ([ROADMAP.md](ROADMAP.md) in the repository), the work board, good first tasks, and the forms to report a bug or diff --git a/Cargo.lock b/Cargo.lock index 0e93bba0e..0e0a39038 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -216,6 +216,13 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "beacons" +version = "0.1.0" +dependencies = [ + "horizon-mod-sdk", +] + [[package]] name = "bit-set" version = "0.10.0" @@ -1365,9 +1372,12 @@ dependencies = [ "glam", "horizon-assets", "horizon-bench", + "horizon-client-core", + "horizon-command", "horizon-core", "horizon-dualsense", "horizon-friends", + "horizon-hdr", "horizon-mods", "horizon-protocol", "horizon-server-files", @@ -1395,6 +1405,23 @@ dependencies = [ "zip", ] +[[package]] +name = "horizon-client-core" +version = "0.1.0" +dependencies = [ + "horizon-world", + "serde_json", +] + +[[package]] +name = "horizon-command" +version = "0.1.0" +dependencies = [ + "horizon-client-core", + "horizon-protocol", + "horizon-world", +] + [[package]] name = "horizon-core" version = "0.1.0" @@ -1426,6 +1453,14 @@ dependencies = [ "spake2", ] +[[package]] +name = "horizon-hdr" +version = "0.1.0" +dependencies = [ + "ash", + "wgpu", +] + [[package]] name = "horizon-mod-sdk" version = "0.1.0" @@ -2962,6 +2997,13 @@ dependencies = [ "objc2-quartz-core 0.3.2", ] +[[package]] +name = "recipes" +version = "1.0.0" +dependencies = [ + "horizon-mod-sdk", +] + [[package]] name = "redox_syscall" version = "0.4.1" diff --git a/Cargo.toml b/Cargo.toml index e4628f962..933901dce 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,45 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask"] +members = [ + "crates/horizon-core", + "crates/horizon-dualsense", + "crates/horizon-threads", + "crates/horizon-hdr", + "crates/horizon-world", + "crates/horizon-client", + "crates/horizon-client-core", + "crates/horizon-command", + "crates/horizon-server-files", + "crates/horizon-server", + "crates/horizon-bots", + "crates/horizon-assets", + "crates/horizon-protocol", + "crates/horizon-theme", + "crates/horizon-prepare", + "crates/horizon-telemetry", + "crates/horizon-bench", + "crates/horizon-friends", + "crates/horizon-relay", + "crates/horizon-mod-sdk", + "crates/horizon-mods", + "crates/horizon-mods/tests/guest", + "crates/horizon-mods/tests/ui_guest", + "crates/cargo-horizon-mod", + "crates/horizon-port-pack", + "crates/horizon-shaders", + "crates/horizon-shader-api", + "crates/horizon-release-sign", + "crates/horizon-mod-sdk/examples/coords-hud", + "crates/horizon-mod-sdk/examples/predator-missile", + "crates/horizon-mod-sdk/examples/welcome", + "crates/horizon-mod-sdk/examples/beacons", + "mods/official/fps-overlay", + "mods/official/keystrokes", + "mods/official/minimap", + "mods/official/zoom", + "xtask", + "mods/official/recipes", +] resolver = "2" [workspace.package] diff --git a/ROADMAP.md b/ROADMAP.md index a04eca2ce..9b82f4fac 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -134,7 +134,7 @@ Better tools for mod makers: a test runner that needs no game window, templates `cargo horizon-mod test` runs a mod's test scripts against a fake game snapshot ([#1816](https://github.com/ludovic111/horizon/issues/1816)) and, for server mods, scripted server events ([#1837](https://github.com/ludovic111/horizon/issues/1837)); the content template and the guides are merged ([#1859](https://github.com/ludovic111/horizon/issues/1859), [#1810](https://github.com/ludovic111/horizon/issues/1810), [docs/api/stability.md](docs/api/stability.md)). Left: templates for hud, server and machine mods, typed wrappers in the SDK, a frozen 0.1 compatibility mod that every runtime must load, a CI check that fails when a stable reference entry is removed without a new major version, and the SDK on crates.io once the API is stable. -More: [website/docs/test-a-mod.md](website/docs/test-a-mod.md) +More: [https://playhorizon.dev/docs/test-a-mod](https://playhorizon.dev/docs/test-a-mod) @@ -160,6 +160,66 @@ Translatable components resolved through the selected language for items, contai +#### Cooldowns drawn on items + +After you throw an ender pearl, its slot should show the cooldown sweeping away, as in vanilla. + +
Technical + +Vanilla draws `ItemCooldowns`' percent as a white overlay over the slot (`GuiGraphicsExtractor.itemDecorations` and `itemCooldown`) in the hotbar and in inventories. Issue [#1763](https://github.com/ludovic111/horizon/issues/1763). + +More: [#1933](https://github.com/ludovic111/horizon/issues/1933) + +
+ +#### Chat settings and team prefixes + +The Hidden and Commands Only chat settings should hide chat, and team prefixes should appear before names in chat. + +
Technical + +Vanilla checks `ChatVisiblity` before it delivers chat and system messages ([#1376](https://github.com/ludovic111/horizon/issues/1376)), and chat uses the team-formatted display name ([#1378](https://github.com/ludovic111/horizon/issues/1378)). Both issues have exact steps to reproduce. + +More: [#1932](https://github.com/ludovic111/horizon/issues/1932) · [#1841](https://github.com/ludovic111/horizon/issues/1841) + +
+ +#### A pointing hand over buttons + +The mouse pointer should turn into a pointing hand over menu buttons, as in vanilla 26.3. + +
Technical + +26.3's `AbstractWidget` asks for a cursor from `CursorTypes` when it is hovered; winit's `CursorIcon::Pointer` gives the same shape. Issue [#1347](https://github.com/ludovic111/horizon/issues/1347). + +More: [#1897](https://github.com/ludovic111/horizon/issues/1897) + +
+ +#### Ctrl+Backspace and scroll bars in menus + +Ctrl+Backspace should delete a whole word in the creative search, and every list's scroll bar should be draggable. + +
Technical + +`EditBox` deletes by word with Ctrl ([#1764](https://github.com/ludovic111/horizon/issues/1764)); the Game Rules and Statistics lists' scroll bars can't be dragged ([#1782](https://github.com/ludovic111/horizon/issues/1782), after [#978](https://github.com/ludovic111/horizon/issues/978)). + +More: [#1884](https://github.com/ludovic111/horizon/issues/1884) · [#1931](https://github.com/ludovic111/horizon/issues/1931) + +
+ +#### Chickens flap while they fall + +Chickens should flap their wings while they fall, not stand still in the air. + +
Technical + +Vanilla's `Chicken.aiStep` updates `flap` and `flapSpeed` when the chicken isn't on the ground, and the model's wings follow them. Issue [#1706](https://github.com/ludovic111/horizon/issues/1706). + +More: [#1892](https://github.com/ludovic111/horizon/issues/1892) + +
+ ### Rendering #### Shader packs, written again from scratch @@ -250,7 +310,7 @@ Horizon should run well on small machines: integrated graphics, the Steam Deck, Partly done: an opt-in 60 FPS cap with fewer workers on battery, Far Detail Reduced for integrated GPUs and animated textures on the GPU (both shipped). Left: measured targets and fixes per class of machine (memory use, worker counts, startup) on a Steam Deck, old Intel and Apple Silicon Macs and 8 GB computers, reported on the Benchmarks page. -More: [docs/benchmark.md](docs/benchmark.md) · [website/docs/performance.md](website/docs/performance.md) +More: [docs/benchmark.md](docs/benchmark.md) · [https://playhorizon.dev/docs/performance](https://playhorizon.dev/docs/performance) @@ -540,7 +600,9 @@ You can port a mod to Horizon with your own AI agent on your own computer. Horiz
Technical -A player runs their own agent locally with `horizon-ctl` and the MCP servers ([docs/agent-control.md](docs/agent-control.md)), `cargo horizon-mod`, `horizon-port-pack` and the parity harnesses as the check. Horizon writes the guide ([website/docs/agents.md](website/docs/agents.md), [docs/modpacks.md](docs/modpacks.md)) and runs no agents, accounts or keys for players. The No AI switch turns all of it off. +A player runs their own agent locally with `horizon-ctl` and the MCP servers ([docs/agent-control.md](docs/agent-control.md)), `cargo horizon-mod`, `horizon-port-pack` and the parity harnesses as the check. Horizon writes the guide (playhorizon.dev/docs/agents, [docs/modpacks.md](docs/modpacks.md)) and runs no agents, accounts or keys for players. The No AI switch turns all of it off. + +More: [https://playhorizon.dev/docs/agents](https://playhorizon.dev/docs/agents)
@@ -876,7 +938,9 @@ Run Horizon's built-in benchmark and share the report: every new computer makes
Technical -`horizon-launcher play --arg=--benchmark --arg=standard` writes a JSON report; `horizon-launcher data benchmark ` shows what would be sent and uploads it ([website/docs/performance.md](website/docs/performance.md)). Results from three installs with the same hardware appear on the Benchmarks page. Example: [#1711](https://github.com/ludovic111/horizon/issues/1711). +`horizon-launcher play --arg=--benchmark --arg=standard` writes a JSON report; `horizon-launcher data benchmark ` shows what would be sent and uploads it (playhorizon.dev/docs/performance). Results from three installs with the same hardware appear on the Benchmarks page. Example: [#1711](https://github.com/ludovic111/horizon/issues/1711). + +More: [https://playhorizon.dev/docs/performance](https://playhorizon.dev/docs/performance)
@@ -902,56 +966,6 @@ Armour and tools in End city chests should come enchanted, as in vanilla. -#### Cooldowns drawn on items - -After you throw an ender pearl, its slot should show the cooldown sweeping away, as in vanilla. - -
Technical - -Vanilla draws `ItemCooldowns`' percent as a white overlay over the slot (`GuiGraphicsExtractor.itemDecorations` and `itemCooldown`) in the hotbar and in inventories. Issue [#1763](https://github.com/ludovic111/horizon/issues/1763). - -
- -#### Chat settings and team prefixes - -The Hidden and Commands Only chat settings should hide chat, and team prefixes should appear before names in chat. - -
Technical - -Vanilla checks `ChatVisiblity` before it delivers chat and system messages ([#1376](https://github.com/ludovic111/horizon/issues/1376)), and chat uses the team-formatted display name ([#1378](https://github.com/ludovic111/horizon/issues/1378)). Both issues have exact steps to reproduce. - -
- -#### A pointing hand over buttons - -The mouse pointer should turn into a pointing hand over menu buttons, as in vanilla 26.3. - -
Technical - -26.3's `AbstractWidget` asks for a cursor from `CursorTypes` when it is hovered; winit's `CursorIcon::Pointer` gives the same shape. Issue [#1347](https://github.com/ludovic111/horizon/issues/1347). - -
- -#### Ctrl+Backspace and scroll bars in menus - -Ctrl+Backspace should delete a whole word in the creative search, and every list's scroll bar should be draggable. - -
Technical - -`EditBox` deletes by word with Ctrl ([#1764](https://github.com/ludovic111/horizon/issues/1764)); the Game Rules and Statistics lists' scroll bars can't be dragged ([#1782](https://github.com/ludovic111/horizon/issues/1782), after [#978](https://github.com/ludovic111/horizon/issues/978)). - -
- -#### Chickens flap while they fall - -Chickens should flap their wings while they fall, not stand still in the air. - -
Technical - -Vanilla's `Chicken.aiStep` updates `flap` and `flapSpeed` when the chicken isn't on the ground, and the model's wings follow them. Issue [#1706](https://github.com/ludovic111/horizon/issues/1706). - -
- ## Recently shipped - **OpenGL for old computers** (v0.2.63): Horizon now starts on old PCs whose graphics card has no Vulkan or DirectX 12 driver: it switches to OpenGL by itself, and Options > Graphics can pick OpenGL by hand. [#1917](https://github.com/ludovic111/horizon/issues/1917) · [#1920](https://github.com/ludovic111/horizon/issues/1920) · [#1936](https://github.com/ludovic111/horizon/issues/1936) diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 63a1f7da3..e83ccd840 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -17,4 +17,5 @@ by The Pixelify Sans Project Authors, licensed under the SIL Open Font License 1 `crates/horizon-theme/icons/pixel/*.svg` are icons from [Pixelarticons](https://github.com/halfmage/pixelarticons) by Gerrit Halfmann, under the MIT -license (`crates/horizon-theme/icons/pixel/LICENSE-pixelarticons.txt`). +license (`crates/horizon-theme/icons/pixel/LICENSE-pixelarticons.txt`). `star.svg` is Horizon's own, drawn on +the same grid. diff --git a/crates/cargo-horizon-mod/src/check.rs b/crates/cargo-horizon-mod/src/check.rs index f42674da8..988ba826d 100644 --- a/crates/cargo-horizon-mod/src/check.rs +++ b/crates/cargo-horizon-mod/src/check.rs @@ -200,7 +200,7 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> { return Err(format!("it didn't start: {reason}")); } let client: Vec = mods.commands().map(str::to_owned).collect(); - let server: Vec = mods.server_commands().map(str::to_owned).collect(); + let server: Vec = mods.server_commands().map(|c| c.name.clone()).collect(); report.commands = [client.clone(), server.clone()].concat(); // A server mod plays with one player on, who joins, chats and leaves. let steve = ServerPlayer { @@ -262,9 +262,21 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> { format!("{}: {text}", if error { "error" } else { "feedback" }) } Output::Command { line } => format!("command: /{line}"), + Output::QuietCommands { lines, .. } => { + format!("{} quiet command(s)", lines.len()) + } Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")), + Output::SetBlocks { + dimension, blocks, .. + } => { + format!("set {} block(s) in {dimension}", blocks.len()) + } Output::OpenScreen { .. } => "opened a screen".to_string(), Output::CloseScreen { .. } => "closed its screen".to_string(), + Output::PlaceRecipe { book_id, all } => { + format!("placed recipe {book_id}{}", if all { " (all)" } else { "" }) + } + Output::Give { item, count, .. } => format!("gave {count} {item}"), Output::Shake { strength, seconds } => { format!("shook the camera: {strength:.2} for {seconds:.1} s") } diff --git a/crates/horizon-assets/src/item_model.rs b/crates/horizon-assets/src/item_model.rs index 5999805eb..d567bc6ac 100644 --- a/crates/horizon-assets/src/item_model.rs +++ b/crates/horizon-assets/src/item_model.rs @@ -1031,19 +1031,22 @@ pub struct ItemModels { } impl ItemModels { - pub fn components(&self, stack: &StackView) -> Components { - let mut out = self - .prototypes - .get(&stack.item) - .cloned() - .unwrap_or_default(); + /// The stack's components: its item's defaults with the stack's patch on top. A stack + /// with no patch (most stacks a screen draws) borrows the defaults instead of copying them. + pub fn components(&self, stack: &StackView) -> std::borrow::Cow<'_, Components> { + static NONE: Components = BTreeMap::new(); + let prototype = self.prototypes.get(&stack.item).unwrap_or(&NONE); + if stack.patch.is_empty() { + return std::borrow::Cow::Borrowed(prototype); + } + let mut out = prototype.clone(); for (key, value) in &stack.patch { match value { Some(v) => out.insert(key.clone(), v.clone()), None => out.remove(key), }; } - out + std::borrow::Cow::Owned(out) } /// `ItemModelResolver.updateForTopItem`. pub fn resolve(&self, stack: &StackView, ctx: &Context, env: &dyn ItemEnv) -> ResolvedItem { diff --git a/crates/horizon-client-core/Cargo.toml b/crates/horizon-client-core/Cargo.toml new file mode 100644 index 000000000..8809a5216 --- /dev/null +++ b/crates/horizon-client-core/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "horizon-client-core" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version = "1.90" +description = "The client's lowest layer: chat text and translations, SNBT and NBT paths, the scoreboard, boss bars, game rules and the registry and particle tables commands name" + +[dependencies] +horizon-world = { path = "../horizon-world" } +serde_json = { version = "1.0.151", features = ["raw_value"] } + +[lints] +workspace = true diff --git a/crates/horizon-client/src/block_entity_nbt.rs b/crates/horizon-client-core/src/block_entity_nbt.rs similarity index 97% rename from crates/horizon-client/src/block_entity_nbt.rs rename to crates/horizon-client-core/src/block_entity_nbt.rs index 54d230eb4..6e214fd61 100644 --- a/crates/horizon-client/src/block_entity_nbt.rs +++ b/crates/horizon-client-core/src/block_entity_nbt.rs @@ -259,7 +259,7 @@ fn is_pos(tag: &Tag) -> bool { matches!(tag, Tag::IntArray(v) if v.len() == 3) } /// The loaded `SignText` of one side, or the empty text. -pub(crate) fn sign_side(tag: Option<&Tag>) -> Tag { +pub fn sign_side(tag: Option<&Tag>) -> Tag { let empty = || string(""); let mut messages: Vec = match tag.and_then(|t| t.get("messages")) { Some(Tag::List(list)) => list.iter().filter_map(component).collect(), @@ -664,7 +664,9 @@ pub fn canonical(tag: &Tag) -> Option { } "minecraft:trial_spawner" => { // `TrialSpawnerStateData.Packed` and `FullConfig`: every key is optional - // and defaulted by vanilla; they are kept as loaded. + // and defaulted by vanilla; they are kept as loaded. No `spawn_data` is + // added: an absent one loads as Optional.empty and is not stored, and + // an empty entity would keep the spawner from ever picking a mob. if let Tag::Compound(c) = tag { for (k, v) in c { let key = k.to_string_lossy(); @@ -676,12 +678,6 @@ pub fn canonical(tag: &Tag) -> Option { } } } - if !f.out.contains_key(&"spawn_data".into()) { - f.put( - "spawn_data", - Tag::compound([("entity", Tag::Compound(Compound::new()))]), - ); - } } "minecraft:vault" => { // `VaultConfig.DEFAULT` (when the config is absent): the trial key and the @@ -827,6 +823,21 @@ mod tests { canonical(&snbt(s)).expect("known type") } + #[test] + fn a_trial_spawner_without_spawn_data_saves_none() { + let fresh = canon( + r#"{id:"minecraft:trial_spawner",x:1,y:2,z:3,normal_config:"minecraft:trial_chamber/ranged/skeleton/normal"}"#, + ); + assert_eq!(fresh.get("spawn_data"), None); + let picked = canon( + r#"{id:"minecraft:trial_spawner",x:1,y:2,z:3,spawn_data:{entity:{id:"minecraft:skeleton"}}}"#, + ); + assert_eq!( + picked.get("spawn_data"), + Some(&snbt(r#"{entity:{id:"minecraft:skeleton"}}"#)) + ); + } + #[test] fn every_type_has_defaults() { for id in TYPES.iter().chain(NEWEST.iter()) { diff --git a/crates/horizon-client/src/bossbar.rs b/crates/horizon-client-core/src/bossbar.rs similarity index 100% rename from crates/horizon-client/src/bossbar.rs rename to crates/horizon-client-core/src/bossbar.rs diff --git a/crates/horizon-client/src/component.rs b/crates/horizon-client-core/src/component.rs similarity index 99% rename from crates/horizon-client/src/component.rs rename to crates/horizon-client-core/src/component.rs index fced49898..5b828b305 100644 --- a/crates/horizon-client/src/component.rs +++ b/crates/horizon-client-core/src/component.rs @@ -252,7 +252,7 @@ pub fn to_text_with( } else if let Some(sel) = o.get("selector").and_then(Value::as_str) { resolve(sel) } else if let Some(key) = o.get("keybind").and_then(Value::as_str) { - crate::keybinds::display_name(key) + crate::key_display::display_name(key) } else { Text::empty() }; diff --git a/crates/horizon-client/src/fastutil_order.rs b/crates/horizon-client-core/src/fastutil_order.rs similarity index 100% rename from crates/horizon-client/src/fastutil_order.rs rename to crates/horizon-client-core/src/fastutil_order.rs diff --git a/crates/horizon-client/src/gamerules.rs b/crates/horizon-client-core/src/gamerules.rs similarity index 90% rename from crates/horizon-client/src/gamerules.rs rename to crates/horizon-client-core/src/gamerules.rs index 7198fd202..6715e01ec 100644 --- a/crates/horizon-client/src/gamerules.rs +++ b/crates/horizon-client-core/src/gamerules.rs @@ -292,27 +292,4 @@ mod tests { assert_eq!(GameRules::load(&dir), rules); let _ = fs::remove_dir_all(dir); } - /// The world's save (Level.write) writes the rules as they are now, and a - /// world opened again reads them back (#74). - #[test] - fn level_save_keeps_changed_rules() { - let dir = - std::env::temp_dir().join(format!("horizon-gamerules-level-{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - let mut level = crate::save::Level::default(); - level.write(&dir).unwrap(); - // Rules changed while playing, then saved and loaded again. - let mut rules = GameRules::load(&dir); - assert_eq!(rules, GameRules::default()); - assert!(rules.set("advance_time", Value::Bool(false))); - assert!(rules.set("advance_weather", Value::Bool(false))); - assert!(rules.set("random_tick_speed", Value::Int(0))); - level.game_rules = rules.by_name(); - level.write(&dir).unwrap(); - assert_eq!(GameRules::load(&dir), rules); - let read = crate::save::Level::read(&dir).unwrap(); - assert_eq!(read.game_rules, rules.by_name()); - assert_eq!(read.game_rule("advance_time"), 0); - let _ = fs::remove_dir_all(dir); - } } diff --git a/crates/horizon-client-core/src/identifier.rs b/crates/horizon-client-core/src/identifier.rs new file mode 100644 index 000000000..1e76f7731 --- /dev/null +++ b/crates/horizon-client-core/src/identifier.rs @@ -0,0 +1,18 @@ +//! Resource identifiers (`Identifier`). + +/// Identifier.parse: `ns:path` or `path`, validated. +pub fn parse_identifier(raw: &str) -> Option { + let (ns, path) = match raw.split_once(':') { + Some(("", path)) => ("minecraft", path), + Some((ns, path)) => (ns, path), + None => ("minecraft", raw), + }; + let ns_ok = ns != ".." + && ns + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-')); + let path_ok = path.chars().all(|c| { + c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/') + }); + (ns_ok && path_ok).then(|| format!("{ns}:{path}")) +} diff --git a/crates/horizon-client-core/src/key_display.rs b/crates/horizon-client-core/src/key_display.rs new file mode 100644 index 000000000..fc57c97bd --- /dev/null +++ b/crates/horizon-client-core/src/key_display.rs @@ -0,0 +1,38 @@ +//! Key display names (`InputConstants.Key.getDisplayName`), shared by key +//! mappings and `keybind` text components. +use crate::text::Text; + +/// InputConstants.Key.getDisplayName: one-character keys as the upper-case +/// character, others by translation. +pub fn display_name(key: &str) -> Text { + if let Some(rest) = key.strip_prefix("key.keyboard.") + && rest.chars().count() == 1 + { + let c = rest.to_uppercase(); + return Text::literal(c); + } + let symbol = match key { + "key.keyboard.minus" => Some("-"), + "key.keyboard.equal" => Some("="), + "key.keyboard.left.bracket" => Some("["), + "key.keyboard.right.bracket" => Some("]"), + "key.keyboard.backslash" => Some("\\"), + "key.keyboard.semicolon" => Some(";"), + "key.keyboard.apostrophe" => Some("'"), + "key.keyboard.grave.accent" => Some("`"), + "key.keyboard.comma" => Some(","), + "key.keyboard.period" => Some("."), + "key.keyboard.slash" => Some("/"), + _ => None, + }; + if let Some(s) = symbol { + return Text::literal(s); + } + if let Some(n) = key.strip_prefix("key.mouse.") + && n.parse::().is_ok() + && !crate::lang::has(key) + { + return Text::translate("key.mouse", &[Text::literal(n)]); + } + Text::translate(key, &[]) +} diff --git a/crates/horizon-client/src/lang.rs b/crates/horizon-client-core/src/lang.rs similarity index 96% rename from crates/horizon-client/src/lang.rs rename to crates/horizon-client-core/src/lang.rs index cb96cc373..6213cedc8 100644 --- a/crates/horizon-client/src/lang.rs +++ b/crates/horizon-client-core/src/lang.rs @@ -42,8 +42,12 @@ struct Bundled; impl ResourceSource for Bundled { fn read(&self, path: &str) -> Option> { let body = match path { - "assets/horizon/lang/en_us.json" => include_str!("../assets/horizon/lang/en_us.json"), - "assets/horizon/lang/ru_ru.json" => include_str!("../assets/horizon/lang/ru_ru.json"), + "assets/horizon/lang/en_us.json" => { + include_str!("../../horizon-client/assets/horizon/lang/en_us.json") + } + "assets/horizon/lang/ru_ru.json" => { + include_str!("../../horizon-client/assets/horizon/lang/ru_ru.json") + } _ => return None, }; Some(body.as_bytes().to_vec()) diff --git a/crates/horizon-client-core/src/lib.rs b/crates/horizon-client-core/src/lib.rs new file mode 100644 index 000000000..ca40141d1 --- /dev/null +++ b/crates/horizon-client-core/src/lib.rs @@ -0,0 +1,23 @@ +//! The client's lowest layer, below commands and gameplay: chat text and +//! translations, SNBT and NBT paths, text components, the scoreboard, boss +//! bars, game rules, block entity NBT tables, and the registry, particle and +//! sound source tables commands name. horizon-client re-exports each module +//! under its old path (`horizon_client::text`, ...). +#![forbid(unsafe_code)] +pub mod block_entity_nbt; +pub mod bossbar; +pub mod component; +pub mod fastutil_order; +pub mod gamerules; +pub mod identifier; +pub mod key_display; +pub mod lang; +pub mod nbt_path; +pub mod particle_type; +pub mod registries; +pub mod scoreboard; +pub mod snbt; +pub mod sound_source; +pub mod text; +pub mod uuid; +pub type Result = std::result::Result>; diff --git a/crates/horizon-client/src/nbt_path.rs b/crates/horizon-client-core/src/nbt_path.rs similarity index 100% rename from crates/horizon-client/src/nbt_path.rs rename to crates/horizon-client-core/src/nbt_path.rs diff --git a/crates/horizon-client-core/src/particle_type.rs b/crates/horizon-client-core/src/particle_type.rs new file mode 100644 index 000000000..98de2380b --- /dev/null +++ b/crates/horizon-client-core/src/particle_type.rs @@ -0,0 +1,209 @@ +//! Particle types (`ParticleTypes`): the vanilla particle types with a client +//! implementation, by registry name, and their per-type flags. + +macro_rules! particle_types { + ($($variant:ident = $name:literal),* $(,)?) => { + /// Vanilla particle types with a client implementation here. + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + pub enum ParticleType { $($variant),* } + impl ParticleType { + pub const ALL: &'static [ParticleType] = &[$(ParticleType::$variant),*]; + /// Registry path (`minecraft:`), also the sprite-set file name. + pub fn name(self) -> &'static str { + match self { $(ParticleType::$variant => $name),* } + } + pub fn from_name(name: &str) -> Option { + let name = name.strip_prefix("minecraft:").unwrap_or(name); + match name { $($name => Some(ParticleType::$variant),)* _ => None } + } + } + }; +} +particle_types! { + Block = "block", + BlockCrumble = "block_crumble", + Trail = "trail", + DustPillar = "dust_pillar", + FallingDust = "falling_dust", + Smoke = "smoke", + LargeSmoke = "large_smoke", + WhiteSmoke = "white_smoke", + Flame = "flame", + SoulFireFlame = "soul_fire_flame", + CopperFireFlame = "copper_fire_flame", + SmallFlame = "small_flame", + Lava = "lava", + DrippingWater = "dripping_water", + FallingWater = "falling_water", + DrippingLava = "dripping_lava", + FallingLava = "falling_lava", + LandingLava = "landing_lava", + DrippingHoney = "dripping_honey", + FallingHoney = "falling_honey", + LandingHoney = "landing_honey", + FallingNectar = "falling_nectar", + FallingSporeBlossom = "falling_spore_blossom", + SporeBlossomAir = "spore_blossom_air", + DrippingObsidianTear = "dripping_obsidian_tear", + FallingObsidianTear = "falling_obsidian_tear", + LandingObsidianTear = "landing_obsidian_tear", + DrippingDripstoneWater = "dripping_dripstone_water", + FallingDripstoneWater = "falling_dripstone_water", + DrippingDripstoneLava = "dripping_dripstone_lava", + FallingDripstoneLava = "falling_dripstone_lava", + Splash = "splash", + Rain = "rain", + Bubble = "bubble", + SulfurBubbles = "sulfur_bubbles", + BubblePop = "bubble_pop", + BubbleColumnUp = "bubble_column_up", + CurrentDown = "current_down", + Underwater = "underwater", + Portal = "portal", + ReversePortal = "reverse_portal", + Enchant = "enchant", + Nautilus = "nautilus", + VaultConnection = "vault_connection", + Crit = "crit", + EnchantedHit = "enchanted_hit", + DamageIndicator = "damage_indicator", + Heart = "heart", + AngryVillager = "angry_villager", + HappyVillager = "happy_villager", + Composter = "composter", + Mycelium = "mycelium", + Dolphin = "dolphin", + EggCrack = "egg_crack", + Poof = "poof", + Explosion = "explosion", + ExplosionEmitter = "explosion_emitter", + CampfireCosySmoke = "campfire_cosy_smoke", + CampfireSignalSmoke = "campfire_signal_smoke", + Note = "note", + Dust = "dust", + TotemOfUndying = "totem_of_undying", + Firework = "firework", + EndRod = "end_rod", + Ash = "ash", + WhiteAsh = "white_ash", + CrimsonSpore = "crimson_spore", + WarpedSpore = "warped_spore", + CherryLeaves = "cherry_leaves", + PaleOakLeaves = "pale_oak_leaves", + TintedLeaves = "tinted_leaves", + Effect = "effect", + InstantEffect = "instant_effect", + EntityEffect = "entity_effect", + Witch = "witch", + Infested = "infested", + Cloud = "cloud", + Sneeze = "sneeze", + Snowflake = "snowflake", + Soul = "soul", + SculkSoul = "sculk_soul", + DragonBreath = "dragon_breath", + Gust = "gust", + SmallGust = "small_gust", + GustEmitterLarge = "gust_emitter_large", + GustEmitterSmall = "gust_emitter_small", + DustColorTransition = "dust_color_transition", + SculkCharge = "sculk_charge", + SculkChargePop = "sculk_charge_pop", + Shriek = "shriek", + SonicBoom = "sonic_boom", + Vibration = "vibration", + SweepAttack = "sweep_attack", + Glow = "glow", + WaxOn = "wax_on", + WaxOff = "wax_off", + ElectricSpark = "electric_spark", + Scrape = "scrape", + SquidInk = "squid_ink", + GlowSquidInk = "glow_squid_ink", + Item = "item", + ItemSlime = "item_slime", + ItemSnowball = "item_snowball", + ItemCobweb = "item_cobweb", + SulfurCubeGoo = "sulfur_cube_goo", + Flash = "flash", + Firefly = "firefly", + TrialSpawnerDetection = "trial_spawner_detection", + TrialSpawnerDetectionOminous = "trial_spawner_detection_ominous", + TrialOmen = "trial_omen", + RaidOmen = "raid_omen", + OminousSpawning = "ominous_spawning", + Spit = "spit", + Fishing = "fishing", + DustPlume = "dust_plume", + RedPoplarLeaves = "red_poplar_leaves", + OrangePoplarLeaves = "orange_poplar_leaves", + YellowPoplarLeaves = "yellow_poplar_leaves", + PauseMobGrowth = "pause_mob_growth", + ResetMobGrowth = "reset_mob_growth", + BlockMarker = "block_marker", +} +impl ParticleType { + /// `ParticleType.getOverrideLimiter` (`ParticleTypes.register(name, true)`): + /// spawned regardless of distance. + pub fn override_limiter(self) -> bool { + matches!( + self, + Self::BlockMarker + | Self::DamageIndicator + | Self::ExplosionEmitter + | Self::Explosion + | Self::Gust + | Self::GustEmitterLarge + | Self::GustEmitterSmall + | Self::SonicBoom + | Self::SculkCharge + | Self::SculkChargePop + | Self::Vibration + | Self::Poof + | Self::Spit + | Self::SquidInk + | Self::SweepAttack + | Self::CampfireCosySmoke + | Self::CampfireSignalSmoke + | Self::GlowSquidInk + | Self::Glow + | Self::WaxOn + | Self::WaxOff + | Self::ElectricSpark + | Self::Scrape + | Self::TrialSpawnerDetection + | Self::TrialSpawnerDetectionOminous + | Self::VaultConnection + | Self::OminousSpawning + ) + } + /// `SingleQuadParticle.Layer.translucent`: types whose vanilla particle class + /// hardcodes the translucent layer, drawn after translucent terrain. + /// `TerrainParticle`, `BreakingItemParticle` and `BlockMarker` resolve their + /// layer from the sprite instead (`Layer.bySprite`); see the `translucent` + /// sprite set on the engine. + pub fn translucent_layer(self) -> bool { + match self { + // CampfireSmokeParticle. + Self::CampfireCosySmoke | Self::CampfireSignalSmoke + // PlayerCloudParticle. + | Self::Cloud | Self::Sneeze + // SpellParticle. + | Self::Effect | Self::InstantEffect | Self::EntityEffect + | Self::Witch | Self::Infested | Self::TrialOmen | Self::RaidOmen + // EmissiveRisingParticle. + | Self::Soul | Self::SculkSoul + // SculkChargeParticle, SculkChargePopParticle, ShriekParticle, + // VibrationSignalParticle, FireflyParticle, OverlayParticle. + | Self::SculkCharge | Self::SculkChargePop | Self::Shriek + | Self::Vibration | Self::Firefly | Self::Flash + // SimpleAnimatedParticle and its subclasses: EndRodParticle, + // SparkParticle (firework), SquidInkParticle, TotemParticle. + | Self::EndRod | Self::Firework | Self::SquidInk | Self::GlowSquidInk + | Self::TotemOfUndying + // FlyTowardsPositionParticle: its LifetimeAlpha(0, 0.6, 0.25, 1) is not opaque. + | Self::VaultConnection => true, + _ => false, + } + } +} diff --git a/crates/horizon-client-core/src/registries.rs b/crates/horizon-client-core/src/registries.rs new file mode 100644 index 000000000..310115cf8 --- /dev/null +++ b/crates/horizon-client-core/src/registries.rs @@ -0,0 +1,188 @@ +//! Registry contents and source state that commands validate and complete +//! arguments against (what the server's registry access holds). +use std::collections::BTreeMap; + +/// Registry contents and source state used to validate and complete arguments. +#[derive(Clone, Debug, Default)] +pub struct Registries { + /// Permission level of the command source. + pub permission: u8, + pub items: Vec, + pub item_tags: Vec, + /// Block id -> (property, allowed values). + pub blocks: BTreeMap)>>, + pub block_tags: Vec, + /// Entity types that `summon` can create. + pub summonable: Vec, + /// Every entity type (selector `type=`). + pub entity_types: Vec, + pub effects: Vec, + pub enchantments: Vec, + pub structures: Vec, + pub biomes: Vec, + pub dimensions: Vec, + pub clocks: Vec, + pub timelines: Vec, + pub time_markers: Vec, + pub advancements: Vec, + /// Game rule name -> integer-valued. + pub game_rules: Vec<(String, bool)>, + pub players: Vec, + /// Scoreboard objective names, team names and tracked score holders. + pub objectives: Vec, + pub teams: Vec, + pub tracked: Vec, + /// Loaded datapack functions (`ns:path`) and function tags (`ns:path`). + pub functions: Vec, + /// `/data ... storage` ids. + pub storages: Vec, + /// Boss bar ids and datapack predicate ids. + pub bossbars: Vec, + pub predicates: Vec, + pub item_modifiers: Vec, + pub schedules: Vec, + pub stopwatches: Vec, + pub recipes: Vec, + pub sounds: Vec, + pub damage_types: Vec, + pub attributes: Vec, + pub loot_tables: Vec, + pub templates: Vec, + pub random_sequences: Vec, + pub datapacks_enabled: Vec, + pub datapacks_disabled: Vec, + pub function_tags: Vec, + /// The block the source is looking at (relevant coordinates). + pub target_block: Option<[i32; 3]>, + /// Every registry's element and tag ids (`minecraft:item` -> ...), as + /// the server's registry access and reloadable registries hold them. + pub by_registry: BTreeMap, + /// Blocks whose default state has a block entity. + pub block_entities: std::collections::BTreeSet, + /// Block tag -> member blocks. + pub block_tag_members: BTreeMap>, + /// Data component types with a codec (not transient). + pub persistent_components: Vec, + /// Recipes `/recipe` can give (not special). + pub learnable_recipes: Vec, + /// Advancement id -> criterion names. + pub advancement_criteria: BTreeMap>, + /// World clock -> time markers shown in commands. + pub clock_time_markers: BTreeMap>, + /// Trigger objectives the source may use (`/trigger` suggestions). + pub trigger_objectives: Vec, + /// Objectives with the `trigger` criterion -> holder -> whether its score is locked. + pub trigger_scores: BTreeMap>, +} +/// The ids and tag ids of one registry. +#[derive(Clone, Debug, Default)] +pub struct RegistryIds { + pub ids: Vec, + pub tags: Vec, +} +const EMPTY: &[String] = &[]; +impl Registries { + /// Fill what the game did not build itself from vanilla's exported + /// registries (`command-registries.json`, written by + /// `VanillaCommandParseOracle registries`): built-in registries such as + /// mob effects, data component types and dialogs, block entities and tag + /// members. Registries that data packs reload stay with the game. + pub fn fill_from_export(&mut self, r: &serde_json::Value) { + fn strings(v: &serde_json::Value) -> Vec { + v.as_array() + .map(|a| { + a.iter() + .filter_map(|x| x.as_str().map(str::to_owned)) + .collect() + }) + .unwrap_or_default() + } + let fill = |field: &mut Vec, key: &str| { + if field.is_empty() { + *field = strings(&r[key]); + } + }; + fill(&mut self.effects, "effects"); + fill(&mut self.enchantments, "enchantments"); + fill(&mut self.attributes, "attributes"); + fill(&mut self.damage_types, "damage_types"); + fill(&mut self.templates, "templates"); + fill(&mut self.persistent_components, "persistent_components"); + fill(&mut self.learnable_recipes, "learnable_recipes"); + const RELOADED: [&str; 5] = [ + "minecraft:advancement", + "minecraft:recipe", + "minecraft:loot_table", + "minecraft:predicate", + "minecraft:item_modifier", + ]; + for (name, entry) in r["by_registry"].as_object().into_iter().flatten() { + if RELOADED.contains(&name.as_str()) || self.by_registry.contains_key(name) { + continue; + } + self.by_registry.insert( + name.clone(), + RegistryIds { + ids: strings(&entry["ids"]), + tags: strings(&entry["tags"]), + }, + ); + } + if self.block_entities.is_empty() { + self.block_entities = strings(&r["block_entities"]).into_iter().collect(); + } + if self.block_tag_members.is_empty() { + for (tag, members) in r["block_tag_members"].as_object().into_iter().flatten() { + self.block_tag_members.insert(tag.clone(), strings(members)); + } + } + if self.clock_time_markers.is_empty() { + for (clock, markers) in r["clock_time_markers"].as_object().into_iter().flatten() { + self.clock_time_markers + .insert(clock.clone(), strings(markers)); + } + } + if self.advancement_criteria.is_empty() { + for (id, criteria) in r["advancement_criteria"].as_object().into_iter().flatten() { + self.advancement_criteria + .insert(id.clone(), strings(criteria)); + } + } + } + /// The element ids of a registry (sorted). + pub fn ids(&self, registry: &str) -> &[String] { + if let Some(r) = self.by_registry.get(registry) { + return &r.ids; + } + match registry { + "minecraft:item" => &self.items, + "minecraft:entity_type" => &self.entity_types, + "minecraft:mob_effect" => &self.effects, + "minecraft:enchantment" => &self.enchantments, + "minecraft:worldgen/structure" => &self.structures, + "minecraft:worldgen/biome" => &self.biomes, + "minecraft:world_clock" => &self.clocks, + "minecraft:timeline" => &self.timelines, + "minecraft:attribute" => &self.attributes, + "minecraft:damage_type" => &self.damage_types, + "minecraft:sound_event" => &self.sounds, + "minecraft:predicate" => &self.predicates, + "minecraft:item_modifier" => &self.item_modifiers, + "minecraft:loot_table" => &self.loot_tables, + "minecraft:recipe" => &self.recipes, + "minecraft:advancement" => &self.advancements, + _ => EMPTY, + } + } + /// The tag ids of a registry (sorted). + pub fn tags(&self, registry: &str) -> &[String] { + if let Some(r) = self.by_registry.get(registry) { + return &r.tags; + } + match registry { + "minecraft:item" => &self.item_tags, + "minecraft:block" => &self.block_tags, + _ => EMPTY, + } + } +} diff --git a/crates/horizon-client/src/scoreboard.rs b/crates/horizon-client-core/src/scoreboard.rs similarity index 99% rename from crates/horizon-client/src/scoreboard.rs rename to crates/horizon-client-core/src/scoreboard.rs index 4796be51a..3e820e4eb 100644 --- a/crates/horizon-client/src/scoreboard.rs +++ b/crates/horizon-client-core/src/scoreboard.rs @@ -2,9 +2,9 @@ //! `ObjectiveCriteria`, `NumberFormat`) and its saved data //! (`data/minecraft/scoreboard.dat`, `ScoreboardSaveData.Packed`). use crate::{ - command::Registries, component, fastutil_order::{HashSetOrder, OpenOrder}, + registries::Registries, text::{self, Style, Text}, }; use horizon_world::nbt::Tag; @@ -1266,7 +1266,7 @@ fn entity_uuids(tag: &mut Tag) { }) .collect::>>(), Tag::String(s) => { - crate::save::uuid_from_text(&s.to_string_lossy()).map(Vec::from) + crate::uuid::uuid_from_text(&s.to_string_lossy()).map(Vec::from) } _ => None, }; diff --git a/crates/horizon-client/src/snbt.rs b/crates/horizon-client-core/src/snbt.rs similarity index 100% rename from crates/horizon-client/src/snbt.rs rename to crates/horizon-client-core/src/snbt.rs diff --git a/crates/horizon-client-core/src/sound_source.rs b/crates/horizon-client-core/src/sound_source.rs new file mode 100644 index 000000000..d181d6ac5 --- /dev/null +++ b/crates/horizon-client-core/src/sound_source.rs @@ -0,0 +1,7 @@ +//! Sound sources (`SoundSource`), by name. + +/// SoundSource names in vanilla order. +pub const SOUND_SOURCES: [&str; 11] = [ + "master", "music", "record", "weather", "block", "hostile", "neutral", "player", "ambient", + "voice", "ui", +]; diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client-core/src/text.rs similarity index 99% rename from crates/horizon-client/src/text.rs rename to crates/horizon-client-core/src/text.rs index 4c04c9da5..0a2b6eadb 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client-core/src/text.rs @@ -67,7 +67,7 @@ pub struct Style { } /// A style's `font` field: an identifier (`alt` is `minecraft:alt`). pub fn font_id(v: &Value) -> Option { - crate::command::args::parse_identifier(v.as_str()?) + crate::identifier::parse_identifier(v.as_str()?) } impl Style { pub fn color(c: u32) -> Self { diff --git a/crates/horizon-client-core/src/uuid.rs b/crates/horizon-client-core/src/uuid.rs new file mode 100644 index 000000000..4ede9b141 --- /dev/null +++ b/crates/horizon-client-core/src/uuid.rs @@ -0,0 +1,24 @@ +//! UUIDs as vanilla's four-int form, to and from their text form. + +pub fn uuid_text(u: [i32; 4]) -> String { + let hex: String = u.iter().map(|v| format!("{:08x}", *v as u32)).collect(); + format!( + "{}-{}-{}-{}-{}", + &hex[0..8], + &hex[8..12], + &hex[12..16], + &hex[16..20], + &hex[20..32] + ) +} +pub fn uuid_from_text(s: &str) -> Option<[i32; 4]> { + let hex: String = s.chars().filter(|c| *c != '-').collect(); + if hex.len() != 32 { + return None; + } + let mut out = [0i32; 4]; + for (i, v) in out.iter_mut().enumerate() { + *v = u32::from_str_radix(&hex[i * 8..i * 8 + 8], 16).ok()? as i32; + } + Some(out) +} diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index d7c6d812b..5611edbc9 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -9,9 +9,12 @@ description = "Horizon native development client" [dependencies] horizon-assets = { path = "../horizon-assets" } +horizon-client-core = { path = "../horizon-client-core" } +horizon-command = { path = "../horizon-command" } horizon-core = { path = "../horizon-core" } # The server thread ahead of the workers (MinecraftServer.spin's Thread.setPriority). horizon-threads = { path = "../horizon-threads" } +horizon-hdr = { path = "../horizon-hdr" } horizon-world = { path = "../horizon-world" } horizon-protocol = { path = "../horizon-protocol" } # server.properties, eula.txt and the user lists, shared with horizon-server. diff --git a/crates/horizon-client/examples/probe/arrow_probe.rs b/crates/horizon-client/examples/probe/arrow_probe.rs index f72e6276e..411561c4e 100644 --- a/crates/horizon-client/examples/probe/arrow_probe.rs +++ b/crates/horizon-client/examples/probe/arrow_probe.rs @@ -163,6 +163,8 @@ pub fn main() -> Result<()> { ArrowSound::HitGround => "hit", ArrowSound::Splash => "splash", ArrowSound::Extinguish => "extinguish", + ArrowSound::TridentHitGround => "trident_hit_ground", + ArrowSound::TridentHit => "trident_hit", }, volume.to_bits(), pitch.to_bits() diff --git a/crates/horizon-client/examples/probe/creative_mining_probe.rs b/crates/horizon-client/examples/probe/creative_mining_probe.rs new file mode 100644 index 000000000..897e4bf81 --- /dev/null +++ b/crates/horizon-client/examples/probe/creative_mining_probe.rs @@ -0,0 +1,48 @@ +use horizon_client::{ + Result, + item_data::StackData, + items::{ItemStack, Items}, +}; +use horizon_world::nbt::Tag; +use serde_json::Value; +use std::{ + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, + path::Path, +}; + +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().collect(); + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + let items = Items::catalog(&root)?; + let mut out = BufWriter::new(File::create(&args[2])?); + for line in BufReader::new(File::open(&args[1])?).lines() { + let row: Value = serde_json::from_str(&line?)?; + let mut stack = ItemStack::new( + row["item"].as_str().unwrap(), + row["count"].as_u64().unwrap() as u32, + ); + match row["tool"].as_str().unwrap() { + "default" => {} + mode => { + let mut data = StackData::default(); + let tool = if mode == "implicit" { + Tag::compound([] as [(&str, Tag); 0]) + } else { + Tag::compound([( + "can_destroy_blocks_in_creative", + Tag::Byte(i8::from(mode == "allow")), + )]) + }; + data.set_other("minecraft:tool", Some(tool)); + stack.extra = Some(Box::new(data)); + } + } + writeln!( + out, + "{}", + items.can_destroy_block(Some(&stack), row["creative"].as_bool().unwrap()) + )?; + } + Ok(()) +} diff --git a/crates/horizon-client/examples/probe/cushion_placement_probe.rs b/crates/horizon-client/examples/probe/cushion_placement_probe.rs new file mode 100644 index 000000000..45fbdbd72 --- /dev/null +++ b/crates/horizon-client/examples/probe/cushion_placement_probe.rs @@ -0,0 +1,89 @@ +use horizon_client::{ + Result, + cushion::{self, World}, +}; +use horizon_core::geometry::{Aabb, ShapeOp, Vec3, VoxelShape}; +use serde_json::Value; +use std::{ + collections::HashMap, + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, +}; + +struct Cell { + outline: VoxelShape, + collision: VoxelShape, + suffocating: bool, +} +struct Fixture(HashMap<[i32; 3], Cell>); +impl World for Fixture { + fn outline_bounds(&self, p: [i32; 3]) -> Option { + self.0 + .get(&p)? + .outline + .bounds() + .map(|b| b.move_by(Vec3::new(p[0] as f64, p[1] as f64, p[2] as f64))) + } + fn collision_shapes(&self, _: Aabb) -> Vec { + self.0 + .iter() + .map(|(p, c)| { + c.collision + .moved(Vec3::new(p[0] as f64, p[1] as f64, p[2] as f64)) + }) + .collect() + } + fn suffocating(&self, p: [i32; 3]) -> bool { + self.0.get(&p).is_some_and(|c| c.suffocating) + } +} +fn shape(value: &Value) -> Result { + let mut shape = VoxelShape::empty(); + for b in value.as_array().unwrap() { + let f = |i: usize| b[i].as_f64().unwrap(); + shape = shape.join( + &VoxelShape::from_box(Aabb::new( + Vec3::new(f(0), f(1), f(2)), + Vec3::new(f(3), f(4), f(5)), + ))?, + ShapeOp::OR, + )?; + } + Ok(shape) +} +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().collect(); + let mut out = BufWriter::new(File::create(&args[2])?); + for line in BufReader::new(File::open(&args[1])?).lines() { + let row: Value = serde_json::from_str(&line?)?; + let mut world = Fixture(HashMap::new()); + for c in row["cells"].as_array().unwrap() { + let p = std::array::from_fn(|i| c[i].as_i64().unwrap() as i32); + world.0.insert( + p, + Cell { + outline: shape(&c[3])?, + collision: shape(&c[4])?, + suffocating: c[5].as_bool().unwrap(), + }, + ); + } + let p = &row["pos"]; + let (x, y, z) = ( + p[0].as_f64().unwrap(), + p[1].as_f64().unwrap(), + p[2].as_f64().unwrap(), + ); + let bounds = Aabb::new( + Vec3::new(x - 0.5, y, z - 0.5), + Vec3::new(x + 0.5, y + 0.25, z + 0.5), + ); + writeln!( + out, + "{} {}", + cushion::can_place(&world, bounds), + cushion::survives(&world, bounds) + )?; + } + Ok(()) +} diff --git a/crates/horizon-client/examples/probe/entity_anim_fixture.rs b/crates/horizon-client/examples/probe/entity_anim_fixture.rs index 0a2e2951f..4582033fe 100644 --- a/crates/horizon-client/examples/probe/entity_anim_fixture.rs +++ b/crates/horizon-client/examples/probe/entity_anim_fixture.rs @@ -9,7 +9,7 @@ use horizon_client::mesher::Vertex; use horizon_client::mobs::{ Mob, MobData, MobTypes, Part, Species, allay, anim::{self, Poses, State}, - aquatic, body_anim as b_anim, equine, guardian, + aquatic, bat, body_anim as b_anim, equine, guardian, keyframes::AnimationState, render, shulker, sniffer, species, tame, }; @@ -108,6 +108,22 @@ fn entity_state(mob: &mut Mob, species: Species, case: &Value) { let flag = |k: &str| case[k].as_bool().unwrap_or(false); let num = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32; match species { + Species::Bat => { + mob.extra.flag = flag("isResting"); + mob.anim.states[0].started = case["flyAnimationState"].as_f64().map(|v| v as f32); + mob.anim.states[1].started = case["restAnimationState"].as_f64().map(|v| v as f32); + if let Some(ticks) = case["@batTicks"].as_array() { + for (i, flags) in ticks.iter().enumerate() { + mob.age = i as u32 + 1; + bat::set_resting(mob, flags.as_i64().unwrap_or(0) & 1 != 0); + if flag("@batInFrame") { + bat::tick(mob); + } else { + bat::setup_animation_states(mob); + } + } + } + } Species::Sheep => mob.extra.anim_ticks = num("eatTick") as i32, Species::Guardian | Species::ElderGuardian => { mob.anim.v[guardian::TAIL] = num("tailAnimation"); @@ -377,7 +393,7 @@ pub fn main() -> horizon_client::Result<()> { mob.extra.age = -24000; } mob.age = f("ageInTicks") as u32; - let state = State { + let mut state = State { pos: f("walkAnimationPos"), speed: f("walkAnimationSpeed"), age: f("ageInTicks"), @@ -389,6 +405,20 @@ pub fn main() -> horizon_client::Result<()> { }; let mut poses = Poses::new(&model); entity_state(&mut mob, def.species, case); + if let Some(ticks) = case["@walkTicks"].as_array() { + for speed in ticks { + mob.previous_limb_speed = mob.limb_speed; + mob.limb_speed += (speed.as_f64().unwrap() as f32 - mob.limb_speed) * 0.4; + mob.limb_position += mob.limb_speed; + } + if !case["@alive"].as_bool().unwrap() { + mob.health = 0.0; + } + let extracted = anim::state(&mob, f("@partial")); + state.pos = extracted.pos; + state.speed = extracted.speed; + } + let flag = |k: &str| case[k].as_bool().unwrap_or(false); let num = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32; let started = |k: &str| AnimationState { @@ -456,14 +486,6 @@ pub fn main() -> horizon_client::Result<()> { roll_amount: num("rollAmount"), }, ), - Species::Bat => b_anim::bat( - p, - s, - flag("isResting"), - &started("flyAnimationState"), - &started("restAnimationState"), - &animations, - ), Species::Armadillo => b_anim::armadillo( p, s, @@ -570,6 +592,7 @@ pub fn main() -> horizon_client::Result<()> { pose, num("maxCrossbowChageDuration"), num("ticksUsingItem"), + false, ); } Species::Evoker | Species::Illusioner | Species::Pillager | Species::Vindicator => { @@ -590,7 +613,11 @@ pub fn main() -> horizon_client::Result<()> { } _ => anim::setup(&mob, s, p, &animations), } - out.push_str(&format!("{}\n", emit(&model, &mut poses, case, layer))); + let mut result = emit(&model, &mut poses, case, layer); + if case["@walkTicks"].is_array() { + result["walk"] = json!([state.pos, state.speed]); + } + out.push_str(&format!("{result}\n")); } fs::write(&args[2], out)?; Ok(()) diff --git a/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs b/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs index 86ef275d9..3f47ba787 100644 --- a/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs +++ b/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs @@ -23,6 +23,7 @@ fn stack(spec: &str) -> LootStack { map: false, exploration: None, ominous_amplifier: None, + stew_effects: Vec::new(), }; for e in parts { let (name, level) = e.rsplit_once(':').unwrap_or((e, "1")); diff --git a/crates/horizon-client/examples/probe/main.rs b/crates/horizon-client/examples/probe/main.rs index e80088fd0..6b4c3d7dd 100644 --- a/crates/horizon-client/examples/probe/main.rs +++ b/crates/horizon-client/examples/probe/main.rs @@ -27,7 +27,9 @@ mod chat_screen_fixture; mod cloud_fixture; mod command_parse_fixture; mod container_screen_probe; +mod creative_mining_probe; mod creative_search_fixture; +mod cushion_placement_probe; mod emitter_particles_probe; mod enchanting_fixture; mod entity_anim_fixture; @@ -83,6 +85,7 @@ mod sound_engine_fixture; mod sound_event_fixture; mod spawn_rules_fixture; mod sprint_probe; +mod squid_client_probe; mod subtitle_fixture; mod tab_list_fixture; mod team_rules_fixture; @@ -107,6 +110,9 @@ probes! { block_transform_fixture, breaking_fixture, camera_probe, + squid_client_probe, + creative_mining_probe, + cushion_placement_probe, cauldron_fixture, chat_screen_fixture, cloud_fixture, diff --git a/crates/horizon-client/examples/probe/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs index 49f56c250..5b6c26d2f 100644 --- a/crates/horizon-client/examples/probe/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -49,6 +49,7 @@ struct Scenario { name: String, ticks: i32, time: i64, + difficulty: u8, rain: bool, thunder: bool, origin: [i32; 2], @@ -85,11 +86,13 @@ fn parse(text: &str) -> Vec { "scenario" => { s.name = f[1].to_owned(); s.time = 6000; + s.difficulty = 2; for kv in &f[2..] { let (k, v) = kv.split_once('=').unwrap_or((kv, "")); match k { "ticks" => s.ticks = v.parse().unwrap(), "time" => s.time = v.parse().unwrap(), + "difficulty" => s.difficulty = v.parse().unwrap(), "rain" => s.rain = true, "thunder" => s.thunder = true, "levelseed" => {} @@ -954,6 +957,10 @@ pub fn main() -> horizon_client::Result<()> { for flag in &spec.flags { match flag.as_str() { "persistent" => m.persistent = true, + "named" => { + m.custom_name = Some("Peaceful regression".into()); + m.persistent = true; + } "ridden" => { m.extra.head = Some("minecraft:red_harness".into()); m.rider = Some(horizon_client::mobs::equine::Rider::default()); @@ -1050,6 +1057,7 @@ pub fn main() -> horizon_client::Result<()> { velocity: Vec3::ZERO, yaw: 0.0, hero: false, + effects: Vec::new(), uuid: PLAYER_UUID, allies: Default::default(), remote: false, @@ -1090,7 +1098,7 @@ pub fn main() -> horizon_client::Result<()> { block_tags: &items.block_tags, biomes: &biomes, mob_griefing: true, - difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0), + difficulty: LocalDifficulty::new(s.difficulty, world.day_time, 0, 0.0), end: false, world_seed: 0, // FlatLevelSource.getSeaLevel. diff --git a/crates/horizon-client/examples/probe/scene_motion_probe.rs b/crates/horizon-client/examples/probe/scene_motion_probe.rs index 21977eeab..6153e098b 100644 --- a/crates/horizon-client/examples/probe/scene_motion_probe.rs +++ b/crates/horizon-client/examples/probe/scene_motion_probe.rs @@ -164,6 +164,8 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> { .iter() .filter_map(|e| match e { MotionEvent::Fall(e) => Some(e.trace()), + // The oracle's player wears no armor; the game applies this one. + MotionEvent::Health(horizon_client::health::HealthEvent::ArmorHurt { .. }) => None, MotionEvent::Health(e) => Some(e.trace()), MotionEvent::Snowflake { position, velocity } => Some(format!( "snowflake {:016x},{:016x},{:016x} {:016x},{:016x},{:016x}", diff --git a/crates/horizon-client/examples/probe/section_mesh_fixture.rs b/crates/horizon-client/examples/probe/section_mesh_fixture.rs index e212a5268..89624b78c 100644 --- a/crates/horizon-client/examples/probe/section_mesh_fixture.rs +++ b/crates/horizon-client/examples/probe/section_mesh_fixture.rs @@ -7,7 +7,7 @@ use horizon_client::{ biome::{BiomeInfo, Biomes, GrassModifier}, blocks::BlockFacts, chunk::{Chunk, Light, MIN_Y, index}, - mesher::{MeshTables, Mesher, OPAQUE_LAYER, TerrainVertex}, + mesher::{EMISSION_BITS, MeshTables, Mesher, OPAQUE_LAYER, TerrainVertex}, models, }; use horizon_core::biome::BiomeZoom; @@ -161,7 +161,15 @@ fn scene( .iter() .map(|v| { let ([x, y, z], [u, w]) = (v.pos, v.uv()); - json!([x, y, z, u, w, argb(v.color), light_coords(v.light)]) + json!([ + x, + y, + z, + u, + w, + argb(v.color | EMISSION_BITS), + light_coords(v.light) + ]) }) .collect(); quads.push(json!({"layer": layer, "sprite": sprite, "vertices": vertices})); diff --git a/crates/horizon-client/examples/probe/squid_client_probe.rs b/crates/horizon-client/examples/probe/squid_client_probe.rs new file mode 100644 index 000000000..f9f9c9b2c --- /dev/null +++ b/crates/horizon-client/examples/probe/squid_client_probe.rs @@ -0,0 +1,51 @@ +use horizon_client::{ + Result, + mobs::{Mob, MobTypes, aquatic}, +}; +use horizon_core::geometry::Vec3; +use serde_json::Value; +use std::{ + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, + path::Path, + sync::Arc, +}; + +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().collect(); + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + let types = MobTypes::load(&root)?; + let mut out = BufWriter::new(File::create(&args[2])?); + for line in BufReader::new(File::open(&args[1])?).lines() { + let row: Value = serde_json::from_str(&line?)?; + let kind = Arc::new( + types.types[&format!("minecraft:{}", row["species"].as_str().unwrap())].clone(), + ); + let mut mob = Mob::new(1, kind, Vec3::ZERO, 0.0); + mob.fluids.in_water = row["water"].as_bool().unwrap(); + mob.velocity = Vec3::new( + row["x"].as_f64().unwrap(), + row["y"].as_f64().unwrap(), + row["z"].as_f64().unwrap(), + ); + mob.body_yaw = row["body"].as_f64().unwrap() as f32; + for (i, value) in row["v"].as_array().unwrap().iter().enumerate() { + mob.anim.v[i] = value.as_f64().unwrap() as f32; + } + if row["reset"].as_bool().unwrap() { + aquatic::squid_cycle_event(&mut mob); + } + let velocity = mob.velocity; + aquatic::squid_client_step(&mut mob); + assert_eq!( + velocity, mob.velocity, + "a remote animation must preserve packet velocity" + ); + write!(out, "{:08x}", mob.body_yaw.to_bits())?; + for value in &mob.anim.v[..6] { + write!(out, " {:08x}", value.to_bits())?; + } + writeln!(out)?; + } + Ok(()) +} diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index 48e8f16f4..0e0a3319b 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -35,8 +35,9 @@ enum Animate { Campfire { spawn_particles: bool, }, - /// Leaves: optional falling-leaf particle and chance, tinted by foliage. - Leaves(Option<(T, f32)>), + /// Leaves: optional falling-leaf particle and chance; a tinted leaf takes + /// the biome foliage colour unless a fixed colour is given (azalea). + Leaves(Option<(T, f32)>, Option), NetherPortal, EnchantingTable, EndRod([i32; 3]), @@ -49,6 +50,8 @@ enum Animate { EnderChest, /// FallingBlock with its dust colour. Falling(u32), + /// A beehive or bee nest full of honey (`BeehiveBlock.animateTick`). + Beehive, RedstoneOre, RedstoneWire { power: u8, @@ -58,7 +61,10 @@ enum Animate { BubbleColumn { drag: bool, }, - Fire, + /// `BaseFireBlock` (`SoulFireBlock.canBurn` is always true). + Fire { + soul: bool, + }, /// An active sculk sensor. SculkSensor, /// Potent sulfur that is not dry. @@ -101,10 +107,17 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { spawn_particles: false, }, "oak_leaves" | "birch_leaves" | "jungle_leaves" | "acacia_leaves" | "dark_oak_leaves" - | "mangrove_leaves" => Animate::Leaves(Some((T::TintedLeaves, 0.01))), - "cherry_leaves" => Animate::Leaves(Some((T::CherryLeaves, 0.1))), - "pale_oak_leaves" => Animate::Leaves(Some((T::PaleOakLeaves, 0.02))), - "spruce_leaves" | "azalea_leaves" | "flowering_azalea_leaves" => Animate::Leaves(None), + | "mangrove_leaves" => Animate::Leaves(Some((T::TintedLeaves, 0.01)), None), + "cherry_leaves" => Animate::Leaves(Some((T::CherryLeaves, 0.1)), None), + "pale_oak_leaves" => Animate::Leaves(Some((T::PaleOakLeaves, 0.02)), None), + "red_poplar_leaves" => Animate::Leaves(Some((T::RedPoplarLeaves, 0.01)), None), + "orange_poplar_leaves" => Animate::Leaves(Some((T::OrangePoplarLeaves, 0.01)), None), + "yellow_poplar_leaves" => Animate::Leaves(Some((T::YellowPoplarLeaves, 0.01)), None), + // The azalea blocks drop tinted leaves of the fixed colour -9399763. + "azalea_leaves" | "flowering_azalea_leaves" => { + Animate::Leaves(Some((T::TintedLeaves, 0.01)), Some(0x0070_922D)) + } + "spruce_leaves" => Animate::Leaves(None, None), "nether_portal" => Animate::NetherPortal, "enchanting_table" => Animate::EnchantingTable, "end_rod" => Animate::EndRod(facing()), @@ -116,6 +129,14 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { "sand" => Animate::Falling(0xDBD3A0), "red_sand" => Animate::Falling(0xA95821), "gravel" => Animate::Falling(0x807C7B), + // AnvilBlock/ConcretePowderBlock.getDustColor is the map colour; + // DragonEggBlock's is black. + "anvil" | "chipped_anvil" | "damaged_anvil" => Animate::Falling(0xA7A7A7), + "dragon_egg" => Animate::Falling(0x000000), + _ if name.ends_with("_concrete_powder") => Animate::Falling(concrete_powder_color( + name.trim_end_matches("_concrete_powder"), + )), + "beehive" | "bee_nest" if prop("honey_level").as_deref() == Some("5") => Animate::Beehive, "redstone_ore" | "deepslate_redstone_ore" if lit => Animate::RedstoneOre, "redstone_wire" => { let power = prop("power").and_then(|p| p.parse().ok()).unwrap_or(0); @@ -140,7 +161,8 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { "bubble_column" => Animate::BubbleColumn { drag: prop("drag").as_deref() == Some("true"), }, - "fire" | "soul_fire" => Animate::Fire, + "fire" => Animate::Fire { soul: false }, + "soul_fire" => Animate::Fire { soul: true }, "dried_ghast" => Animate::DriedGhast { waterlogged: prop("waterlogged").as_deref() == Some("true"), }, @@ -157,6 +179,27 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { _ => Animate::None, } } +/// `DyeColor.getMapColor` of a concrete powder colour. +fn concrete_powder_color(dye: &str) -> u32 { + match dye { + "white" => 0xFFFFFF, + "orange" => 0xD87F33, + "magenta" => 0xB24CD8, + "light_blue" => 0x6699D8, + "yellow" => 0xE5E533, + "lime" => 0x7FCC19, + "pink" => 0xF27FA5, + "gray" => 0x4C4C4C, + "light_gray" => 0x999999, + "cyan" => 0x4C7F99, + "purple" => 0x7F3FB2, + "blue" => 0x334CB2, + "brown" => 0x664C33, + "green" => 0x667F33, + "red" => 0x993333, + _ => 0x191919, + } +} /// `RedstoneWireBlock.COLORS`. fn redstone_color(power: u8) -> [f32; 3] { let f = f32::from(power) / 15.0; @@ -190,6 +233,8 @@ pub struct AnimateTables { power_transmitter: Vec, /// `#triggers_ambient_dried_ghast_block_sounds` (soul sand, soul soil). dried_ghast_sounds: Vec, + /// `FireBlock.canBurn`: states with ignite odds above zero (none waterlogged). + burnable: Vec, /// Biome id -> ambient particles and probabilities (`minecraft:visual/ambient_particles`). ambient: Vec>, } @@ -220,6 +265,21 @@ impl AnimateTables { }) .collect() }; + let behaviour: serde_json::Value = + serde_json::from_slice(&std::fs::read(root.join("block-behaviours.json"))?)?; + let ignite_odds = behaviour["fire"]["igniteOdds"].as_object(); + let burnable = (0..registry.len() as u32) + .map(|id| { + // FireBlock.getIgniteOdds: a waterlogged state never burns. + registry.state(BlockStateId(id)).is_some_and(|s| { + s.properties.get("waterlogged").map(String::as_str) != Some("true") + && ignite_odds + .and_then(|m| m.get(s.name.as_str())) + .and_then(serde_json::Value::as_i64) + .is_some_and(|odds| odds > 0) + }) + }) + .collect(); let mut ambient = vec![Vec::new(); biomes.list.len()]; for (name, &id) in &biomes.index { let path = root.join(format!( @@ -248,6 +308,7 @@ impl AnimateTables { power_provider: by_state("minecraft:enchantment_power_provider"), power_transmitter: by_state("minecraft:enchantment_power_transmitter"), dried_ghast_sounds: by_state("minecraft:triggers_ambient_dried_ghast_block_sounds"), + burnable, ambient, }) } @@ -482,6 +543,53 @@ fn try_spawn_drip( } } } +/// `BeehiveBlock.trySpawnDripParticles`. +fn beehive_drip( + tables: &AnimateTables, + engine: &mut ParticleEngine, + ctx: &AnimateContext, + state: BlockStateId, + pos: [i32; 3], +) { + if ctx.facts.get(state).fluid != Fluid::None || engine.random().next_float() < 0.3 { + return; + } + let Some((bottom, top, bounds)) = ctx.shape_y(pos) else { + return; + }; + if top < 1.0 + || tables + .impermeable + .get(state.0 as usize) + .copied() + .unwrap_or(false) + { + return; + } + let y = if bottom > 0.0 { + f64::from(pos[1]) + bottom - 0.05 + } else { + let below = [pos[0], pos[1] - 1, pos[2]]; + let below_top = ctx.shape_y(below).map_or(1.0, |s| s.1); + // `belowTop < 1 || !isCollisionShapeFullBlock` and no fluid below. + if (below_top < 1.0 || !ctx.sturdy(below)) + && ctx.facts.get(ctx.state(below)).fluid == Fluid::None + { + f64::from(pos[1]) - 0.05 + } else { + return; + } + }; + let r = engine.random(); + let (a, b) = (r.next_double(), r.next_double()); + let (fx, fz) = (f64::from(pos[0]), f64::from(pos[2])); + let p = [ + fx + bounds[0] + (bounds[1] - bounds[0]) * a, + y, + fz + bounds[2] + (bounds[3] - bounds[2]) * b, + ]; + add(engine, T::DrippingHoney, p, [0.0; 3]); +} /// `WaterFluid.animateTick` / `LavaFluid.animateTick`. fn fluid_animate_tick( engine: &mut ParticleEngine, @@ -663,7 +771,7 @@ fn block_animate_tick( } } } - Animate::Leaves(falling) => { + Animate::Leaves(falling, fixed_tint) => { let below = [pos[0], pos[1] - 1, pos[2]]; // LeavesBlock.makeDrippingWaterParticles. if (ctx.raining_at)([pos[0], pos[1] + 1, pos[2]]) && next_int(engine.random(), 15) == 1 @@ -683,7 +791,7 @@ fn block_animate_tick( let r = engine.random(); let p = [fx + r.next_double(), fy - 0.05, fz + r.next_double()]; let options = if ty == T::TintedLeaves { - let c = ctx.foliage(pos); + let c = fixed_tint.unwrap_or_else(|| ctx.foliage(pos)); let f = |s: u32| ((c >> s) & 255) as f32 / 255.0; ParticleOptions::colored(ty, [f(16), f(8), f(0), 1.0]) } else { @@ -955,6 +1063,13 @@ fn block_animate_tick( } } } + Animate::Beehive => { + // BeehiveBlock.animateTick: nextInt(1) + 1 attempts. + let attempts = next_int(engine.random(), 1) + 1; + for _ in 0..attempts { + beehive_drip(tables, engine, ctx, state, pos); + } + } Animate::RedstoneOre => { for d in [ [0, -1, 0], @@ -1103,7 +1218,7 @@ fn block_animate_tick( } } } - Animate::Fire => { + Animate::Fire { soul } => { let r = engine.random(); if next_int(r, 24) == 0 { let (volume, pitch) = (1.0 + r.next_float(), r.next_float() * 0.7 + 0.3); @@ -1115,6 +1230,55 @@ fn block_animate_tick( pitch, ); } + // BaseFireBlock.animateTick: three large smoke above the fire, or + // two at each burnable neighbour's face when nothing burnable or + // sturdy supports it (SoulFireBlock.canBurn is always true). + let can_burn = |p: [i32; 3]| { + soul || tables + .burnable + .get(ctx.state(p).0 as usize) + .copied() + .unwrap_or(false) + }; + let below = [pos[0], pos[1] - 1, pos[2]]; + let sturdy = ctx.facts.get(ctx.state(below)).sturdy_full & (1 << 1) != 0; + if !can_burn(below) && !sturdy { + // (neighbour, coordinate axis, face at the axis' high end): the + // west, east, north, south and above faces, in vanilla order. + for (at, axis, high) in [ + ([pos[0] - 1, pos[1], pos[2]], 0usize, false), + ([pos[0] + 1, pos[1], pos[2]], 0, true), + ([pos[0], pos[1], pos[2] - 1], 2, false), + ([pos[0], pos[1], pos[2] + 1], 2, true), + ([pos[0], pos[1] + 1, pos[2]], 1, true), + ] { + if !can_burn(at) { + continue; + } + for _ in 0..2 { + let r = engine.random(); + let d = [r.next_double(), r.next_double(), r.next_double()]; + let mut p = [fx + d[0], fy + d[1], fz + d[2]]; + // The face coordinate hugs the edge: `* 0.1F` (float). + p[axis] = if high { + f64::from(pos[axis]) + 1.0 - d[axis] * f64::from(0.1f32) + } else { + f64::from(pos[axis]) + d[axis] * f64::from(0.1f32) + }; + add(engine, T::LargeSmoke, p, [0.0; 3]); + } + } + } else { + for _ in 0..3 { + let r = engine.random(); + let p = [ + fx + r.next_double(), + fy + r.next_double() * 0.5 + 0.5, + fz + r.next_double(), + ]; + add(engine, T::LargeSmoke, p, [0.0; 3]); + } + } } } } @@ -1138,32 +1302,71 @@ fn candle(engine: &mut ParticleEngine, p: [f64; 3]) { } add(engine, T::SmallFlame, p, [0.0; 3]); } -/// `CampfireBlockEntity.particleTick` for every lit campfire (no cooking items). +/// `CampfireBlockEntity.particleTick` for every lit campfire; `cooking` says +/// which of a campfire's four slots hold an item. pub fn campfire_particles<'a>( tables: &AnimateTables, engine: &mut ParticleEngine, ctx: &AnimateContext, blocks: impl Iterator, + cooking: &dyn Fn([i32; 3]) -> [bool; 4], ) { for &(pos, state) in blocks { if !tables.is_lit_campfire(state) { continue; } - let signal = ctx + let properties = ctx .registry .state(BlockStateId(state)) - .is_some_and(|s| s.properties.get("signal_fire").map(String::as_str) == Some("true")); + .map(|s| &s.properties); + let prop = |k: &str| properties.and_then(|p| p.get(k)).map(String::as_str); + let signal = prop("signal_fire") == Some("true"); + // Direction.get2DDataValue: south, west, north, east. + let rotation = match prop("facing") { + Some("west") => 1, + Some("north") => 2, + Some("east") => 3, + _ => 0, + }; let r = engine.random(); if r.next_float() < 0.11 { let count = next_int(r, 2) + 2; for _ in 0..count { - make_campfire_smoke(engine, pos, signal); + make_campfire_smoke(engine, pos, signal, false); + } + } + // The smoke over each cooking item, at the slot's corner of the fire. + let occupied = cooking(pos); + for (slot, _) in occupied.iter().enumerate().filter(|(_, held)| **held) { + if engine.random().next_float() >= 0.2 { + continue; + } + // Direction.from2DDataValue((slot + rotation) % 4) and its clockwise side. + let (step, clockwise) = match (slot + rotation) % 4 { + 0 => ([0.0, 1.0], [-1.0, 0.0]), + 1 => ([-1.0, 0.0], [0.0, -1.0]), + 2 => ([0.0, -1.0], [1.0, 0.0]), + _ => ([1.0, 0.0], [0.0, 1.0]), + }; + let at = [ + f64::from(pos[0]) + 0.5 - step[0] * 0.3125 + clockwise[0] * 0.3125, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5 - step[1] * 0.3125 + clockwise[1] * 0.3125, + ]; + for _ in 0..4 { + add(engine, T::Smoke, at, [0.0, 5.0e-4, 0.0]); } } } } -/// `CampfireBlock.makeParticles` (always visible, overriding the limiter). -pub fn make_campfire_smoke(engine: &mut ParticleEngine, pos: [i32; 3], signal: bool) { +/// `CampfireBlock.makeParticles` (always visible, overriding the limiter); +/// `smoking` adds the plain smoke puff at the logs. +pub fn make_campfire_smoke( + engine: &mut ParticleEngine, + pos: [i32; 3], + signal: bool, + smoking: bool, +) { let r = engine.random(); let sign = |r: &mut LegacyRandom| if r.next_boolean() { 1.0 } else { -1.0 }; let dx = r.next_double() / 3.0; @@ -1177,6 +1380,17 @@ pub fn make_campfire_smoke(engine: &mut ParticleEngine, pos: [i32; 3], signal: b T::CampfireCosySmoke }; engine.create(&ParticleOptions::simple(ty), [x, y, z], [0.0, 0.07, 0.0]); + if smoking { + let r = engine.random(); + let dx = r.next_double() / 4.0 * sign(r); + let dz = r.next_double() / 4.0 * sign(r); + let at = [ + f64::from(pos[0]) + 0.5 + dx, + f64::from(pos[1]) + 0.4, + f64::from(pos[2]) + 0.5 + dz, + ]; + engine.create(&ParticleOptions::simple(T::Smoke), at, [0.0, 0.005, 0.0]); + } } #[cfg(test)] diff --git a/crates/horizon-client/src/arrows.rs b/crates/horizon-client/src/arrows.rs index 30b501011..6d8dc528b 100644 --- a/crates/horizon-client/src/arrows.rs +++ b/crates/horizon-client/src/arrows.rs @@ -9,7 +9,7 @@ use crate::{ collisions::SceneCollisions, mobs::Who, motion::{FluidResources, LAVA, WATER}, - projectiles::{Hit, Projectile}, + projectiles::{Hit, Projectile, ProjectileKind}, world::World, }; use horizon_core::{ @@ -132,6 +132,10 @@ pub enum ArrowSound { HitGround, /// `entity.generic.extinguish_fire`. Extinguish, + /// A thrown trident's `getDefaultHitGroundSoundEvent` (`item.trident.hit_ground`). + TridentHitGround, + /// `ThrownTrident.onHitEntity`'s `item.trident.hit`. + TridentHit, } /// What a burning arrow does to the block it hits (`onProjectileHit`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -156,7 +160,11 @@ pub struct ArrowState { /// `pickupItemStack`: what picking the arrow up gives. pub pickup_item: crate::items::ItemStack, pub no_physics: bool, + /// `AbstractArrow.getPierceLevel`. pub pierce: u8, + /// `piercingIgnoreEntityIds`: the entities a piercing arrow has gone + /// through (cleared when it sticks in a block). + pub pierced: Vec, /// `Entity.remainingFireTicks`. pub fire_ticks: i32, pub fall_distance: f64, @@ -165,6 +173,9 @@ pub struct ArrowState { pub was_eye_in_water: bool, pub first_tick: bool, pub has_been_shot: bool, + /// `ThrownTrident.dealtDamage`: it has hit an entity (or sat in a block + /// for over 4 ticks) and hits no more. + pub dealt_damage: bool, pub removed: bool, /// The arrow's own random (`Entity.random`). pub random: LegacyRandom, @@ -199,6 +210,7 @@ impl ArrowState { pickup_item: crate::items::ItemStack::new("minecraft:arrow", 1), no_physics: false, pierce: 0, + pierced: Vec::new(), fire_ticks: 0, fall_distance: 0.0, fluids: EntityFluidInteraction::new([WATER, LAVA]), @@ -206,6 +218,7 @@ impl ArrowState { was_eye_in_water: false, first_tick: true, has_been_shot: false, + dealt_damage: false, removed: false, random, events: Vec::new(), @@ -362,6 +375,29 @@ fn bounds(at: Vec3) -> Aabb { Vec3::new(at.x + w, at.y + f64::from(HEIGHT), at.z + w), ) } +/// The bounding box of an arrow, or a thrown trident, at `at`. +pub fn arrow_bounds(at: Vec3) -> Aabb { + bounds(at) +} +/// The blocks an arrow that moved from `from` to `to` was inside +/// (`Entity.checkInsideBlocks`: the sweep of its box, 16 steps at most), for +/// the blocks that react to it (`entityInside`). +pub fn blocks_inside(from: Vec3, to: Vec3) -> Vec { + let deflated = bounds(to).deflate(Vec3::new( + f64::from(1.0e-5f32), + f64::from(1.0e-5f32), + f64::from(1.0e-5f32), + )); + let mut inside = Vec::new(); + let _ = sweep_intersected_blocks(from, to, deflated, 1_000_000, |p, iteration| { + if iteration >= 16 { + return false; + } + inside.push(p); + true + }); + inside +} /// `Projectile.lerpRotation`. fn lerp_rotation(mut old: f32, new: f32) -> f32 { while new - old < -180.0 { @@ -423,18 +459,29 @@ pub fn finish_entity_hit(p: &mut Projectile, scene: &ArrowScene, outcome: Entity let Some(mut st) = p.arrow.take() else { return false; }; + let trident = matches!(p.kind, ProjectileKind::Trident); let mut ticker = Ticker { p, st: &mut st, scene, }; match outcome { + EntityHit::Hurt | EntityHit::Refused if trident => ticker.trident_bounce(), EntityHit::Hurt => { ticker.hit_sound(); - ticker.st.removed = true; + // A piercing arrow flies on (`getPierceLevel() <= 0` discards). + if ticker.st.pierce == 0 { + ticker.st.removed = true; + } } EntityHit::Refused => ticker.turn_back(), - EntityHit::Deflected => {} + EntityHit::Deflected => { + // The deflection comes before `onHitEntity` adds the entity to + // `piercingIgnoreEntityIds`. + if ticker.st.pierce > 0 { + ticker.st.pierced.pop(); + } + } } ticker.finish(); p.stuck = st.in_ground; @@ -464,7 +511,16 @@ impl Ticker<'_, '_, '_, '_> { p.z, )) } + /// Whether this is a `ThrownTrident` (`AbstractArrow` with its own water + /// inertia, sounds and hit). + fn trident(&self) -> bool { + matches!(self.p.kind, ProjectileKind::Trident) + } fn tick(&mut self, targets: &[(Who, Aabb)]) -> Hit { + // ThrownTrident.tick. + if self.trident() && self.st.in_ground_time > 4 { + self.st.dealt_damage = true; + } let physics = !self.st.no_physics; let movement = self.p.velocity; let block_pos = self.block_position(); @@ -512,8 +568,9 @@ impl Ticker<'_, '_, '_, '_> { self.st.in_ground_time = 0; let original = self.position(); if self.st.was_touching_water { - // getWaterInertia, then the bubbles behind it. - self.p.velocity = self.p.velocity.scale(f64::from(0.6f32)); + // getWaterInertia (0.99 for a trident), then the bubbles behind it. + let inertia = if self.trident() { 0.99f32 } else { 0.6f32 }; + self.p.velocity = self.p.velocity.scale(f64::from(inertia)); let v = self.p.velocity; for _ in 0..4 { self.st.events.push(ArrowEvent::Particle { @@ -639,7 +696,8 @@ impl Ticker<'_, '_, '_, '_> { self.st.life = 0; } /// `AbstractArrow.stepMoveAndHit`: the nearest entity on the way, else the - /// block (piercing is not modelled). + /// block. A piercing arrow that hits an entity here goes on from it next + /// tick (`finish_entity_hit`); vanilla's loop goes on within the same tick. fn step_move_and_hit(&mut self, from: Vec3, to: Vec3, targets: &[(Who, Aabb)]) -> Hit { let block = self.scene.clip(from, to); let end = block.map_or(to, |b| b.0); @@ -649,10 +707,16 @@ impl Ticker<'_, '_, '_, '_> { .expand_towards(self.p.velocity) .inflate(Vec3::new(1.0, 1.0, 1.0)); let mut best: Option<(Who, Vec3, f64)> = None; + // ThrownTrident.findHitEntity: none once it has dealt damage. + let targets = if self.st.dealt_damage { &[] } else { targets }; for (who, b) in targets { if Some(*who) == self.p.owner && !self.p.left_owner || !b.intersects(area) { continue; } + // canHitEntity: not an entity a piercing arrow has gone through. + if self.st.pierced.contains(who) { + continue; + } if let Some(at) = self.entity_hit(b, from, end, margin) { // Sorted by the distance to the entity's position (the // stable sort keeps the first of equals). @@ -667,6 +731,15 @@ impl Ticker<'_, '_, '_, '_> { self.p.position = next; self.apply_effects_from_blocks(from, next); if let Some((who, at, _)) = best { + // AbstractArrow.onHitEntity: past pierce level + 1 entities the + // arrow is discarded before it hurts the next one. + if self.st.pierce > 0 { + if self.st.pierced.len() > usize::from(self.st.pierce) { + self.st.removed = true; + return Hit::None; + } + self.st.pierced.push(who); + } return Hit::Entity { who, at }; } let Some((at, pos, face)) = block else { @@ -706,12 +779,33 @@ impl Ticker<'_, '_, '_, '_> { /// `playSound(soundEvent, 1, 1.2 / (random * 0.2 + 0.9))`. fn hit_sound(&mut self) { let pitch = 1.2 / (self.st.random.next_float() * 0.2 + 0.9); + let sound = if self.trident() { + ArrowSound::TridentHitGround + } else { + ArrowSound::HitGround + }; self.st.events.push(ArrowEvent::Sound { - sound: ArrowSound::HitGround, + sound, volume: 1.0, pitch, }); } + /// `ThrownTrident.onHitEntity` after the hurt, whether it landed or not: + /// the hit sound, then `deflect(REVERSE, ..., (0.02, 0.2, 0.02))`. The + /// trident keeps flying (it has dealt its damage) and falls. + fn trident_bounce(&mut self) { + self.st.dealt_damage = true; + self.st.events.push(ArrowEvent::Sound { + sound: ArrowSound::TridentHit, + volume: 1.0, + pitch: 1.0, + }); + // ProjectileDeflection.REVERSE. + let rotation = 170.0 + self.st.random.next_float() * 20.0; + let v = self.p.velocity; + self.p.velocity = Vec3::new(v.x * (-0.02 * 0.5), v.y * (-0.2 * 0.5), v.z * (-0.02 * 0.5)); + self.p.yaw += rotation; + } /// `onHitEntity` when the entity took no damage: `deflect(REVERSE, 0.2)`, /// a half turn give or take ten degrees at a tenth of the speed; one /// left almost still drops its pickup (ALLOWED) and is discarded. @@ -752,6 +846,7 @@ impl Ticker<'_, '_, '_, '_> { self.st.shake = 7; self.p.set_critical(false); self.st.pierce = 0; + self.st.pierced.clear(); } /// `Projectile.mayInteract`: a mob's arrows need `mob_griefing`. fn may_interact(&self) -> bool { diff --git a/crates/horizon-client/src/benchmark.rs b/crates/horizon-client/src/benchmark.rs index bcb94589c..12e38e78a 100644 --- a/crates/horizon-client/src/benchmark.rs +++ b/crates/horizon-client/src/benchmark.rs @@ -323,10 +323,15 @@ const QUIET_MESHES_PER_S: f64 = 100.0; /// happened (`tools/perf_bench.py`'s `wait_loaded`). With `status.streaming`, the sections are /// drawn once no stage has held work for half a second: blocks changing after the load (fluids /// settling, random ticks) only remesh in bursts. Without it, meshing has to go quiet. +/// +/// Right after a teleport (and at spawn) the game reports nothing queued and steady counts for over +/// a second before it starts loading: the counts must change once, or stay full for 5 s, and the +/// resident chunks reach [`view_chunks`], before "steady" means loaded. fn wait_loaded(control: &Control, near: impl Fn(&Value) -> bool) -> Result { let deadline = Instant::now() + LOAD_LIMIT; let (mut last, mut changed, mut meshing) = (None, Instant::now(), Instant::now()); let mut previous: Option<(Instant, f64)> = None; + let (mut first, mut moved, began) = (None, false, Instant::now()); while Instant::now() < deadline { let s = control.status(); let now = Instant::now(); @@ -339,6 +344,19 @@ fn wait_loaded(control: &Control, near: impl Fn(&Value) -> bool) -> Result 0 + && resident >= min_chunks + && now - began > Duration::from_secs(5)); + if min_chunks > 0 && (!moved || resident < min_chunks) { + (last, changed, previous, meshing) = (None, now, None, now); + thread::sleep(Duration::from_millis(50)); + continue; + } if last != Some(counts) { (last, changed) = (Some(counts), now); } @@ -370,6 +388,12 @@ fn wait_loaded(control: &Control, near: impl Fn(&Value) -> bool) -> Result u64 { + (0.8 * std::f64::consts::PI * (distance * distance) as f64) as u64 +} + /// Vanilla's yaw facing from `start` to `end`. fn yaw(start: [f64; 3], end: [f64; 3]) -> f64 { (-(end[0] - start[0])).atan2(end[2] - start[2]).to_degrees() @@ -420,6 +444,13 @@ mod tests { assert!(scenes("nether").is_none()); } + #[test] + fn view_chunks_matches_perf_bench() { + assert_eq!(view_chunks(12), 361); + assert_eq!(view_chunks(32), 2573); + assert_eq!(view_chunks(0), 0); + } + #[test] fn yaw_matches_vanilla() { // South (+Z) is 0, west (-X) 90, east (+X) -90. diff --git a/crates/horizon-client/src/biome.rs b/crates/horizon-client/src/biome.rs index 63ad004d4..46c1e16ca 100644 --- a/crates/horizon-client/src/biome.rs +++ b/crates/horizon-client/src/biome.rs @@ -1,7 +1,7 @@ //! Biome colours from the pinned biome definitions and colormaps //! (`Biome.getGrassColor`/`getFoliageColor`/..., `BlockTintSources`). use crate::Result; -use horizon_core::{noise::SimplexNoise, random::LegacyRandom}; +use horizon_core::{noise::SimplexNoise, position::BlockPos, random::LegacyRandom}; use serde_json::Value; use std::{collections::HashMap, fs, path::Path}; @@ -28,8 +28,13 @@ pub struct BiomeInfo { pub spawn_costs: HashMap, /// The `gameplay/creature_world_gen_spawn_probability` attribute. pub creature_probability: f32, + /// The `gameplay/increased_fire_burnout` attribute (jungles, swamps, peaks, + /// mushroom fields). + pub increased_fire_burnout: bool, pub name: String, pub temperature: f32, + /// `temperature_modifier: frozen` (the frozen oceans). + pub frozen: bool, pub downfall: f32, pub precipitation: bool, pub grass: u32, @@ -42,6 +47,26 @@ pub struct BiomeInfo { pub fog: Option, pub water_fog: u32, } +impl BiomeInfo { + /// `Biome.getHeightAdjustedTemperature`: the frozen modifier, then cooler + /// with height above `sea_level + 17`. + pub fn temperature_at(&self, pos: BlockPos, sea_level: i32) -> f32 { + use horizon_world::worldgen::biome_temperature::{ + BiomeTemperatureSettings, TemperatureModifier, + }; + BiomeTemperatureSettings { + base_temperature: self.temperature, + modifier: if self.frozen { + TemperatureModifier::Frozen + } else { + TemperatureModifier::None + }, + has_precipitation: self.precipitation, + downfall: self.downfall, + } + .height_adjusted(pos, sea_level) + } +} pub struct Biomes { pub list: Vec, pub index: HashMap, @@ -128,7 +153,11 @@ impl Biomes { attributes["minecraft:gameplay/creature_world_gen_spawn_probability"] .as_f64() .unwrap_or(0.1) as f32, + increased_fire_burnout: attributes["minecraft:gameplay/increased_fire_burnout"] + .as_bool() + .unwrap_or(false), temperature, + frozen: v["temperature_modifier"].as_str() == Some("frozen"), downfall, precipitation: v["has_precipitation"].as_bool().unwrap_or(true), grass: color(&effects["grass_color"]) diff --git a/crates/horizon-client/src/block_entity_anim.rs b/crates/horizon-client/src/block_entity_anim.rs index d91748e73..fd91051fa 100644 --- a/crates/horizon-client/src/block_entity_anim.rs +++ b/crates/horizon-client/src/block_entity_anim.rs @@ -648,6 +648,61 @@ impl Conduit { } } +/// What `ConduitBlockEntity.serverTick`'s 40-tick check decided. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct ConduitCheck { + /// The shape changed: `CONDUIT_ACTIVATE` (true) or `CONDUIT_DEACTIVATE`. + pub toggled: Option, + /// The frame blocks counted, while the conduit is active: `applyEffects` + /// and `updateAndAttackTarget` follow (the attack needs 42 or more). + pub frames: Option, +} + +/// `ConduitBlockEntity` (server side): what `serverTick` keeps between ticks. +#[derive(Clone, Debug, Default)] +pub struct ConduitServer { + shape: Conduit, + /// `destroyTarget`: the mob id of the enemy being struck. + pub target: Option, + next_ambient_sound: i64, +} + +impl ConduitServer { + /// The `gameTime % 40` part of `serverTick`: the shape is checked again. + pub fn check( + &mut self, + pos: [i32; 3], + game_time: i64, + is_water: impl Fn([i32; 3]) -> bool, + is_frame: impl Fn([i32; 3]) -> bool, + ) -> Option { + if game_time % 40 != 0 { + return None; + } + let active = self.shape.update_shape(pos, &is_water, &is_frame); + let toggled = (active != self.shape.is_active).then_some(active); + self.shape.is_active = active; + Some(ConduitCheck { + toggled, + frames: active.then_some(self.shape.effect_blocks.len()), + }) + } + /// The sounds of an active conduit at the end of `serverTick`: whether + /// `CONDUIT_AMBIENT` (every 80 ticks) and `CONDUIT_AMBIENT_SHORT` (every + /// 60 to 99 ticks) play. + pub fn ambient(&mut self, game_time: i64, random: &mut impl RandomSource) -> (bool, bool) { + if !self.shape.is_active { + return (false, false); + } + let short = game_time > self.next_ambient_sound; + if short { + self.next_ambient_sound = + game_time + 60 + i64::from(random.next_int_bound(40).unwrap_or(0)); + } + (game_time % 80 == 0, short) + } +} + /// `SkullBlockEntity` animation (client ticker of dragon and piglin heads). #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct Skull { @@ -832,6 +887,8 @@ pub struct BlockEntityAnims { pub gateways: FxHashMap<[i32; 3], EndGateway>, /// The integrated server's copies of the gateways (`portalTick`). pub gateway_servers: FxHashMap<[i32; 3], EndGateway>, + /// The integrated server's copies of the conduits (`serverTick`). + pub conduit_servers: FxHashMap<[i32; 3], ConduitServer>, /// The client level's random (conduit particles). pub random: LegacyRandom, /// [`Ticker`] by block state id (see [`BlockEntityAnims::classify`]). @@ -854,6 +911,7 @@ impl Default for BlockEntityAnims { pots: FxHashMap::default(), gateways: FxHashMap::default(), gateway_servers: FxHashMap::default(), + conduit_servers: FxHashMap::default(), random: LegacyRandom::new(0x6c6576656c), kinds: Vec::new(), present: Vec::new(), @@ -909,6 +967,7 @@ impl BlockEntityAnims { self.pots.retain(|p, _| keep(*p)); self.gateways.retain(|p, _| keep(*p)); self.gateway_servers.retain(|p, _| keep(*p)); + self.conduit_servers.retain(|p, _| keep(*p)); } /// `getOpenNess(partial)` of the chest or ender chest at `pos`. pub fn lid(&self, pos: [i32; 3], partial: f32) -> f32 { diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 10c5e2509..28a876d80 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -558,12 +558,11 @@ fn frac(x: f32) -> f32 { /// `StringSplitter.splitLines(...).get(0)` for plain text: the first line, /// wrapped at the last space that fits or mid-word when none does. fn first_line(line: &str, max_width: f32, advance: &dyn Fn(char) -> f32) -> String { - let chars: Vec = line.chars().collect(); let mut width = 0.0; let mut last_space = None; - for (i, &c) in chars.iter().enumerate() { + for (i, c) in line.char_indices() { if c == '\n' { - return chars[..i].iter().collect(); + return line[..i].to_owned(); } if c == ' ' { last_space = Some(i); @@ -572,9 +571,11 @@ fn first_line(line: &str, max_width: f32, advance: &dyn Fn(char) -> f32) -> Stri if width > max_width { let end = match last_space { Some(s) if s > 0 => s, - _ => i.max(1), + _ if i > 0 => i, + // The first char alone is too wide: take that one char. + _ => c.len_utf8(), }; - return chars[..end].iter().collect(); + return line[..end].to_owned(); } } line.to_owned() @@ -2098,4 +2099,13 @@ mod tests { assert_eq!(out[1].pos, [2.0, 0.0, 0.0]); assert_eq!(out[2].uv, [0.5, 0.5]); } + + #[test] + fn first_line_wraps_on_bytes_without_splitting_a_char() { + let advance = |c: char| if c == ' ' { 4.0 } else { 6.0 }; + assert_eq!(first_line("ab cd ef", 13.0, &advance), "ab"); + assert_eq!(first_line("abcdef", 13.0, &advance), "ab"); + assert_eq!(first_line("\u{6771}", 3.0, &advance), "\u{6771}"); + assert_eq!(first_line("ab\ncd", 100.0, &advance), "ab"); + } } diff --git a/crates/horizon-client/src/blocks.rs b/crates/horizon-client/src/blocks.rs index 27a36396a..8e906e1bc 100644 --- a/crates/horizon-client/src/blocks.rs +++ b/crates/horizon-client/src/blocks.rs @@ -90,7 +90,7 @@ pub const MAP_COLORS: [u32; 62] = [ 14200723, 8365974, ]; /// The 12 edges of the unit cube (outline data predating the export). -fn cube_edges() -> Vec<[f64; 6]> { +pub fn cube_edges() -> Vec<[f64; 6]> { let mut edges = Vec::new(); for a in 0..3 { for (u, v) in [(0., 0.), (1., 0.), (0., 1.), (1., 1.)] { diff --git a/crates/horizon-client/src/bundle.rs b/crates/horizon-client/src/bundle.rs index 8658b5815..948e2f4a9 100644 --- a/crates/horizon-client/src/bundle.rs +++ b/crates/horizon-client/src/bundle.rs @@ -1,6 +1,7 @@ //! `BundleContents.Mutable`: what a bundle takes in and gives back, by //! weight. The menus (`menu`, `lan::menu`) run `BundleItem`'s click //! overrides on it. +use crate::item_data::BundleSelected; use crate::items::{ItemStack, Items}; use horizon_world::nbt::Tag; @@ -97,6 +98,8 @@ pub fn can_be_in_bundle(stack: &ItemStack) -> bool { pub struct Contents { items: Vec, weight: Weight, + /// `selectedItem`: an index into `items`, -1 for none. + selected: i32, } impl Contents { @@ -104,9 +107,11 @@ impl Contents { pub fn of(items: &Items, stack: &ItemStack) -> Option { let inside = contents_of(items, stack)?.to_vec(); let weight = contents_weight(items, &inside); + let selected = stack.data().map_or(-1, |d| d.bundle_selected.0); Some(Self { items: inside, weight, + selected, }) } @@ -154,25 +159,82 @@ impl Contents { amount } - /// `removeOne`: the first stack (Horizon keeps no selected item). + /// `removeOne`: the selected stack, else the first; nothing is selected after. pub fn remove_one(&mut self, items: &Items) -> Option { if self.items.is_empty() { return None; } - let stack = self.items.remove(0); + let at = + usize::try_from(self.selected).map_or(0, |i| if i < self.items.len() { i } else { 0 }); + let stack = self.items.remove(at); self.weight = self .weight .sub(item_weight(items, &stack).times(stack.count)); + self.selected = -1; Some(stack) } + /// `getSelectedItemIndex`. + pub fn selected(&self) -> i32 { + self.selected + } + + /// The stacks inside, in display order (the first is the next out). + pub fn items(&self) -> &[ItemStack] { + &self.items + } + + /// `getNumberOfItemsToShow`: a full grid shows 11 and a `+N`, so the last + /// row keeps its fourth cell for the count. + pub fn shown_count(&self) -> usize { + let count = self.items.len(); + let available: usize = if count > 12 { 11 } else { 12 }; + let on_last_row = count % 4; + let empty = if on_last_row == 0 { 0 } else { 4 - on_last_row }; + count.min(available.saturating_sub(empty)) + } + + /// The items the tooltip shows, and how many sit beyond them. + pub fn shown(&self) -> (&[ItemStack], u32) { + let n = self.shown_count(); + let hidden = self.items[n..].iter().map(|s| s.count).sum(); + (&self.items[..n], hidden) + } + + /// The `Fraction` weight as the float the progress bar reads. + pub fn weight_fraction(&self) -> f32 { + self.weight.n as f32 / self.weight.d as f32 + } + + /// `Fraction.ONE`: a full bundle draws the full bar and says so. + pub fn is_full(&self) -> bool { + self.weight.n >= self.weight.d + } + /// `toImmutable`, written back into the bundle's component. pub fn store(self, bundle: &mut ItemStack) { - bundle.data_mut().bundle_contents = self.items; + let data = bundle.data_mut(); + data.bundle_contents = self.items; + data.bundle_selected = BundleSelected(self.selected); bundle.tidy(); } } +/// `BundleItem.toggleSelectedItem`: select `index`, or nothing when it is the +/// selected one already or outside the contents. +pub fn toggle_selected(bundle: &mut ItemStack, index: i32) { + let Some(data) = bundle.extra.as_deref_mut() else { + return; + }; + let inside = (0..data.bundle_contents.len() as i32).contains(&index); + let selected = if data.bundle_selected.0 != index && inside { + index + } else { + -1 + }; + data.bundle_selected = BundleSelected(selected); +} + #[cfg(test)] mod tests { use super::Weight; @@ -190,3 +252,184 @@ mod tests { assert_eq!(over.how_many(Weight::new(1, 64)), 0); } } + +// ------------------------------------------------------------- the tooltip + +/// `ClientBundleTooltip`'s geometry, relative to the tooltip box's top-left: +/// the 96 pixel column of a 4 wide slot grid and the progress bar under it. +#[derive(Clone, Debug, PartialEq)] +pub struct TooltipLayout { + /// The component's own width (96) and height, the text's excluded. + pub width: f32, + pub height: f32, + /// Each slot's top-left and the stack in it, in drawing order. + pub slots: Vec<([f32; 2], ItemStack)>, + /// The position in `slots` of the selected item, which is drawn highlighted. + pub selected: Option, + /// The `+N` of the items past the grid: its top-left and the count. + pub overflow: Option<([f32; 2], u32)>, + /// The progress bar's top-left, its fill's width out of 94, and whether + /// the weight fills it (the full sprite). + pub bar: [f32; 2], + pub fill: f32, + pub full: bool, + /// `item.minecraft.bundle.empty` / `.full`, centred over the bar. + pub label: Option<&'static str>, + /// An empty bundle's description, wrapped at `width` from here. + pub empty_description: Option<[f32; 2]>, +} + +/// The tooltip of a bundle's contents (`ClientBundleTooltip`), or None when +/// the stack is not a bundle. `x`/`y` are the box's top-left, `box_width` the +/// tooltip's width, which the component is centred in. +pub fn tooltip_layout( + items: &Items, + stack: &ItemStack, + x: f32, + y: f32, + box_width: f32, +) -> Option { + let contents = Contents::of(items, stack)?; + let offset = ((box_width - 96.0) / 2.0).floor(); + if contents.items().is_empty() { + // The description takes the top; the bar follows it. + let description_height = 9.0 * 2.0; + return Some(TooltipLayout { + width: 96.0, + height: description_height + 13.0 + 8.0, + slots: Vec::new(), + selected: None, + overflow: None, + bar: [x + offset, y + description_height + 4.0], + fill: 0.0, + full: false, + label: Some("item.minecraft.bundle.empty"), + empty_description: Some([x + offset, y]), + }); + } + let (shown, hidden) = contents.shown(); + // `gridSizeY` counts `slotCount()` (at most twelve), not the slots the + // overflow count leaves room for. + let rows = contents.items().len().min(12).div_ceil(4).max(1); + let grid_height = rows as f32 * 24.0; + let x_start = x + offset + 96.0; + let y_start = y + grid_height; + let mut slots = Vec::with_capacity(shown.len()); + let mut selected = None; + let mut overflow = None; + // Rows fill bottom-up and columns right-to-left, as vanilla draws them. + let mut slot = 0; + for row in 1..=rows { + for column in 1..=4 { + let at = [x_start - column as f32 * 24.0, y_start - row as f32 * 24.0]; + if hidden > 0 && row == 1 && column == 1 { + overflow = Some((at, hidden)); + } else if slot < shown.len() { + // `extractSlot`: the cell of slot number n holds item `size - n`. + let index = shown.len() - 1 - slot; + if usize::try_from(contents.selected()) == Ok(index) { + selected = Some(slots.len()); + } + slots.push((at, shown[index].clone())); + slot += 1; + } + } + } + let weight = contents.weight_fraction(); + Some(TooltipLayout { + width: 96.0, + height: grid_height + 13.0 + 8.0, + slots, + selected, + overflow, + bar: [x + offset, y + grid_height + 4.0], + // `Mth.mulAndTruncate(weight, 94)`, kept within the bar. + fill: (weight * 94.0).trunc().clamp(0.0, 94.0), + full: contents.is_full(), + label: if contents.is_full() { + Some("item.minecraft.bundle.full") + } else { + None + }, + empty_description: None, + }) +} + +#[cfg(test)] +mod tooltip_tests { + use super::*; + + /// The prepared resources, when they are on this machine: the tooltip + /// asks the item registry whether a stack is a bundle. + fn items() -> Option { + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client/26.3"); + if !root.join("items.json").exists() { + return None; + } + let assets = crate::assets::Assets::load(&root).ok()?; + let facts = crate::blocks::BlockFacts::load(&root, assets.registry).ok()?; + Items::load(&root, assets.registry, &facts).ok() + } + + fn bundle_with(counts: &[(&str, u32)]) -> ItemStack { + let mut bundle = ItemStack::new("minecraft:bundle", 1); + bundle.data_mut().bundle_contents = counts + .iter() + .map(|(item, n)| ItemStack::new(item, *n)) + .collect(); + bundle + } + + #[test] + fn a_grid_shows_twelve_stacks_and_counts_the_rest() { + let Some(items) = items() else { return }; + let twelve: Vec<(&str, u32)> = (0..12).map(|_| ("minecraft:stone", 1)).collect(); + let layout = tooltip_layout(&items, &bundle_with(&twelve), 0.0, 0.0, 96.0).unwrap(); + assert_eq!(layout.slots.len(), 12); + assert_eq!(layout.overflow, None); + assert_eq!(layout.height, 3.0 * 24.0 + 13.0 + 8.0); + // Rows fill bottom-up and columns right-to-left: the twelfth item is in + // the bottom-right cell, the first in the top-left. + assert_eq!(layout.slots[0].0, [96.0 - 24.0, 3.0 * 24.0 - 24.0]); + assert_eq!(&*layout.slots[0].1.item, "minecraft:stone"); + assert_eq!(layout.slots[11].0, [0.0, 0.0]); + // A wider tooltip centres the 96 pixel column in it. + let centred = tooltip_layout(&items, &bundle_with(&twelve), 0.0, 0.0, 120.0).unwrap(); + assert_eq!(centred.slots[0].0[0], 12.0 + 96.0 - 24.0); + // Thirteen stacks: `getNumberOfItemsToShow` leaves the last row room + // for the count, so 8 slots show and `+6` (four stones and two dirt) + // takes the first cell. + let mut counts = twelve; + counts.push(("minecraft:dirt", 2)); + let layout = tooltip_layout(&items, &bundle_with(&counts), 0.0, 0.0, 96.0).unwrap(); + assert_eq!(layout.slots.len(), 8); + assert_eq!(layout.overflow, Some(([96.0 - 24.0, 48.0], 6))); + } + + #[test] + fn the_bar_fills_with_the_weight_and_an_empty_bundle_explains_itself() { + let Some(items) = items() else { return }; + let layout = tooltip_layout(&items, &bundle_with(&[]), 4.0, 8.0, 96.0).unwrap(); + assert!(layout.slots.is_empty()); + assert_eq!(layout.fill, 0.0); + assert_eq!(layout.label, Some("item.minecraft.bundle.empty")); + assert_eq!(layout.empty_description, Some([4.0, 8.0])); + assert_eq!(layout.bar, [4.0, 8.0 + 18.0 + 4.0]); + // A bundle holding one 64 stack is full: the whole bar, the full label. + let layout = tooltip_layout( + &items, + &bundle_with(&[("minecraft:stone", 64)]), + 0.0, + 0.0, + 96.0, + ) + .unwrap(); + assert!(layout.full); + assert_eq!(layout.fill, 94.0); + assert_eq!(layout.label, Some("item.minecraft.bundle.full")); + // Something that is not a bundle has no component. + let dirt = ItemStack::new("minecraft:dirt", 1); + assert!(tooltip_layout(&items, &dirt, 0.0, 0.0, 96.0).is_none()); + } +} diff --git a/crates/horizon-client/src/chat_tests.rs b/crates/horizon-client/src/chat_tests.rs index 6b058c0fb..beec6cd81 100644 --- a/crates/horizon-client/src/chat_tests.rs +++ b/crates/horizon-client/src/chat_tests.rs @@ -436,3 +436,34 @@ fn the_chat_option_filters_the_lines_both_ways() { chat.set_abilities(&font, ChatAbilities::new(ChatVisibility::Full)); assert_eq!(shown(&chat), ["client", "server", "player"]); } + +/// The in-frame LAN host's chat: a guest's line is a player message, so the +/// Chat option's player-message permission hides it at Commands Only and +/// Hidden; command feedback (`/list`, `/tp`) is a system message and stays +/// at Commands Only. +#[test] +fn a_guests_line_follows_the_player_message_permission() { + let font = font(); + let shown = |visibility, source| { + let mut chat = Chat::default(); + chat.set_abilities(&font, ChatAbilities::new(visibility)); + chat.add_message(&font, Text::literal("line"), None, source, 0, false); + chat.messages.len() + }; + for (visibility, player, system) in [ + (ChatVisibility::Full, 1, 1), + (ChatVisibility::System, 0, 1), + (ChatVisibility::Hidden, 0, 0), + ] { + assert_eq!( + shown(visibility, ChatSource::Player), + player, + "{visibility:?}" + ); + assert_eq!( + shown(visibility, ChatSource::Server), + system, + "{visibility:?}" + ); + } +} diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs index 41330df5f..7cd375343 100644 --- a/crates/horizon-client/src/chunk.rs +++ b/crates/horizon-client/src/chunk.rs @@ -24,6 +24,20 @@ pub fn block_strategy() -> Strategy { Strategy::blocks(BLOCK_BITS.load(std::sync::atomic::Ordering::Relaxed)) } +/// Frees `columns` (`count` of them) on a short-lived thread of its own +/// when there are many: a teleport or a dimension change drops a few +/// thousand columns at once, and freeing their sections took the frame +/// 15-20 ms. A few are freed here. +pub fn free_columns(columns: T, count: usize) { + if count < 64 { + return; + } + // Should the thread not start, the closure drops `columns` here. + let _ = std::thread::Builder::new() + .name("Chunk freeing".into()) + .spawn(move || drop(columns)); +} + /// Sizes the block states' global palette for a registry of `states`. pub fn set_block_states(states: usize) { let bits = horizon_core::paletted::ceil_log2(states).max(16); @@ -147,6 +161,9 @@ pub struct Chunk { /// Structure starts reaching into this chunk (`structures.References`): /// structure id and the start's chunk. pub structure_refs: Vec<(Arc, (i32, i32))>, + /// The starts generation made in this chunk (`structures.starts`), saved + /// with the state their placement has reached by then. + pub structure_starts: Vec>, } impl Chunk { pub fn empty(x: i32, z: i32) -> Self { @@ -164,6 +181,7 @@ impl Chunk { block_entities: Vec::new(), block_names: Vec::new(), structure_refs: Vec::new(), + structure_starts: Vec::new(), postprocess: Vec::new(), saved: None, entities: Vec::new(), diff --git a/crates/horizon-client/src/clipboard.rs b/crates/horizon-client/src/clipboard.rs index c21460cdb..76872091c 100644 --- a/crates/horizon-client/src/clipboard.rs +++ b/crates/horizon-client/src/clipboard.rs @@ -346,6 +346,11 @@ mod tests { assert_eq!(filter_text(s, true), "abc\nde\u{80}"); assert_eq!(strip_formatting("§aRed§r §zx§"), "Red §zx§"); assert_eq!(helper_clipboard_contents("§lone\r\ntwo"), "one\ntwo"); + // TextFieldHelper.getClipboardContents runs before insertText's filter. + assert_eq!( + filter_text(&helper_clipboard_contents("§aHello"), false), + "Hello" + ); } struct Field { diff --git a/crates/horizon-client/src/container_screen.rs b/crates/horizon-client/src/container_screen.rs index 2c490861a..77c7ad8aa 100644 --- a/crates/horizon-client/src/container_screen.rs +++ b/crates/horizon-client/src/container_screen.rs @@ -275,4 +275,30 @@ mod tests { Release::Click(Input::QuickMove) ); } + + /// A press whose release never arrives (the pointer left the window, or + /// the screen closed first) leaves `isQuickCrafting` set; the next screen + /// starts with its own state, as `AbstractContainerScreen` does, so the + /// reset the game runs on open/close makes clicks work again. + #[test] + fn a_lost_release_does_not_wedge_the_next_screen() { + let mut clicks = Clicks::default(); + let slot = Target::::Slot(3); + // Pressed with a stack carried: a quick craft drag starts, and its + // release is lost. + assert_eq!(clicks.press(&slot, Button::Left, false, false, false), None); + assert!(clicks.quick_crafting().is_some()); + assert_eq!( + clicks.press(&slot, Button::Left, true, false, false), + None, + "the stuck drag swallows the next press" + ); + // A new screen: fresh state, so the press is a normal click again. + clicks = Clicks::default(); + assert!(clicks.quick_crafting().is_none()); + assert_eq!( + clicks.press(&slot, Button::Left, true, false, false), + Some(Input::Pickup) + ); + } } diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index d13c5e45b..8ca9af0ad 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -49,6 +49,17 @@ pub struct Furnace { /// rather than per item, and a save keeps it as the `RecipesUsed` compound. pub recipes_used: HashMap, } +/// The key `recipes_used` keeps a recipe under: its full id, as vanilla's `ResourceKey` +/// writes it in `RecipesUsed`. Horizon's own recipe ids are file names without the namespace, so +/// keeping both forms would write a key twice, and vanilla refuses such a furnace +/// ("Duplicate entry for key"). +pub fn recipe_used_key(id: &str) -> String { + if id.contains(':') { + id.to_owned() + } else { + format!("minecraft:{id}") + } +} /// A hopper's slots: the only plain container with five. pub const HOPPER_SLOTS: usize = 5; @@ -83,8 +94,68 @@ pub enum BlockEntity { Beehive(Box), /// `CommandBlockEntity` of the three command blocks (`crate::command_block`). CommandBlock(Box), + /// `CampfireBlockEntity` of campfires and soul campfires. + Campfire(Box), /// `SkullBlockEntity` of every skull and head block. Skull(Skull), + /// `DaylightDetectorBlockEntity`: no data, only the ticker + /// (`DaylightDetectorBlock.tickEntity`). + DaylightDetector, +} +/// `CampfireBlockEntity`: four cooking slots, each with its +/// `cookingProgress` and `cookingTime` (the recipe's). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Campfire { + pub items: [Option; 4], + pub progress: [i32; 4], + pub total: [i32; 4], +} +impl Campfire { + /// `placeFood`'s slot: the first empty one, given the item's + /// `campfire_cooking` time; it takes one item of `held`. + pub fn place_food(&mut self, held: &mut ItemStack, cooking_time: i32) -> bool { + let Some(slot) = self.items.iter().position(Option::is_none) else { + return false; + }; + self.total[slot] = cooking_time; + self.progress[slot] = 0; + self.items[slot] = Some(ItemStack { + count: 1, + ..held.clone() + }); + held.count = held.count.saturating_sub(1); + true + } + /// `cookTick` (lit): each item's progress rises by one; the slots whose + /// progress reached their cooking time give up their item (the caller + /// drops its result). + pub fn cook_tick(&mut self) -> Vec<(usize, ItemStack)> { + let mut done = Vec::new(); + for i in 0..4 { + if self.items[i].is_none() { + continue; + } + self.progress[i] += 1; + if self.progress[i] >= self.total[i] + && let Some(item) = self.items[i].take() + { + done.push((i, item)); + } + } + done + } + /// `cooldownTick` (unlit): the progress falls by two, no lower than 0. + /// Whether anything changed (`setChanged`). + pub fn cooldown_tick(&mut self) -> bool { + let mut changed = false; + for i in 0..4 { + if self.progress[i] > 0 { + changed = true; + self.progress[i] = (self.progress[i] - 2).clamp(0, self.total[i]); + } + } + changed + } } /// `SkullBlockEntity`: the player profile the head shows (kept as loaded: /// a compound, or a string when it names a player only), the note block @@ -295,6 +366,9 @@ impl BlockEntity { if is_skull(name) { return Some(Self::Skull(Skull::default())); } + if name == "minecraft:daylight_detector" { + return Some(Self::DaylightDetector); + } if name == "minecraft:beacon" { return Some(Self::Beacon(Box::new(Beacon { last_check_y: i32::MIN / 2, @@ -304,6 +378,9 @@ impl BlockEntity { if name == "minecraft:brewing_stand" { return Some(Self::Brewing(Box::new(crate::brewing::BrewingStand::new()))); } + if name == "minecraft:campfire" || name == "minecraft:soul_campfire" { + return Some(Self::Campfire(Box::default())); + } let size = match name { "minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" => 27, n if n.ends_with("copper_chest") => 27, @@ -341,6 +418,8 @@ impl BlockEntity { Self::Beehive(_) => "minecraft:beehive", Self::CommandBlock(_) => "minecraft:command_block", Self::Skull(_) => "minecraft:skull", + Self::DaylightDetector => "minecraft:daylight_detector", + Self::Campfire(_) => "minecraft:campfire", } } pub fn contents(&self) -> Vec { @@ -357,11 +436,13 @@ impl BlockEntity { | Self::Vault(_) | Self::Beehive(_) | Self::CommandBlock(_) - | Self::Skull(_) => Vec::new(), + | Self::Skull(_) + | Self::DaylightDetector => Vec::new(), Self::Lectern(l) => l.book.iter().cloned().collect(), Self::Sculk(_) => Vec::new(), Self::Banner(_) => Vec::new(), Self::Crafter(c) => c.items.iter().flatten().cloned().collect(), + Self::Campfire(c) => c.items.iter().flatten().cloned().collect(), } } pub fn slots(&self) -> &[Option] { @@ -375,14 +456,17 @@ impl BlockEntity { | Self::Lectern(_) | Self::Sculk(_) | Self::Banner(_) - | Self::Skull(_) => &[], + | Self::Skull(_) + | Self::DaylightDetector => &[], Self::Crafter(c) => &c.items, Self::CreakingHeart(_) | Self::Spawner(_) | Self::TrialSpawner(_) | Self::Vault(_) | Self::Beehive(_) - | Self::CommandBlock(_) => &[], + | Self::CommandBlock(_) + // Not a Container (only Clearable): hoppers don't reach in. + | Self::Campfire(_) => &[], } } pub fn slots_mut(&mut self) -> &mut [Option] { @@ -396,14 +480,16 @@ impl BlockEntity { | Self::Lectern(_) | Self::Sculk(_) | Self::Banner(_) - | Self::Skull(_) => &mut [], + | Self::Skull(_) + | Self::DaylightDetector => &mut [], Self::Crafter(c) => &mut c.items, Self::CreakingHeart(_) | Self::Spawner(_) | Self::TrialSpawner(_) | Self::Vault(_) | Self::Beehive(_) - | Self::CommandBlock(_) => &mut [], + | Self::CommandBlock(_) + | Self::Campfire(_) => &mut [], } } } @@ -638,7 +724,10 @@ impl Furnace { Some(out) => out.count += recipe.result.count, None => self.items[2] = Some(recipe.result.clone()), } - *self.recipes_used.entry(recipe.id.clone()).or_insert(0) += 1; + *self + .recipes_used + .entry(recipe_used_key(&recipe.id)) + .or_insert(0) += 1; if let Some(i) = self.items[0].as_mut() { i.count -= 1; if i.count == 0 { @@ -692,6 +781,41 @@ mod tests { use super::*; use horizon_core::random::{LegacyRandom, RandomSource}; + #[test] + fn campfire_slots_take_food_cook_it_and_cool_down() { + let mut c = Campfire::default(); + let mut beef = ItemStack::new("minecraft:beef", 2); + // placeFood: the first free slot, one item, its recipe's time. + assert!(c.place_food(&mut beef, 600)); + assert_eq!(beef.count, 1); + assert_eq!(c.items[0].as_ref().map(|s| s.count), Some(1)); + assert_eq!((c.progress[0], c.total[0]), (0, 600)); + let mut fish = ItemStack::new("minecraft:cod", 1); + assert!(c.place_food(&mut fish, 3)); + assert_eq!(c.items[1].as_ref().map(|s| &*s.item), Some("minecraft:cod")); + // cookTick: the cod is done on its third tick, the beef keeps cooking. + assert!(c.cook_tick().is_empty()); + assert!(c.cook_tick().is_empty()); + let done = c.cook_tick(); + assert_eq!(done.len(), 1); + assert_eq!((done[0].0, &*done[0].1.item), (1, "minecraft:cod")); + assert!(c.items[1].is_none()); + assert_eq!(c.progress[0], 3); + // cooldownTick: two a tick, never below zero. + assert!(c.cooldown_tick()); + assert_eq!(c.progress[0], 1); + assert!(c.cooldown_tick()); + assert_eq!(c.progress[0], 0); + // Full: four slots, no fifth. + for _ in 0..3 { + let mut more = ItemStack::new("minecraft:potato", 1); + assert!(c.place_food(&mut more, 600)); + } + let mut fifth = ItemStack::new("minecraft:potato", 1); + assert!(!c.place_food(&mut fifth, 600)); + assert_eq!(fifth.count, 1); + } + /// A whole amount pays itself without a draw; a fraction is a chance of one more. #[test] fn create_experience_rounds_the_fraction_by_chance() { diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index 690383963..899ce90d9 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -1612,7 +1612,9 @@ impl Recipes { } /// The `experience` of the cooking recipe with this file name, and 0 for one this data /// pack does not have (a save from another pack can name it). + /// `id` with or without the `minecraft:` namespace (a furnace keeps the full id). pub fn cooking_experience(&self, id: &str) -> f32 { + let id = id.strip_prefix("minecraft:").unwrap_or(id); self.cooking .iter() .find(|c| c.id == id) diff --git a/crates/horizon-client/src/creative.rs b/crates/horizon-client/src/creative.rs index 249e40b11..1a227db65 100644 --- a/crates/horizon-client/src/creative.rs +++ b/crates/horizon-client/src/creative.rs @@ -1,9 +1,14 @@ //! Creative inventory (CreativeModeInventoryScreen): vanilla's tabs and their //! contents as built by the game's own display generators //! (`creative-inventory.json`), a 9x5 scrolling grid and the search tab. -use crate::{Result, items::ItemStack}; +use crate::{Result, items::ItemStack, ui::EditBox}; use serde_json::Value; -use std::{collections::HashMap, fs, path::Path}; +use std::{ + collections::HashMap, + fs, + path::Path, + sync::{Arc, Mutex}, +}; #[derive(Clone, Debug)] pub struct Tab { @@ -35,13 +40,22 @@ pub struct Creative { pub scroll: f32, /// The scrollbar is held (scrolling): dragging moves it. pub scrolling: bool, - pub search: String, - /// When the search box took the focus (`EditBox.setFocused`): its - /// cursor blinks from then. - pub search_focused: std::time::Instant, + /// CreativeModeInventoryScreen's search box: an unbordered `EditBox` of 50. + pub search: EditBox, /// The search tab's stacks, in its display order. search_items: Vec, search_index: Vec, + /// ItemPickerMenu.items: what the grid shows, filled when the tab or the + /// search changes (selectTab, refreshSearchResults), not on every frame. + shown: Mutex>, +} +/// The grid's stacks for one tab, search text and language. +struct Shown { + tab: usize, + search: String, + /// A display name, so a language change refills the search results. + language: String, + items: Arc<[ItemStack]>, } /// Display names from the pinned en_us language file. #[derive(Default)] @@ -284,10 +298,16 @@ impl Creative { selected: 0, scroll: 0.0, scrolling: false, - search: String::new(), - search_focused: std::time::Instant::now(), + search: { + let mut search = EditBox::new(0.0, 0.0, 80.0, 9.0); + search.bordered = false; + search.max_length = 50; + search.text_color = u32::MAX; + search + }, search_items, search_index, + shown: Mutex::new(None), } } /// Where a stack comes in the creative tabs (the search tab lists them @@ -300,18 +320,35 @@ impl Creative { .position(|s| s.same_item_same_components(stack)) .or_else(|| items.iter().position(|s| s.item == stack.item)) } + /// The tabs without their stacks: what the screen draws of them each frame. + pub fn tab_headers(&self) -> Vec { + self.tabs + .iter() + .map(|t| Tab { + id: t.id.clone(), + title: t.title.clone(), + icon: t.icon.clone(), + items: Vec::new(), + top: t.top, + column: t.column, + search: t.search, + inventory: t.inventory, + }) + .collect() + } pub fn tab(&self) -> &Tab { &self.tabs[self.selected.min(self.tabs.len() - 1)] } /// selectTab: a different tab empties the search box; the scrollbar goes to the top. pub fn select(&mut self, tab: usize) { if tab != self.selected { - self.search.clear(); + self.search.set_value(""); } self.selected = tab; self.scroll = 0.0; if self.tab().search { - self.search_focused = std::time::Instant::now(); + self.search.focused = true; + self.search.reset_blink(); } } /// The search tab's stacks. @@ -380,17 +417,44 @@ impl Creative { }) .collect() } - /// Items shown by the selected tab (the search tab filters by `search`). - pub fn items(&self, names: &Names) -> Vec { - let tab = self.tab(); - if tab.search { - return self - .search_results(&self.search, names) + /// Items shown by the selected tab (the search tab filters by `search`), + /// worked out again only when the tab, the search or the language changed. + pub fn items(&self, names: &Names) -> Arc<[ItemStack]> { + let tab = self.selected.min(self.tabs.len() - 1); + let search = if self.tab().search { + self.search.value.as_str() + } else { + "" + }; + let language = names.display_get("itemGroup.search").unwrap_or_default(); + let mut shown = self.shown.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(s) = shown.as_ref() + && s.tab == tab + && s.search == search + && s.language == language + { + return s.items.clone(); + } + let items: Arc<[ItemStack]> = if self.tab().search { + self.search_results(search, names) .into_iter() .map(|i| self.search_items[i].clone()) - .collect(); - } - tab.items.clone() + .collect() + } else { + self.tab().items.as_slice().into() + }; + *shown = Some(Shown { + tab, + search: search.to_owned(), + language, + items: items.clone(), + }); + items + } + /// Drop the shown items, so the next `items` works them out again: a + /// reload can rename items without changing the Search label. + pub fn forget_items(&self) { + *self.shown.lock().unwrap_or_else(|e| e.into_inner()) = None; } pub fn rows(&self, names: &Names) -> usize { self.items(names).len().div_ceil(9) @@ -754,13 +818,13 @@ mod tests { (1, false, true), (2, true, false), ] { - c.search = "anvil".into(); + c.search.set_value("anvil"); c.scroll = 0.5; c.select(selected); assert_eq!(c.selected, selected); assert_eq!(c.tab().inventory, inventory); assert_eq!(c.tab().search, search); - assert!(c.search.is_empty()); + assert!(c.search.value.is_empty()); assert_eq!(c.scroll, 0.0); } } @@ -780,12 +844,12 @@ mod tests { assert_eq!(c.tabs[0].items[0].item.as_ref(), "minecraft:anvil"); let mut c = c; c.select(1); - c.search = "anvil".into(); + c.search.set_value("anvil"); c.scroll = 0.5; c.select(1); - assert_eq!((c.search.as_str(), c.scroll), ("anvil", 0.0)); + assert_eq!((c.search.value.as_str(), c.scroll), ("anvil", 0.0)); c.select(0); - assert_eq!(c.search, ""); + assert_eq!(c.search.value, ""); } #[test] @@ -899,4 +963,25 @@ mod tests { c.scroll = 1.0; assert_eq!(c.scroller_offset(), 95.0); } + + #[test] + fn search_edits_at_its_cursor() { + use winit::keyboard::KeyCode; + let mut c = creative(0); + c.select(1); + c.search.insert_text("hello world"); + for _ in 0..5 { + assert!(c.search.key(KeyCode::ArrowLeft, false, false)); + } + c.search.insert_text("X"); + assert_eq!(c.search.value, "hello Xworld"); + c.search.key(KeyCode::Home, false, true); + c.search.insert_text("Y"); + assert_eq!(c.search.value, "Yworld"); + // Ctrl+Left jumps a word; one step right and Backspace deletes before the cursor. + c.search.key(KeyCode::ArrowLeft, true, false); + c.search.key(KeyCode::ArrowRight, false, false); + c.search.key(KeyCode::Backspace, false, false); + assert_eq!(c.search.value, "world"); + } } diff --git a/crates/horizon-client/src/cushion.rs b/crates/horizon-client/src/cushion.rs new file mode 100644 index 000000000..7610a4aab --- /dev/null +++ b/crates/horizon-client/src/cushion.rs @@ -0,0 +1,59 @@ +//! Cushion placement and support checks (`Cushion.canBePlacedAt`/`wouldSurviveAt`). +use horizon_core::geometry::{Aabb, ShapeOp, Vec3, VoxelShape}; + +pub trait World { + fn outline_bounds(&self, pos: [i32; 3]) -> Option; + fn collision_shapes(&self, bounds: Aabb) -> Vec; + fn suffocating(&self, pos: [i32; 3]) -> bool; +} + +pub fn blocks_in(a: Aabb) -> impl Iterator { + let (lo, hi) = (a.min_position(), a.max_position()); + let (x0, y0, z0) = ( + lo.x.floor() as i32, + lo.y.floor() as i32, + lo.z.floor() as i32, + ); + let (x1, y1, z1) = ( + hi.x.floor() as i32, + hi.y.floor() as i32, + hi.z.floor() as i32, + ); + (y0..=y1).flat_map(move |y| (z0..=z1).flat_map(move |z| (x0..=x1).map(move |x| [x, y, z]))) +} + +pub fn survives(world: &impl World, bounds: Aabb) -> bool { + let (lo, hi) = (bounds.min_position(), bounds.max_position()); + let anchor = Aabb::new( + Vec3::new(lo.x, lo.y - 0.015625, lo.z), + Vec3::new(hi.x.next_down(), lo.y, hi.z.next_down()), + ); + // The extra eighth block expands the scan, not the intersection test. + let supported = blocks_in(anchor.expand_towards(Vec3::new(0.0, -0.125, 0.0))).any(|p| { + world + .outline_bounds(p) + .is_some_and(|shape| shape.intersects(anchor)) + }); + supported && !blocks_in(bounds.next_deflated()).all(|p| world.suffocating(p)) +} + +pub fn can_place(world: &impl World, bounds: Aabb) -> bool { + if !survives(world, bounds) { + return false; + } + let (lo, hi) = (bounds.min_position(), bounds.max_position()); + let slab = Aabb::new(lo, Vec3::new(hi.x, lo.y + 0.015625, hi.z)).next_deflated(); + let Ok(mut remaining) = VoxelShape::from_box(slab) else { + return false; + }; + for shape in world.collision_shapes(slab) { + let Ok(next) = remaining.join(&shape, ShapeOp::ONLY_FIRST) else { + return false; + }; + remaining = next; + if remaining.is_empty() { + return false; + } + } + true +} diff --git a/crates/horizon-client/src/debug_overlay.rs b/crates/horizon-client/src/debug_overlay.rs index 7140905a8..f55d4ee6e 100644 --- a/crates/horizon-client/src/debug_overlay.rs +++ b/crates/horizon-client/src/debug_overlay.rs @@ -221,18 +221,17 @@ pub fn scale( pub fn draw(font: &Font, columns: [&[String]; 2], scale: f32, width: i32) -> Vec { let mut out = vec![GuiDraw::Push(vec![PoseOp::Scale(scale, scale)])]; for (lines, align_left) in [(columns[0], true), (columns[1], false)] { - let placed: Vec<(&String, i32, i32)> = lines + let placed: Vec<(&String, i32, i32, i32)> = lines .iter() .enumerate() .filter(|(_, l)| !l.is_empty()) .map(|(i, l)| { let w = font.width(l) as i32; let left = if align_left { 2 } else { width - 2 - w }; - (l, left, 2 + LINE_HEIGHT * i as i32) + (l, left, 2 + LINE_HEIGHT * i as i32, w) }) .collect(); - for (line, left, top) in &placed { - let w = font.width(line) as i32; + for (_, left, top, w) in &placed { out.push(fill( left - 1, top - 1, @@ -241,7 +240,7 @@ pub fn draw(font: &Font, columns: [&[String]; 2], scale: f32, width: i32) -> Vec BACKGROUND, )); } - for (line, left, top) in placed { + for (line, left, top, _) in placed { out.push(GuiDraw::Text { text: Text::literal(line.clone()), x: left, diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs index 2f418ae82..73b9bf090 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-client/src/enchant.rs @@ -545,6 +545,32 @@ impl Enchantments { } out } + /// `EnchantmentHelper.forEachModifier` as an item's tooltip lists them: the + /// `minecraft:attributes` effects of `stack`'s enchantments as rows of + /// (attribute, id, amount, operation, slot group), one per slot group the + /// enchantment lists. + pub fn modifier_rows(&self, stack: &ItemStack) -> Vec<(String, String, f64, String, String)> { + let mut rows = Vec::new(); + for (id, level) in stack.enchantments() { + let Some(e) = self.get(id) else { continue }; + for a in e.effects["minecraft:attributes"] + .as_array() + .into_iter() + .flatten() + { + for slot in &e.slots { + rows.push(( + a["attribute"].as_str().unwrap_or("").to_owned(), + a["id"].as_str().unwrap_or("").to_owned(), + f64::from(level_value(&a["amount"], *level)), + a["operation"].as_str().unwrap_or("add_value").to_owned(), + slot.clone(), + )); + } + } + } + rows + } /// Sum of `add_value` amounts of one attribute from enchantments on `stack`. pub fn attribute_add(&self, stack: Option<&ItemStack>, attribute: &str) -> f64 { stack.map_or(0.0, |s| { diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index 6e8089e9d..44f07dc82 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -95,6 +95,15 @@ impl ItemEntity { self.health -= fire_damage as i32; } } + // CactusBlock.entityInside: `entity.hurt(cactus, 1.0)`. An item has no + // hurt cooldown, so it loses 1 health every tick it touches a cactus + // (5 health: gone in 5 ticks). Fire resistance does not help; + // `ItemStack.canBeHurtBy` only skips it for a damage_resistant stack. + if crate::motion::environment::cactus_contact(world, registry, self.bounds()) + && !items.resists_cactus(&self.stack) + { + self.health -= 1; + } ItemEnvironmentTick { alive: self.health > 0, lava_hurt, @@ -385,8 +394,29 @@ pub struct ExperienceOrb { pub value: u32, pub age: u32, pub on_ground: bool, + /// `ExperienceOrb.count`: orbs merged into this one; each pickup gives + /// `value` once and takes one off. + pub count: u32, + /// `Entity.tickCount`, which paces `ExperienceOrb.scanForMerges`. + pub ticks: u32, } impl ExperienceOrb { + pub fn bounds(&self) -> Aabb { + let h = 0.25; + Aabb::new( + Vec3::new(self.position.x - h, self.position.y, self.position.z - h), + Vec3::new( + self.position.x + h, + self.position.y + 0.5, + self.position.z + h, + ), + ) + } + /// `ExperienceOrb.canMerge(orb, id, value)` for an orb that is not removed: + /// the same value and ids a multiple of 40 apart. + pub fn can_merge(&self, id: u32, value: u32) -> bool { + self.value == value && (self.id as i32).wrapping_sub(id as i32) % 40 == 0 + } /// ExperienceOrb.getExperienceValue: the largest orb size not above `value`. pub fn split(value: u32) -> u32 { [2477, 1237, 617, 307, 149, 73, 37, 17, 7, 3, 1] @@ -416,7 +446,9 @@ impl ExperienceOrb { facts: &BlockFacts, collision: &BlockCollisionRegistry<'_>, player: Option<[f64; 3]>, + next_float: &mut dyn FnMut() -> f32, ) -> bool { + self.ticks += 1; self.previous = self.position; let block = world.block( self.position.x.floor() as i32, @@ -432,6 +464,14 @@ impl ExperienceOrb { } else { self.velocity.y -= 0.03; } + if facts.get(block).fluid == Fluid::Lava { + // ExperienceOrb.tick: lava throws the orb back out. + self.velocity = Vec3::new( + f64::from((next_float() - next_float()) * 0.2), + f64::from(0.2f32), + f64::from((next_float() - next_float()) * 0.2), + ); + } if let Some(p) = player { let d = [ (p[0] - self.position.x) / 8.0, @@ -449,15 +489,7 @@ impl ExperienceOrb { ); } } - let h = 0.25; - let bounds = Aabb::new( - Vec3::new(self.position.x - h, self.position.y, self.position.z - h), - Vec3::new( - self.position.x + h, - self.position.y + 0.5, - self.position.z + h, - ), - ); + let bounds = self.bounds(); let mut scene = SceneCollisions { world, binding: collision, @@ -494,6 +526,31 @@ impl ExperienceOrb { self.age < 6000 } } +/// `ExperienceOrb.scanForMerges`, run by each orb on `tickCount % 20 == 1`: +/// it absorbs the orbs that `canMerge` within 0.5 blocks of its box, +/// adding their counts and keeping the smaller age. +pub fn merge_orbs(orbs: &mut Vec) { + let mut removed = vec![false; orbs.len()]; + for i in 0..orbs.len() { + if removed[i] || orbs[i].ticks % 20 != 1 { + continue; + } + let area = orbs[i].bounds().inflate(Vec3::new(0.5, 0.5, 0.5)); + for j in 0..orbs.len() { + if j != i + && !removed[j] + && orbs[j].can_merge(orbs[i].id, orbs[i].value) + && orbs[j].bounds().intersects(area) + { + orbs[i].count += orbs[j].count; + orbs[i].age = orbs[i].age.min(orbs[j].age); + removed[j] = true; + } + } + } + let mut removed = removed.into_iter(); + orbs.retain(|_| !removed.next().unwrap_or(false)); +} /// Player experience (Player.giveExperiencePoints / getXpNeededForNextLevel). #[derive(Clone, Copy, Debug, Default)] pub struct Experience { @@ -591,6 +648,57 @@ impl Painting { ) } } +/// The `DyeColor` ordinal of a colour name (`DyeColor.byName`), white when +/// the name is unknown. +pub fn dye_index(name: &str) -> u8 { + crate::mobs::render::DYE_NAMES + .iter() + .position(|n| *n == name) + .unwrap_or(0) as u8 +} +/// A cushion (`Cushion`, a `BlockAttachedEntity`): a 1 x 0.25 block pillow +/// that seats a player. It sits on the top face of a block, at the clicked +/// height, and is coloured by its `DyeColor`. +#[derive(Clone, Debug)] +pub struct Cushion { + pub id: u32, + /// `Entity.position`: the bottom centre of the cushion. + pub position: Vec3, + /// `BlockAttachedEntity.pos` (the saved `block_pos`). + pub pos: [i32; 3], + pub yaw: f32, + /// `DyeColor` ordinal: white 0, orange 1, ..., black 15. + pub color: u8, + /// BlockAttachedEntity.ticksSinceLastCheck. + pub check_interval: u32, +} +impl Cushion { + /// `Entity.makeBoundingBox`: x and z half a block out, y to y + 0.25. + pub fn bounds(&self) -> ([f64; 3], [f64; 3]) { + let p = self.position; + ( + [p.x - 0.5, p.y, p.z - 0.5], + [p.x + 0.5, p.y + 0.25, p.z + 0.5], + ) + } + /// The `DyeColor` name of the cushion. + pub fn color_name(&self) -> &'static str { + crate::mobs::render::DYE_NAMES[usize::from(self.color.min(15))] + } + /// `Cushion.getCushionItemStackWithData`: the matching coloured item. + pub fn item(&self) -> String { + format!("minecraft:{}_cushion", self.color_name()) + } + /// `Cushion.interact`'s seat: the vehicle's PASSENGER attachment + /// `(0, 0.25, 0)` less the player's `(0, 0.6, 0)`. + pub fn seat(&self) -> Vec3 { + Vec3::new(self.position.x, self.position.y - 0.35, self.position.z) + } + /// `Entity.getDismountLocationForPassenger`: on top of the cushion. + pub fn dismount(&self) -> Vec3 { + Vec3::new(self.position.x, self.position.y + 0.25, self.position.z) + } +} /// An item frame or glow item frame (`ItemFrame`). #[derive(Clone, Debug)] pub struct ItemFrame { diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index 2e865dfb1..79e11719f 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -166,12 +166,23 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { if d >= end { return 1.0; } return (d - start) / (end - start); } +// CRUMBLING_UV_BEGIN +fn crumbling_uv(uv: vec2, packed_origin: vec2, sprite_size: vec2, dimensions: vec2) -> vec2 { + let size = vec2(dimensions); + // Undo stage_light's 16-bit quantization before adding local texels. Otherwise + // different stages can fall on opposite sides of a nearest-sampling boundary. + let origin = round(packed_origin * size); + let extent = max(round(sprite_size * size), vec2(1.0)); + let local = min(floor(fract(uv) * extent), extent - vec2(1.0)); + return (origin + local + vec2(0.5)) / size; +} +// CRUMBLING_UV_END @fragment fn fs_entity(in: Out, @builtin(front_facing) front: bool) -> @location(0) vec4 { var uv = in.uv; if in.overlay == 6u { uv.y = in.wrap.x + fract(in.uv.y) * in.wrap.y; } if in.overlay == 11u || in.overlay == 12u { // Each crack's stage sprite origin comes in its light bytes (breaking::stage_light). - uv = in.wrap + fract(in.uv) * globals.crumbling_sprite.zw; + uv = crumbling_uv(in.uv, in.wrap, globals.crumbling_sprite.zw, textureDimensions(atlas)); } var color = textureSample(atlas, atlas_sampler, uv) * select(in.back_color, in.color, front); if in.overlay == 9u || in.overlay == 10u { diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 00576ea02..c49af48c9 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -6,7 +6,7 @@ //! survive a Horizon save. use crate::{ arrows::Pickup, - entities::{ArmorStand, ExperienceOrb, ItemEntity, ItemFrame, Painting}, + entities::{ArmorStand, Cushion, ExperienceOrb, ItemEntity, ItemFrame, Painting}, mobs::{Mob, MobType, Who}, projectiles::{Projectile, ProjectileKind}, save::{ @@ -180,7 +180,6 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { ("Silent", m.silent), ("NoGravity", m.no_gravity), ("Glowing", m.glowing), - ("Invulnerable", m.invulnerable_flag), ] { if on { map.insert(key.into(), Tag::Byte(1)); @@ -188,6 +187,26 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { map.remove(&horizon_world::nbt::JavaString::from(key)); } } + map.insert( + "Invulnerable".into(), + Tag::Byte(i8::from(m.invulnerable_flag)), + ); + map.insert( + "LeftHanded".into(), + Tag::Byte(i8::from(m.extra.left_handed)), + ); + // Keys of older formats that structure templates still carry. + for key in [ + "HandItems", + "ArmorItems", + "HandDropChances", + "ArmorDropChances", + "Dimension", + "HurtByTimestamp", + "Leashed", + ] { + map.remove(&horizon_world::nbt::JavaString::from(key)); + } if m.ticks_frozen > 0 { map.insert("TicksFrozen".into(), Tag::Int(m.ticks_frozen)); } else { @@ -197,7 +216,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { ("AbsorptionAmount", Tag::Float(0)), ("FallFlying", Tag::Byte(0)), ("CanPickUpLoot", Tag::Byte(i8::from(m.can_pick_up_loot()))), - ("LeftHanded", Tag::Byte(0)), + ("current_impulse_context_reset_grace_time", Tag::Int(0)), ( "Brain", Tag::compound([("memories", Tag::Compound(Compound::new()))]), @@ -209,7 +228,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { // Only breedable animals have an age; a loaded creature that was saved without // one (a frog) stays without. let aged = raw.is_none_or(|r| r.get("Age").is_some()); - if m.kind.category == "creature" && aged { + if (m.kind.category == "creature" || m.species() == crate::mobs::Species::Hoglin) && aged { map.insert("Age".into(), Tag::Int(m.extra.age)); map.insert("AgeLocked".into(), Tag::Byte(i8::from(m.extra.age_locked))); map.insert("ForcedAge".into(), Tag::Int(m.extra.forced_age)); @@ -260,11 +279,28 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { .or_insert_with(|| string("minecraft:classic")); } "minecraft:piglin" | "minecraft:piglin_brute" | "minecraft:hoglin" => { + // Only Piglin.addAdditionalSaveData writes CannotHunt. + if id == "minecraft:piglin_brute" { + map.remove(&"CannotHunt".into()); + } map.insert( "IsImmuneToZombification".into(), Tag::Byte(i8::from(m.extra.flag2)), ); map.insert("TimeInOverworld".into(), Tag::Int(m.extra.counter2)); + if id == "minecraft:piglin" { + // InventoryCarrier.writeInventoryToTag. + map.insert( + "Inventory".into(), + Tag::List( + m.extra + .inventory + .iter() + .map(crate::save::item_to_nbt) + .collect(), + ), + ); + } } "minecraft:horse" | "minecraft:donkey" @@ -357,6 +393,12 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { "minecraft:bat" => { map.insert("BatFlags".into(), Tag::Byte(i8::from(m.extra.flag))); } + "minecraft:turtle" => { + map.insert("has_egg".into(), Tag::Byte(i8::from(m.extra.flag))); + if let Some(home) = m.extra.home { + map.insert("home_pos".into(), Tag::IntArray(home.to_vec())); + } + } "minecraft:creaking" => { // home_pos: the heart it is bound to. if let Some(home) = m.extra.home { @@ -479,10 +521,8 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { )]) }); } - "minecraft:zombie" => { - map.insert("IsBaby".into(), Tag::Byte(i8::from(m.is_baby()))); + "minecraft:zombie" | "minecraft:husk" | "minecraft:drowned" => { for (key, value) in [ - ("CanBreakDoors", Tag::Byte(0)), ("DrownedConversionTime", Tag::Int(-1)), ("InWaterTime", Tag::Int(-1)), ] { @@ -507,6 +547,28 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } _ => {} } + // Zombie.addAdditionalSaveData: CanBreakDoors. + if crate::mobs::doors::is_zombie(m.species()) { + map.insert( + "CanBreakDoors".into(), + Tag::Byte(i8::from(m.extra.can_break_doors)), + ); + } + if matches!( + id, + "minecraft:zombie" + | "minecraft:husk" + | "minecraft:drowned" + | "minecraft:zombie_villager" + | "minecraft:zombified_piglin" + | "minecraft:piglin" + | "minecraft:zoglin" + ) { + map.insert("IsBaby".into(), Tag::Byte(i8::from(m.is_baby()))); + } + if let Some(a) = m.extra.attributes.as_deref() { + put_attributes(map, m, a); + } crate::mobs::raider::write_nbt(m, map); crate::mobs::riders::write_nbt(m, map); // LivingEntity equipment: what the mob holds now. @@ -589,6 +651,89 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } tag } +/// `AttributeMap.pack` for the attributes with a base or permanent modifier +/// finalizeSpawn set, over the saved list. +fn put_attributes(map: &mut Compound, m: &Mob, a: &crate::mobs::finalize::Attributes) { + use crate::mobs::finalize::{self, Attr, Op}; + let mut list = match map.get(&"attributes".into()) { + Some(Tag::List(l)) => l.clone(), + _ => Vec::new(), + }; + for attr in Attr::ALL { + let modifiers: Vec = a + .modifiers + .iter() + .filter(|x| x.attr == attr) + .map(|x| { + let op = match x.op { + Op::AddValue => "add_value", + Op::AddMultipliedBase => "add_multiplied_base", + Op::AddMultipliedTotal => "add_multiplied_total", + }; + Tag::compound([ + ("id", string(x.id)), + ("amount", Tag::Double(x.amount.to_bits())), + ("operation", string(op)), + ]) + }) + .collect(); + if modifiers.is_empty() && !a.bases.iter().any(|(b, _)| *b == attr) { + continue; + } + let id = format!("minecraft:{}", attr.name()); + let mut entry = vec![ + ("id", string(&id)), + ("base", Tag::Double(finalize::base_value(m, attr).to_bits())), + ]; + if !modifiers.is_empty() { + entry.push(("modifiers", Tag::List(modifiers))); + } + let entry = Tag::compound(entry); + match list + .iter_mut() + .find(|t| text(t.get("id")).as_deref() == Some(id.as_str())) + { + Some(t) => *t = entry, + None => list.push(entry), + } + } + map.insert("attributes".into(), Tag::List(list)); +} +/// `Brain.Packed`: the memories finalizeSpawn set, over the saved ones. +pub fn put_brain(map: &mut Compound, m: &Mob, dimension: &str) { + if m.extra.memories.is_empty() { + return; + } + let mut memories = match map.get(&"Brain".into()).and_then(|b| b.get("memories")) { + Some(Tag::Compound(c)) => c.clone(), + _ => Compound::new(), + }; + for &(name, value, ttl) in &m.extra.memories { + let value = match name { + "hunted_recently" => Tag::Byte(value as i8), + "home" => match m.extra.home { + Some(p) => Tag::compound([ + ("dimension", string(dimension)), + ("pos", Tag::IntArray(p.to_vec())), + ]), + None => continue, + }, + _ => Tag::Int(value as i32), + }; + let mut memory = vec![("value", value)]; + if ttl != i64::MAX { + memory.push(("ttl", Tag::Long(ttl))); + } + memories.insert( + format!("minecraft:{name}").as_str().into(), + Tag::compound(memory), + ); + } + map.insert( + "Brain".into(), + Tag::compound([("memories", Tag::Compound(memories))]), + ); +} /// `CustomName`: a text component saved as a string or a `{text: ..}` compound. fn custom_name(tag: &Tag) -> Option { match tag.get("CustomName")? { @@ -608,6 +753,22 @@ pub fn name_text(tag: &Tag) -> Text { t => crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t)), } } +/// Mob.finalizeSpawn's follow range bonus in the saved attributes. +pub(crate) fn spawn_bonus(tag: &Tag) -> Option { + let Some(Tag::List(attrs)) = tag.get("attributes") else { + return None; + }; + let range = attrs + .iter() + .find(|a| text(a.get("id")).as_deref() == Some("minecraft:follow_range"))?; + let Some(Tag::List(modifiers)) = range.get("modifiers") else { + return None; + }; + let bonus = modifiers + .iter() + .find(|x| text(x.get("id")).as_deref() == Some("minecraft:random_spawn_bonus"))?; + float(bonus.get("amount")) +} pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) -> Option { let kind = types.get(&self::kind(tag)?)?.clone(); let position = position(tag)?; @@ -633,6 +794,11 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - } } } + if let Some(bonus) = spawn_bonus(tag) { + use crate::mobs::finalize::{Attr, Op, add_modifier}; + let id = "minecraft:random_spawn_bonus"; + add_modifier(&mut m, Attr::FollowRange, id, bonus, Op::AddMultipliedBase); + } m.health = float(tag.get("Health")).map_or(m.attrs.max_health, |h| h as f32); m.hurt_time = number(tag.get("HurtTime")).unwrap_or(0) as i32; // What it holds (equipment.mainhand / offhand), when saved. @@ -674,7 +840,8 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.pick_up_loot = flag(tag, "CanPickUpLoot"); m.custom_name = custom_name(tag); m.custom_name_text = tag.get("CustomName").map(name_text); - if m.kind.category == "creature" { + m.extra.left_handed = flag(tag, "LeftHanded"); + if m.kind.category == "creature" || m.species() == crate::mobs::Species::Hoglin { m.extra.age = number(tag.get("Age")).unwrap_or(0) as i32; m.extra.forced_age = number(tag.get("ForcedAge")).unwrap_or(0) as i32; m.extra.age_locked = flag(tag, "AgeLocked"); @@ -706,6 +873,16 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - ) { m.extra.flag2 = flag(tag, "IsImmuneToZombification"); m.extra.counter2 = number(tag.get("TimeInOverworld")).unwrap_or(0) as i32; + if m.species() == crate::mobs::Species::Piglin + && let Some(Tag::List(items)) = tag.get("Inventory") + { + // InventoryCarrier.readInventoryFromTag (eight slots). + m.extra.inventory = items + .iter() + .filter_map(crate::save::item_from_nbt) + .take(8) + .collect(); + } } if matches!( m.species(), @@ -847,6 +1024,18 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - { crate::mobs::creaking::set_transient(&mut m, [home[0], home[1], home[2]]); } + if m.species() == crate::mobs::Species::Turtle { + // Turtle.readAdditionalSaveData: `home_pos` (else where it stands) and `has_egg`. + m.extra.flag = flag(tag, "has_egg"); + m.extra.home = Some(match tag.get("home_pos") { + Some(Tag::IntArray(home)) if home.len() == 3 => [home[0], home[1], home[2]], + _ => [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ], + }); + } if m.species() == crate::mobs::Species::Wither { m.extra.counter = number(tag.get("Invul")).unwrap_or(0) as i32; } @@ -925,6 +1114,10 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - if !crate::mobs::finalize::ageable(m.species()) && flag(tag, "IsBaby") { crate::mobs::finalize::set_baby(&mut m, true); } + // Zombie.readAdditionalSaveData: setCanBreakDoors. + if crate::mobs::doors::is_zombie(m.species()) { + crate::mobs::doors::set_can_break_doors(&mut m, flag(tag, "CanBreakDoors")); + } crate::mobs::raider::read_nbt(&mut m, tag); crate::mobs::riders::read_nbt(&mut m, tag); // A mob saved mid-death finishes dying; one saved dead is dropped. @@ -1043,18 +1236,18 @@ pub fn orb_to_nbt(o: &ExperienceOrb, uuid: [i32; 4]) -> Tag { ("Health", Tag::Short(5)), ("Age", Tag::Short(o.age.min(i16::MAX as u32) as i16)), ("Value", Tag::Short(o.value.min(i16::MAX as u32) as i16)), - ("Count", Tag::Int(1)), + ("Count", Tag::Int(o.count.min(i32::MAX as u32) as i32)), ] { put(&mut tag, key, value); } tag } -/// One Horizon orb per counted orb (vanilla merges orbs of equal value). +/// One orb with its merged `Count`. pub fn orbs_from_nbt(tag: &Tag) -> Vec { let Some(position) = position(tag) else { return Vec::new(); }; - let count = number(tag.get("Count")).unwrap_or(1).clamp(1, 64) as usize; + let count = number(tag.get("Count")).unwrap_or(1).max(1) as u32; let orb = ExperienceOrb { id: 0, position, @@ -1063,8 +1256,10 @@ pub fn orbs_from_nbt(tag: &Tag) -> Vec { value: number(tag.get("Value")).unwrap_or(1).max(1) as u32, age: number(tag.get("Age")).unwrap_or(0).max(0) as u32, on_ground: flag(tag, "OnGround"), + count, + ticks: 0, }; - vec![orb; count] + vec![orb] } /// `Projectile` + `AbstractArrow.addAdditionalSaveData` of a live arrow; @@ -1313,6 +1508,79 @@ pub fn painting_from_nbt(tag: &Tag) -> Option<([i32; 3], u8, String)> { let facing = (number(tag.get("facing")).unwrap_or(0) & 3) as u8; Some((pos, facing, text(tag.get("variant"))?)) } +/// Cushion.addAdditionalSaveData: the block it sits on and its colour. +pub fn cushion_to_nbt(c: &Cushion, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { + let base = Base { + id: "minecraft:cushion", + uuid, + position: c.position, + motion: Vec3::ZERO, + rotation: [c.yaw, 0.0], + on_ground: false, + fall_distance: 0.0, + }; + let mut tag = base.tag(raw); + put(&mut tag, "block_pos", Tag::IntArray(c.pos.to_vec())); + put(&mut tag, "color", string(c.color_name())); + tag +} +/// The position, block position, yaw and colour of a saved cushion. +pub fn cushion_from_nbt(tag: &Tag, id: u32) -> Option { + let position = position(tag)?; + let pos = match tag.get("block_pos") { + Some(Tag::IntArray(v)) if v.len() == 3 => [v[0], v[1], v[2]], + _ => [ + position.x.floor() as i32, + position.y.floor() as i32, + position.z.floor() as i32, + ], + }; + let yaw = match tag.get("Rotation") { + Some(Tag::List(l)) => l + .first() + .and_then(|v| crate::save::float(Some(v))) + .unwrap_or(0.0) as f32, + _ => 0.0, + }; + let color = + crate::entities::dye_index(&text(tag.get("color")).unwrap_or_else(|| "white".into())); + Some(Cushion { + id, + position, + pos, + yaw, + color, + check_interval: 0, + }) +} + +#[cfg(test)] +mod cushion_tests { + use super::*; + + #[test] + fn cushion_save_preserves_color_anchor_rotation_and_unknown_data() { + let cushion = Cushion { + id: 7, + position: Vec3::new(-1.5, 64.5, 3.5), + pos: [-2, 64, 3], + yaw: 270.0, + color: 14, + check_interval: 55, + }; + let raw = Tag::compound([("CustomName", string("Seat"))]); + let tag = cushion_to_nbt(&cushion, [1, 2, 3, 4], Some(&raw)); + assert_eq!(text(tag.get("CustomName")).as_deref(), Some("Seat")); + let loaded = cushion_from_nbt(&tag, 8).unwrap(); + assert_eq!(loaded.id, 8); + assert_eq!(loaded.position, cushion.position); + assert_eq!(loaded.pos, cushion.pos); + assert_eq!(loaded.yaw, cushion.yaw); + assert_eq!(loaded.color_name(), "red"); + assert_eq!(loaded.check_interval, 0); + assert_eq!(loaded.bounds(), cushion.bounds()); + } +} /// ItemFrame.addAdditionalSaveData. pub fn item_frame_to_nbt(f: &ItemFrame, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { let (lo, hi) = f.bounds(); @@ -1840,7 +2108,7 @@ mod tests { assert_eq!(number(tag.get("Health")), Some(5)); } #[test] - fn orbs_expand_their_count() { + fn orbs_keep_their_count() { let o = ExperienceOrb { id: 0, position: Vec3::new(1.0, 2.0, 3.0), @@ -1849,12 +2117,14 @@ mod tests { value: 7, age: 3, on_ground: false, + count: 3, + ticks: 0, }; - let mut tag = orb_to_nbt(&o, [0; 4]); - put(&mut tag, "Count", Tag::Int(3)); + let tag = orb_to_nbt(&o, [0; 4]); let back = orbs_from_nbt(&tag); - assert_eq!(back.len(), 3); + assert_eq!(back.len(), 1); assert_eq!(back[0].value, 7); + assert_eq!(back[0].count, 3); } } @@ -1919,12 +2189,39 @@ fn restore_axolotl_memories(m: &mut Mob, tag: &Tag) { } } const AXOLOTL_VARIANTS: [&str; 5] = ["lucy", "wild", "gold", "cyan", "blue"]; +/// `Salmon.Variant` names, by id. +const SALMON_SIZES: [&str; 3] = ["small", "medium", "large"]; +/// `TropicalFish.Pattern` names in enum order: the six small patterns, then +/// the six large ones (the order of `extra.variant`). +const TROPICAL_PATTERNS: [&str; 12] = [ + "kob", + "sunstreak", + "snooper", + "dasher", + "brinely", + "spotty", + "flopper", + "stripey", + "glitter", + "blockfish", + "betty", + "clayfish", +]; +/// `Bucketable.saveDefaultDataToBucketTag`, with the age an axolotl and a +/// tadpole add (`saveToBucketTag`). pub fn bucket_data(m: &Mob) -> Tag { - let mut data = Tag::compound([ - ("Age", Tag::Int(m.extra.age)), - ("AgeLocked", Tag::Byte(i8::from(m.extra.age_locked))), - ("Health", Tag::Float(m.health.to_bits())), - ]); + let mut data = Tag::compound([("Health", Tag::Float(m.health.to_bits()))]); + if matches!( + m.species(), + crate::mobs::Species::Axolotl | crate::mobs::Species::Tadpole + ) { + put(&mut data, "Age", Tag::Int(m.extra.age)); + put( + &mut data, + "AgeLocked", + Tag::Byte(i8::from(m.extra.age_locked)), + ); + } for (key, on) in [ ("NoAI", m.no_ai), ("Silent", m.silent), @@ -1954,6 +2251,29 @@ pub fn bucket_components(m: &Mob) -> crate::item_data::StackData { .unwrap_or(&"lucy"); data.set_other("minecraft:axolotl/variant", Some(string(variant))); } + // Salmon.saveToBucketTag: the size. + if m.species() == crate::mobs::Species::Salmon { + let size = SALMON_SIZES + .get(usize::from(m.extra.variant)) + .unwrap_or(&"medium"); + data.set_other("minecraft:salmon/size", Some(string(size))); + } + // TropicalFish.saveToBucketTag: the pattern and both colours. + if m.species() == crate::mobs::Species::TropicalFish { + let dye = |i: u8| crate::mobs::render::DYE_NAMES[usize::from(i) & 15]; + let pattern = TROPICAL_PATTERNS + .get(usize::from(m.extra.variant)) + .unwrap_or(&"kob"); + data.set_other("minecraft:tropical_fish/pattern", Some(string(pattern))); + data.set_other( + "minecraft:tropical_fish/base_color", + Some(string(dye(m.extra.variant2))), + ); + data.set_other( + "minecraft:tropical_fish/pattern_color", + Some(string(dye(m.extra.variant3))), + ); + } data } pub fn load_bucket_data(m: &mut Mob, stack: &crate::items::ItemStack) { @@ -2004,6 +2324,39 @@ pub fn load_bucket_data(m: &mut Mob, stack: &crate::items::ItemStack) { { m.extra.variant = id as u8; } + // Salmon.applyImplicitComponents: the size. + if m.species() == crate::mobs::Species::Salmon + && let Some(name) = text(components.other("minecraft:salmon/size")) + && let Some(id) = SALMON_SIZES + .iter() + .position(|&v| v == name.trim_start_matches("minecraft:")) + { + m.extra.variant = id as u8; + } + // TropicalFish.applyImplicitComponent: the pattern and both colours. + if m.species() == crate::mobs::Species::TropicalFish { + let name = |key| text(components.other(key)); + let dye = |key| { + name(key).and_then(|n| { + crate::mobs::render::DYE_NAMES + .iter() + .position(|&v| v == n.trim_start_matches("minecraft:")) + }) + }; + if let Some(id) = name("minecraft:tropical_fish/pattern").and_then(|n| { + TROPICAL_PATTERNS + .iter() + .position(|&v| v == n.trim_start_matches("minecraft:")) + }) { + m.extra.variant = id as u8; + } + if let Some(id) = dye("minecraft:tropical_fish/base_color") { + m.extra.variant2 = id as u8; + } + if let Some(id) = dye("minecraft:tropical_fish/pattern_color") { + m.extra.variant3 = id as u8; + } + } } #[cfg(test)] diff --git a/crates/horizon-client/src/falling_block.rs b/crates/horizon-client/src/falling_block.rs index 79ca28f7a..4faf105b9 100644 --- a/crates/horizon-client/src/falling_block.rs +++ b/crates/horizon-client/src/falling_block.rs @@ -35,6 +35,18 @@ impl Damage { ..Self::default() } } + /// A block that starts to fall: anvils hurt, and a brushable block + /// breaks where it lands (BrushableBlock.tick: disableDrop). + pub fn falling(block: &str) -> Self { + if block.ends_with("anvil") { + Self::anvil() + } else { + Self { + cancel_drop: block.starts_with("minecraft:suspicious_"), + ..Self::default() + } + } + } pub fn from_nbt(tag: &Tag, anvil: bool) -> Self { Self { hurt_entities: number(tag.get("HurtEntities")).map_or(anvil, |v| v != 0), @@ -181,6 +193,14 @@ pub fn hurt_mobs(mobs: &mut [Mob], position: Vec3, amount: f32) { #[cfg(test)] mod tests { use super::*; + #[test] + fn only_brushable_blocks_break_where_they_land() { + assert!(Damage::falling("minecraft:suspicious_gravel").cancel_drop); + assert!(Damage::falling("minecraft:suspicious_sand").cancel_drop); + assert!(!Damage::falling("minecraft:gravel").cancel_drop); + assert!(Damage::falling("minecraft:chipped_anvil").hurt_entities); + } + #[test] fn impact_uses_ceil_distance_capped_damage_and_positive_damage_wear() { let damage = Damage::anvil(); diff --git a/crates/horizon-client/src/font.rs b/crates/horizon-client/src/font.rs index 1903cab7e..d0e8c8499 100644 --- a/crates/horizon-client/src/font.rs +++ b/crates/horizon-client/src/font.rs @@ -1201,6 +1201,31 @@ mod tests { assert!(!font.take_patches().is_empty()); } + /// A renderer rebuilt over the same font (the loading screen's handoff) + /// makes its atlas texture from the textures alone, so the glyphs it had + /// rasterized into the previous texture must be placed into the new one. + #[test] + fn a_rebuilt_atlas_gets_its_glyphs_again() { + let sheet = png(16, 8, |x, _| x < 2 || (8..14).contains(&x)); + let default = br#"{"providers":[{"type":"bitmap","file":"minecraft:font/a.png","ascent":7,"chars":["ab"]}]}"#; + let root = root( + "rebuild", + &[ + ("assets/minecraft/font/default.json", default), + ("assets/minecraft/textures/font/a.png", &sheet), + ], + ); + let font = load(&root); + let _ = std::fs::remove_dir_all(&root); + let first = font.glyph('a'); + assert_eq!(font.take_patches().len(), 1); + font.reset_cache(); + // Nothing is left over: drawing the character again places its pixels. + assert!(font.take_patches().is_empty()); + assert_eq!(font.glyph('a').advance, first.advance); + assert_eq!(font.take_patches().len(), 1); + } + #[test] fn provider_filters_follow_the_font_options() { let sheet = png(8, 8, |x, _| x < 4); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f042bc28d..23e28eab7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -18,6 +18,9 @@ mod boats; mod books; mod bossbars; mod breezes; +mod bundles; +mod campfire; +mod campfire_douse; mod cartography; mod chat; mod client_ambient; @@ -33,6 +36,7 @@ mod copper_golems; mod creaking; mod creatures; mod crossbow; +pub(crate) mod cushions; mod debug_keys; mod decorated_pot; mod dedicated; @@ -80,6 +84,7 @@ mod lan_mobs; mod lan_mount_menu; mod lan_particles; mod lan_pvp; +mod lan_quiet; mod lan_screen; mod lan_stations; mod lan_trading; @@ -98,7 +103,12 @@ mod maps; mod minecarts; mod mob_blocks; mod mob_gear; +mod mod_browser; +#[cfg(feature = "mods")] +mod mod_browser_recipes; mod mod_input; +#[cfg(feature = "mods")] +mod mod_recipes; mod mod_render; mod mods; mod mount_menu; @@ -147,6 +157,7 @@ mod scoreboard; mod screens; mod sculk; mod sculk_fixture; +mod server_mods; mod server_packs; mod server_travel; mod shader_packs; @@ -181,6 +192,7 @@ mod win; mod wind; mod wither; mod world_loading; +mod zombie_reinforcements; mod zombie_villagers; use horizon_client::{ Result, @@ -364,7 +376,7 @@ impl Options { match arg.as_str() { "--help" | "-h" => { println!( - "Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --width N, --height N Window size (default 1280 x 720)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --in-frame Run single player's world in the frame, not on its server thread\n --pregen Add Horizon's /pregen command (docs/pregeneration.md)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.", + "Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --width N, --height N Window size (default 1280 x 720)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --quickPlaySingleplayer WORLD Open this world of saves/ at start, only if it exists (vanilla's)\n --quickPlayMultiplayer HOST[:PORT] The same as --server (vanilla's name)\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --in-frame Run single player's world in the frame, not on its server thread\n --pregen Add Horizon's /pregen command (docs/pregeneration.md)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.", horizon_core::VANILLA_VERSION ); return Ok(None); @@ -419,6 +431,16 @@ impl Options { "--width" => o.window_size[0] = value.parse::()?.max(1), "--height" => o.window_size[1] = value.parse::()?.max(1), "--world" => o.world = Some(value), + // Vanilla's quick play (Main, QuickPlay.joinSingleplayerWorld): only a + // world that exists opens; else the title screen. --world also creates one. + "--quickPlaySingleplayer" => { + let folder = std::env::current_dir()?.join("saves").join(&value); + if folder.join("level.dat").is_file() { + o.world = Some(value); + } else { + eprintln!("Quick play: there is no world {value} in saves/"); + } + } "--dev-mod" => o.dev_mods.push(std::path::absolute(&value)?), "--benchmark" => { if horizon_client::benchmark::scenes(&value).is_none() { @@ -429,7 +451,7 @@ impl Options { } o.benchmark = Some(value); } - "--server" => o.server = Some(value), + "--server" | "--quickPlayMultiplayer" => o.server = Some(value), "--name" => o.player_name = Some(value), "--session-file" => session_file = Some(value), "--control-socket" => o.control = Some(value.into()), @@ -532,6 +554,8 @@ struct GameLevel<'w> { events: &'w mut Vec, dimension: LevelDimension, darken: i32, + /// The environment of the level's dimension (`SUN_ANGLE`). + environment: &'w Environment, raining: bool, thundering: bool, player_box: Option<([f64; 3], [f64; 3])>, @@ -540,6 +564,8 @@ struct GameLevel<'w> { player_collision: Option, /// Minecart boxes (detector rails). cart_boxes: Vec<([f64; 3], [f64; 3])>, + /// Arrow and thrown trident boxes (wooden buttons). + arrow_boxes: Vec<([f64; 3], [f64; 3])>, /// The other entities that keep blocks from being placed into them. blockers: Blockers<'w>, biomes: &'w Biomes, @@ -552,6 +578,11 @@ struct GameLevel<'w> { loot: Option>, registry: &'static horizon_world::registry::BlockRegistry, rules: horizon_world::level::GameRules, + /// `Difficulty.getId()` (peaceful 0 .. hard 3). + difficulty: i32, + /// The feet of the players who keep fire spreading around them: the local + /// player and the LAN guests in this level, spectators aside. + fire_players: Vec<[f64; 3]>, /// Block loot random sequences (`ServerLevel.getRandomSequence`). rand_sequences: &'w mut horizon_client::random_sequences::RandomSequences, pending: &'w mut spill::Pending, @@ -561,6 +592,9 @@ struct GameLevel<'w> { random_tick_sections: &'w mut horizon_client::random_tick_sections::RandomTickSections, /// Players with each chest open (a trapped chest's signal). lid_openers: &'w HashMap<(i32, i32, i32), i32>, + /// `Level.isClientSide`: a client's copy of the level (a guest of a LAN + /// world, a window on its server thread, a dedicated server's client). + client_side: bool, } struct PlayerCollision { y: f64, @@ -650,6 +684,9 @@ impl GameLevel<'_> { } } impl LevelAccess for GameLevel<'_> { + fn is_client_side(&self) -> bool { + self.client_side + } fn world_surface(&self, x: i32, z: i32) -> i32 { self.world.world_surface(x, z, |s| self.facts.is_air(s)) } @@ -715,6 +752,34 @@ impl LevelAccess for GameLevel<'_> { fn game_rules(&self) -> horizon_world::level::GameRules { self.rules } + fn difficulty(&self) -> i32 { + self.difficulty + } + /// `ServerLevel.canSpreadFireAround`: a player (not a spectator) closer + /// than the `fire_spread_radius_around_player` rule to the block's corner + /// (`ChunkMap.anyPlayerCloseEnoughTo`); -1 spreads everywhere. + fn can_spread_fire_around(&self, pos: BlockPos) -> bool { + let radius = self.rules.fire_spread_radius_around_player; + radius == -1 + || self.fire_players.iter().any(|p| { + let d = [ + p[0] - f64::from(pos.x), + p[1] - f64::from(pos.y), + p[2] - f64::from(pos.z), + ]; + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < f64::from(radius) * f64::from(radius) + }) + } + fn increased_fire_burnout(&self, pos: BlockPos) -> bool { + self.world + .chunks + .get(&(pos.x >> 4, pos.z >> 4)) + .is_some_and(|chunk| { + self.biomes + .get(chunk.biome(pos.x, pos.y, pos.z)) + .increased_fire_burnout + }) + } fn block_state(&self, pos: BlockPos) -> BlockStateId { self.world.block(pos.x, pos.y, pos.z) } @@ -759,6 +824,11 @@ impl LevelAccess for GameLevel<'_> { fn sky_darken(&self) -> i32 { self.darken } + fn sun_angle(&self, _pos: BlockPos) -> f32 { + self.environment + .sample(self.world.day_time, None, None) + .sun_angle + } fn is_raining(&self) -> bool { self.raining } @@ -827,8 +897,9 @@ impl LevelAccess for GameLevel<'_> { 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 players (the host and the LAN guests, mobs) and the minecarts. + /// Entities that trigger pressure plates, tripwires, detector rails and + /// wooden buttons: the players (the host and the LAN guests, mobs) and + /// the minecarts, and for `EntityQuery::Arrows` the arrows. fn count_entities(&self, area: Aabb, query: EntityQuery) -> usize { let hit = |(lo, hi): &([f64; 3], [f64; 3])| { area.intersects(Aabb::new( @@ -837,6 +908,7 @@ impl LevelAccess for GameLevel<'_> { )) }; let carts = || self.cart_boxes.iter().filter(|b| hit(b)).count(); + let arrows = || self.arrow_boxes.iter().filter(|b| hit(b)).count(); let players = || { self.player_box .iter() @@ -846,6 +918,7 @@ impl LevelAccess for GameLevel<'_> { }; match query { EntityQuery::Minecart => carts(), + EntityQuery::Arrows => arrows(), EntityQuery::Mobs => players(), EntityQuery::Everything => players() + carts(), } @@ -853,7 +926,16 @@ impl LevelAccess for GameLevel<'_> { fn emit(&mut self, event: LevelEvent) { match event { // Block.dropResources draws its loot and spots right away. - LevelEvent::DropResources { pos, state } => self.drop_resources_now(pos, state), + // `popResource` only drops server-side (`!level.isClientSide`): + // a client's moveBlocks (a piston's block event) skips it. + LevelEvent::DropResources { pos, state } if !self.client_side => { + self.drop_resources_now(pos, state) + } + LevelEvent::DropResources { .. } => {} + // `ClientLevel.playSeededSound` plays only when the excluded + // player is this client's own: the block's `playSound(null, ...)` + // (a piston's move, a note) reaches it from the server instead. + LevelEvent::Sound { .. } if self.client_side => {} // Block.popResource of the block's own item (tall flowers, flower beds). LevelEvent::BlockEvent { pos, @@ -1194,6 +1276,8 @@ struct Game<'a> { inv_clicks: horizon_client::container_screen::Clicks, /// The Mouse Tweaks extra's drag and wheel (`tweaks`). tweaks: tweaks::Tweaks, + /// The wheel and hovered slot of `BundleMouseActions`. + bundle_mouse: bundles::BundleMouse, /// The last inventory click, for the double click that gathers a stack. last_inv_click: Option<(std::time::Instant, usize, bool)>, /// `lastQuickMoved`: what the last Shift click moved, which a Shift @@ -1266,6 +1350,13 @@ struct Game<'a> { /// Controllers (Horizon's own). pad: pad::Pads, frames: u64, + /// `item_level` for one frame, game time, day time and dimension. + item_level_cache: std::cell::RefCell< + Option<( + (u64, i64, i64, &'static str), + horizon_assets::item_model::LevelState, + )>, + >, /// Frames drawn with the player in the world, for `--world-frames`. world_frames: u64, fps: f32, @@ -1354,6 +1445,10 @@ struct Game<'a> { titles: titles::Titles, /// `Hud.toolHighlightTimer`: the selected item name. tool_highlight: horizon_client::hud_overlays::ToolHighlight, + /// `Hud.autosaveIndicatorValue`. + saving_indicator: horizon_client::hud_overlays::SavingIndicator, + /// This game's world is autosaving this tick (`MinecraftServer.isSaving`). + autosaving: bool, applied_modifiers: Vec<(String, String)>, experience: Experience, orbs: Vec, @@ -1429,6 +1524,8 @@ struct Game<'a> { map_frame_model: frames::FrameModel, glow_map_frame_model: frames::FrameModel, armor_stands: Vec, + /// `Cushion` decoration entities (game/cushions.rs). + cushions: Vec, /// Entities of types Horizon does not simulate. others: Vec, armor_stand_assets: armor_stands::ArmorStandAssets, @@ -1444,6 +1541,8 @@ struct Game<'a> { boat_models: boats::BoatModels, /// EndCrystalModel's baked layer. crystal_model: Option, + /// CushionModel's baked layer. + cushion_model: Option, carts: Vec, /// Songs playing from jukeboxes (tracked sound handles). jukebox_sounds: HashMap<(i32, i32, i32), u64>, @@ -1580,6 +1679,8 @@ struct Game<'a> { /// position) for the guests. lan_block_events: Vec<([i32; 3], i32, i32, u32)>, lan_entity_events: Vec<(i32, i8, [f64; 3])>, + /// Successful crits (attacking guest, hit entity), queued while the hub is taken. + lan_critical_hits: Vec<(Option, i32, bool)>, /// Global level events for every guest (`ServerLevel.globalLevelEvent`). lan_global_events: Vec<(i32, [i32; 3], i32)>, /// `ContainerOpenersCounter`: how many players (the host and the guests) @@ -1727,9 +1828,46 @@ impl Game<'_> { fn reach(&self) -> f64 { if self.creative { 5.0 } else { 4.5 } } + /// Outline shapes that depend on more than the block state, as one box + /// in block space: `LightBlock` and `ScaffoldingBlock.getShape` are a full + /// block while the main hand holds the block's own item + /// (`CollisionContext.isHoldingItem`), and `ShulkerBoxBlock.getShape` + /// grows with the lid (`ShulkerBoxBlockEntity.getBoundingBox`). + fn context_outline(&self, pos: [i32; 3], state: BlockStateId) -> Option<[f64; 6]> { + let name = &self.res.facts().get(state).name; + if matches!(&**name, "minecraft:light" | "minecraft:scaffolding") { + return self + .held() + .is_some_and(|s| *s.item == **name) + .then_some([0.0, 0.0, 0.0, 1.0, 1.0, 1.0]); + } + if !name.ends_with("shulker_box") { + return None; + } + let progress = self.be_anims.shulkers.get(&pos).map_or(0.0, |s| s.progress); + let facing = self + .pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("facing").cloned()); + let d = facing_offset(facing.as_deref().unwrap_or("up")); + let mut b = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]; + for a in 0..3 { + match d[a] { + 1 => b[a + 3] += 0.5 * f64::from(progress), + -1 => b[a] -= 0.5 * f64::from(progress), + _ => {} + } + } + Some(b) + } /// 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]); + if let Some(b) = self.context_outline(pos, state) { + return vec![std::array::from_fn(|i| f64::from(pos[i % 3]) + b[i])]; + } let f = self.res.facts().get(state); let o = if f.outline_offset { self.pack @@ -2024,6 +2162,33 @@ impl Game<'_> { } /// `TerrainParticle` at `pos`: the model's particle sprite and tint source /// 0's `colorAsTerrainParticle` (white when the block has none). + /// `HoneyBlock.showSlideParticles` (entity event 53): five honey block + /// particles at the entity. + fn honey_slide_particles(&mut self, at: [f64; 3]) { + use horizon_client::particles::{ParticleOptions, ParticleType}; + let Some(honey) = self + .pack + .assets + .registry + .default_state("minecraft:honey_block") + else { + return; + }; + let block = [ + at[0].floor() as i32, + at[1].floor() as i32, + at[2].floor() as i32, + ]; + if let Some((sprite, tint)) = self.particle_sprite(honey, block) { + for _ in 0..5 { + self.particles.add( + &ParticleOptions::block(ParticleType::Block, sprite.clone(), tint), + at, + [0.0; 3], + ); + } + } + } fn particle_sprite(&self, state: BlockStateId, pos: [i32; 3]) -> Option<(String, u32)> { let sprite = Self::block_particle_sprite(&self.pack, state)?; let chunks = &self.world.chunks; @@ -2159,8 +2324,9 @@ impl Game<'_> { ticks: 0, }); } - /// `Block.getDrops`: the block's loot table, drawing from its server random - /// sequence (`LootContext.Builder.create`), else the level random. + /// `Block.getDrops` for a block a player breaks: the block's loot table + /// with the player as `this`, drawing from its server random sequence + /// (`LootContext.Builder.create`), else the level random. fn block_loot_at( &mut self, pos: [i32; 3], @@ -2174,9 +2340,9 @@ impl Game<'_> { let random = self.rand_sequences.get(&sequence, self.level.seed); self.res .items() - .block_drops_with(registry, state, held, &dynamic, random) + .block_drops_by_player(registry, state, held, &dynamic, random) } - None => self.res.items().block_drops_with( + None => self.res.items().block_drops_by_player( registry, state, held, @@ -2220,11 +2386,13 @@ impl Game<'_> { // Player.drop: the drop statistics. self.stats.add("dropped", &thrown.item, thrown.count as i32); self.stats.custom("drop", 1); - self.throw_from_eyes(thrown, eye); + self.throw_from_eyes(thrown, eye, true); } /// `Player.createItemStackToDrop`: an item entity thrown from the eyes - /// along the view direction. - fn throw_from_eyes(&mut self, thrown: ItemStack, eye: [f64; 3]) { + /// along the view direction. `thrown_from_hand` (`drop(stack, true)`, the + /// drop key) names the player as the thrower; `drop(stack, false)`, for + /// what no longer fits in the inventory, does not. + fn throw_from_eyes(&mut self, thrown: ItemStack, eye: [f64; 3], thrown_from_hand: bool) { let (yaw, pitch) = ( f64::from(self.yaw).to_radians(), f64::from(self.pitch).to_radians(), @@ -2238,11 +2406,18 @@ impl Game<'_> { yaw.cos() * pitch.cos() * 0.3 + spread.sin() * strength, ]; self.spawn_item(thrown, [eye[0], eye[1] - 0.3, eye[2]], v, 40); - if self.lan_acting.is_none() { - let uuid = self.level.ensure_player_uuid(); + if thrown_from_hand { + let uuid = self.acting_player_uuid(); self.dropped.last_mut().unwrap().thrower = Some(uuid); } } + /// The UUID of the player acting: the guest whose turn it is, else the host. + pub(super) fn acting_player_uuid(&mut self) -> [i32; 4] { + match self.lan_acting_uuid { + Some(guest) => horizon_client::lan::playerdata::uuid_ints(guest), + None => self.level.ensure_player_uuid(), + } + } fn tick_items(&mut self) { let mut items = std::mem::take(&mut self.dropped); // ServerLevel.tick: only entities in entity-ticking chunks tick. @@ -2445,6 +2620,18 @@ impl Game<'_> { ) }) .collect(); + let arrow_boxes = self + .creatures + .projectiles + .iter() + .filter(|p| p.arrow.is_some()) + .map(|p| p.position) + .chain(self.tridents.iter().map(|t| t.position)) + .map(|at| { + let b = horizon_client::arrows::arrow_bounds(at); + (b.min_position().components(), b.max_position().components()) + }) + .collect(); let guest_boxes = self.lan_block_trigger_boxes(); let dimension = match self.dim { Dim::Overworld => LevelDimension::Overworld, @@ -2452,6 +2639,19 @@ impl Game<'_> { Dim::End => LevelDimension::End, }; let rules = self.level_rules(); + let fire_players: Vec<[f64; 3]> = self + .player + .iter() + .filter(|_| !spectator) + .map(|p| [p.position.x, p.position.y, p.position.z]) + .chain(self.lan.iter().flat_map(|h| { + h.hub + .guests + .iter() + .filter(|g| h.hub.here(g) && !g.spectator()) + .map(|g| g.position) + })) + .collect(); let blockers = Blockers { mobs: &self.mobs, armor_stands: &self.armor_stands, @@ -2462,6 +2662,7 @@ impl Game<'_> { }; let mut level = GameLevel { cart_boxes, + arrow_boxes, blockers, world: &mut self.world, facts: self.res.facts(), @@ -2469,6 +2670,11 @@ impl Game<'_> { events: &mut self.level_events, dimension, darken, + environment: match dimension { + LevelDimension::Overworld => self.res.environment(), + LevelDimension::Nether => self.res.nether_environment(), + LevelDimension::End => self.res.end_environment(), + }, raining: rain > 0.2, thundering: thunder > 0.9, player_box, @@ -2482,12 +2688,15 @@ impl Game<'_> { loot: horizon_client::structure_blocks::loot_data(&self.options.resources), registry: self.pack.assets.registry, rules, + difficulty: i32::from(self.ui.difficulty), + fire_players, rand_sequences: &mut self.rand_sequences, pending: &mut self.pending, spill: &mut self.spill, tickets: self.tickets.levels(), random_tick_sections: &mut self.random_tick_sections, lid_openers: &self.lid_openers, + client_side: self.remote.is_some(), }; let result = f(self.res.behaviours(), &mut level, &mut self.block_ticks); self.flush_spill(); @@ -2549,14 +2758,15 @@ impl Game<'_> { (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), - } - }); + let sources = + (!self.options.execution_role.is_client() || !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 @@ -2591,8 +2801,9 @@ impl Game<'_> { .copied() .filter(|&(x, z)| levels.random_ticking(x, z) && ticking_chunk(&self.world, x, z)) .collect(); - // Entity.checkInsideBlocks for the plates, tripwires and detector rails - // under the players (the host and the LAN guests) and the minecarts. + // Entity.checkInsideBlocks for the plates, tripwires, detector rails and + // buttons under the players (the host and the LAN guests), the minecarts + // and the arrows. let mut inside = Vec::new(); let guests = self.lan_block_trigger_boxes(); let boxes = self @@ -2624,6 +2835,24 @@ impl Game<'_> { } } } + // AbstractArrow.applyEffectsFromBlocks: the blocks every arrow passed + // through this tick (a wooden button is pressed by one inside it), and + // the ones a thrown trident is in. + for p in self + .creatures + .projectiles + .iter() + .filter(|p| p.arrow.is_some()) + { + inside.extend(horizon_client::arrows::blocks_inside( + p.previous, p.position, + )); + } + for t in &self.tridents { + inside.extend(horizon_client::arrows::blocks_inside( + t.position, t.position, + )); + } // BigDripleafBlock.entityInside also asks whether the player stands on // the ground and how high its feet are: the leaves its box's feet // layer is inside (the host and the LAN guests). @@ -2785,11 +3014,25 @@ impl Game<'_> { pos, data, } => self.consume_teleport_particles([pos.x, pos.y, pos.z], data), + LevelEvent::LevelEvent { id: 2003, pos, .. } => { + self.eye_break_particles([pos.x, pos.y, pos.z]); + } LevelEvent::LevelEvent { id: 2013, pos, data, } => self.smash_dust(pos, data), + // LevelEventHandler 2002 and 2007: a potion's splash. + LevelEvent::LevelEvent { + id: 2002, + pos, + data, + } => self.potion_splash_particles(pos, data, false), + LevelEvent::LevelEvent { + id: 2007, + pos, + data, + } => self.potion_splash_particles(pos, data, true), LevelEvent::LevelEvent { id: id @ 3002..=3005, pos, @@ -2853,6 +3096,9 @@ impl Game<'_> { "minecraft:block.pointed_dripstone.drip_water_into_cauldron", 2.0, )), + // LevelEvent.SOUND_ZOMBIE_WOODEN_DOOR (attack, break). + 1019 => Some(("minecraft:entity.zombie.attack_wooden_door", 2.0)), + 1021 => Some(("minecraft:entity.zombie.break_wooden_door", 2.0)), 1030 => Some(("minecraft:block.anvil.use", 1.0)), 1029 => Some(("minecraft:block.anvil.destroy", 1.0)), 1031 => Some(("minecraft:block.anvil.land", 0.3)), @@ -2860,6 +3106,8 @@ impl Game<'_> { 1044 => Some(("minecraft:block.smithing_table.use", 1.0)), // LevelEvent.SOUND_PAGE_TURN (a lectern's page). 1043 => Some(("minecraft:item.book.page_turn", 1.0)), + // LevelEvent.SOUND_SPLASH_POTION and its instant twin. + 1053 | 1054 => Some(("minecraft:entity.splash_potion.break", 1.0)), _ => None, }; if let Some((name, volume)) = sound { @@ -2869,12 +3117,17 @@ impl Game<'_> { - self.world.random.next_float()) * 0.8 } - 1029 | 1030 | 1042 | 1043 | 1044 | 1046 | 1047 => { + 1029 | 1030 | 1042 | 1043 | 1044 | 1046 | 1047 | 1053 | 1054 => { self.world.random.next_float() * 0.1 + 0.9 } + 1019 | 1021 => { + (self.world.random.next_float() - self.world.random.next_float()) + * 0.2 + + 1.0 + } _ => 1.0, }; - if matches!(id, 1029 | 1030) { + if matches!(id, 1019 | 1021 | 1029 | 1030 | 1053 | 1054) { // Clients play the anvil sound from its level event; // capturing it also sends a duplicate sound packet. self.audio.play_unshared(name, c, volume, pitch); @@ -2932,11 +3185,9 @@ impl Game<'_> { drop_item: true, fall_distance: 0.0, stuck: Vec3::ZERO, - damage: if self.res.facts().get(state).name.ends_with("anvil") { - horizon_client::falling_block::Damage::anvil() - } else { - Default::default() - }, + damage: horizon_client::falling_block::Damage::falling( + &self.res.facts().get(state).name, + ), saved: None, }); } @@ -3013,6 +3264,11 @@ impl Game<'_> { kind: "hatch_sniffer", .. } => self.hatch_sniffer([pos.x, pos.y, pos.z]), + LevelEvent::BlockEvent { + pos, + state, + kind: "hatch_turtles", + } => self.hatch_turtles([pos.x, pos.y, pos.z], state), LevelEvent::BlockEvent { pos, kind: "portal_spawn", @@ -3034,6 +3290,31 @@ impl Game<'_> { LevelEvent::BlockEntityEvent { pos, a, b, .. } => { self.block_entity_event([pos.x, pos.y, pos.z], a, b) } + // NoteBlock.triggerEvent: a NOTE particle above, coloured by + // the note (`note / 24.0` in the x speed). + LevelEvent::BlockEvent { + pos, + state, + kind: "note_particle", + } => { + use horizon_client::particles::{ParticleOptions, ParticleType}; + let note = self + .pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("note")?.parse::().ok()) + .unwrap_or(0.0); + self.particles.add( + &ParticleOptions::simple(ParticleType::Note), + [ + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 1.2, + f64::from(pos.z) + 0.5, + ], + [note / 24.0, 0.0, 0.0], + ); + } LevelEvent::GrowTree { .. } | LevelEvent::PlaceFeature { .. } | LevelEvent::BlockEvent { .. } => {} @@ -3050,6 +3331,10 @@ impl Game<'_> { .name .clone(); let key = (pos[0], pos[1], pos[2]); + if self.chest_menu_blocked(key, &name) { + // The use still succeeds, but no menu, stat or piglin anger. + return; + } if &*name == "minecraft:lectern" { self.open_lectern(pos); return; @@ -3380,9 +3665,17 @@ impl Game<'_> { self.with_player_actor(|game| game.break_block_as_player(pos)) } fn break_block_as_player(&mut self, pos: [i32; 3]) -> Result<()> { + if !self + .res + .items() + .can_destroy_block(self.held(), self.creative) + { + return Ok(()); + } self.pad_rumble(horizon_client::gamepad::Rumble::BlockBroken); // ServerPlayerGameMode.destroyBlock. let state = self.world.block(pos[0], pos[1], pos[2]); + let broken = state; 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. @@ -3397,7 +3690,7 @@ impl Game<'_> { } else if let Some(tag) = spill::saved_entity(&self.world, pos) { self.pending.record_saved(pos, &tag); } - self.creaking_heart_broken(pos); + self.creaking_heart_broken(pos, true); let hive = match self.world.block_entities.get(&key) { Some(BlockEntity::Beehive(h)) => self.hive_state(pos).map(|s| ((**h).clone(), s)), _ => None, @@ -3414,6 +3707,9 @@ impl Game<'_> { creative, ) }); + if removed { + self.mod_block_event(pos, broken, false); + } if removed && !creative { let held = self.held().cloned(); self.mine_block_with_held(&facts.name, facts.hardness); @@ -3522,6 +3818,7 @@ impl Game<'_> { fn interact_entity(&mut self) -> Result { Ok(self.interact_frame() || self.interact_armor_stand() + || self.interact_cushion() || self.interact_boat() || self.interact_cart() || self.interact_mob()? @@ -3583,6 +3880,10 @@ impl Game<'_> { self.swing_arm(); return Ok(true); } + if self.use_campfire_douse(hit.pos, held.as_ref())? { + self.swing_arm(); + return Ok(true); + } match self.use_respawn_anchor(hit.pos, held.as_ref())? { respawn_anchor::AnchorUse::Charged => { self.swing_arm(); @@ -3708,6 +4009,7 @@ impl Game<'_> { || self.place_painting(hit, &stack) || self.place_item_frame(hit, &stack) || self.place_armor_stand(hit, &stack) + || self.place_cushion(hit, &stack) || self.place_end_crystal(hit, &stack)) { return Ok(true); @@ -3756,6 +4058,7 @@ impl Game<'_> { return Ok(true); }; let target = [pos.x, pos.y, pos.z]; + self.mod_block_event(target, state, true); 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); @@ -3998,7 +4301,12 @@ impl Game<'_> { return Ok(()); }; // GameType.isBlockPlacingRestricted: adventure and spectator. - if !self.may_build() { + if !self.may_build() + || !self + .res + .items() + .can_destroy_block(self.held(), self.creative) + { self.mining = None; return Ok(()); } @@ -4174,6 +4482,12 @@ impl Game<'_> { // The world's spawn from the start, not only once saved: a bed set // before the first save must not become it. self.level.world_spawn.get_or_insert([x, y, z]); + // The "Bonus Chest" create-world option, placed once with the spawn. + if horizon_client::save::WorldGen::read(&self.world_root) + .is_some_and(|g| g.bonus_chest) + { + self.place_bonus_chest([x, y, z])?; + } } let s = self .level @@ -4272,11 +4586,16 @@ impl Game<'_> { if running { self.world.game_time += 1; if self.ui.rules.bool("advance_weather") { - self.world.weather.tick(&mut self.world.random); + self.world.weather.tick_timers(&mut self.world.random); } + self.world.weather.tick_levels(); self.tick_weather_effects(); } - if self.ticks.is_multiple_of(6000) { + self.autosaving = self.ticks.is_multiple_of(6000); + if let Some(serving) = &self.serving { + serving.set_saving(self.autosaving); + } + if self.autosaving { self.save_game_with(false)?; } if running { @@ -4289,6 +4608,7 @@ impl Game<'_> { self.update_totem_ready(); self.tick_command_extras(); self.tick_mods(); + self.tick_server_mods(); let camera_eye = self.camera_eye_height(); let stick = self.pad_move(); if self.riding.is_some() && self.player.is_some() { @@ -4371,12 +4691,6 @@ impl Game<'_> { let events = std::mem::take(&mut player.events); let spin_hit = player.spin_hit.take(); let glider_wear = std::mem::take(&mut player.glider_wear); - if glider_wear > 0 - && !self.creative - && let Some(elytra) = self.armor[1].as_mut() - { - elytra.damage += glider_wear; - } let feet = [player.position.x, player.position.y, player.position.z]; let player_velocity = [player.velocity.x, player.velocity.y, player.velocity.z]; self.previous_eye = self.eye; @@ -4387,9 +4701,36 @@ impl Game<'_> { }; self.eye += (camera_eye.unwrap_or(eye_height) - self.eye) * 0.5; let crouching = player.pose == horizon_client::pose::Pose::Crouching; + // `LivingEntity.baseTick` (Soul Speed) comes before `aiStep` (the + // glide's wear): both draw from the level random. + if let Some((at, velocity)) = self.tick_soul_speed() { + self.particles.send_particles( + &horizon_client::particles::ParticleOptions::simple( + horizon_client::particles::ParticleType::Soul, + ), + at, + velocity, + 1.0, + 0, + ); + if let Some(host) = self.lan.as_ref() { + lan_particles::send_soul_particle(host, at, velocity); + } + } + // `ItemStack.hurtAndBreak` for the glide: Unbreaking can save the wear. + if glider_wear > 0 + && !self.creative + && let Some(stack) = self.armor[1].clone() + { + let loss = self.durability_loss(&stack, glider_wear); + if let Some(elytra) = self.armor[1].as_mut() { + elytra.damage += loss; + } + } self.tick_avatar(before, riding); self.end_spin_attack(spin_hit); self.record_combat(&events); + self.wear_armor(&events); for event in events { match event { MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, feet), @@ -4465,9 +4806,32 @@ impl Game<'_> { }; self.audio.play(name, Some(feet), volume, pitch); } + // LivingEntity.checkFallDamage: the block's crumbs where the fall landed. + MotionEvent::Fall(horizon_client::landing::FallEvent::Particles { + state, + position, + count, + speed, + }) => self.landing_dust(None, state, position, count, speed), MotionEvent::Fall(event) => self.landing_block_updates(&event), MotionEvent::Snowflake { position, velocity } => self.snowflake(position, velocity), MotionEvent::EnterBlock { state } => self.trigger_enter_block(state), + MotionEvent::HoneySlide { + sound, particles, .. + } => { + if sound { + self.audio + .play("minecraft:block.honey_block.slide", Some(feet), 1.0, 1.0); + } + if particles { + self.honey_slide_particles(feet); + // The server's event 53 reaches the guests too. + let id = self.lan.as_ref().map(|h| h.host_entity); + if let Some(id) = id { + self.lan_entity_event(id, 53, feet); + } + } + } MotionEvent::InsidePortal { pos } => self.player_inside_nether_portal(pos), MotionEvent::CauldronExtinguish { pos } => self.cauldron_extinguish(pos), MotionEvent::InsideWitherRose => self.wither_rose_contact(), @@ -4562,7 +4926,7 @@ impl Game<'_> { && let Some(stack) = self.carried.take() && let Some(eye) = self.eye_position() { - self.throw_from_eyes(stack, eye); + self.throw_from_eyes(stack, eye, false); } } self.tick_world(running) @@ -4570,6 +4934,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.share_spawn_conditions(); self.update_chunk_tickets(); horizon_client::spans::time("tick_effects", || self.tick_effects(running)); // Player.tick's ItemCooldowns.tick for the window's player (a @@ -4577,6 +4942,7 @@ impl Game<'_> { self.shield_cooldown = self.shield_cooldown.saturating_sub(1); self.cooldowns.tick(); horizon_client::spans::time("tick_using", || self.tick_using()); + self.tick_bundle_hover(); horizon_client::spans::time("tick_hud", || self.tick_hud()); // The player's digging comes in with its packets, before the level // ticks; ServerLevel.tick then runs the scheduled and random block @@ -4591,6 +4957,7 @@ impl Game<'_> { horizon_client::spans::time("tick_paintings", || self.tick_paintings()); horizon_client::spans::time("tick_item_frames", || self.tick_item_frames()); horizon_client::spans::time("tick_armor_stands", || self.tick_armor_stands()); + horizon_client::spans::time("tick_cushions", || self.tick_cushions()); horizon_client::spans::time("tick_boats", || self.tick_boats()); horizon_client::spans::time("tick_carts", || self.tick_carts()); horizon_client::spans::time("tick_thunder", || self.tick_thunder()); @@ -4799,7 +5166,10 @@ impl Game<'_> { if capture && !self.focused { return; } - if !capture { + if capture { + // The inventory's screens are behind us: no drag survives them. + self.reset_inventory_clicks(); + } else { self.stop_mining(); } // The real pointer takes over from an agent's. @@ -4878,7 +5248,7 @@ impl Game<'_> { self.capture(true); } } - fn draw_item(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) { + fn draw_item(&self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) { // `GuiGraphics.renderItem`: the resolved item model (tints, foil and // special renderers included), then the decorations. self.draw_item_model(batch, stack, x, y); @@ -4968,7 +5338,7 @@ impl Game<'_> { /// `GuiGraphicsExtractor.itemDecorations`: the count (or `count_text`) /// and damage bar. fn draw_item_decorations( - &mut self, + &self, batch: &mut HudBatch, stack: &ItemStack, x: f32, @@ -5095,12 +5465,12 @@ impl Game<'_> { for d in &draws { if let hud_layout::GuiDraw::Item { slot, x, y, .. } = *d { let stack = if slot == 40 { - self.offhand.clone() + self.offhand.as_ref() } else { - self.inventory[slot as usize].clone() + self.inventory[slot as usize].as_ref() }; if let Some(stack) = stack { - self.draw_item(&mut batch, &stack, x as f32, y as f32); + self.draw_item(&mut batch, stack, x as f32, y as f32); } } } @@ -5261,6 +5631,7 @@ impl Game<'_> { Screen::CommandBlock => self.draw_command_block(&mut batch), Screen::Inventory => { self.draw_inventory(&mut batch); + self.draw_mod_browser(&mut batch); } Screen::Creative => { self.draw_creative(&mut batch); @@ -5269,6 +5640,7 @@ impl Game<'_> { Screen::Mod => self.draw_mod_screen(&mut batch), Screen::Playing | Screen::Options | Screen::Win => {} } + self.draw_saving_indicator(&mut batch); self.draw_toasts(&mut batch); self.draw_pack_toasts(&mut batch); self.remote_hud(&mut batch); @@ -5325,7 +5697,9 @@ impl Game<'_> { | BlockEntity::Vault(_) | BlockEntity::Beehive(_) | BlockEntity::CommandBlock(_) - | BlockEntity::Skull(_), + | BlockEntity::Skull(_) + | BlockEntity::DaylightDetector + | BlockEntity::Campfire(_), ) => {} None => { v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); @@ -5595,7 +5969,9 @@ impl Game<'_> { | BlockEntity::Vault(_) | BlockEntity::Beehive(_) | BlockEntity::CommandBlock(_) - | BlockEntity::Skull(_), + | BlockEntity::Skull(_) + | BlockEntity::DaylightDetector + | BlockEntity::Campfire(_), ) => {} None if self.mount_active() => self.draw_mount_background(batch, ox, oy), None => { @@ -5638,7 +6014,19 @@ impl Game<'_> { self.draw_inventory_effects(batch, (ox, oy), 176); } } + /// `AbstractContainerScreen` keeps `isQuickCrafting` and the drag it + /// belongs to on the screen; Horizon keeps them on the game, so they are + /// dropped when a screen closes. A press whose release never reaches the + /// screen (the pointer left the window, or the screen closed first) would + /// otherwise leave every later press on every later screen swallowed. + pub(super) fn reset_inventory_clicks(&mut self) { + self.inv_clicks = Default::default(); + self.inv_drag = None; + self.last_inv_click = None; + } pub(super) fn close_container(&mut self) { + self.mod_browser_closed(); + self.reset_inventory_clicks(); self.close_station(); self.mount_closed(); self.recipe_ui.reset_screen(); @@ -5651,7 +6039,8 @@ impl Game<'_> { if let Some(rest) = self.give(stack) && let Some(eye) = self.eye_position() { - self.spawn_item(rest, [eye[0], eye[1] - 0.3, eye[2]], [0.0, 0.1, 0.0], 40); + // AbstractContainerMenu.dropOrPlaceInInventory: `drop(stack, false)`. + self.throw_from_eyes(rest, eye, false); } } self.craft_size = 2; @@ -5734,8 +6123,9 @@ impl Game<'_> { if self.creative_screen.tab().search { // CreativeModeInventoryScreen.slotClicked: moveCursorToEnd, then // setHighlightPos(0), so typing replaces the whole query. - let search = &self.creative_screen.search; - self.text_selection.select(("creative.search", 0), search); + let search = &mut self.creative_screen.search; + search.move_cursor_to_end(false); + search.highlight = 0; } let items = self.creative_screen.items(&self.pack.names); let first = self.creative_screen.first_row(&self.pack.names); @@ -5751,6 +6141,12 @@ 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; + // BundleMouseActions.onSlotClicked: a Shift click or a swap clears the bundle's selection. + for &(slot, _, input) in ops { + if let (Some(slot), Input::QuickMove | Input::Swap) = (slot, input) { + self.unselect_bundle(slot); + } + } 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); @@ -6363,6 +6759,9 @@ impl Game<'_> { fn inventory_press(&mut self, right: bool) { use horizon_client::container_screen::Target; use horizon_client::menu::Input; + if self.mod_browser_press(right) { + return; + } if !right && self.sort_press() { return; } @@ -6377,6 +6776,13 @@ impl Game<'_> { false, ); if outside { + // AbstractRecipeBookScreen.mouseClicked: the book takes the click + // before the outside test, and its tabs sit left of the strip + // hasClickedOutside counts as the book. + if self.recipe_book_click(right) { + self.inv_clicks.skip_release(); + return; + } // slotId -999: an empty hand throws nothing; a carried stack // starts a drag whose release drops it. match input { @@ -6539,24 +6945,8 @@ impl Game<'_> { } /// `hasClickedOutside` of the open screen at the cursor. fn clicked_outside(&self, batch: &HudBatch) -> bool { - use horizon_client::container_screen::{Book, Image, clicked_outside}; - let (ox, oy) = self.inventory_origin(batch); - let (shift, width, height) = if self.screen == Screen::Creative { - (0.0, Creative::WIDTH as i32, Creative::HEIGHT as i32) - } else { - let (shift, width) = match self.station.as_ref().map(|s| s.kind) { - Some(stations::Kind::Merchant) => (-50.0, 276), - Some(stations::Kind::Beacon) => (beacon::SHIFT, 230), - _ => (0.0, 176), - }; - (shift, width, self.screen_height() as i32) - }; - let image = Image { - left: (ox + shift) as i32, - top: oy as i32, - width, - height, - }; + use horizon_client::container_screen::{Book, clicked_outside}; + let image = self.container_image(batch); let book = self .recipe_book_area(batch) .map(|(visible, tab_hovered)| Book { @@ -6570,6 +6960,26 @@ impl Game<'_> { book, ) } + /// The open container screen's window: its place and size. + fn container_image(&self, batch: &HudBatch) -> horizon_client::container_screen::Image { + let (ox, oy) = self.inventory_origin(batch); + let (shift, width, height) = if self.screen == Screen::Creative { + (0.0, Creative::WIDTH as i32, Creative::HEIGHT as i32) + } else { + let (shift, width) = match self.station.as_ref().map(|s| s.kind) { + Some(stations::Kind::Merchant) => (-50.0, 276), + Some(stations::Kind::Beacon) => (beacon::SHIFT, 230), + _ => (0.0, 176), + }; + (shift, width, self.screen_height() as i32) + }; + horizon_client::container_screen::Image { + left: (ox + shift) as i32, + top: oy as i32, + width, + height, + } + } /// A click outside the window (slot id -999): `THROW` does nothing; a /// `PICKUP` drops the carried stack (left) or one of it (right), thrown /// from the hand (`AbstractContainerMenu.doClick`, `LivingEntity.drop`). @@ -6730,7 +7140,7 @@ impl Game<'_> { } } fn click_inventory(&mut self, right: bool) { - if self.mount_click(right) { + if self.mod_browser_press(right) || self.mount_click(right) { return; } if self.recipe_book_click(right) { @@ -6942,6 +7352,9 @@ impl Game<'_> { self.prepare_entity_culling(camera); self.prepare_trims(); self.mark_entity(out.len(), "minecraft:entity_flame"); + // One scan for both passes that draw them (block entities below and the + // overlay near the end of this function). + let cracks = self.cracks(camera); let fire_yaw = if self.camera_type == perspective::CameraType::ThirdPersonFront { self.yaw + 180.0 } else { @@ -7038,6 +7451,9 @@ impl Game<'_> { // `VaultRenderer`. self.mark_entity(out.len(), ""); self.vault_geometry(camera, alpha, &mut out); + // `CampfireRenderer`. + self.mark_entity(out.len(), ""); + self.campfire_geometry(camera, &mut out); self.mark_entity(out.len(), "minecraft:ominous_item_spawner"); self.ominous_item_spawner_geometry(camera, alpha, &mut out); // Mobs and their projectiles (a span each). @@ -7056,7 +7472,12 @@ impl Game<'_> { self.see_through_vertices = see_through; // Entity shadows (EntityRenderer.extractShadow). self.mark_translucent_entity(out.len(), "minecraft:entity_shadow"); - if let Some(sprite) = self.gui.atlas.sprites.get("misc/shadow").copied() { + let shadow_sprite = self + .settings + .entity_shadows + .then(|| self.gui.atlas.sprites.get("misc/shadow").copied()) + .flatten(); + if let Some(sprite) = shadow_sprite { let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 }; let darken = self.sky_darken(); let a = alpha; @@ -7167,7 +7588,7 @@ impl Game<'_> { .render(&scene, visible, &mut out); } self.mark_stage(out.len(), "DESTROY"); - for (pos, stage) in self.cracks(camera) { + for &(pos, stage) in &cracks { let state = self.world.block(pos[0], pos[1], pos[2]); self.res .block_entity_render() @@ -7280,6 +7701,7 @@ impl Game<'_> { self.frame_geometry(camera, &mut out); self.mark_entity(out.len(), "minecraft:armor_stand"); self.armor_stand_geometry(camera, alpha, &mut out); + self.cushion_geometry(camera, &mut out); self.mark_entity(out.len(), "minecraft:oak_boat"); self.boat_geometry(camera, alpha, &mut out); self.mark_entity(out.len(), "minecraft:minecart"); @@ -7310,7 +7732,7 @@ impl Game<'_> { ); // Breaking progress overlays (destroy_stage_0..9): ours and the other players'. self.mark_stage(out.len(), "DESTROY"); - for (pos, stage) in self.cracks(camera) { + for &(pos, stage) in &cracks { let o = (glam::DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])) - camera) .as_vec3(); @@ -7358,6 +7780,20 @@ impl Game<'_> { /// other players' (`renderBlockDestroyAnimation`: within 32 blocks of the camera, the /// furthest progress on each block). fn cracks(&self, camera: glam::DVec3) -> Vec<([i32; 3], [f32; 2])> { + // `destroy_stage_0` .. `destroy_stage_9`: the sprite name by stage, so the + // lookup does not format a string per crack. + const DESTROY_STAGES: [&str; 10] = [ + "block/destroy_stage_0", + "block/destroy_stage_1", + "block/destroy_stage_2", + "block/destroy_stage_3", + "block/destroy_stage_4", + "block/destroy_stage_5", + "block/destroy_stage_6", + "block/destroy_stage_7", + "block/destroy_stage_8", + "block/destroy_stage_9", + ]; let mut stages: Vec<([i32; 3], u32)> = Vec::new(); let mut add = |pos: [i32; 3], stage: u32| match stages.iter_mut().find(|c| c.0 == pos) { Some(c) => c.1 = c.1.max(stage), @@ -7383,11 +7819,8 @@ impl Game<'_> { d.length_squared() <= 1024.0 }) .filter_map(|(pos, stage)| { - let r = self - .gui - .atlas - .sprites - .get(&format!("block/destroy_stage_{stage}"))?; + let name = DESTROY_STAGES.get(stage as usize)?; + let r = self.gui.atlas.sprites.get(*name)?; Some((pos, [r.u0, r.v0])) }) .collect() @@ -7443,7 +7876,7 @@ impl Game<'_> { /// strength and whether it is a critical hit): the weapon and effects /// scaled by the attack strength, a mace's smash, the critical hit, then /// enchantments. - pub(super) fn melee_damage(&mut self, target_kind: &str) -> (f32, f32, bool) { + pub(super) fn melee_damage(&mut self, target_kind: &str) -> (f32, f32, bool, bool) { let hand_damage = 1.0 + self.attack_item_info().map_or(0.0, |i| i.attack_damage); // Riptide's spin replaces the attack damage attribute. let spin = self.player.as_ref().map_or(0.0, |p| p.auto_spin_attack_dmg); @@ -7471,8 +7904,9 @@ impl Game<'_> { amount *= 1.5; } // Enchantment damage (sharpness, smite, bane) scaled by the attack strength. - amount += self.enchant_damage_bonus(target_kind) * scale; - (amount, scale, crit) + let magic_boost = self.enchant_damage_bonus(target_kind) * scale; + amount += magic_boost; + (amount, scale, crit, magic_boost > 0.0) } /// `Player.getAttackStrengthScale(0.5)`. fn attack_strength_scale(&self) -> f32 { @@ -7512,6 +7946,69 @@ impl Game<'_> { self.audio .play("minecraft:entity.player.attack.sweep", from, 1.0, 1.0); } + /// The damage and knockback part of `Player.doSweepAttack` after a sweep + /// hit on the mob at `target`: every other living mob in its box grown by + /// (1, 0.25, 1) and closer than 3 blocks (`distanceToSqr < 9`, in creative + /// too), but the player's allies + /// (`isAlliedTo`), takes `1 + sweeping_damage_ratio * baseDamage` with the + /// weapon's enchantments, scaled by the attack strength, and is pushed 0.4 + /// along the player's yaw. + pub(super) fn sweep_damage(&mut self, target: usize, scale: f32) { + let Some(p) = self.player.as_ref() else { + return; + }; + let from = [p.position.x, p.position.y, p.position.z]; + // `baseDamage` of `Player.attack` before a critical hit (a sweep has + // none) and the enchantments: the attack damage attribute with the + // strength and weakness effects, scaled by the attack strength. + let hand_damage = 1.0 + self.attack_item_info().map_or(0.0, |i| i.attack_damage); + let base_damage = (hand_damage + self.effect_attack_bonus()) * (0.2 + scale * scale * 0.8); + // The enchantment's attribute modifier on the attribute's 0 to 1 range. + let ratio = self + .res + .stations() + .enchantments + .attribute_add( + self.inventory[self.selected].as_ref(), + "minecraft:sweeping_damage_ratio", + ) + .clamp(0.0, 1.0) as f32; + let sweep_damage = 1.0 + ratio * base_damage; + let hit_box = self.mobs[target] + .bounds() + .inflate(horizon_core::geometry::Vec3::new(1.0, 0.25, 1.0)); + let (uuid, allies) = ( + self.level.player_uuid.or(Some([0, 0, 0, 1])), + self.player_allies(), + ); + let nearby: Vec = self + .mobs + .iter() + .enumerate() + .filter(|(i, m)| { + *i != target + && m.alive() + && !m.removed + && !allies.contains(&m.id) + && !mace::ally_of_player(m, uuid) + && m.bounds().intersects(hit_box) + && m.position.distance_squared(p.position) < 9.0 + }) + .map(|(i, _)| i) + .collect(); + let (xd, zd) = self.extra_knockback_direction(); + for i in nearby { + let kind = self.mobs[i].kind.id.clone(); + let kind = format!("minecraft:{}", kind.trim_start_matches("minecraft:")); + let damage = (sweep_damage + self.enchant_damage_bonus(&kind)) * scale; + let source = self.attack_source(from); + if self.hurt_by_player(i, damage, source) { + self.mobs[i].knockback(0.4, xd, zd); + self.last_hurt_by_player + .insert(self.mobs[i].id, self.lan_acting); + } + } + } /// `Player.attack`'s sounds when a vehicle takes the hit (it always does, /// and can't be hit critically): knockback when sprinting at full /// strength, then strong or weak. Before `swing_arm` resets the charge. @@ -7565,6 +8062,7 @@ impl Game<'_> { .map_or(0.0, |i| i.attack_damage); if self.attack_frame() || self.attack_armor_stand() + || self.attack_cushion() || self.attack_boat(hand_damage) || self.attack_cart(hand_damage) || self.attack_dragon() @@ -7595,7 +8093,7 @@ impl Game<'_> { pub(super) fn attack_mob(&mut self, index: usize) { let target_kind = self.mobs[index].kind.id.clone(); let target_kind = format!("minecraft:{}", target_kind.trim_start_matches("minecraft:")); - let (amount, scale, crit) = self.melee_damage(&target_kind); + let (amount, scale, crit, magic) = self.melee_damage(&target_kind); let sweep = self.sweep_attack_position(scale, crit); let (knockback, knockback_attack) = self.extra_knockback(&target_kind, scale); self.attack_ticks = 0; @@ -7652,13 +8150,24 @@ impl Game<'_> { self.stats .custom("damage_dealt", (actual * 10.0).round() as i32); if crit { - self.particles.tracking_emitter( - horizon_client::particles::ParticleOptions::simple( - horizon_client::particles::ParticleType::Crit, - ), + self.critical_hit( + self.lan_acting, + self.mobs[index].id as i32, feet, width, height, + false, + ); + } + // Player.attackVisualEffects: magicCrit when the enchantments added damage. + if magic { + self.critical_hit( + self.lan_acting, + self.mobs[index].id as i32, + feet, + width, + height, + true, ); } if actual > 2.0 { @@ -7685,6 +8194,7 @@ impl Game<'_> { // Player.playServerSideSound: at the player. if let Some(at) = sweep { self.sweep_attack(at, from); + self.sweep_damage(index, scale); } else { self.audio.play(sound, from, 1.0, 1.0); } @@ -7695,6 +8205,9 @@ impl Game<'_> { if let horizon_client::mobs::MobEvent::Sound(s, at, volume, pitch) = event { self.audio .play(&format!("minecraft:{s}"), Some(at), volume, pitch); + } else { + // Left for the end of the tick. + self.mobs[index].outbox.push(event); } } self.weapon_hit(index); @@ -7704,15 +8217,18 @@ impl Game<'_> { } } /// ServerExplosion: rays from a 16^3 grid lose (resistance + 0.3) * 0.3 per step. - /// A mob explosion (`Level.ExplosionInteraction.MOB`: drop decay with the - /// default mobGriefing rule). + /// A mob explosion (`ServerLevel.explode` with `ExplosionInteraction.MOB`: + /// blocks are kept without mobGriefing, else the mob_explosion_drop_decay + /// rule picks decay). fn explode(&mut self, center: [f64; 3], radius: f32) -> Result<()> { - self.server_explode( - center, - radius, - explosion::BlockInteraction::DestroyWithDecay, - false, - ) + let interaction = if !self.ui.rules.bool("mob_griefing") { + explosion::BlockInteraction::Keep + } else if self.ui.rules.bool("mob_explosion_drop_decay") { + explosion::BlockInteraction::DestroyWithDecay + } else { + explosion::BlockInteraction::Destroy + }; + self.server_explode(center, radius, interaction, false) } /// Copies of a save batch carrying its live block entities and save data. fn with_entities<'a>( @@ -7814,6 +8330,7 @@ impl Game<'_> { creative: bool, create: Option<&horizon_client::title::WorldOptions>, ) -> Result<()> { + world_loading::world_data_used(); if self.defer_world_entry(PendingWorldEntry::Local { folder: folder.to_owned(), name: name.map(str::to_owned), @@ -7879,6 +8396,7 @@ impl Game<'_> { ); self.session_lock = Some(session_lock); self.end.set_locator(locator); + self.share_spawn_conditions(); self.score = Default::default(); self.fns = Default::default(); self.bosses = Default::default(); @@ -8017,6 +8535,7 @@ impl Game<'_> { seed, )?; self.end.set_locator(locator); + self.share_spawn_conditions(); Ok((streaming, save)) } /// Change dimension through a portal (Entity.changeDimension with @@ -8037,6 +8556,7 @@ impl Game<'_> { /// (scaled coordinates, or the End portal's fixed destination). pub(super) fn switch_level(&mut self, target: Dim, from: Vec3) -> Result { // Save the departing dimension's changed chunks. + self.save.save_forced_chunks(&self.streaming.forced)?; self.streaming.save(&mut self.world, true); let keys: Vec<_> = self.world.modified.drain().collect(); let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k))); @@ -8310,6 +8830,7 @@ impl Game<'_> { self.boats.clear(); self.carts.clear(); self.armor_stands.clear(); + self.cushions.clear(); self.item_frames.clear(); self.paintings.clear(); self.others.clear(); @@ -8364,15 +8885,54 @@ impl Game<'_> { } self.apply_enchantment_attributes(); } - /// Inventory.hurtArmor: each piece loses max(1, damage / 4) durability. - fn hurt_armor(&mut self, damage: f32) { + /// The armor hits among a tick's motion events (`Player.hurtArmor` from + /// `getDamageAfterArmorAbsorb`), whatever the damage: a mob, an explosion, + /// a cactus, lava, a campfire. + fn wear_armor(&mut self, events: &[MotionEvent]) { + for event in events { + if let MotionEvent::Health(horizon_client::health::HealthEvent::ArmorHurt { + source, + amount, + }) = event + { + self.hurt_armor(*source, *amount); + } + } + } + /// `Player.hurtArmor` -> `LivingEntity.doHurtEquipment`: each worn piece that + /// wears when its wearer is hurt loses max(1, damage / 4) durability, except + /// to a fire source when the piece resists fire (`ItemStack.canBeHurtBy`). + fn hurt_armor(&mut self, source: horizon_world::damage_source::DamageTypeId, damage: f32) { + if damage <= 0.0 { + return; + } let amount = ((damage / 4.0) as u32).max(1); + let name = self + .motion + .health + .damage + .definition(source) + .map(|d| d.name.clone()) + .unwrap_or_default(); + let fire = self + .motion + .health + .damage + .in_tag(source, "minecraft:is_fire"); let mut broke = false; let losses: Vec = (0..4) - .map(|i| { - self.armor[i] - .clone() - .map_or(amount, |s| self.durability_loss(&s, amount)) + .map(|i| match self.armor[i].clone() { + Some(s) + if self + .res + .items() + .get(&s.item) + .is_some_and(|info| info.equip_damage_on_hurt) + && !(fire && self.res.items().resists_fire(&s, &name)) => + { + self.durability_loss(&s, amount) + } + _ => 0, }) .collect(); for (slot, amount) in self.armor.iter_mut().zip(losses) { @@ -8469,7 +9029,8 @@ impl Game<'_> { } fn drop_stack(&mut self, stack: ItemStack) { if let Some(eye) = self.0.eye_position() { - self.0.spawn_item(stack, eye, [0.0, 0.1, 0.0], 40); + // ItemUtils.createFilledResult: `player.drop(stack, false)`. + self.0.throw_from_eyes(stack, eye, false); } } } @@ -8707,6 +9268,24 @@ impl Game<'_> { } } } + /// `ItemStack.hurtWithoutBreaking`: Unbreaking applies, but the stack stops at + /// one point of durability left instead of breaking. + fn hurt_held_without_breaking(&mut self, amount: u32) { + if self.creative { + return; + } + let Some(held) = self.held().cloned() else { + return; + }; + let amount = self.durability_loss(&held, amount); + let max = self.res.items().get(&held.item).map_or(0, |i| i.max_damage); + if amount == 0 || max == 0 { + return; + } + if let Some(stack) = self.held_mut().as_mut() { + stack.damage = (stack.damage + amount).min(max - 1); + } + } /// Block tool use: distinguish success, failure and fall-through for hand feedback. fn use_tool( &mut self, @@ -8728,6 +9307,13 @@ impl Game<'_> { { return Ok(UseResult::Success { swing: true }); } + if allow_block_actions + && let Some(hit) = self.pick() + && let Some(placed) = self.use_on_campfire(hit.pos)? + { + // SUCCESS_SERVER swings; a full campfire's CONSUME does not. + return Ok(UseResult::Success { swing: placed }); + } // BucketItem has no useOn: a guest's UseItemOn leaves it to UseItem. let bucket = horizon_client::items::bucket_contents(&stack.item); if matches!(self.guest_use, Some(GuestUse::OnBlock(_))) @@ -8787,7 +9373,8 @@ impl Game<'_> { } else if let Some(rest) = self.give(filled) && let Some(eye) = self.eye_position() { - self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40); + // ItemUtils.createFilledResult: `player.drop(stack, false)`. + self.throw_from_eyes(rest, eye, false); } } return Ok(UseResult::Success { swing: true }); @@ -8937,8 +9524,29 @@ impl Game<'_> { while value > 0 { let v = ExperienceOrb::split(value); value -= v; - let _merge_id = self.world.random.next_int_bound(40); - self.add_orb(at, v); + let merge_id = self.world.random.next_int_bound(40).unwrap_or(0); + self.award_orb(at, v, merge_id); + } + } + /// `ExperienceOrb.tryMergeToExisting`: an orb of the same value within a + /// 1 block box of `at`, whose id is a multiple of 40 from `merge_id`, takes + /// the new one as one more in its count (and restarts its age); otherwise + /// a fresh orb spawns. + fn award_orb(&mut self, at: [f64; 3], value: u32, merge_id: i32) { + let centre = Vec3::new(at[0], at[1], at[2]); + let half = Vec3::new(0.5, 0.5, 0.5); + let area = Aabb::new(centre.subtract(half), centre.add_vector(half)); + // A server's orbs are its own; a LAN or server guest only shows them. + let target = self.remote.is_none().then(|| { + self.orbs + .iter_mut() + .find(|o| o.can_merge(merge_id as u32, value) && o.bounds().intersects(area)) + }); + if let Some(Some(orb)) = target { + orb.count += 1; + orb.age = 0; + } else { + self.add_orb(at, value); } } /// `new ExperienceOrb(level, pos, Vec3.ZERO, value)`: yaw and motion from @@ -8960,6 +9568,8 @@ impl Game<'_> { value, age: 0, on_ground: false, + count: 1, + ticks: 0, }); } fn can_place_used_fire(&mut self, target: [i32; 3]) -> bool { @@ -9036,18 +9646,31 @@ impl Game<'_> { }), ); } + // Player.aiStep: the pickup area is the box inflated by (1, 0.5, 1). let bounds = player.map(|p| { let w = f64::from(p.dimensions.width) / 2.0; ( - [p.position.x - w, p.position.y, p.position.z - w], [ - p.position.x + w, - p.position.y + f64::from(p.dimensions.height), - p.position.z + w, + p.position.x - w - 1.0, + p.position.y - 0.5, + p.position.z - w - 1.0, + ], + [ + p.position.x + w + 1.0, + p.position.y + f64::from(p.dimensions.height) + 0.5, + p.position.z + w + 1.0, ], ) }); let mut orbs = std::mem::take(&mut self.orbs); + // An orb has no random of its own here: lava draws from one made on + // first use, apart from the level stream. + let mut lava_random = None; + let mut next_float = || { + lava_random + .get_or_insert_with(dispenser::entity_random) + .next_float() + }; orbs.retain_mut(|o| { let distance = |feet: &[f64; 3]| -> f64 { (feet[0] - o.position.x).powi(2) @@ -9059,12 +9682,22 @@ impl Game<'_> { .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) + o.tick( + &self.world, + self.res.facts(), + self.collision, + target, + &mut next_float, + ) }); + // ExperienceOrb.scanForMerges runs on the server only. + if self.remote.is_none() { + horizon_client::entities::merge_orbs(&mut orbs); + } let mut gained = 0; let mut taken = Vec::new(); if let Some((min, max)) = bounds { - orbs.retain(|o| { + orbs.retain_mut(|o| { let touching = o.position.x + 0.25 > min[0] && o.position.x - 0.25 < max[0] && o.position.y + 0.5 > min[1] @@ -9072,11 +9705,13 @@ impl Game<'_> { && o.position.z + 0.25 > min[2] && o.position.z - 0.25 < max[2]; if touching && self.xp_delay == 0 { - // ExperienceOrb.playerTouch: one orb every 2 ticks. + // ExperienceOrb.playerTouch: one orb every 2 ticks; a + // merged orb gives its value once per count. self.xp_delay = 2; gained += o.value; taken.push(o.clone()); - return false; + o.count -= 1; + return o.count > 0; } true }); @@ -9152,7 +9787,10 @@ impl Game<'_> { }; // BowItem.shootProjectile: shootFromRotation(power * 3, inaccuracy 1). let p = Vec3::new(eye[0], eye[1] - 0.1, eye[2]); - let (power_bonus, infinity) = self.bow_enchantments(); + let ammo = arrow_slot + .and_then(|i| self.stack_in(i).cloned()) + .unwrap_or_else(|| ItemStack::new("minecraft:arrow", 1)); + let (power_bonus, infinity) = self.bow_enchantments(&ammo.item); let kind = horizon_client::projectiles::ProjectileKind::Arrow { base_damage: 2.0 + power_bonus, critical: power >= 1.0, @@ -9166,9 +9804,6 @@ impl Game<'_> { // ProjectileWeaponItem.useAmmo: creative and Infinity draw without // using the ammo, so the arrow is CREATIVE_ONLY; else setOwner(player) // lets it be picked up. - let ammo = arrow_slot - .and_then(|i| self.stack_in(i).cloned()) - .unwrap_or_else(|| ItemStack::new("minecraft:arrow", 1)); if let Some(a) = arrow.arrow.as_mut() { a.set_item(&horizon_client::arrows::drawn_ammo( &ammo, @@ -9626,8 +10261,9 @@ impl Game<'_> { rain.extend(snow_vertices); rain } - /// Player.startSleepInBed: night or thunder, no monsters within 8 blocks; - /// the bed becomes the respawn point either way. + /// ServerPlayer.startSleepInBed: in reach, not obstructed, night or thunder, + /// and (outside creative) no monsters within 8 blocks; the bed becomes the + /// respawn point either way. fn try_sleep(&mut self, pos: [i32; 3]) { let Some(p) = self.player.as_ref() else { return; @@ -9642,22 +10278,40 @@ impl Game<'_> { .state(state) .map(|s| s.properties.clone()) .unwrap_or_default(); - let head = if props.get("part").map(String::as_str) == Some("foot") { - let d = facing_offset(props.get("facing").map_or("north", String::as_str)); - [pos[0] + d[0], pos[1], pos[2] + d[2]] + // The head and the foot: the block faces from the foot to the head. + let d = facing_offset(props.get("facing").map_or("north", String::as_str)); + let (head, foot) = if props.get("part").map(String::as_str) == Some("foot") { + ([pos[0] + d[0], pos[1], pos[2] + d[2]], pos) } else { - pos + (pos, [pos[0] - d[0], pos[1], pos[2] - d[2]]) }; - let dist = ((p.position.x - f64::from(head[0]) - 0.5).powi(2) - + (p.position.z - f64::from(head[2]) - 0.5).powi(2)) - .sqrt(); - if dist > 3.0 { + // ServerPlayer.bedInRange / isReachableBedBlock: within 3 blocks + // sideways and 2 vertically of the head or the foot. + let reachable = |bed: [i32; 3]| { + (p.position.x - f64::from(bed[0]) - 0.5).abs() <= 3.0 + && (p.position.y - f64::from(bed[1])).abs() <= 2.0 + && (p.position.z - f64::from(bed[2]) - 0.5).abs() <= 3.0 + }; + if !reachable(head) && !reachable(foot) { self.message = Some(( "You may not rest now; the bed is too far away".into(), Instant::now(), )); return; } + // ServerPlayer.bedBlocked: Player.freeAt (not suffocating) for the + // blocks above the head and the foot, as `in_wall` reads suffocating. + let blocked = [head, foot].iter().any(|bed| { + let f = self + .res + .facts() + .get(self.world.block(bed[0], bed[1] + 1, bed[2])); + f.full_collision && f.solid_render + }); + if blocked { + self.message = Some(("This bed is obstructed".into(), Instant::now())); + return; + } // In reach (bedInRange), day or night: setRespawnPosition( // RespawnConfig(the head, the player's yaw), not forced). It replaces // an anchor or a spawnpoint; respawning checks the bed is still there @@ -9687,13 +10341,15 @@ impl Game<'_> { )); return; } - let monsters = self.mobs.iter().any(|m| { - m.hostile() - && m.alive() - && (m.position.x - p.position.x).abs() < 8.0 - && (m.position.y - p.position.y).abs() < 5.0 - && (m.position.z - p.position.z).abs() < 8.0 - }); + // Creative players skip the monster check (`!this.isCreative()`). + let monsters = !self.creative + && self.mobs.iter().any(|m| { + m.hostile() + && m.alive() + && (m.position.x - p.position.x).abs() < 8.0 + && (m.position.y - p.position.y).abs() < 5.0 + && (m.position.z - p.position.z).abs() < 8.0 + }); if monsters { self.message = Some(( "You may not rest now; there are monsters nearby".into(), @@ -9743,14 +10399,20 @@ impl Game<'_> { } } // ServerLevel.tick: once enough of the players have slept 100 ticks, - // skip to morning, clear the weather and wake everyone. + // skip to morning if `advance_time` is on, wake everyone, and + // resetWeatherCycle if `advance_weather` is on and it is raining. 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; + if self.ui.rules.bool("advance_time") { + let t = self.world.day_time; + self.world.day_time = t + 24000 - t.rem_euclid(24000); + } + // Level.isRaining: the rain level is above 0.2. + if self.ui.rules.bool("advance_weather") && self.world.weather.levels(1.0).0 > 0.2 { + self.world.weather.raining = false; + self.world.weather.thundering = false; + self.world.weather.rain_time = 0; + self.world.weather.thunder_time = 0; + } if self.sleeping.is_some() { self.wake_up(); } @@ -9778,8 +10440,9 @@ impl Game<'_> { fn draw_creative(&mut self, batch: &mut HudBatch) { let (ox, oy) = Self::creative_origin(batch); let selected = self.creative_screen.selected; - let tabs = self.creative_screen.tabs.clone(); - let tab = self.creative_screen.tab().clone(); + // Only what is drawn of the tabs: their stacks stay where they are. + let tabs = self.creative_screen.tab_headers(); + let tab = tabs[selected.min(tabs.len() - 1)].clone(); let tab_sprite = |t: &horizon_client::creative::Tab, on: bool| { format!( "gui/sprites/container/creative_inventory/tab_{}_{}_{}", @@ -9845,20 +10508,16 @@ impl Game<'_> { ); } if tab.search { - // The search box: an unbordered EditBox of 80 at (82, 6), white. - let search = &self.creative_screen.search; - horizon_client::ui::append_field( - batch, - atlas, - search, - (ox + 82.0, oy + 6.0, 80.0), - (u32::MAX, true), - clipboard::CREATIVE_SEARCH_CHARS, - self.text_selection - .covers(clipboard::CREATIVE_SEARCH, search), - true, - self.creative_screen.search_focused.elapsed().as_millis(), - ); + // CreativeModeInventoryScreen: an unbordered EditBox of 50 at (82, 6). + let search = &mut self.creative_screen.search; + search.x = ox + 82.0; + search.y = oy + 6.0; + search.width = 80.0; + search.bordered = false; + search.focused = true; + search.text_color = u32::MAX; + search.max_length = clipboard::CREATIVE_SEARCH_CHARS; + search.draw(batch, atlas, None); } let mut hovered: Option = None; if tab.inventory { @@ -9966,8 +10625,7 @@ impl Game<'_> { } else if self.carried.is_none() && let Some(item) = hovered { - let lines = self.stack_tooltip(&item); - self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1); + self.draw_stack_tooltip(batch, &item, self.cursor.0, self.cursor.1); } self.draw_inventory_effects(batch, (ox, oy), Creative::WIDTH as i32); } @@ -10020,6 +10678,9 @@ impl Game<'_> { } return; } + if !right && self.creative_search_click(ox, oy) { + return; + } // Holding the scrollbar scrolls as the mouse moves (mouseDragged). if !right && self @@ -10032,6 +10693,24 @@ impl Game<'_> { self.inventory_press(right); } } + /// A click on the search tab's box (`EditBox.onClick`). + fn creative_search_click(&mut self, ox: f32, oy: f32) -> bool { + if !self.creative_screen.tab().search { + return false; + } + let (x, y, w, h) = (ox + 82.0, oy + 6.0, 80.0, 9.0); + let (mx, my) = self.cursor; + if mx < x || my < y || mx >= x + w || my >= y + h { + return false; + } + let shift = self.has_shift_down(); + let search = &mut self.creative_screen.search; + search.x = x; + search.y = y; + search.width = w; + search.click(&self.gui.atlas, mx, shift, false); + true + } /// Copy the live player and world state into the `Level` that gets saved. pub(super) fn sync_level(&mut self) { // Level.write saves the game rules (game_rules.dat) with the rest. @@ -10151,6 +10830,7 @@ impl Game<'_> { } /// Save the level in place: its changed chunks, its entities and its raids. fn save_level(&mut self, wait: bool) -> Result<()> { + self.save.save_forced_chunks(&self.streaming.forced)?; self.streaming.save(&mut self.world, wait); let keys: Vec<_> = self.world.modified.drain().collect(); let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k))); @@ -10340,6 +11020,17 @@ impl Game<'_> { [0.0; 3] }; let p = h.pos.map(f64::from); + if let Some(b) = self.context_outline(h.pos, state) { + return horizon_client::blocks::cube_edges() + .iter() + .map(|e| { + std::array::from_fn(|i| { + let k = i % 3; + p[k] + b[k] + e[i] * (b[k + 3] - b[k]) + }) + }) + .collect(); + } f.outline_edges .iter() .map(|e| std::array::from_fn(|i| p[i % 3] + o[i % 3] + e[i])) @@ -10350,8 +11041,6 @@ impl Game<'_> { Vec::new() }; let mut hud = horizon_client::spans::time("hud", || self.hud(size)); - // Map textures changed since the last drawn frame (game/maps.rs). - hud.patches.append(&mut self.map_patches); // LevelLoadingScreen (Reason.OTHER) draws the title's panorama. let title = self.title.is_some() || self.loading_reason() == Some(horizon_client::level_loading::Reason::Other); @@ -10453,6 +11142,10 @@ impl Game<'_> { } else { self.shader_pack_inputs(camera, alpha as f32) }; + // Map textures and font glyphs changed while building this frame's + // geometry (game/maps.rs, world text) upload with this batch; draining + // map_patches any earlier leaves them a frame behind. + hud.patches.append(&mut self.map_patches); let entity_spans = std::mem::take(self.entity_spans.get_mut()); let frame = Frame { weather: &weather, @@ -11068,11 +11761,7 @@ impl Game<'_> { bytes += size; } } - for c in unloaded { - for sy in 0..(HEIGHT / 16) { - renderer.remove((c.x, sy, c.z)); - } - } + renderer.remove_columns(unloaded.iter().map(|c| (c.x, c.z))); if let (Some(lod), Some(player)) = (&mut self.lod, &self.player) { let lod_distance = self.settings.horizon.lod_distance_on(&renderer.info); lod.set_near_loading(self.streaming.busy()); @@ -11402,6 +12091,7 @@ impl ApplicationHandler for Game<'_> { } if self.screen == Screen::Inventory && d != 0.0 + && !self.bundle_scroll(scaled(raw_x), scaled(raw_y)) && !self.tweak_scroll(d, self.inventory_target().0) { self.station_scroll(d); @@ -11543,16 +12233,17 @@ impl ApplicationHandler for Game<'_> { } self.extras_mouse(button, pressed); self.mod_mouse_key(button, pressed); - match self.settings.keys.translate_mouse(button) { - Some(Err(b)) => self.play_mouse(b, pressed)?, - Some(Ok(k)) if pressed => { - self.keys.insert(k); - self.key_pressed(k)?; + for mapped in self.settings.keys.translate_mouse_all(button) { + match mapped { + Err(b) => self.play_mouse(b, pressed)?, + Ok(k) if pressed => { + self.keys.insert(k); + self.key_pressed(k)?; + } + Ok(k) => { + self.keys.remove(&k); + } } - Some(Ok(k)) => { - self.keys.remove(&k); - } - None => {} } } Screen::Inventory | Screen::Creative @@ -11679,8 +12370,17 @@ impl ApplicationHandler for Game<'_> { // The hovered slot took the key (`ignoreTextInput`). } else if let Some(shortcut) = self.edit_shortcut(&event) { self.creative_search_shortcut(shortcut); - } else if event.physical_key == PhysicalKey::Code(KeyCode::Backspace) { - self.creative_search_backspace(self.has_control_down()); + } else if let PhysicalKey::Code(key) = event.physical_key { + // EditBox.keyPressed: arrows, Home, End, Delete and Backspace. + let before = self.creative_screen.search.value.clone(); + let (ctrl, shift) = (self.has_control_down(), self.has_shift_down()); + if self.creative_screen.search.key(key, ctrl, shift) { + if self.creative_screen.search.value != before { + self.creative_screen.scroll = 0.0; + } + } else { + self.creative_search_edit(event.text.as_deref()); + } } else { self.creative_search_edit(event.text.as_deref()); } @@ -11693,6 +12393,14 @@ impl ApplicationHandler for Game<'_> { // The recipe book's search box takes every key but Escape. self.recipe_key(&event); } + WindowEvent::KeyboardInput { event, .. } + if self.mod_browser_typing() + && event.state == ElementState::Pressed + && !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) => + { + // A mod's item panel's search box, as the recipe book's. + self.mod_browser_key(&event); + } WindowEvent::KeyboardInput { event, .. } if self.station_typing() && event.state == ElementState::Pressed @@ -11701,6 +12409,9 @@ impl ApplicationHandler for Game<'_> { // The anvil rename box takes every key but Escape (AnvilScreen.keyPressed). if let Some(shortcut) = self.edit_shortcut(&event) { self.station_shortcut(shortcut); + } else if let PhysicalKey::Code(key) = event.physical_key + && self.station_key(key) + { } else { let backspace = event.physical_key == PhysicalKey::Code(KeyCode::Backspace); self.station_text(event.text.as_deref(), backspace); @@ -11788,18 +12499,24 @@ impl ApplicationHandler for Game<'_> { { self.smooth_camera = !self.smooth_camera; } - // Key binds: act as the default key of the bound mapping. - let key = match self.settings.keys.translate(key) { - Some(Ok(k)) => k, - Some(Err(button)) => { - if self.screen == Screen::Playing && !event.repeat { - self.play_mouse(button, event.state == ElementState::Pressed)?; + // Key binds: act as the default key of every mapping bound + // to it (KeyMapping.set drives them all). + for mapped in self.settings.keys.translate_all(key) { + match mapped { + Ok(k) => { + self.mapped_key( + k, + event.state == ElementState::Pressed, + event.repeat, + )?; + } + Err(button) => { + if self.screen == Screen::Playing && !event.repeat { + self.play_mouse(button, event.state == ElementState::Pressed)?; + } } - return Ok(()); } - None => return Ok(()), - }; - self.mapped_key(key, event.state == ElementState::Pressed, event.repeat)?; + } } WindowEvent::RedrawRequested => { self.observe_fullscreen(); @@ -12164,6 +12881,7 @@ impl<'a> Game<'a> { craft_table: None, inv_drag: None, tweaks: Default::default(), + bundle_mouse: Default::default(), inv_clicks: Default::default(), last_inv_click: None, last_quick_moved: None, @@ -12213,6 +12931,7 @@ impl<'a> Game<'a> { last_input: now, pad: Default::default(), frames: 0, + item_level_cache: Default::default(), world_frames: 0, fps: 0.0, fps_frames: 0, @@ -12224,7 +12943,14 @@ impl<'a> Game<'a> { level, session_lock: None, audio, - music: Default::default(), + music: { + // The manager starts with the saved option (MusicManager's constructor). + let mut music = horizon_client::music::MusicManager::default(); + music.frequency = horizon_client::music::MusicFrequency::parse( + &settings.file.name("musicFrequency"), + ); + music + }, ambience: Default::default(), sound_paused: false, cart_sounds: HashSet::new(), @@ -12268,6 +12994,8 @@ impl<'a> Game<'a> { command_source: None, titles: Default::default(), tool_highlight: Default::default(), + saving_indicator: Default::default(), + autosaving: false, applied_modifiers: Vec::new(), experience: Experience::default(), orbs: Vec::new(), @@ -12317,6 +13045,7 @@ impl<'a> Game<'a> { map_frame_model: prepared.map_frame_model, glow_map_frame_model: prepared.glow_map_frame_model, armor_stands: Vec::new(), + cushions: Vec::new(), others: Vec::new(), armor_stand_assets: prepared.armor_stand_assets, waypoint_styles: prepared.waypoint_styles, @@ -12326,6 +13055,7 @@ impl<'a> Game<'a> { boats: Vec::new(), boat_models: prepared.boat_models, crystal_model: prepared.crystal_model, + cushion_model: prepared.cushion_model, carts: Vec::new(), jukebox_sounds: HashMap::new(), bolts: Vec::new(), @@ -12412,6 +13142,7 @@ impl<'a> Game<'a> { lan_events: Vec::new(), lan_block_events: Vec::new(), lan_entity_events: Vec::new(), + lan_critical_hits: Vec::new(), lan_global_events: Vec::new(), lid_openers: HashMap::new(), lan_acting: None, @@ -12463,6 +13194,7 @@ struct GameCpuResources { boat_models: boats::BoatModels, cart_models: minecarts::CartModels, crystal_model: Option, + cushion_model: Option, dragon_model: Option, arrow_model: Option, trident_model: Option, @@ -12483,6 +13215,7 @@ impl GameCpuResources { boat_models: boats::BoatModels::load(document.as_ref()), cart_models: minecarts::CartModels::load(document.as_ref()), crystal_model: model("minecraft:end_crystal#main"), + cushion_model: model("minecraft:cushion#main"), dragon_model: model("minecraft:ender_dragon#main"), arrow_model: model("minecraft:arrow#main"), trident_model: model("minecraft:trident#main"), @@ -12586,6 +13319,17 @@ impl Game<'_> { if self.rest_loader.is_some() { return Ok(()); } + let on_world_screens = self.title.as_ref().is_some_and(|title| { + !matches!( + title.mode, + horizon_client::title::Mode::Main | horizon_client::title::Mode::Multiplayer(_) + ) + }); + world_loading::preload_world_data( + on_world_screens, + &self.options.resources, + self.pack.assets.registry, + ); if std::mem::take(&mut self.pending_pack_reload) { self.reload_packs(); } @@ -13042,6 +13786,14 @@ fn build_renderer( ) -> Result { let assets = &pack.render; let atlas = &gui.atlas; + // The new renderer's atlas texture starts from `HudAtlas.pixels`, which + // holds the textures but never a glyph rasterized at run time. The font's + // cache still answers with the rects it drew into the previous renderer's + // texture, so forget them: the glyphs that are drawn again are placed into + // this texture (as `ui_theme` does when its atlas changes). Without this, + // Chinese and Japanese menu labels go blank when the loading screen hands + // over to the game. + atlas.font.reset_cache(); let mut renderer = pollster::block_on(Renderer::new( window, offscreen, @@ -13088,6 +13840,12 @@ fn loading_renderer( Some(atlas) => (atlas.pixels.as_slice(), atlas.width, atlas.height), None => (EMPTY_HUD.as_slice(), 1, 1), }; + // A glyph rasterized into an earlier texture is not in these pixels; the + // new texture gets it again when the character is drawn (see + // `build_renderer`). + if let Some(atlas) = atlas { + atlas.font.reset_cache(); + } let mut renderer = pollster::block_on(Renderer::new( window, offscreen, @@ -13824,7 +14582,7 @@ mod startup_cpu_tests { r#"{ "minecraft:end_crystal#main": {}, "minecraft:ender_dragon#main": {}, "minecraft:arrow#main": {}, "minecraft:trident#main": {}, - "minecraft:armor_stand#main": {} + "minecraft:armor_stand#main": {}, "minecraft:cushion#main": {} }"#, ) .unwrap(); @@ -13844,6 +14602,7 @@ mod startup_cpu_tests { .unwrap(); std::fs::remove_dir_all(&root).unwrap(); assert!(prepared.crystal_model.is_some()); + assert!(prepared.cushion_model.is_some()); assert!(prepared.dragon_model.is_some()); assert!(prepared.arrow_model.is_some()); assert!(prepared.trident_model.is_some()); diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index f175af401..9a8c846c5 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -453,6 +453,11 @@ impl Game<'_> { } // ArmorStand.swapItem. match held { + // A player with infinite materials puts a copy of one on an empty + // slot and keeps the stack. + Some(h) if self.creative && current.is_none() => { + self.armor_stands[i].equipment[slot] = Some(ItemStack { count: 1, ..h }); + } Some(h) if h.count > 1 => { if current.is_some() { return true; diff --git a/crates/horizon-client/src/game/beacon.rs b/crates/horizon-client/src/game/beacon.rs index 24ead3a3d..97177f2b9 100644 --- a/crates/horizon-client/src/game/beacon.rs +++ b/crates/horizon-client/src/game/beacon.rs @@ -515,8 +515,7 @@ impl Game<'_> { if self.carried.is_some() { self.draw_carried(batch); } else if let Some(stack) = stack_tip { - let lines = self.stack_tooltip(&stack); - self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1); + self.draw_stack_tooltip(batch, &stack, self.cursor.0, self.cursor.1); } else if let Some(key) = tooltip { let text = self.translate(&key, &key); self.draw_tooltip_lines( diff --git a/crates/horizon-client/src/game/block_entity_anims.rs b/crates/horizon-client/src/game/block_entity_anims.rs index 3d452596e..6f92d7f55 100644 --- a/crates/horizon-client/src/game/block_entity_anims.rs +++ b/crates/horizon-client/src/game/block_entity_anims.rs @@ -5,10 +5,14 @@ //! [`Game::block_anim`] and [`Game::chest_lid`]. use super::Game; use horizon_client::{ - block_entity_anim::{BellEntity, EndGateway, Shulker, ShulkerStatus, Ticker}, + block_entity_anim::{ + BellEntity, ConduitServer, ConduitTarget, EndGateway, Shulker, ShulkerStatus, Ticker, + }, block_entity_render::BlockAnim, collisions::{SceneCollisions, no_collision_empty}, containers::BlockEntity, + effects::EffectInstance, + mobs::{Damage, DamageKind}, particles::{ParticleOptions, ParticleType}, save::number, skins, @@ -16,6 +20,7 @@ use horizon_client::{ use horizon_core::{ geometry::{Aabb, Vec3}, position::BlockPos, + random::RandomSource, }; use horizon_world::nbt::Tag; @@ -218,9 +223,12 @@ impl Game<'_> { /// The client tickers of the loaded animated block entities, once per /// client tick (`ClientLevel.tickBlockEntities`). pub(super) fn tick_block_entity_anims(&mut self) { + // A server has no window, but its gateways and conduits still run + // their server tickers; a client of one only animates what it is sent. + if self.remote.is_none() { + self.tick_conduit_servers(); + } let Some(r) = &self.renderer else { - // A server has no window, but its gateways still run their - // server ticker. if self.remote.is_none() { self.tick_gateway_servers(); } @@ -337,6 +345,7 @@ impl Game<'_> { } } Ticker::Conduit => { + let target = self.conduit_target(pos); let world = &self.world; let facts = self.res.facts(); let registry = self.pack.assets.registry; @@ -356,7 +365,7 @@ impl Game<'_> { time, is_water, is_frame, - None, + target, self.particles.random(), ); let nautilus = ParticleOptions::simple(ParticleType::Nautilus); @@ -383,6 +392,248 @@ impl Game<'_> { } self.be_anims.present = positions; } + /// `ConduitBlockEntity.serverTick` of every conduit in the chunks that + /// tick blocks, with or without a renderer. The conduits are looked for + /// when the shape is checked, every 40 ticks (they have no block entity + /// of their own here). + fn tick_conduit_servers(&mut self) { + if self.world.game_time % 40 == 0 { + self.find_conduits(); + } + let mut positions: Vec<[i32; 3]> = self.be_anims.conduit_servers.keys().copied().collect(); + positions.sort_unstable(); + for pos in positions { + self.tick_conduit_server(pos); + } + } + /// Sets `be_anims.conduit_servers` to the conduits in the + /// chunks that tick blocks, keeping the state of those already known. + fn find_conduits(&mut self) { + let levels = self.tickets.levels(); + let kinds = &self.be_anims.kinds; + let is_conduit = |id: u32| matches!(kinds.get(id as usize), Some(Some(Ticker::Conduit))); + let mut found = Vec::new(); + for (&(cx, cz), chunk) in &self.world.chunks { + if !levels.block_ticking_at(cx * 16, cz * 16) { + continue; + } + for (si, section) in chunk.sections.iter().enumerate() { + if !section.blocks.maybe_has(is_conduit) { + continue; + } + for i in 0..4096 { + if is_conduit(section.get(i)) { + found.push([ + cx * 16 + (i & 15) as i32, + horizon_client::chunk::MIN_Y + si as i32 * 16 + (i >> 8) as i32, + cz * 16 + ((i >> 4) & 15) as i32, + ]); + } + } + } + } + let mut old = std::mem::take(&mut self.be_anims.conduit_servers); + for pos in found { + let known = old.remove(&pos).unwrap_or_default(); + self.be_anims.conduit_servers.insert(pos, known); + } + } + /// `ConduitBlockEntity.serverTick` of the conduit at `pos`, in a chunk + /// that ticks blocks: the shape check every 40 ticks with its sounds, the + /// power for players in range, the hurt for an enemy, then the ambient + /// sounds. + fn tick_conduit_server(&mut self, pos: [i32; 3]) { + let state = self.world.block(pos[0], pos[1], pos[2]).0; + if self.be_anims.ticker(state) != Some(Ticker::Conduit) { + // Broken since the chunks were searched. + self.be_anims.conduit_servers.remove(&pos); + return; + } + if !self.tickets.levels().block_ticking_at(pos[0], pos[2]) + || !self.border.contains(f64::from(pos[0]), f64::from(pos[2])) + { + return; + } + let time = self.world.game_time; + let mut conduit = self + .be_anims + .conduit_servers + .remove(&pos) + .unwrap_or_default(); + let check = { + let world = &self.world; + let facts = self.res.facts(); + let registry = self.pack.assets.registry; + let frames = self + .res + .items() + .block_tags + .get("minecraft:conduit_effect_block"); + // Level.isWaterAt: the fluid at the position is water. + let is_water = |p: [i32; 3]| { + facts.get(world.block(p[0], p[1], p[2])).fluid + == horizon_client::blocks::Fluid::Water + }; + let is_frame = |p: [i32; 3]| { + registry + .state(world.block(p[0], p[1], p[2])) + .is_some_and(|s| frames.is_some_and(|f| f.contains(&s.name))) + }; + conduit.check(pos, time, is_water, is_frame) + }; + let centre = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + if let Some(check) = check { + if let Some(active) = check.toggled { + let sound = if active { + "minecraft:block.conduit.activate" + } else { + "minecraft:block.conduit.deactivate" + }; + self.audio.play(sound, Some(centre), 1.0, 1.0); + } + if let Some(frames) = check.frames { + self.conduit_apply_effects(pos, frames); + self.conduit_attack(&mut conduit, pos, frames >= 42); + } + } + let (ambient, short) = conduit.ambient(time, &mut self.world.random); + if ambient { + self.audio + .play("minecraft:block.conduit.ambient", Some(centre), 1.0, 1.0); + } + if short { + self.audio.play( + "minecraft:block.conduit.ambient_short", + Some(centre), + 1.0, + 1.0, + ); + } + self.be_anims.conduit_servers.insert(pos, conduit); + } + /// `ConduitBlockEntity.applyEffects`: conduit power for every player + /// in water or rain within `frames / 7 * 16` blocks. + fn conduit_apply_effects(&mut self, pos: [i32; 3], frames: usize) { + let range = (frames / 7 * 16) as i64; + self.for_each_player(|g| { + let Some(p) = g.player.as_ref().filter(|p| !p.health.dead_or_dying()) else { + return; + }; + if g.spectator() { + return; + } + let at = p.position; + let in_water = p.fluids.was_touching_water; + let top = at.y + f64::from(p.dimensions.height); + // BlockPos.closerThan: the squared distance under range squared. + let d = [at.x, at.y, at.z] + .map(|v| v.floor() as i64) + .iter() + .zip(pos) + .map(|(a, b)| (a - i64::from(b)).pow(2)) + .sum::(); + if d >= range * range || !(in_water || g.in_rain(at, top)) { + return; + } + let power = EffectInstance { + ambient: true, + ..EffectInstance::new("conduit_power", 260, 0) + }; + g.potions.effects.add(power); + }); + } + /// `Entity.isInRain`: rain at the block position or at the top of the box. + fn in_rain(&mut self, at: Vec3, top: f64) -> bool { + let p = BlockPos::new( + at.x.floor() as i32, + at.y.floor() as i32, + at.z.floor() as i32, + ); + let up = BlockPos::new(p.x, top.floor() as i32, p.z); + self.with_level(|b, level, _| b.is_raining_at(level, p) || b.is_raining_at(level, up)) + } + /// `ConduitBlockEntity.updateAndAttackTarget`: while the conduit hunts + /// (42 frame blocks) its target stays until it dies or leaves the 8 + /// blocks, else a random enemy in water or rain is chosen; the target + /// takes 4 magic damage. + fn conduit_attack(&mut self, conduit: &mut ConduitServer, pos: [i32; 3], hunting: bool) { + conduit.target = match conduit.target { + _ if !hunting => None, + None => self.conduit_new_target(pos), + Some(id) => self + .mobs + .iter() + .find(|m| m.id == id && !m.removed) + .filter(|m| { + let at = [m.position.x, m.position.y, m.position.z].map(|v| v.floor() as i64); + m.alive() + && at + .iter() + .zip(pos) + .map(|(a, b)| (a - i64::from(b)).pow(2)) + .sum::() + < 64 + }) + .map(|m| m.id), + }; + let Some(m) = conduit + .target + .and_then(|id| self.mobs.iter_mut().find(|m| m.id == id)) + else { + return; + }; + let at = [m.position.x, m.position.y, m.position.z]; + m.damage(4.0, Damage::of(DamageKind::Magic)); + self.audio + .play("minecraft:block.conduit.attack.target", Some(at), 1.0, 1.0); + } + /// `ConduitBlockEntity.selectNewTarget`: one of the enemies in water or + /// rain whose box meets the conduit's block inflated by 8. + fn conduit_new_target(&mut self, pos: [i32; 3]) -> Option { + let [x, y, z] = pos.map(f64::from); + let area = Aabb::new( + Vec3::new(x - 8.0, y - 8.0, z - 8.0), + Vec3::new(x + 9.0, y + 9.0, z + 9.0), + ); + let near: Vec<(u32, bool, Vec3, f64)> = self + .mobs + .iter() + .filter(|m| m.hostile() && !m.removed && m.bounds().intersects(area)) + .map(|m| { + let top = m.position.y + f64::from(m.height()); + (m.id, m.fluids.in_water, m.position, top) + }) + .collect(); + let candidates: Vec = near + .into_iter() + .filter(|&(_, in_water, at, top)| in_water || self.in_rain(at, top)) + .map(|(id, ..)| id) + .collect(); + if candidates.is_empty() { + return None; + } + let pick = self + .world + .random + .next_int_bound(candidates.len() as i32) + .unwrap_or(0); + Some(candidates[pick as usize]) + } + /// The conduit's `destroyTarget` as the client draws it. + fn conduit_target(&self, pos: [i32; 3]) -> Option { + let id = self.be_anims.conduit_servers.get(&pos)?.target?; + let m = self.mobs.iter().find(|m| m.id == id && !m.removed)?; + Some(ConduitTarget { + position: [m.position.x, m.position.y, m.position.z], + eye_y: m.eye_y(), + width: m.width(), + height: m.height(), + }) + } /// `TheEndGatewayBlockEntity.portalTick` (the server ticker) of the /// gateways a server keeps a copy of, in block-ticking chunks /// (`Level.tickBlockEntities`): the cooldown an entry started runs out, diff --git a/crates/horizon-client/src/game/block_entity_ticks.rs b/crates/horizon-client/src/game/block_entity_ticks.rs index e48c8f398..2778bb531 100644 --- a/crates/horizon-client/src/game/block_entity_ticks.rs +++ b/crates/horizon-client/src/game/block_entity_ticks.rs @@ -10,6 +10,7 @@ use horizon_client::{ block_entities::{Pos, Ticking}, containers::{BlockEntity, FurnaceKind, HOPPER_SLOTS}, }; +use horizon_core::position::BlockPos; use horizon_world::registry::BlockStateId; impl Game<'_> { @@ -56,6 +57,8 @@ impl Game<'_> { Some(BlockEntity::Beehive(_)) => self.tick_beehive(pos), Some(BlockEntity::Furnace(_)) => self.tick_furnace(pos)?, Some(BlockEntity::Brewing(_)) => self.tick_brewing_stand(pos)?, + Some(BlockEntity::DaylightDetector) => self.tick_daylight_detector(pos), + Some(BlockEntity::Campfire(_)) => self.tick_campfire(pos)?, _ => {} } } @@ -92,7 +95,11 @@ impl Game<'_> { | "minecraft:vault" | "minecraft:beehive" | "minecraft:bee_nest" - | "minecraft:brewing_stand" => Ticking::Yes, + | "minecraft:brewing_stand" + | "minecraft:daylight_detector" + // Lit, cookTick; unlit, cooldownTick. + | "minecraft:campfire" + | "minecraft:soul_campfire" => Ticking::Yes, "minecraft:jukebox" => { let record = registry .state(state) @@ -113,6 +120,16 @@ impl Game<'_> { let levels = self.tickets.levels(); move |x, z| levels.block_ticking_at(x, z) } + /// `DaylightDetectorBlock.tickEntity` of the detector at `pos`. + fn tick_daylight_detector(&mut self, pos: Pos) { + // It updates every 20 game ticks (the behaviour checks this too). + if self.world.game_time % 20 != 0 { + return; + } + let at = BlockPos::new(pos.0, pos.1, pos.2); + self.with_level(|b, level, ticks| b.tick_daylight_detector(level, ticks, at)); + let _ = self.process_level_events(); + } /// `AbstractFurnaceBlockEntity.serverTick` of the furnace at `pos`, and /// its block's `lit` following it. fn tick_furnace(&mut self, pos: Pos) -> Result<()> { diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index df7158d9a..06dfab22d 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -55,7 +55,7 @@ pub(super) struct Boat { /// `ChestBoat.CONTAINER_SIZE`. pub(super) const CHEST_SLOTS: usize = 27; pub(super) const WIDTH: f64 = 1.375; -const HEIGHT: f64 = 0.5625; +pub(super) const HEIGHT: f64 = 0.5625; impl Boat { pub fn new(id: u32, wood: Arc, position: Vec3, yaw: f32) -> Self { Self { @@ -587,6 +587,9 @@ impl Game<'_> { } /// The player's tick while riding: steer, tick the boat, sit in it. pub(super) fn tick_riding(&mut self, keys: Keys) -> horizon_client::Result<()> { + if self.tick_cushion_riding(keys) { + return Ok(()); + } let Some(i) = self.boats.iter().position(|b| Some(b.id) == self.riding) else { if self.tick_cart_riding(keys) || self.tick_mount_riding(keys) { return Ok(()); diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index 9af1da70c..2f38dffd9 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -17,7 +17,6 @@ use horizon_client::{ use horizon_core::position::BlockPos; use horizon_protocol::packets::play::{self, Clientbound as C, Serverbound as S}; use horizon_world::level::flags as level_flags; -use std::time::Instant; use winit::{ event::{ElementState, KeyEvent}, keyboard::{KeyCode, PhysicalKey}, @@ -27,8 +26,24 @@ const BLACK: u32 = 0xFF00_0000; const PAGE_CHARS: usize = 1024; const MAX_PAGES: usize = 100; const LINES: usize = 14; -/// `BookSignScreen`'s title box. -const BOOK_TITLE: horizon_client::clipboard::FieldId = ("book.title", 0); + +fn book_title_box() -> ui::EditBox { + let mut edit = ui::EditBox::new(0.0, 0.0, 114.0, 9.0); + edit.bordered = false; + edit.max_length = 15; + edit.text_color = BLACK; + edit.focused = true; + edit +} +fn book_page_box() -> ui::EditBox { + let mut edit = ui::EditBox::new(0.0, 0.0, 114.0, 9.0); + edit.bordered = false; + edit.multiline = true; + edit.max_length = PAGE_CHARS; + edit.text_color = BLACK; + edit.focused = true; + edit +} pub(super) enum BookScreen { Edit { @@ -38,7 +53,10 @@ pub(super) enum BookScreen { page: usize, signing: bool, title: String, - opened: Instant, + /// BookSignScreen's title box (`EditBox` of 15). + title_edit: ui::EditBox, + /// BookEditScreen's page (`MultiLineEditBox`). + page_edit: ui::EditBox, }, View { pages: Vec, @@ -84,13 +102,16 @@ impl Game<'_> { if pages.is_empty() { pages.push(String::new()); } + let mut page_edit = book_page_box(); + page_edit.set_value(&pages[0]); BookScreen::Edit { slot: self.held_slot(), pages, page: 0, signing: false, title: String::new(), - opened: Instant::now(), + title_edit: book_title_box(), + page_edit, } } "minecraft:written_book" => BookScreen::View { @@ -239,34 +260,24 @@ impl Game<'_> { Some(KeyCode::PageDown) => self.turn_page(true), _ => {} }, - Some(BookScreen::Edit { - signing: true, - title, - .. - }) => match key { + Some(BookScreen::Edit { signing: true, .. }) => match key { Some(KeyCode::Escape) => { if let Some(BookScreen::Edit { signing, .. }) = self.book.as_mut() { *signing = false; } } - Some(KeyCode::Backspace) => { - if !self.text_selection.take(BOOK_TITLE, title) { - title.pop(); - } - } Some(KeyCode::Enter | KeyCode::NumpadEnter) => { - if !title.trim().is_empty() { + let blank = self.book.as_ref().is_some_and( + |b| matches!(b, BookScreen::Edit { title, .. } if title.trim().is_empty()), + ); + if !blank { self.save_book(true); } } + Some(key) if self.book_title_key(key) => {} _ => { if let Some(typed) = text { - self.text_selection.take(BOOK_TITLE, title); - for c in typed.chars().filter(|c| !c.is_control()) { - if title.chars().count() < 15 { - title.push(c); - } - } + self.book_title_insert(typed); } } }, @@ -274,24 +285,13 @@ impl Game<'_> { Some(KeyCode::Escape) => self.save_book(false), Some(KeyCode::PageUp) => self.turn_page(false), Some(KeyCode::PageDown) => self.turn_page(true), - Some(KeyCode::Backspace) => { - if !self.take_page_selection() { - self.edit_page(|p| { - p.pop(); - }) - } - } - Some(KeyCode::Enter | KeyCode::NumpadEnter) => { - self.take_page_selection(); - self.type_into_page("\n") - } + Some(KeyCode::ArrowUp) => self.book_move_line(-1), + Some(KeyCode::ArrowDown) => self.book_move_line(1), + Some(KeyCode::Enter | KeyCode::NumpadEnter) => self.page_insert("\n"), + Some(key) if self.book_page_key(key) => {} _ => { if let Some(typed) = text { - let typed: String = typed.chars().filter(|c| !c.is_control()).collect(); - if !typed.is_empty() { - self.take_page_selection(); - } - self.type_into_page(&typed); + self.page_insert(typed); } } }, @@ -302,99 +302,258 @@ impl Game<'_> { pub(super) fn book_type(&mut self, text: &str) { let text = text.replace("\\n", "\n"); match self.book.as_mut() { - Some(BookScreen::Edit { - signing: true, - title, - .. - }) => { - for c in text.chars().filter(|c| !c.is_control()) { - if title.chars().count() < 15 { - title.push(c); - } - } - } - Some(BookScreen::Edit { .. }) => self.type_into_page(&text), + Some(BookScreen::Edit { signing: true, .. }) => self.book_title_insert(&text), + Some(BookScreen::Edit { .. }) => self.page_insert(&text), _ => {} } } - /// Before typing on a page: Select All's selection is cleared (true). - fn take_page_selection(&mut self) -> bool { - match self.book.as_mut() { - Some(BookScreen::Edit { pages, page, .. }) => self - .text_selection - .take(("book.page", *page), &mut pages[*page]), - _ => false, + /// `BookSignScreen.keyPressed` on the title box. + fn book_title_key(&mut self, key: KeyCode) -> bool { + let (ctrl, shift) = (self.has_control_down(), self.has_shift_down()); + let Some(BookScreen::Edit { + title, title_edit, .. + }) = self.book.as_mut() + else { + return false; + }; + if !title_edit.key(key, ctrl, shift) { + return false; } + title.clone_from(&title_edit.value); + true } - /// Ctrl+A/C/V/X: the title box (an `EditBox` of 15) while signing, else - /// the page (`MultilineTextField.insertText`: line breaks kept, cut to - /// the 1024 characters left, rejected when it overflows the 14 lines). - pub(super) fn book_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) { - let font = &self.gui.atlas.font; - match self.book.as_mut() { - Some(BookScreen::Edit { - signing: true, - title, - .. - }) => { - Self::append_shortcut( - &mut self.text_selection, - &mut self.clipboard, - BOOK_TITLE, - title, - shortcut, - 15, - ); - } - Some(BookScreen::Edit { pages, page, .. }) => { - // truncateInsertionText counts the whole value, selection included. - let room = PAGE_CHARS.saturating_sub(pages[*page].chars().count()); - self.text_selection.apply( - ("book.page", *page), - &mut pages[*page], - shortcut, - &mut self.clipboard, - |value, pasted| { - let text: String = horizon_client::clipboard::filter_text(pasted, true) - .chars() - .take(room) - .collect(); - let next = format!("{value}{text}"); - font.split(&Text::literal(&next), 114.0).len() <= LINES && { - *value = next; - true - } - }, - ); - } - _ => {} - } - } - fn edit_page(&mut self, f: impl FnOnce(&mut String)) { - if let Some(BookScreen::Edit { pages, page, .. }) = self.book.as_mut() { - f(&mut pages[*page]); - } - } - /// MultiLineEditBox: characters that keep the page within 14 lines and 1024 characters. - fn type_into_page(&mut self, typed: &str) { - let Some(BookScreen::Edit { pages, page, .. }) = self.book.as_ref() else { + fn book_title_insert(&mut self, text: &str) { + let Some(BookScreen::Edit { + title, title_edit, .. + }) = self.book.as_mut() + else { return; }; - let mut text = pages[*page].clone(); - for c in typed.chars() { - let mut next = text.clone(); - next.push(c); - if next.chars().count() <= PAGE_CHARS && self.book_lines(&next).len() <= LINES { - text = next; + title_edit.insert_text(text); + title.clone_from(&title_edit.value); + } + /// `BookEditScreen.keyPressed` on the page, apart from the line moves. + fn book_page_key(&mut self, key: KeyCode) -> bool { + let (ctrl, shift) = (self.has_control_down(), self.has_shift_down()); + let before = match self.book.as_ref() { + Some(BookScreen::Edit { page_edit, .. }) => Some(( + page_edit.value.clone(), + page_edit.cursor, + page_edit.highlight, + )), + _ => return false, + }; + let handled = if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() { + page_edit.key(key, ctrl, shift) + } else { + false + }; + if handled { + self.page_keep(before); + } + handled + } + /// One character at a time, so a page stops at the last character that fits. + fn page_insert(&mut self, text: &str) { + for c in text.chars() { + self.page_change(|edit| edit.insert_text(&c.to_string())); + } + } + /// Ctrl+A/C/V/X: the title box while signing, else the page. + pub(super) fn book_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) { + let signing = matches!(self.book, Some(BookScreen::Edit { signing: true, .. })); + if signing { + if let Some(BookScreen::Edit { + title, title_edit, .. + }) = self.book.as_mut() + { + title_edit.shortcut(shortcut, &mut self.clipboard); + title.clone_from(&title_edit.value); + } + return; + } + let before = match self.book.as_ref() { + Some(BookScreen::Edit { page_edit, .. }) => Some(( + page_edit.value.clone(), + page_edit.cursor, + page_edit.highlight, + )), + _ => None, + }; + if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() { + page_edit.shortcut(shortcut, &mut self.clipboard); + } + self.page_keep(before); + } + /// Edit the page box, then keep it only within 14 lines and 1024 characters. + fn page_change(&mut self, f: impl FnOnce(&mut ui::EditBox)) -> bool { + let before = match self.book.as_ref() { + Some(BookScreen::Edit { page_edit, .. }) => Some(( + page_edit.value.clone(), + page_edit.cursor, + page_edit.highlight, + )), + _ => return false, + }; + let ran = if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() { + f(page_edit); + true + } else { + false + }; + ran && self.page_keep(before) + } + /// Write the page, or put the previous text back when it no longer fits. + fn page_keep(&mut self, before: Option<(String, usize, usize)>) -> bool { + let next = match self.book.as_ref() { + Some(BookScreen::Edit { page_edit, .. }) => page_edit.value.clone(), + _ => return false, + }; + let ok = next.chars().count() <= PAGE_CHARS && self.book_lines(&next).len() <= LINES; + let Some(BookScreen::Edit { + pages, + page, + page_edit, + .. + }) = self.book.as_mut() + else { + return false; + }; + if ok { + pages[*page].clone_from(&page_edit.value); + } else if let Some((value, cursor, highlight)) = before { + page_edit.value = value; + page_edit.cursor = cursor; + page_edit.highlight = highlight; + } + ok + } + /// ArrowUp and ArrowDown move a visual line, keeping the column. + fn book_move_line(&mut self, dir: isize) { + let shift = self.has_shift_down(); + let (text, cursor) = match self.book.as_ref() { + Some(BookScreen::Edit { + pages, + page, + page_edit, + .. + }) => (pages[*page].clone(), page_edit.cursor), + _ => return, + }; + let rows = self.page_rows(&text); + let (x, line) = self.caret_on(&text, &rows, cursor); + let next = (line as isize + dir).clamp(0, rows.len() as isize - 1) as usize; + let (start, end) = rows[next]; + let chars: Vec = text.chars().collect(); + let slice: String = chars[start..end].iter().collect(); + let pos = start + self.gui.atlas.font.fit(&slice, x); + if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() { + page_edit.set_cursor(pos, shift); + } + } + /// Wrapped rows of a page as character ranges, the same breaks as `font.split`. + fn page_rows(&self, page: &str) -> Vec<(usize, usize)> { + let font = &self.gui.atlas.font; + let chars: Vec = page.chars().collect(); + let mut rows = Vec::new(); + let mut start = 0; + while start < chars.len() { + let mut end = chars.len(); + let mut next = chars.len(); + let mut last_space = None; + for i in start..chars.len() { + if chars[i] == '\n' { + end = i; + next = i + 1; + break; + } + if chars[i] == ' ' { + last_space = Some(i); + } + let slice: String = chars[start..=i].iter().collect(); + if font.width(&slice) > 114.0 { + match last_space { + Some(s) if s > start => { + end = s; + next = s + 1; + } + _ => { + end = i.max(start + 1); + next = end; + } + } + break; + } + } + rows.push((start, end)); + start = next; + if start == chars.len() && chars.last() == Some(&'\n') { + rows.push((chars.len(), chars.len())); } } - self.edit_page(|p| *p = text); + if rows.is_empty() { + rows.push((0, 0)); + } + rows + } + /// GUI x of the caret and the row it sits on. + fn caret_on(&self, page: &str, rows: &[(usize, usize)], cursor: usize) -> (f32, usize) { + let chars: Vec = page.chars().collect(); + for (i, &(start, end)) in rows.iter().enumerate() { + if cursor <= end || i + 1 == rows.len() { + let take = cursor.saturating_sub(start).min(end.saturating_sub(start)); + let prefix: String = chars.iter().skip(start).take(take).collect(); + return (self.gui.atlas.font.width(&prefix), i); + } + } + (0.0, 0) + } + fn page_index_at(&self, page: &str, local_x: f32, local_y: f32) -> usize { + let rows = self.page_rows(page); + let line = (local_y / 9.0).floor().max(0.0) as usize; + let line = line.min(rows.len().saturating_sub(1)); + let (start, end) = rows[line]; + let chars: Vec = page.chars().collect(); + let slice: String = chars[start..end].iter().collect(); + start + self.gui.atlas.font.fit(&slice, local_x.max(0.0)) + } + /// A click on the centred title (`EditBox.onClick`). + fn book_title_click(&mut self, field_x: f32, mx: f32) { + let shift = self.has_shift_down(); + let Some(BookScreen::Edit { + title, title_edit, .. + }) = self.book.as_mut() + else { + return; + }; + let tx = field_x + ((114.0 - self.gui.atlas.font.width(title)) / 2.0).floor(); + let rel = (mx - tx).max(0.0); + let pos = self.gui.atlas.font.fit(title, rel); + title_edit.set_cursor(pos, shift); + } + /// A click on the open page. + fn book_page_click(&mut self, origin_x: f32, origin_y: f32, mx: f32, my: f32) { + let shift = self.has_shift_down(); + let text = match self.book.as_ref() { + Some(BookScreen::Edit { pages, page, .. }) => pages[*page].clone(), + _ => return, + }; + let pos = self.page_index_at(&text, mx - origin_x, my - origin_y); + if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() { + page_edit.set_cursor(pos, shift); + } } /// The page buttons (`pageForward` adds a page while editing). fn turn_page(&mut self, forward: bool) { let mut lectern_page = None; match self.book.as_mut() { - Some(BookScreen::Edit { pages, page, .. }) => { + Some(BookScreen::Edit { + pages, + page, + page_edit, + .. + }) => { + let before = *page; if forward { if *page + 1 >= pages.len() && pages.len() < MAX_PAGES { pages.push(String::new()); @@ -405,6 +564,10 @@ impl Game<'_> { } else if *page > 0 { *page -= 1; } + if *page != before { + let text = pages[*page].clone(); + page_edit.set_value(&text); + } } Some(BookScreen::View { lectern: Some(key), .. @@ -764,6 +927,8 @@ impl Game<'_> { if let Some(BookScreen::Edit { signing, .. }) = self.book.as_mut() { *signing = false; } + } else if inside(left + 36.0, 50.0, 114.0, 9.0) { + self.book_title_click(left + 36.0, mx); } } Some(BookScreen::Edit { page, .. }) => { @@ -780,6 +945,8 @@ impl Game<'_> { } else if inside(w / 2.0 + 2.0, 196.0, 98.0, 20.0) { click(self); self.save_book(false); + } else if inside(left + 36.0, 32.0, 114.0, 14.0 * 9.0) { + self.book_page_click(left + 36.0, 32.0, mx, my); } } Some(BookScreen::View { @@ -865,7 +1032,7 @@ impl Game<'_> { BookScreen::Edit { signing: true, title, - opened, + title_edit, .. } => { let edit = tr("book.editTitle", "Enter Book Title:"); @@ -881,19 +1048,35 @@ impl Game<'_> { // The title box: an unbordered, centred EditBox of 114 with // black text and no shadow; the value alone is centred, the // cursor follows it. + let value = &title_edit.value; let x = left + 36.0; - let tx = x + ((114.0 - HudBatch::text_width(atlas, title)) / 2.0).floor(); - horizon_client::ui::append_field( - batch, - atlas, - title, - (tx, 50.0, x + 114.0 - tx), - (BLACK, false), - 15, - self.text_selection.covers(BOOK_TITLE, title), - true, - opened.elapsed().as_millis(), - ); + let tx = x + ((114.0 - HudBatch::text_width(atlas, value)) / 2.0).floor(); + batch.text(atlas, value, tx, 50.0, BLACK, false); + if title_edit.cursor != title_edit.highlight { + let (a, b) = ( + title_edit.cursor.min(title_edit.highlight), + title_edit.cursor.max(title_edit.highlight), + ); + let pre: String = value.chars().take(a).collect(); + let sel: String = value.chars().skip(a).take(b - a).collect(); + let sx = tx + HudBatch::text_width(atlas, &pre); + batch.text_highlight( + atlas, + (sx, 49.0, HudBatch::text_width(atlas, &sel), 11.0), + true, + ); + } + if title_edit.cursor_visible() { + let pre: String = value.chars().take(title_edit.cursor).collect(); + batch.fill( + atlas, + tx + HudBatch::text_width(atlas, &pre), + 49.0, + 1.0, + 9.0, + BLACK, + ); + } let by = tr("book.byAuthor", "by %1$s").replace("%1$s", super::chat::PLAYER_NAME); let tw = HudBatch::text_width(atlas, &by); batch.text( @@ -941,12 +1124,12 @@ impl Game<'_> { BookScreen::Edit { pages, page, - opened, + page_edit, .. } => { indicator(batch, *page, pages.len()); - let blink = (opened.elapsed().as_millis() / 300) % 2 == 0; - let lines = self.book_lines(&pages[*page]); + let text = &pages[*page]; + let lines = self.book_lines(text); for (i, line) in lines.iter().take(LINES).enumerate() { batch.text_styled( atlas, @@ -957,27 +1140,39 @@ impl Game<'_> { false, ); } - if blink { - // The cursor after the last character. - let last = lines - .last() - .map(|l| atlas.font.width_text(l)) - .unwrap_or(0.0); - let row = lines.len().saturating_sub(1) as f32 - + if pages[*page].ends_with('\n') { - 1.0 - } else { - 0.0 - }; - let x = if pages[*page].ends_with('\n') { - 0.0 - } else { - last - }; + let rows = self.page_rows(text); + let (sel_a, sel_b) = ( + page_edit.cursor.min(page_edit.highlight), + page_edit.cursor.max(page_edit.highlight), + ); + if sel_a != sel_b { + let chars: Vec = text.chars().collect(); + for (i, &(start, end)) in rows.iter().enumerate().take(LINES) { + let from = sel_a.max(start); + let to = sel_b.min(end); + if from >= to { + continue; + } + let pre: String = chars[start..from].iter().collect(); + let sel: String = chars[from..to].iter().collect(); + batch.text_highlight( + atlas, + ( + left + 36.0 + atlas.font.width(&pre), + top + 29.0 + i as f32 * 9.0, + atlas.font.width(&sel), + 9.0, + ), + true, + ); + } + } + if page_edit.cursor_visible() { + let (x, row) = self.caret_on(text, &rows, page_edit.cursor); batch.fill( atlas, left + 36.0 + x, - top + 29.0 + row * 9.0, + top + 29.0 + row as f32 * 9.0, 1.0, 9.0, BLACK, diff --git a/crates/horizon-client/src/game/bundles.rs b/crates/horizon-client/src/game/bundles.rs new file mode 100644 index 000000000..198964803 --- /dev/null +++ b/crates/horizon-client/src/game/bundles.rs @@ -0,0 +1,103 @@ +//! `BundleMouseActions`: the wheel over a bundle in a container screen selects +//! one of the items it shows, which a click that takes one out of it then takes +//! (`BundleContents.Mutable.removeOne`). Moving off the bundle clears the +//! selection. On a server the selection is sent to it (`ServerboundSelectBundleItemPacket`). +use super::{Game, Screen}; +use horizon_client::{ + bundle::{Contents, toggle_selected}, + mouse::ScrollWheelHandler, +}; +use horizon_protocol::packets::play::{self, Serverbound as S}; + +#[derive(Default)] +pub(super) struct BundleMouse { + wheel: ScrollWheelHandler, + /// The slot under the cursor at the last tick (`AbstractContainerScreen.hoveredSlot`). + hovered: Option, +} + +impl Game<'_> { + /// A slot a bundle can be selected in: the player's inventory, the off hand and a + /// container's own slots. A server only knows these in the inventory and chest-like menus. + fn bundle_slot(&mut self, slot: usize) -> bool { + (slot < 36 || slot == 504 || (300..500).contains(&slot)) + && (self.remote.is_none() || self.remote_storage_open()) + && (slot < 36 || slot == 504 || self.slots().contains(&slot)) + } + + /// `BundleMouseActions.onMouseScrolled`: the wheel over a bundle moves the selection + /// through the items its tooltip shows. True when the bundle took the wheel. + pub(super) fn bundle_scroll(&mut self, x: f64, y: f64) -> bool { + let Some(slot) = self.inventory_target().0 else { + return false; + }; + if !self.bundle_slot(slot) { + return false; + } + let stack = self.slot_mut(slot).clone(); + let items = self.res.items(); + let Some(bundle) = stack.filter(|s| items.get(&s.item).is_some_and(|i| i.bundle)) else { + return false; + }; + let shown = Contents::of(items, &bundle).map_or(0, |c| c.shown_count()); + if shown == 0 { + return false; + } + let (wheel_x, wheel_y) = self.bundle_mouse.wheel.on_mouse_scroll(x, y); + let wheel = if wheel_y == 0 { -wheel_x } else { wheel_y }; + if wheel != 0 { + let selected = bundle.data().map_or(-1, |d| d.bundle_selected.0); + let next = ScrollWheelHandler::next_selection(f64::from(wheel), selected, shown as i32); + if next != selected { + self.select_bundle(slot, next); + } + } + true + } + + /// `BundleMouseActions.toggleSelectedBundleItem`: the stack here and, on a server, there. + fn select_bundle(&mut self, slot: usize, index: i32) { + if let Some(stack) = self.slot_mut(slot) { + toggle_selected(stack, index); + } + if self.remote.is_some() { + let (_, menu) = self.remote_menu(); + if let Some(menu_slot) = Self::menu_slot_index(&menu, slot) { + self.send(S::SelectBundleItem(play::SelectBundleItem { + slot: menu_slot as i32, + index, + })); + } + } + } + + /// `BundleMouseActions.unselectedBundleItem` for the bundle in `slot`, if it has a selection. + pub(super) fn unselect_bundle(&mut self, slot: usize) { + if !self.bundle_slot(slot) { + return; + } + let selected = self + .slot_mut(slot) + .as_ref() + .and_then(|s| s.data()) + .is_some_and(|d| d.bundle_selected.0 >= 0); + if selected { + self.select_bundle(slot, -1); + } + } + + /// `AbstractContainerScreen.onStopHovering` (and `onClose`): leaving a slot, or the + /// screen, clears the bundle's selection. + pub(super) fn tick_bundle_hover(&mut self) { + let now = if self.screen == Screen::Inventory { + self.inventory_target().0 + } else { + None + }; + if let Some(left) = std::mem::replace(&mut self.bundle_mouse.hovered, now) + && Some(left) != now + { + self.unselect_bundle(left); + } + } +} diff --git a/crates/horizon-client/src/game/campfire.rs b/crates/horizon-client/src/game/campfire.rs new file mode 100644 index 000000000..c388b7561 --- /dev/null +++ b/crates/horizon-client/src/game/campfire.rs @@ -0,0 +1,190 @@ +//! Campfires' cooking: `CampfireBlock.useItemOn` (`CampfireBlockEntity.placeFood`) +//! and the block entity's `cookTick` (lit) and `cooldownTick` (unlit). The +//! items drawn on the fire are `campfire_geometry`'s; a server's clients get +//! them through the block entity's update tag (`lan::chunks::entity_tag`). +use super::Game; +use horizon_assets::item_model::DisplayContext; +use horizon_client::{ + Result, block_entities::Pos, block_entity_render::vertex_light, containers::BlockEntity, + items::ItemStack, mesher::Vertex, mobs::Who, +}; +use horizon_core::position::BlockPos; + +/// The `campfire_cooking` recipe kind (`RecipeType.CAMPFIRE_COOKING`). +const KIND: &str = "minecraft:campfire_cooking"; + +fn is_campfire(name: &str) -> bool { + name == "minecraft:campfire" || name == "minecraft:soul_campfire" +} + +impl Game<'_> { + /// `CampfireBlock.useItemOn` with a held item that is a campfire recipe's + /// input (`RecipePropertySet.CAMPFIRE_INPUT`): on a server level the food + /// goes into the first free slot (`placeFood`), and the use is consumed + /// whether or not there was room. A client of a server leaves the placing + /// to the server. Whether the food went in; None when this isn't a + /// campfire use, so the item's own use runs. + pub(super) fn use_on_campfire(&mut self, pos: [i32; 3]) -> Result> { + let state = self.world.block(pos[0], pos[1], pos[2]); + if !is_campfire(&self.res.facts().get(state).name) { + return Ok(None); + } + let Some(held) = self.held().cloned() else { + return Ok(None); + }; + let Some(time) = self.res.recipes().cook(KIND, &held).map(|r| r.time as i32) else { + return Ok(None); + }; + // A client of a server predicts the placing; the server decides. + if self.remote.is_some() { + return Ok(Some(true)); + } + let key = (pos[0], pos[1], pos[2]); + let placed = match self.world.block_entities.get_mut(&key) { + Some(BlockEntity::Campfire(c)) => { + let mut one = held.clone(); + c.place_food(&mut one, time) + } + _ => false, + }; + if placed { + // ItemStack.consumeAndReturn: creative keeps the item. + self.consume_held(); + self.stats.custom("interact_with_campfire", 1); + self.post_block_game_event( + "minecraft:block_change", + pos, + Some(Who::Player), + Some(state), + ); + self.mark_block_entity_updated(key); + } + Ok(Some(placed)) + } + + /// `CampfireBlockEntity.cookTick` of a lit campfire, `cooldownTick` of an + /// unlit one. A finished item's result (the recipe's, or the item itself + /// when no recipe takes it any more) drops at the block's corner + /// (`Containers.dropItemStack` at its integer position), then the clients + /// see the slot empty and a `block_change` goes out. + pub(super) fn tick_campfire(&mut self, pos: Pos) -> Result<()> { + let state = self.world.block(pos.0, pos.1, pos.2); + let lit = self + .pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("lit")) + .is_some_and(|v| v == "true"); + let Some(BlockEntity::Campfire(c)) = self.world.block_entities.get_mut(&pos) else { + return Ok(()); + }; + // BlockEntity.setChanged: a timer that moved is saved with the + // chunk (no update to the clients, who don't see the timers). + let changed = if lit { + c.items.iter().any(Option::is_some) + } else { + c.cooldown_tick() + }; + if changed { + self.world.modified.insert((pos.0 >> 4, pos.2 >> 4)); + } + if !lit { + return Ok(()); + } + let Some(BlockEntity::Campfire(c)) = self.world.block_entities.get_mut(&pos) else { + return Ok(()); + }; + let done = c.cook_tick(); + for (_, item) in done { + let result = self + .res + .recipes() + .cook(KIND, &item) + .map_or_else(|| item.clone(), |r| r.result.clone()); + self.campfire_drop(pos, result); + self.mark_block_entity_updated(pos); + self.post_block_game_event( + "minecraft:block_change", + [pos.0, pos.1, pos.2], + None, + Some(state), + ); + } + Ok(()) + } + + /// `CampfireRenderer`: each cooking item lies on the fire, slot `i` + /// turned to `Direction.from2DDataValue((i + facing) % 4)`, laid flat + /// (90° about X), at a corner and three eighths of its size, drawn as a + /// FIXED item seeded by the block's position plus the slot. + pub(super) fn campfire_geometry(&self, camera: glam::DVec3, out: &mut Vec) { + for (key, entity) in &self.world.block_entities { + let BlockEntity::Campfire(c) = entity else { + continue; + }; + if c.items.iter().all(Option::is_none) { + continue; + } + let at = glam::DVec3::new(f64::from(key.0), f64::from(key.1), f64::from(key.2)); + if at.distance_squared(camera) >= 64.0 * 64.0 { + continue; + } + // Direction.get2DDataValue: south 0, west 1, north 2, east 3. + let state = self.world.block(key.0, key.1, key.2); + let facing = match self + .pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("facing")) + .map(String::as_str) + { + Some("west") => 1, + Some("north") => 2, + Some("east") => 3, + _ => 0, + }; + let light = vertex_light(self.world.light(key.0, key.1, key.2)); + let packed = BlockPos::new(key.0, key.1, key.2).pack(); + for (i, stack) in c.items.iter().enumerate() { + let Some(stack) = stack else { + continue; + }; + let seed = (packed as i32).wrapping_add(i as i32); + let item = self.resolve_item(stack, DisplayContext::Fixed, None, seed); + if item.is_empty() { + continue; + } + // Direction.toYRot: 90° per 2D step from south. + let yaw = -(((i + facing) % 4) as f32 * 90.0); + let pose = glam::Mat4::from_translation( + (at - camera).as_vec3() + glam::Vec3::new(0.5, 0.449_218_75, 0.5), + ) * glam::Mat4::from_rotation_y(yaw.to_radians()) + * glam::Mat4::from_rotation_x(90f32.to_radians()) + * glam::Mat4::from_translation(glam::Vec3::new(-0.3125, -0.3125, 0.0)) + * glam::Mat4::from_scale(glam::Vec3::splat(0.375)); + self.submit_item_world(&item, pose, light, out); + } + } + } + + /// `Containers.dropItemStack(level, x, y, z, stack)` at the block's + /// integer position. + fn campfire_drop(&mut self, pos: Pos, stack: ItemStack) { + let at = BlockPos::new(pos.0, pos.1, pos.2); + for piece in + horizon_world::level::removal::drop_item_stack(&mut self.world.random, at, stack.count) + { + self.spawn_item( + ItemStack { + count: piece.count, + ..stack.clone() + }, + piece.pos, + piece.motion, + 0, + ); + } + } +} diff --git a/crates/horizon-client/src/game/campfire_douse.rs b/crates/horizon-client/src/game/campfire_douse.rs new file mode 100644 index 000000000..04accb2d3 --- /dev/null +++ b/crates/horizon-client/src/game/campfire_douse.rs @@ -0,0 +1,53 @@ +//! `CampfireBlock.useItemOn`: an item in `#minecraft:douses_campfires` (the +//! shovels) put on a lit campfire puts it out. +use super::Game; +use horizon_client::{Result, animate_tick::make_campfire_smoke, items::ItemStack}; + +impl Game<'_> { + /// `CampfireBlock.useItemOn` with `held` in the hand that acts, the block + /// at `pos` clicked: true when it doused a lit campfire (SUCCESS). + pub(super) fn use_campfire_douse( + &mut self, + pos: [i32; 3], + held: Option<&ItemStack>, + ) -> Result { + let Some(tool) = held.filter(|s| { + self.res + .items() + .item_tags + .get("minecraft:douses_campfires") + .is_some_and(|members| members.contains(&*s.item)) + }) else { + return Ok(false); + }; + let registry = self.pack.assets.registry; + let Some(mut state) = registry + .state(self.world.block(pos[0], pos[1], pos[2])) + .filter(|s| matches!(&*s.name, "minecraft:campfire" | "minecraft:soul_campfire")) + .filter(|s| s.properties.get("lit").map(String::as_str) == Some("true")) + .cloned() + else { + return Ok(false); + }; + // Level event 1009 (SOUND_EXTINGUISH_FIRE) goes to every player. + self.level_event_at(1009, pos, 0); + // CampfireBlock.douse: the acting client's own smoke (twenty puffs), + // then the block change game event from the player. + if self.lan_acting.is_none() { + let signal = state.properties.get("signal_fire").map(String::as_str) == Some("true"); + for _ in 0..20 { + make_campfire_smoke(&mut self.particles, pos, signal, true); + } + } + self.post_block_game_event("minecraft:block_change", pos, self.sculk_actor(), None); + state.properties.insert("lit".into(), "false".into()); + if let Ok(unlit) = registry.resolve(&state) { + self.level_set(pos, unlit)?; + } + let used = tool.clone(); + self.damage_held(1); + // ServerPlayerGameMode.useItemOn: the action was consumed. + self.trigger_block("minecraft:item_used_on_block", pos, &used); + Ok(true) + } +} diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 5d3919c8b..03174c009 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -464,7 +464,28 @@ impl Game<'_> { return; } // The Chat option's Hidden level takes the server's messages too. - if !self.ui.chat.shows(ChatSource::Server) { + self.local_chat_line(text, Some(SYSTEM_INDICATOR), ChatSource::Server); + } + /// A player's chat line on the window's own chat: a LAN guest's message + /// while the host runs in-frame (`HostEvent::Chat`). `ChatListener` + /// checks `canReceivePlayerMessages` for these, so Commands Only and + /// Hidden drop them; command feedback (`/list`, `/tp`) is a system + /// message and takes the system-message permission instead. + pub(super) fn player_message(&mut self, text: Text) { + if let Some(capture) = self.chat_capture.as_mut() { + capture.push(text); + return; + } + // A server's client receives the line as a packet (PlayerChat or + // DisguisedChat) and filters it there. + if self.remote.is_none() { + self.local_chat_line(text, None, ChatSource::Player); + } + } + /// A line on the window's own chat when the Chat option lets `source` + /// through; running mods hear it. + fn local_chat_line(&mut self, text: Text, indicator: Option, source: ChatSource) { + if !self.ui.chat.shows(source) { return; } let focused = self.screen == Screen::Chat; @@ -472,8 +493,8 @@ impl Game<'_> { self.ui.chat.add( &self.gui.atlas, text, - Some(SYSTEM_INDICATOR), - ChatSource::Server, + indicator, + source, self.ticks, focused, ); @@ -602,7 +623,10 @@ impl Game<'_> { return; } if let Some(command) = message.strip_prefix('/') { - self.run_command(command); + // A client mod's command first, then a server mod's, as on a server. + if !self.mod_command(command) && !self.local_server_mod_command(command) { + self.run_command(command); + } } else { let line = Text::translate( "chat.type.text", @@ -622,6 +646,7 @@ impl Game<'_> { self.mods_chat(&line); } self.lan_host_chat(message); + self.mod_player_chat(super::server_mods::Who::Local, message); } } pub(super) fn chat_scroll(&mut self, amount: f32) { @@ -757,6 +782,7 @@ impl Game<'_> { max_snow_accumulation_height: r.int("max_snow_accumulation_height"), spawn_mobs: r.bool("spawn_mobs"), spawn_monsters: r.bool("spawn_monsters"), + fire_spread_radius_around_player: r.int("fire_spread_radius_around_player"), } } /// Apply rules mirrored in other state (natural regeneration, difficulty). diff --git a/crates/horizon-client/src/game/client_ambient.rs b/crates/horizon-client/src/game/client_ambient.rs index a10c6da49..1cf59733d 100644 --- a/crates/horizon-client/src/game/client_ambient.rs +++ b/crates/horizon-client/src/game/client_ambient.rs @@ -4,8 +4,12 @@ //! on the game that has the window, in-frame or following a server, never on //! a server: nothing of them goes over the network. use super::Game; +use horizon_client::blocks::RenderShape; use horizon_client::mobs::{MobEvent, ambient}; -use horizon_client::particles::{ParticleOptions, ParticleType}; +use horizon_client::motion::{LAVA, WATER}; +use horizon_client::particles::{ParticleEngine, ParticleOptions, ParticleType}; +use horizon_client::pose::Pose; +use horizon_core::{geometry::Vec3, random::RandomSource}; impl Game<'_> { pub(super) fn tick_client_ambient(&mut self) { @@ -33,5 +37,209 @@ impl Game<'_> { } } self.eye_particles(); + self.sprint_dust(); + self.effect_swirls(); + } + + /// `Entity.baseTick`'s `spawnSprintParticle` on a client: dust of the + /// block under a sprinting player's feet streams back from them every + /// tick, for the window's own player and for the other players it sees. + fn sprint_dust(&mut self) { + // Each runner's feet, movement and supporting block. + let mut runners: Vec<(Vec3, Vec3, Option<[i32; 3]>)> = Vec::new(); + // Entity.canSpawnSprintParticle. + if let Some(p) = self.player.as_ref() + && p.sprinting + && !p.spectator + && p.pose != Pose::Crouching + && !p.health.dead_or_dying() + && !p.fluids.was_touching_water + && !p.is_in_lava() + && p.fluid_height(WATER) <= 0.0 + && p.fluid_height(LAVA) <= 0.0 + { + let support = p.ground.supporting_block.map(|b| [b.x, b.y, b.z]); + runners.push((p.position, p.velocity, support)); + } + let guests = self.lan.iter().flat_map(|host| host.models.values()); + for m in self.mobs.iter().chain(guests) { + // Another player's fluids aren't known here: none where they stand. + let feet = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + if m.extra.sprinting + && !m.extra.crouching + && m.alive() + && &*m.kind.id == "minecraft:player" + && self + .res + .facts() + .get(self.world.block(feet[0], feet[1], feet[2])) + .fluid_level + == 0 + { + runners.push((m.position, m.position.subtract(m.previous), None)); + } + } + for (position, movement, support) in runners { + // Entity.getOnPosLegacy: getOnPos(0.2). + let below = (position.y - f64::from(0.2f32)).floor() as i32; + let tall = |game: &Self, s: [i32; 3]| { + let name = game.block_name(s); + [ + "minecraft:fences", + "minecraft:walls", + "minecraft:fence_gates", + ] + .iter() + .any(|tag| game.block_in_tag(tag, &name)) + }; + let at = match support { + Some(s) if tall(self, s) => s, + Some(s) => [s[0], below, s[2]], + None => [position.x.floor() as i32, below, position.z.floor() as i32], + }; + let state = self.world.block(at[0], at[1], at[2]); + if self.res.facts().get(state).render_shape == RenderShape::Invisible { + continue; + } + let Some((sprite, tint)) = self.particle_sprite(state, at) else { + continue; + }; + let width = f64::from(0.6f32); + let r = self.particles.random(); + let mut x = position.x + (r.next_double() - 0.5) * width; + let mut z = position.z + (r.next_double() - 0.5) * width; + // Clamped into the block when the feet are in another column. + if position.x.floor() as i32 != at[0] { + x = x.clamp(f64::from(at[0]), f64::from(at[0]) + 1.0); + } + if position.z.floor() as i32 != at[2] { + z = z.clamp(f64::from(at[2]), f64::from(at[2]) + 1.0); + } + self.particles.add( + &ParticleOptions::block(ParticleType::Block, sprite, tint), + [x, position.y + 0.1, z], + [movement.x * -4.0, 1.5, movement.z * -4.0], + ); + } + } + + /// `LivingEntity.tickEffects` on a client: the swirls around an entity + /// with visible effects, from the particles its synched data lists. The + /// window's player has its own effects, a server's mobs and players the + /// list the server sent, and the mobs and guests of a game in the frame + /// theirs. + fn effect_swirls(&mut self) { + if let Some(p) = self.player.as_ref() { + let effects = &self.potions.effects.list; + let list: Vec<_> = effects + .iter() + .filter(|e| e.visible) + .filter_map(|e| effect_particle(e.id, e.ambient)) + .collect(); + let ambient = effects.iter().filter(|e| e.visible).all(|e| e.ambient); + let invisible = effects.iter().any(|e| e.id == "invisibility"); + let size = ( + f64::from(p.dimensions.width), + f64::from(p.dimensions.height), + ); + swirl( + &mut self.particles, + p.position, + size, + &list, + ambient, + invisible, + ); + } + let guests = self.lan.iter().flat_map(|host| host.models.values()); + for m in self.mobs.iter().chain(guests) { + if !m.alive() { + continue; + } + let size = (f64::from(m.width()), f64::from(m.height())); + let invisible = m.invisible || m.has_effect("minecraft:invisibility"); + if m.extra.effect_particles.is_empty() { + // A mob of this game: its own effects, visible and not ambient. + if m.extra.effects.is_empty() { + continue; + } + let list: Vec<_> = m + .extra + .effects + .iter() + .filter(|e| !m.extra.hidden_effects.contains(&e.0)) + .filter_map(|e| effect_particle(e.0, false)) + .collect(); + swirl( + &mut self.particles, + m.position, + size, + &list, + false, + invisible, + ); + } else { + let list = &m.extra.effect_particles; + let ambient = m.extra.effect_ambient; + swirl( + &mut self.particles, + m.position, + size, + list, + ambient, + invisible, + ); + } + } } } + +/// `MobEffect.particleFactory`: the omens have particles of their own, any +/// other effect an entity effect in its colour, faint when ambient. +pub(super) fn effect_particle(effect: &str, ambient: bool) -> Option { + Some(match effect.trim_start_matches("minecraft:") { + "trial_omen" => ParticleOptions::simple(ParticleType::TrialOmen), + "raid_omen" => ParticleOptions::simple(ParticleType::RaidOmen), + other => { + let color = horizon_client::brewing::effect(other)?.color; + let channel = |shift: u32| ((color >> shift) & 255) as f32 / 255.0; + // MobEffect.AMBIENT_ALPHA is 38 of 255. + let alpha = if ambient { 38.0 / 255.0 } else { 1.0 }; + ParticleOptions::colored( + ParticleType::EntityEffect, + [channel(16), channel(8), channel(0), alpha], + ) + } + }) +} + +/// One tick of `LivingEntity.tickEffects`' client branch: a one in four +/// chance (one in fifteen while invisible, a fifth of either when all the +/// effects are ambient) of one of the particles at a random spot of the box. +fn swirl( + particles: &mut ParticleEngine, + feet: Vec3, + size: (f64, f64), + list: &[ParticleOptions], + ambient: bool, + invisible: bool, +) { + if list.is_empty() { + return; + } + let bound = if invisible { 15 } else { 4 } * if ambient { 5 } else { 1 }; + let r = particles.random(); + let Ok(0) = r.next_int_bound(bound) else { + return; + }; + // Util.getRandom, then getRandomX(0.5), getRandomY and getRandomZ. + let pick = r.next_int_bound(list.len() as i32).unwrap_or_default() as usize; + let x = feet.x + size.0 * (2.0 * r.next_double() - 1.0) * 0.5; + let y = feet.y + size.1 * r.next_double(); + let z = feet.z + size.0 * (2.0 * r.next_double() - 1.0) * 0.5; + particles.add(&list[pick], [x, y, z], [1.0; 3]); +} diff --git a/crates/horizon-client/src/game/clipboard.rs b/crates/horizon-client/src/game/clipboard.rs index c87aa3681..6e81bf3ee 100644 --- a/crates/horizon-client/src/game/clipboard.rs +++ b/crates/horizon-client/src/game/clipboard.rs @@ -63,8 +63,8 @@ impl Game<'_> { } } } - /// Typing or a backspace in a field of the title screens: in the server - /// screens' append-only fields Select All's selection is replaced first. + /// Typing or a backspace in a title-screen field. A field that still only + /// appends replaces a Select All selection before the edit. pub(super) fn title_edit(&mut self, typed: Option<&str>, backspace: bool) { let Some(title) = self.title.as_mut() else { return; @@ -86,42 +86,31 @@ impl Game<'_> { } /// Shortcuts in the creative inventory's search box (an `EditBox` of 50). pub(super) fn creative_search_shortcut(&mut self, shortcut: EditShortcut) { - if Self::append_shortcut( - &mut self.text_selection, - &mut self.clipboard, - CREATIVE_SEARCH, - &mut self.creative_screen.search, - shortcut, - CREATIVE_SEARCH_CHARS, - ) { + if self + .creative_screen + .search + .shortcut(shortcut, &mut self.clipboard) + { self.creative_screen.scroll = 0.0; } } /// A backspace in the creative search box: with Ctrl, the whole word /// before the caret (`EditBox.deleteWords(-1)`), otherwise one character. - /// A Select All selection is what it deletes, as in `EditBox.keyPressed`. + /// A selection is what it deletes, as in `EditBox.keyPressed`. pub(super) fn creative_search_backspace(&mut self, ctrl: bool) { - let search = &mut self.creative_screen.search; - if !self.text_selection.take(CREATIVE_SEARCH, search) { - if ctrl { - horizon_client::ui::delete_words(search, -1); - } else { - search.pop(); - } - } + self.creative_screen + .search + .key(KeyCode::Backspace, ctrl, false); self.creative_screen.scroll = 0.0; } /// Typing in the creative search box. pub(super) fn creative_search_edit(&mut self, typed: Option<&str>) { - let search = &mut self.creative_screen.search; - self.text_selection.take(CREATIVE_SEARCH, search); if let Some(text) = typed { - clipboard::append_limited(search, text, CREATIVE_SEARCH_CHARS); + self.creative_screen.search.insert_text(text); + self.creative_screen.scroll = 0.0; } - self.creative_screen.scroll = 0.0; } } /// `CreativeModeInventoryScreen`'s search box: `setMaxLength(50)`. pub(super) const CREATIVE_SEARCH_CHARS: usize = 50; -pub(super) const CREATIVE_SEARCH: horizon_client::clipboard::FieldId = ("creative.search", 0); diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index 227aa0332..2d6b75902 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -10,6 +10,9 @@ struct Entry { fall_distance: f32, /// The causing entity: its id (for comparisons) and display name. attacker: Option<(u32, Text)>, + /// The direct entity's display name when no entity caused the damage + /// (`DamageSource.directEntity`: a potion with no thrower, a cloud). + direct: Option, } #[derive(Default)] pub(super) struct CombatTracker { @@ -19,6 +22,8 @@ pub(super) struct CombatTracker { /// Attackers of damage dealt this tick, claimed by the matching /// `RecordedDamage` event. pending: Vec<(String, (u32, Text))>, + /// `pending` for a direct entity with no causing entity: only its name. + pending_direct: Vec<(String, Text)>, /// `LivingEntity.lastHurtByMob` and its timestamp (the kill credit). last_hurt_by: Option<((u32, Text), i64)>, /// The mob the player last hurt (`getLastHurtMob`) and when. @@ -31,6 +36,10 @@ pub(super) struct CombatTracker { /// The mob exploding now (`ServerExplosion.source`): its team's friendly /// fire decides whom the blast may hurt. pub(super) explosion_source: Option, + /// Charged creepers whose blast just went off and that have not dropped + /// a head yet (`Creeper.droppedSkulls`): they are gone from the mob list, + /// but the mobs they killed still ask for their loot. + pub(super) charged_exploders: Vec, /// The player's fall distance before this tick's movement (as of the /// end of the last one). fall_before: f64, @@ -52,11 +61,24 @@ impl Game<'_> { /// Remember who deals the next `damage_type` damage to the player. pub(super) fn note_attacker(&mut self, damage_type: &str, mob: u32) { if let Some(name) = self.mob_display_name(mob) { - self.combat - .pending - .push((damage_type.to_owned(), (mob, name))); + self.note_named_attacker(damage_type, mob, name); } } + /// `note_attacker` for an entity that is not one of `self.mobs` (the + /// ender dragon). + pub(super) fn note_named_attacker(&mut self, damage_type: &str, id: u32, name: Text) { + self.combat + .pending + .push((damage_type.to_owned(), (id, name))); + } + /// The `DamageSource.directEntity` of the next `damage_type` damage when + /// nothing caused it (a splash potion nobody threw): the death message + /// names it instead (`getLocalizedDeathMessage`). It is no kill credit. + pub(super) fn note_direct_entity(&mut self, damage_type: &str, name: Text) { + self.combat + .pending_direct + .push((damage_type.to_owned(), name)); + } /// `LivingEntity.handleDamageEvent` for the player: the hurt sound of the /// source's `DamageEffects` (`Player.getHurtSound`). pub(super) fn player_hurt_sound(&mut self, sound: &str, at: [f64; 3]) { @@ -85,6 +107,15 @@ impl Game<'_> { .iter() .position(|(t, _)| *t == name) .map(|i| self.combat.pending.remove(i).1); + let direct = match attacker { + Some(_) => None, + None => self + .combat + .pending_direct + .iter() + .position(|(t, _)| *t == name) + .map(|i| self.combat.pending_direct.remove(i).1), + }; let (fall_location, fall_distance) = self.fall_location(); let now = self.world.game_time; if let Some(a) = &attacker { @@ -102,10 +133,12 @@ impl Game<'_> { fall_location, fall_distance, attacker, + direct, }); self.combat.last_damage = now; } self.combat.pending.clear(); + self.combat.pending_direct.clear(); self.combat.fall_before = self.player.as_ref().map_or(0.0, |p| p.fall_distance); } /// `FallLocation.getCurrentFallLocation` and the fall distance so far. @@ -215,6 +248,7 @@ impl Game<'_> { let entries = std::mem::take(&mut self.combat.entries); let killing = entries.last().expect("checked above"); let killer = killing.attacker.clone(); + let direct = killing.direct.clone(); if def.1 == "fall_variants" && let Some(knock) = knock.and_then(|i| entries.get(i)) { @@ -239,15 +273,22 @@ impl Game<'_> { .append(Text::literal("]")); return Text::translate(&format!("{key}.message"), &[me, link]); } + // `getLocalizedDeathMessage`: the causing entity's name, or the + // direct entity's when nothing caused the damage. if let Some((_, name)) = killer { return Text::translate(&key, &[me, name]); } + if let Some(name) = direct { + return Text::translate(&key, &[me, name]); + } // getKillCredit: the last mob that hurt the player in the past 100 ticks. if let Some(((_, name), at)) = &self.combat.last_hurt_by && self.world.game_time - at <= 100 { return Text::translate(&format!("{key}.player"), &[me, name.clone()]); } + // No entity at all: the one-argument message, as vanilla sends it (a + // template that names a killer then shows as written). Text::translate(&key, &[me]) } } diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index f3afdcab6..f308cfec6 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -85,16 +85,16 @@ fn format_double(v: f64) -> String { impl Game<'_> { /// Commands.performCommand for a line without its slash. - pub(super) fn run_command(&mut self, command: &str) { + pub(super) fn run_command(&mut self, command: &str) -> bool { if self.mod_command(command) { - return; + return true; } let d = vanilla::game_dispatcher(); let parse = d.parse(command, &self.ui.registries); let result = match parse.executable() { Err(e) => { self.syntax_failure(&e, command); - return; + return false; } Ok((ctx, _)) => { let ctx = ctx.clone(); @@ -103,6 +103,7 @@ impl Game<'_> { self.run_chain(&root, &ctx) } }; + let ok = result.is_ok(); if let Err(e) = result { if e.input.is_some() { self.syntax_failure(&e, command); @@ -114,6 +115,20 @@ impl Game<'_> { if self.player.is_some() { self.check_inventory_trigger(); } + ok + } + /// `run_command` with its output suppressed + /// (`CommandSourceStack.withSuppressedOutput`): the player's own source, + /// rights and checks, no feedback and no failure in the chat. + pub(super) fn run_command_quietly(&mut self, command: &str) -> bool { + let quiet = execute::Source { + silent: true, + ..self.player_source() + }; + let outer = self.command_source.replace(quiet); + let ok = self.run_command(command); + self.command_source = outer; + ok } fn syntax_failure(&mut self, e: &CommandError, command: &str) { self.command_failure(e.message.clone()); @@ -526,8 +541,7 @@ impl Game<'_> { .enumerate() // The kinds /data can write (entity_nbt). .filter(|(_, p)| { - p.arrow.is_some() - || matches!(p.kind, K::LargeFireball { .. } | K::SmallFireball) + p.is_arrow() || matches!(p.kind, K::LargeFireball { .. } | K::SmallFireball) }) .map(|(i, _)| Target::Projectile(i)), ); @@ -1682,6 +1696,8 @@ impl Game<'_> { value: 0, age: 0, on_ground: false, + count: 1, + ticks: 0, }); name = Text::translate("entity.minecraft.experience_orb", &[]); } @@ -1870,11 +1886,12 @@ impl Game<'_> { } } } - let Some((_, new)) = horizon_client::save::decode_block_entity(&tag) else { + let Some((_, mut new)) = horizon_client::save::decode_block_entity(&tag) else { return false; }; + let rolled = self.take_loot_table(key, &tag, &mut new); let after = horizon_client::save::encode_block_entity(key, &new, &name); - if after == before { + if after == before && !rolled { return false; } self.world.block_entities.insert(key, new); @@ -1882,6 +1899,79 @@ impl Game<'_> { let _ = self.world.set(pos[0], pos[1], pos[2], state); true } + /// RandomizableContainer.tryLoadLootTable for a tag a command gives a + /// container (`setblock`, `data`): an empty container with a `LootTable` + /// is rolled now, as a loaded chunk's are (`save::roll_loaded_loot`), and + /// the roll is kept with its chunk, so that the container saves, and + /// `data get` shows, its table and seed until its items change. A tag + /// without one drops what the container had. True when it had a table. + pub(super) fn take_loot_table( + &mut self, + key: (i32, i32, i32), + tag: &horizon_world::nbt::Tag, + entity: &mut horizon_client::containers::BlockEntity, + ) -> bool { + use horizon_client::{containers::BlockEntity, save, structure_blocks}; + let table = save::text(tag.get("LootTable")); + let rolled = match (table, entity) { + (Some(table), BlockEntity::Chest(slots)) if slots.iter().all(Option::is_none) => { + let loot = structure_blocks::loot_data(&self.options.resources); + let at = Vec3::new(f64::from(key.0), f64::from(key.1), f64::from(key.2)); + let biome = self.biome_name_at(at).unwrap_or_default(); + Some(structure_blocks::roll_container( + slots, + loot.as_deref(), + table, + structure_blocks::loot_seed(tag), + key, + &biome, + )) + } + _ => None, + }; + let Some(chunk) = self.world.chunks.get_mut(&(key.0 >> 4, key.2 >> 4)) else { + return false; + }; + let held = |c: &horizon_client::chunk::Chunk| { + c.saved + .as_ref() + .is_some_and(|s| s.rolled_loot.iter().any(|r| r.pos == key)) + }; + if rolled.is_none() && !held(chunk) { + return false; + } + let chunk = std::sync::Arc::make_mut(chunk); + let mut extras = chunk + .saved + .take() + .map(std::sync::Arc::unwrap_or_clone) + .unwrap_or_default(); + extras.rolled_loot.retain(|r| r.pos != key); + let taken = rolled.is_some(); + extras.rolled_loot.extend(rolled); + chunk.saved = Some(std::sync::Arc::new(extras)); + taken + } + /// The loot table and seed a container still holding its roll saves + /// (`RolledLoot::restore`), in place of its items. + pub(super) fn restore_loot_table( + &self, + key: (i32, i32, i32), + tag: &mut horizon_world::nbt::Tag, + ) { + let horizon_world::nbt::Tag::Compound(map) = tag else { + return; + }; + let rolled = self + .world + .chunks + .get(&(key.0 >> 4, key.2 >> 4)) + .and_then(|c| c.saved.as_ref()) + .and_then(|s| s.rolled_loot.iter().find(|r| r.pos == key)); + if let Some(r) = rolled { + r.restore(map); + } + } fn cmd_fill(&mut self, ctx: &Context) -> R { let a = self.block_pos_arg(ctx, "from")?; let b = self.block_pos_arg(ctx, "to")?; @@ -2578,38 +2668,7 @@ impl Game<'_> { /// `PoiTypes`: the point of interest type of a block state. fn poi_type(&self, state: horizon_world::registry::BlockStateId) -> Option<&'static str> { let s = self.pack.assets.registry.state(state)?; - let name = s.name.strip_prefix("minecraft:")?; - Some(match name { - "blast_furnace" => "minecraft:armorer", - "smoker" => "minecraft:butcher", - "cartography_table" => "minecraft:cartographer", - "brewing_stand" => "minecraft:cleric", - "composter" => "minecraft:farmer", - "barrel" => "minecraft:fisherman", - "fletching_table" => "minecraft:fletcher", - "cauldron" | "lava_cauldron" | "water_cauldron" | "powder_snow_cauldron" => { - "minecraft:leatherworker" - } - "lectern" => "minecraft:librarian", - "stonecutter" => "minecraft:mason", - "loom" => "minecraft:shepherd", - "smithing_table" => "minecraft:toolsmith", - "grindstone" => "minecraft:weaponsmith", - "bell" => "minecraft:meeting", - "beehive" => "minecraft:beehive", - "bee_nest" => "minecraft:bee_nest", - "nether_portal" => "minecraft:nether_portal", - "lodestone" => "minecraft:lodestone", - "test_instance_block" => "minecraft:test_instance", - n if n.ends_with("_bed") => { - if s.properties.get("part").map(String::as_str) != Some("head") { - return None; - } - "minecraft:home" - } - n if n.ends_with("lightning_rod") => "minecraft:lightning_rod", - _ => return None, - }) + horizon_client::save::poi_type(s).map(|(kind, _)| kind) } /// `LocateCommand.locatePoi`: `PoiManager.findClosestWithType` within /// 256 blocks of the source, over the loaded chunks. diff --git a/crates/horizon-client/src/game/commands/data.rs b/crates/horizon-client/src/game/commands/data.rs index 18035ddd7..ac16c5e7c 100644 --- a/crates/horizon-client/src/game/commands/data.rs +++ b/crates/horizon-client/src/game/commands/data.rs @@ -286,6 +286,7 @@ impl Game<'_> { if let Tag::Compound(c) = &mut tag { c.remove(&"keepPacked".into()); } + self.restore_loot_table(key, &mut tag); Ok(tag) } DataRef::Storage(id) => Ok(self.score.storage.get(id)), @@ -296,7 +297,8 @@ impl Game<'_> { DataRef::Entity(t) => self.apply_entity_nbt(*t, tag), DataRef::Block(p) => { let key = (p[0], p[1], p[2]); - if let Some((_, new)) = save::decode_block_entity(&tag) { + if let Some((_, mut new)) = save::decode_block_entity(&tag) { + self.take_loot_table(key, &tag, &mut new); self.world.block_entities.insert(key, new); let state = self.world.block(p[0], p[1], p[2]); // Redraw what shows the block entity (signs, banners). diff --git a/crates/horizon-client/src/game/commands/effects.rs b/crates/horizon-client/src/game/commands/effects.rs index 65d6592f7..6516bfe6c 100644 --- a/crates/horizon-client/src/game/commands/effects.rs +++ b/crates/horizon-client/src/game/commands/effects.rs @@ -91,7 +91,12 @@ impl Game<'_> { } Target::Mob(id) => match self.mobs.iter_mut().find(|m| m.id == id) { Some(m) => { - m.add_effect(namespaced(effect.id), duration, amplifier); + let name = namespaced(effect.id); + m.add_effect(name, duration, amplifier); + m.extra.hidden_effects.retain(|h| *h != name); + if !particles { + m.extra.hidden_effects.push(name); + } true } None => false, @@ -154,6 +159,10 @@ impl Game<'_> { m.extra .effects .retain(|x| e.is_some_and(|e| x.0 != namespaced(e.id))); + let left = &m.extra.effects; + m.extra + .hidden_effects + .retain(|h| left.iter().any(|x| x.0 == *h)); m.extra.effects.len() != before } None => false, diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index 3f7e4c2a0..eb4d4b157 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -145,9 +145,42 @@ impl Game<'_> { .iter() .find(|m| m.id == id) .map_or(0.0, |m| m.eye_y() - m.position.y), - _ => 0.0, + // ArmorStand.getDefaultDimensions: a marker's are empty, a small + // stand's are BABY_DIMENSIONS, whose eye height is 0.9875F. + Target::Stand(id) => match self.armor_stands.iter().find(|a| a.id == id) { + Some(a) if a.marker => 0.0, + Some(a) if a.small => f64::from(0.9875f32), + _ => self.type_eye_height(&self.target_type(t)), + }, + // Entity.getEyeHeight: the type's dimensions. + _ => self.type_eye_height(&self.target_type(t)), } } + /// `EntityType.getDimensions().eyeHeight()` from `entity-types.json`, + /// read once: a float, widened as `Entity.getEyeY` does. + fn type_eye_height(&self, ty: &str) -> f64 { + static EYE_HEIGHTS: std::sync::OnceLock> = + std::sync::OnceLock::new(); + EYE_HEIGHTS + .get_or_init(|| { + std::fs::read(self.options.resources.join("entity-types.json")) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .and_then(|v| { + v.as_object().map(|o| { + o.iter() + .filter_map(|(k, t)| { + Some((k.clone(), f64::from(t["eye_height"].as_f64()? as f32))) + }) + .collect() + }) + }) + .unwrap_or_default() + }) + .get(ty) + .copied() + .unwrap_or(0.0) + } /// EntityAnchorArgument.Anchor.apply. pub(super) fn anchor_position(&self, s: &Source) -> [f64; 3] { match s.entity { @@ -467,9 +500,10 @@ impl Game<'_> { "positioned" if c.has("as") => targets(self)? .into_iter() .filter_map(|t| { + // withPosition keeps the anchor (only `positioned ` + // resets it to the feet). Some(Source { pos: self.target_position(t)?, - eyes: false, ..s }) }) @@ -606,6 +640,72 @@ impl Game<'_> { .collect(), _ => Vec::new(), }, + // Leashable.getLeashHolder: a fence knot is not an entity here. + Some("leasher") => match entity { + Target::Mob(id) => self + .mobs + .iter() + .find(|m| m.id == id) + .and_then(|m| m.extra.leash.map(|holder| (holder, m.extra.leash_player))) + .and_then(|(holder, player)| match holder { + // The player who tied it (the host's when unrecorded). + horizon_client::mobs::leash::Holder::Player => { + let uuid = player.or(self.level.player_uuid)?; + self.target_by_uuid(horizon_client::lan::playerdata::ints_uuid(uuid)) + } + horizon_client::mobs::leash::Holder::Mob(i) => Some(Target::Mob(i)), + horizon_client::mobs::leash::Holder::Knot(_) => None, + }) + .into_iter() + .collect(), + _ => Vec::new(), + }, + // TraceableEntity.getOwner: who shot a projectile, who threw an + // item, who summoned a vex. + Some("origin") => match entity { + Target::Projectile(i) => self + .creatures + .projectiles + .get(i) + .and_then(|p| match (p.owner?, p.guest) { + // A guest's shot: `Who::Player` is them. + (horizon_client::mobs::Who::Player, Some(conn)) + if self.lan_acting == Some(conn) => + { + Some(Target::Player) + } + (horizon_client::mobs::Who::Player, Some(conn)) => { + Some(Target::Guest(conn)) + } + (horizon_client::mobs::Who::Player, None) => Some(Target::Player), + (horizon_client::mobs::Who::Mob(id), _) => Some(Target::Mob(id)), + }) + .into_iter() + .collect(), + Target::Item(id) => self + .dropped + .iter() + .find(|d| d.id == id) + .and_then(|d| d.thrower) + .and_then(|words| { + let uuid = words + .iter() + .fold(0u128, |all, w| all << 32 | u128::from(*w as u32)); + self.target_by_uuid(uuid) + }) + .into_iter() + .collect(), + Target::Mob(id) => self + .mobs + .iter() + .find(|m| m.id == id && m.kind.id == "minecraft:vex") + .map(|m| m.extra.counter2 as u32) + .filter(|owner| *owner != 0) + .map(Target::Mob) + .into_iter() + .collect(), + _ => Vec::new(), + }, Some("vehicle") => self.ride_vehicle(entity).into_iter().collect(), Some("controller") | Some("passengers") => match entity { Target::Mob(id) if self.mobs.iter().any(|m| m.id == id && m.rider.is_some()) => { diff --git a/crates/horizon-client/src/game/commands/pregen.rs b/crates/horizon-client/src/game/commands/pregen.rs index d497e2734..eb3c37688 100644 --- a/crates/horizon-client/src/game/commands/pregen.rs +++ b/crates/horizon-client/src/game/commands/pregen.rs @@ -244,7 +244,11 @@ impl Game<'_> { /// hand them the next jobs as soon as each one is done, rather than once /// a tick. pub(in crate::game) fn pump_pregen(&mut self, until: Instant) { - while self.pregen_runs_here() { + // Force-loaded chunks too: decorating in vanilla's order, a chunk + // waits for its neighbours far more often than once a tick allows. + while self.pregen_runs_here() + || (!self.streaming.forced.is_empty() && self.streaming.busy()) + { let now = Instant::now(); if now >= until { break; diff --git a/crates/horizon-client/src/game/commands/terrain_cmds.rs b/crates/horizon-client/src/game/commands/terrain_cmds.rs index d4b1c125c..824ca4d60 100644 --- a/crates/horizon-client/src/game/commands/terrain_cmds.rs +++ b/crates/horizon-client/src/game/commands/terrain_cmds.rs @@ -120,6 +120,9 @@ impl Game<'_> { tracker.track(&holder(chunk_text(x, z)), i32::from(changed)); } } + if add { + self.streaming.rank_forced(cx0, cz0, cx1, cz1); + } let (lo, hi) = (chunk_text(cx0, cz0), chunk_text(cx1, cz1)); let verb = if add { "added" } else { "removed" }; let (message, total) = tracker.message( diff --git a/crates/horizon-client/src/game/commands/text_commands.rs b/crates/horizon-client/src/game/commands/text_commands.rs index dead07d71..020157f83 100644 --- a/crates/horizon-client/src/game/commands/text_commands.rs +++ b/crates/horizon-client/src/game/commands/text_commands.rs @@ -14,10 +14,11 @@ impl Game<'_> { serde_json::from_str(json).map_err(|e| err("argument.component.invalid", &[&e]))?; // NbtContents.resolve: the path's values in the entity, block or // storage data, rich-styled (or plain, or interpreted), ", "-joined. + // ScoreContents.resolve: the holder's score in the objective. let nbt_values = std::cell::RefCell::new(Vec::new()); { let mut collect = |o: &serde_json::Map| { - if o.contains_key("nbt") { + if o.contains_key("nbt") || o.contains_key("score") { nbt_values.borrow_mut().push(o.clone()); } }; @@ -40,7 +41,11 @@ impl Game<'_> { } let mut resolved: Vec<(serde_json::Map, Text)> = Vec::new(); for o in nbt_values.into_inner() { - let t = self.resolve_nbt_component(&o); + let t = if o.contains_key("score") { + self.resolve_score_component(&o)? + } else { + self.resolve_nbt_component(&o) + }; resolved.push((o, t)); } let mut resolve = |raw: &str| -> Text { @@ -73,6 +78,54 @@ impl Game<'_> { }, )) } + /// The text of a `score` component (ScoreContents.resolve): the named + /// holder's score, `*` being the player the command runs for. + fn resolve_score_component( + &mut self, + o: &serde_json::Map, + ) -> R { + let score = o.get("score"); + let field = |k: &str| score.and_then(|s| s.get(k)).and_then(|v| v.as_str()); + let (name, objective) = ( + field("name").unwrap_or(""), + field("objective").unwrap_or(""), + ); + // findTargetName: a selector that matches one entity is that entity, + // one that matches none is just the name. + let mut reader = horizon_client::command::Reader::new(name); + let ty = horizon_client::command::args::ArgType::Entity { + single: false, + players: false, + }; + let mut holder = name.to_owned(); + if let Ok(Arg::Entity(sel)) = ty.parse(&mut reader, &self.ui.registries) + && !reader.can_read() + { + let found = self.select(&sel); + if found.len() > 1 { + return Err(err("argument.entity.toomany", &[])); + } + if let Some(t) = found.first().and_then(|t| self.holder_name(*t)) { + holder = t; + } + } + if holder == "*" { + holder = self.acting_player_name().to_owned(); + } + let board = &self.score.board; + let (Some(objective), Some(score)) = + (board.objective(objective), board.score(&holder, objective)) + else { + return Ok(Text::empty()); + }; + // numberFormatOrDefault(StyledFormat.NO_STYLE). + let format = (score.number_format.clone()) + .or_else(|| objective.number_format.clone()) + .unwrap_or(horizon_client::scoreboard::NumberFormat::Styled( + serde_json::json!({}), + )); + Ok(format.format(score.value)) + } /// The text of an `nbt` component. fn resolve_nbt_component(&mut self, o: &serde_json::Map) -> Text { use horizon_world::nbt::Tag; @@ -136,28 +189,40 @@ impl Game<'_> { } out } - fn player_targets(&mut self, ctx: &Context) -> R { - // Only the local player can receive messages and titles. + /// The players the command reaches: the window's own and the LAN guests. + fn player_targets(&mut self, ctx: &Context) -> R> { let targets = self.entities(ctx, "targets", true)?; - Ok(targets.iter().filter(|t| **t == Target::Player).count()) + Ok(targets + .into_iter() + .filter(|t| matches!(t, Target::Player | Target::Guest(_))) + .collect()) } pub(super) fn cmd_tellraw(&mut self, ctx: &Context) -> R { - let n = self.player_targets(ctx)?; + let players = self.player_targets(ctx)?; let message = self.component_arg(ctx, "message")?; - if n > 0 { - self.system_message(message); + // Each player's chat (a guest's through the connection). + for &t in &players { + self.for_player(t, |g| g.system_message(message.clone())); } - Ok(n as i32) + Ok(players.len() as i32) } pub(super) fn cmd_title(&mut self, ctx: &Context) -> R { - let n = self.player_targets(ctx)?; - let name = self.target_name(Target::Player); + let players = self.player_targets(ctx)?; + let n = players.len(); + let name = players + .first() + .map_or_else(Text::empty, |t| self.target_name(*t)); let single = n == 1; let key = if ctx.has("clear") { - self.titles_or_packet(Titles::clear, C::ClearTitles(play::Bool1 { value: false })); + self.titles_or_packet( + &players, + Titles::clear, + C::ClearTitles(play::Bool1 { value: false }), + ); "cleared" } else if ctx.has("reset") { self.titles_or_packet( + &players, |t| { t.clear(); t.reset_times(); @@ -172,6 +237,7 @@ impl Game<'_> { }; let (fade_in, stay, fade_out) = (get("fadeIn"), get("stay"), get("fadeOut")); self.titles_or_packet( + &players, |t| t.set_times(fade_in, stay, fade_out), C::SetTitlesAnimation(play::TitlesAnimation { fade_in, @@ -186,13 +252,17 @@ impl Game<'_> { text: component_nbt(&text.component()), }; if ctx.has("subtitle") { - self.titles_or_packet(|t| t.set_subtitle(text), C::SetSubtitleText(sent)); + self.titles_or_packet(&players, |t| t.set_subtitle(text), C::SetSubtitleText(sent)); "show.subtitle" } else if ctx.has("actionbar") { - self.titles_or_packet(|t| t.set_overlay(text, false), C::SetActionBarText(sent)); + self.titles_or_packet( + &players, + |t| t.set_overlay(text, false), + C::SetActionBarText(sent), + ); "show.actionbar" } else { - self.titles_or_packet(|t| t.set_title(text), C::SetTitleText(sent)); + self.titles_or_packet(&players, |t| t.set_title(text), C::SetTitleText(sent)); "show.title" } }; @@ -207,13 +277,27 @@ 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); + /// TitleCommand's `connection.send` for each player: a guest is sent the + /// packet, the window's own player shows it. + fn titles_or_packet(&mut self, players: &[Target], local: impl FnOnce(&mut Titles), packet: C) { + let mut local = Some(local); + for &t in players { + match t { + Target::Player if self.lan_acting.is_some() => { + self.guest_packets.push(packet.clone()); + } + Target::Player => { + if let Some(local) = local.take() { + local(&mut self.titles); + } + } + Target::Guest(conn) => { + if let Some(host) = self.lan.as_ref() { + host.hub.send_to(conn, &packet); + } + } + _ => {} + } } } } diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 30f019997..559d30db4 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -49,26 +49,12 @@ impl Game<'_> { let mut tracker = Tracker::default(); for &t in &targets { let h = holder(self.target_name(t)); - // ServerRecipeBook.addRecipes/removeRecipes count recipe book - // 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; - n += if give { - let (count, unlocked) = self.level.recipe_book.add_recipes(index, &recipes); - self.recipe_unlocked(&unlocked); - count as i32 - } else { - let removed = self.level.recipe_book.remove_recipes(index, &recipes); - let count = removed.len() as i32; - // A network player's client drops them from its book. - if self.lan_acting.is_some() && !removed.is_empty() { - self.guest_packets.push(C::RecipeBookRemove( - horizon_protocol::packets::recipes::RecipeBookRemove { ids: removed }, - )); - } - count - }; + // ServerPlayer.awardRecipes / resetRecipes on the target's own + // ServerRecipeBook: a guest's is swapped in for the call, and the + // packets go to its client. + let n = self + .for_player(t, |g| g.change_recipes(give, &recipes)) + .unwrap_or(0); tracker.track(&h, n); } let verb = if give { "give" } else { "take" }; @@ -92,6 +78,27 @@ impl Game<'_> { Ok(total) } + /// ServerRecipeBook.addRecipes/removeRecipes for the player in place: how + /// many recipe book displays changed (a transmute recipe has one per + /// material count). + fn change_recipes(&mut self, give: bool, recipes: &[String]) -> i32 { + let index = &self.res.stations().recipe_index; + if give { + let (count, unlocked) = self.level.recipe_book.add_recipes(index, recipes); + self.recipe_unlocked(&unlocked); + return count as i32; + } + let removed = self.level.recipe_book.remove_recipes(index, recipes); + let count = removed.len() as i32; + // A network player's client drops them from its book. + if self.lan_acting.is_some() && !removed.is_empty() { + self.guest_packets.push(C::RecipeBookRemove( + horizon_protocol::packets::recipes::RecipeBookRemove { ids: removed }, + )); + } + count + } + // ---- /damage ---------------------------------------------------------------- fn damage_kind(ty: &str) -> DamageKind { @@ -108,6 +115,7 @@ impl Game<'_> { "in_fire" | "campfire" | "hot_floor" => DamageKind::InFire, "lava" => DamageKind::Lava, "drown" => DamageKind::Drown, + "dry_out" => DamageKind::DryOut, "magic" | "indirect_magic" | "dragon_breath" => DamageKind::Magic, "sting" => DamageKind::Sting, "cactus" | "sweet_berry_bush" => DamageKind::Cactus, @@ -133,27 +141,37 @@ impl Game<'_> { Some(Arg::Entity(_)) => self.entities(ctx, "entity", false)?.first().copied(), _ => None, }; + let cause = match ctx.get("cause") { + Some(Arg::Entity(_)) => self.entities(ctx, "cause", false)?.first().copied(), + _ => None, + }; let from = match ctx.get("location") { Some(Arg::Coords(_)) => self.position_arg(ctx, "location"), _ => by.and_then(|t| self.target_position(t)), }; let hurt = match target { + // The causing mob is the one the hit is credited to and thorns + // answer; the source position gives the knockback its direction. Target::Player => { - if self.creative || self.spectator() { + // `DamageSource(type, cause, by)`: the death message names the + // causing entity, else the direct one. A mob is noted by + // `hurt_player_from`, a player here. + if let Some(t @ (Target::Player | Target::Guest(_))) = cause.or(by) { + let name = self.target_name(t); + self.note_direct_entity(&ty, name); + } + if self.spectator() { false - } else if let Some(player) = self.player.as_mut() { - match self.motion.health.damage.id(&ty) { - Some(id) => player - .hurt(&self.motion.health, self.world.health_rules, id, amount) - .unwrap_or(false), - None => false, - } } else { - false + let attacker = match cause.or(by) { + Some(Target::Mob(i)) => Some(Some(i)), + _ => Some(None), + }; + self.hurt_player_from(amount, from, &ty, attacker) } } Target::Mob(id) => { - let attacker = by.and_then(|t| match t { + let attacker = cause.or(by).and_then(|t| match t { Target::Player => Some(Who::Player), Target::Mob(i) => Some(Who::Mob(i)), _ => None, @@ -294,9 +312,18 @@ impl Game<'_> { float("minVolume", 0.0), ); let range = if volume > 1.0 { 16.0 * volume } else { 16.0 }; + // PlaySoundCommand: one seed for every player. + let seed = self.world.random.next_long(); + let here = self.dim.id(); let mut tracker = Tracker::default(); for t in targets { - if t != Target::Player { + if !matches!(t, Target::Player | Target::Guest(_)) { + continue; + } + // Only players in the source's level hear it. + if let Target::Guest(conn) = t + && self.command_guest(conn).is_none_or(|g| g.dimension != here) + { continue; } let Some(p) = self.target_position(t) else { @@ -320,8 +347,26 @@ impl Game<'_> { } else { (pos, volume) }; - self.audio.play_on(source, &sound, Some(at), v, pitch); - tracker.mark(&holder(Text::literal(self.acting_player_name()))); + // The connection is sent the sound; the window's own player + // plays it. + let guest = match t { + Target::Guest(conn) => Some(conn), + _ => self.lan_acting, + }; + match guest.and_then(|conn| Some((conn, self.lan.as_ref()?))) { + Some((conn, host)) => { + let packet = host + .hub + .sound_packet(&sound, at, v, pitch, source as i32, seed); + if t == Target::Player { + self.guest_packets.push(packet); + } else { + host.hub.send_to(conn, &packet); + } + } + None => self.audio.play_on(source, &sound, Some(at), v, pitch), + } + tracker.mark(&holder(self.target_name(t))); } let name = Text::literal(sound.clone()); let (message, total) = tracker.message( @@ -598,8 +643,10 @@ impl Game<'_> { let reached = reached.len() as i32; if !local { } else if count <= 0 { - // No count: one particle with the delta as velocity. - self.particles.create(&options, pos, delta); + // handleParticleEvent, count 0: one particle, the speed times + // the delta as velocity (both sent as floats, multiplied as floats). + self.particles + .create(&options, pos, delta.map(|d| f64::from(speed * d as f32))); } else { for _ in 0..count { let r = self.particles.random(); diff --git a/crates/horizon-client/src/game/composter.rs b/crates/horizon-client/src/game/composter.rs index 3f57229ad..4013155ad 100644 --- a/crates/horizon-client/src/game/composter.rs +++ b/crates/horizon-client/src/game/composter.rs @@ -5,6 +5,7 @@ use super::{Game, commands::compute::ComputeContext}; use horizon_client::{ items::ItemStack, + mobs::villager, particles::{ParticleOptions, ParticleType}, }; use horizon_core::{position::BlockPos, random::RandomSource}; @@ -86,6 +87,82 @@ impl Game<'_> { self.composter_add(pos, &layers); (stack.count > 0).then_some(stack) } + /// `WorkAtComposter.compostItems` for the villager at `mob`: a full + /// composter is emptied, then up to 20 wheat or beetroot seeds go in + /// (keeping 10 of each kind) until the composter reaches level 7. Level + /// event 1500 plays once, at the end. + pub(super) fn villager_compost_items(&mut self, mob: usize, pos: [i32; 3]) { + let at = BlockPos::new(pos[0], pos[1], pos[2]); + let Some(mut before) = self.composter_level(pos) else { + return; + }; + if before == 8 { + self.with_level(|b, level, ticks| b.composter_extract(level, ticks, at)); + let _ = self.process_level_events(); + before = 0; + } + let mut remaining = 20; + let mut amounts: Vec<(std::sync::Arc, i32)> = Vec::new(); + let slots = villager::ext(&self.mobs[mob]).map_or(0, |e| e.inventory.len()); + 'slots: for slot in (0..slots).rev() { + if remaining <= 0 { + break; + } + let stack = villager::ext_mut(&mut self.mobs[mob]).inventory[slot].clone(); + if !matches!( + &*stack.item, + "minecraft:wheat_seeds" | "minecraft:beetroot_seeds" + ) { + continue; + } + let known = amounts.iter().position(|(item, _)| *item == stack.item); + let total = known.map_or(0, |k| amounts[k].1) + stack.count as i32; + match known { + Some(k) => amounts[k].1 = total, + None => amounts.push((stack.item.clone(), total)), + } + let uses = (total - 10).min(remaining).min(stack.count as i32); + if uses <= 0 { + continue; + } + remaining -= uses; + for _ in 0..uses { + self.villager_insert_item(mob, slot, &stack, pos); + if self.composter_level(pos) == Some(7) { + break 'slots; + } + } + } + let after = self.composter_level(pos).unwrap_or(before); + self.with_level(|b, level, ticks| { + b.composter_fill_effects(level, ticks, at, after != before) + }); + let _ = self.process_level_events(); + } + /// `ComposterBlock.insertItem` with a villager's stack: below level 7 a + /// compostable item is used up and may add a layer. + fn villager_insert_item(&mut self, mob: usize, slot: usize, stack: &ItemStack, pos: [i32; 3]) { + if self.composter_level(pos).is_none_or(|level| level >= 7) { + return; + } + let Some(layers) = self.compostable(stack) else { + return; + }; + let context = ComputeContext { + block: Some(pos), + target: None, + }; + let layers = self.provider_int(&layers, &context, 0).unwrap_or(0); + let at = BlockPos::new(pos[0], pos[1], pos[2]); + self.with_level(|b, level, ticks| b.composter_layer(level, ticks, at, layers)); + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); + let _ = self.process_level_events(); + let inventory = &mut villager::ext_mut(&mut self.mobs[mob]).inventory; + inventory[slot].count -= 1; + if inventory[slot].count == 0 { + inventory.remove(slot); + } + } /// `ComposterBlock.handleFill` (level event 1500) on the client: the /// fill sound and ten composter particles above the compost. pub(super) fn composter_fill_event(&mut self, pos: BlockPos, success: bool) { diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 3202b23f4..9b5cd93e7 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -628,6 +628,9 @@ impl Game<'_> { // The port, or the game rules' search and number boxes. Screen::WorldOptions if text == "\\b" => self.world_options_text(None), Screen::WorldOptions => self.world_options_text(Some(text)), + Screen::Inventory if self.mod_browser_typing() => { + self.mod_browser_text((text != "\\b").then_some(text), text == "\\b") + } Screen::Inventory if self.recipe_search_focused() => { self.recipe_text(Some(text), false) } @@ -1080,6 +1083,9 @@ impl Game<'_> { "flashes": self.lightning_seen[1], "flash": self.flash}); // Primed TNT, falling blocks, projectiles, tridents and end crystals. status["projectiles"] = json!(self.projectiles_status()); + let mut fangs_vertices = Vec::new(); + self.fangs_geometry(glam::DVec3::ZERO, 0.5, &mut fangs_vertices); + status["fangs_vertices"] = json!(fangs_vertices.len()); status["maps"] = json!(self.maps_status()); // The particles made so far, by type. status["particles"] = json!(self.particles.made()); diff --git a/crates/horizon-client/src/game/creaking.rs b/crates/horizon-client/src/game/creaking.rs index c75325c2f..19b3442c2 100644 --- a/crates/horizon-client/src/game/creaking.rs +++ b/crates/horizon-client/src/game/creaking.rs @@ -218,8 +218,9 @@ impl Game<'_> { ); } /// `CreakingHeartBlock.playerWillDestroy`: the heart's creaking twitches to - /// death and a natural heart drops experience. - pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3]) { + /// death and a natural heart drops experience. `onExplosionHit` does the + /// same for the creaking (`by_player` false), without the experience. + pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3], by_player: bool) { let key = (pos[0], pos[1], pos[2]); if !matches!( self.world.block_entities.get(&key), @@ -242,7 +243,7 @@ impl Game<'_> { .state(state) .and_then(|s| s.properties.get("natural").cloned()) .is_some_and(|v| v == "true"); - if natural && !self.creative && !self.spectator() { + if by_player && natural && !self.creative && !self.spectator() { let xp = 20 + self.world.random.next_int_bound(5).unwrap_or(0) as u32; self.spawn_orbs( [ diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 3a8562ee1..2bc40a7af 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -18,6 +18,7 @@ use horizon_client::{ spawning::{self, BiomeFacts}, }, projectiles::{Hit, Projectile, ProjectileKind, ProjectileWorld}, + text::Text, }; use horizon_core::{ geometry::{Aabb, Vec3, traverse_blocks}, @@ -50,9 +51,9 @@ pub(super) struct Creatures { /// The wandering trader spawner's clock. pub trader: super::wandering_trader::Spawner, } -struct ProjWorld<'a, 'w> { - w: &'a MobWorld<'w>, - targets: Vec<(Who, Aabb)>, +pub(super) struct ProjWorld<'a, 'w> { + pub w: &'a MobWorld<'w>, + pub targets: Vec<(Who, Aabb)>, } impl ProjectileWorld for ProjWorld<'_, '_> { fn clip(&self, from: Vec3, to: Vec3) -> Option<(Vec3, [i32; 3], [i32; 3])> { @@ -193,6 +194,7 @@ impl Game<'_> { velocity: p.velocity, yaw: self.yaw, hero: self.potions.effects.get("hero_of_the_village").is_some(), + effects: self.potions.effects.list.iter().map(|e| e.id).collect(), uuid: self.level.player_uuid.unwrap_or_default(), allies: std::sync::Arc::new(self.player_allies()), remote: false, @@ -373,6 +375,7 @@ impl Game<'_> { // Drawn seated (Entity.isPassenger); set apart because the // json! above is at the macro recursion limit. state["passenger"] = m.extra.passenger.into(); + state["guardian_beam"] = serde_json::json!(horizon_client::mobs::guardian::beam(m, 0.0)); state }) .collect(); @@ -391,6 +394,9 @@ impl Game<'_> { } pub(super) fn mob_world_base<'s>(&'s self, others: &'s [Seen]) -> MobWorld<'s> { let (rain, thunder) = self.world.weather.levels(1.0); + // Level.canHaveWeather: only the overworld's rain and thunder levels + // ever rise, so nothing rains or thunders in the Nether or the End. + let weather = self.dim == Dim::Overworld; let player = self.player_view(); MobWorld { world: &self.world, @@ -407,8 +413,8 @@ impl Game<'_> { daylight: self.dim != Dim::Nether && self.sky_darken() < 4, game_time: self.world.game_time, day_time: self.world.day_time, - raining: rain > 0.2, - thundering: thunder > 0.9, + raining: weather && rain > 0.2, + thundering: weather && thunder > 0.9, nether: self.dim == Dim::Nether, block_tags: &self.res.items().block_tags, biomes: self.res.biomes(), @@ -425,6 +431,12 @@ impl Game<'_> { ), } } + /// What the generator finalizes this level's structure mobs with. + pub(super) fn share_spawn_conditions(&self) { + if let Some(terrain) = self.end.locator() { + terrain.set_spawn_conditions(self.difficulty_id() as u8, self.world.day_time); + } + } /// `ServerLevel.getCurrentDifficultyAt`. pub(super) fn local_difficulty(&self, at: [f64; 3]) -> spawning::LocalDifficulty { use horizon_world::food::Difficulty; @@ -493,6 +505,8 @@ impl Game<'_> { self.died.insert(m.id); self.mob_died(&m); } + // Their victims have been looted: no charged creeper is waiting any more. + self.combat.charged_exploders.clear(); let uuid = self.level.player_uuid; let mut snapshot: Vec = self.mobs.iter().map(|m| seen(m, uuid)).collect(); let mut events = Vec::new(); @@ -519,6 +533,8 @@ impl Game<'_> { _ => Vec::new(), }; let mut guest_events = Vec::new(); + // The mobs whose bodies go this tick: (id, feet, width, height). + let mut gone = Vec::new(); let level_random; { // The level random, lent to the mobs (brain behaviours draw from @@ -591,6 +607,11 @@ impl Game<'_> { let from = events.len(); let kept = m.tick(&w, &mut scratch, &mut events); horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes); + // LivingEntity.tickDeath: after twenty ticks the body is removed. + if !kept && !m.removed && !m.alive() && m.death_time >= 20 { + let (width, height) = (f64::from(m.width()), f64::from(m.height())); + gone.push((m.id, m.position, width, height)); + } if let Some(conn) = seen_guest { // ShulkerBullet.finalTarget is the guest's entity: the // bullet homes on it while the projectiles tick, where @@ -649,6 +670,12 @@ impl Game<'_> { } self.mobs.append(&mut mobs); self.died = died; + // ... and entity event 60 goes out as it is: the poof. + for (id, at, width, height) in gone { + let at = [at.x, at.y, at.z]; + self.lan_entity_event(id as i32, 60, at); + self.death_poof(at, width, height); + } self.sync_riders(); self.tick_skeleton_traps(); self.tick_apparition(); @@ -675,6 +702,22 @@ impl Game<'_> { self.handle_mob_events(queued)?; Ok(()) } + /// `LivingEntity.makePoofParticles` (entity event 60) about a mob's box. + pub(super) fn death_poof(&mut self, at: [f64; 3], width: f64, height: f64) { + let options = horizon_client::particles::ParticleOptions::simple( + horizon_client::particles::ParticleType::Poof, + ); + for _ in 0..20 { + let r = self.particles.level_random(); + let xa = r.next_gaussian() * 0.02; + let ya = r.next_gaussian() * 0.02; + let za = r.next_gaussian() * 0.02; + let x = at[0] + width * (2.0 * r.next_double() - 1.0) - xa * 10.0; + let y = at[1] + height * r.next_double() - ya * 10.0; + let z = at[2] + width * (2.0 * r.next_double() - 1.0) - za * 10.0; + self.particles.add(&options, [x, y, z], [xa, ya, za]); + } + } /// LivingEntity.die / dropAllDeathLoot. fn mob_died(&mut self, m: &Mob) { let killer = self.last_hurt_by_player.remove(&m.id); @@ -775,7 +818,17 @@ impl Game<'_> { .mobs .iter() .find(|o| o.id == id) - .map(|o| drops::loot_entity(o, None)), + .map(|o| drops::loot_entity(o, None)) + // A charged creeper's blast kills after the creeper left the list. + .or_else(|| { + self.combat + .charged_exploders + .contains(&id) + .then(|| LootEntity { + powered: true, + ..LootEntity::new("minecraft:creeper") + }) + }), None => None, }; let direct = match d.kind { @@ -811,12 +864,12 @@ impl Game<'_> { world_seed: self.level.seed, }; let (items, skulls) = drops::die(m, &death, &mut self.rand_sequences); - if skulls - && let Some(Who::Mob(id)) = m.last_damage.and_then(|(d, _)| d.attacker) - && let Some(creeper) = self.mobs.iter_mut().find(|o| o.id == id) - { + if skulls && let Some(Who::Mob(id)) = m.last_damage.and_then(|(d, _)| d.attacker) { // Creeper.droppedSkulls: one head per charged explosion. - creeper.extra.charged = false; + self.combat.charged_exploders.retain(|c| *c != id); + if let Some(creeper) = self.mobs.iter_mut().find(|o| o.id == id) { + creeper.extra.charged = false; + } } let raider = horizon_client::mobs::raider::is_raider(m.species()); for d in items { @@ -834,9 +887,51 @@ impl Game<'_> { } } } + /// `LivingEntity.dropFromGiftLootTable`: the gift table from its random + /// sequence with the mob as `this` (a chicken's egg depends on its + /// variant); the loot data of the game's resources decides, and without it + /// the items' table engine (no entity) rolls it. + fn drop_gift_loot(&mut self, mob: u32, table: &'static str, at: [f64; 3]) { + use horizon_client::mobs::drops; + use horizon_world::loot::EntityLootParams; + let loot = horizon_client::structure_blocks::loot_data(&self.options.resources); + let this = self + .mobs + .iter() + .find(|m| m.id == mob) + .map(|m| drops::loot_entity(m, None)); + let stacks = match (loot, this) { + (Some(loot), Some(this)) if loot.has_table(table) => { + let params = EntityLootParams { + this, + ..EntityLootParams::default() + }; + let seed = self.level.seed; + match loot.random_sequence(table) { + Some(id) => { + let random = self.rand_sequences.get(id, seed); + loot.roll_entity(table, random, ¶ms) + .iter() + .filter(|s| !s.is_empty()) + .map(from_loot) + .collect() + } + None => Vec::new(), + } + } + _ => self + .res + .items() + .loot_table(table, false, None, &mut self.world.random), + }; + for d in stacks { + self.spawn_item(d, at, [0.0, 0.2, 0.0], 10); + } + } pub(super) fn handle_mob_events(&mut self, events: Vec) -> Result<()> { for e in events { match e { + MobEvent::SquidCycle { mob, at } => self.lan_entity_event(mob as i32, 19, at), MobEvent::RabbitHop { mob, at } => self.lan_entity_event(mob as i32, 1, at), MobEvent::Sound(name, at, volume, pitch) | MobEvent::LocalSound(name, at, volume, pitch) => { @@ -898,16 +993,24 @@ impl Game<'_> { owner, } => self.add_fangs(at, yaw, delay, owner), MobEvent::Shoot(..) => {} + MobEvent::ExplosionSource { mob, charged } => { + self.combat.explosion_source = Some(mob); + if charged { + self.combat.charged_exploders.push(mob); + } + } MobEvent::Explode(at, radius) => { // The exploding mob causes the damage (Creeper.explodeCreeper). - let source_mob = self - .mobs - .iter() - .filter(|m| { - (m.position.x - at[0]).powi(2) + (m.position.z - at[2]).powi(2) < 1.0 - }) - .map(|m| m.id) - .next(); + let source_mob = self.combat.explosion_source.or_else(|| { + self.mobs + .iter() + .filter(|m| { + (m.position.x - at[0]).powi(2) + (m.position.z - at[2]).powi(2) + < 1.0 + }) + .map(|m| m.id) + .next() + }); if let Some(id) = source_mob { self.note_attacker("minecraft:explosion", id); } @@ -938,6 +1041,9 @@ impl Game<'_> { volume, pitch, ); + } else { + // Left for the end of the tick. + t.outbox.push(event); } } } @@ -1008,6 +1114,11 @@ impl Game<'_> { self.next_entity += 1; p.id = self.next_entity; let (owner, at) = (p.owner, [p.position.x, p.position.y, p.position.z]); + // LlamaSpit.recreateFromPacket: the spit's burst on the client. + if p.kind == ProjectileKind::LlamaSpit { + let v = p.velocity; + self.particles.llama_spit_burst(at, [v.x, v.y, v.z]); + } self.creatures.projectiles.push(p); self.projectile_event("minecraft:projectile_shoot", owner, at); } @@ -1040,6 +1151,40 @@ impl Game<'_> { self.with_level(|b, level, ticks| b.set_door_open(level, ticks, pos, open)); self.process_level_events()?; } + MobEvent::BreakDoor { pos } => { + // BreakDoorGoal.tick: removeBlock, then level events 1021 + // and 2001 with the state that is there now. + let air = self.world.air; + let at = BlockPos::new(pos[0], pos[1], pos[2]); + self.with_level(|b, level, ticks| b.set_block(level, ticks, at, air, 3)); + self.process_level_events()?; + self.level_event_at(1021, pos, 0); + let left = self.world.block(pos[0], pos[1], pos[2]); + self.level_event_at(2001, pos, left.0 as i32); + } + MobEvent::DestroyProgress { mob, pos, progress } => { + self.destroy_block_progress(mob as i32, pos, progress); + // ServerLevel.destroyBlockProgress: every player nearby sees it. + if let Some(host) = self.lan.as_ref() { + host.hub.broadcast_near( + [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])], + 64.0, + &horizon_protocol::packets::play::Clientbound::BlockDestruction( + horizon_protocol::packets::play::BlockDestruction { + id: mob as i32, + pos, + progress: if (0..10).contains(&progress) { + progress as u8 + } else { + 255 + }, + }, + ), + None, + ); + } + } + MobEvent::LevelEvent { id, pos, data } => self.level_event_at(id, pos, data), MobEvent::SetBlockName { pos, name, effect } => { if effect { let old = self.world.block(pos[0], pos[1], pos[2]); @@ -1062,7 +1207,10 @@ impl Game<'_> { } MobEvent::BreakBlock { pos, drop } => { let old = self.world.block(pos[0], pos[1], pos[2]); - self.destroy_particles(pos, old); + // Block.spawnDestroyParticles: fire breaks leave nothing. + if !self.res.facts().get(old).has_class("BaseFireBlock") { + self.destroy_particles(pos, old); + } if drop { let drops = self.res.items().block_drops_in( self.pack.assets.registry, @@ -1084,6 +1232,9 @@ impl Game<'_> { self.ensure_item_particle_sprites(); } let options = horizon_client::particles::ParticleOptions::simple(ty); + if ty == horizon_client::particles::ParticleType::SonicBoom { + self.lan_sonic_boom(&options, at); + } // Count 0: one particle exactly there, at rest. if count == 0 { self.particles.add(&options, at, [0.0; 3]); @@ -1117,7 +1268,7 @@ impl Game<'_> { self.particles.add(&options, at, velocity); } } - MobEvent::Experience { at, amount } => self.spawn_orbs(at, amount), + MobEvent::Experience { at, amount } => self.spawn_breeding_orb(at, amount), MobEvent::AxolotlSupportPlayer => { let previous = self .potions @@ -1179,6 +1330,10 @@ impl Game<'_> { self.mob_vibration_particle(from, to, ticks) } MobEvent::DigParticles { at } => self.warden_dig_particles(at), + MobEvent::BlockBreakEffect { pos, block } => { + let state = self.world.block(block[0], block[1], block[2]); + self.destroy_particles(pos, state); + } MobEvent::Darkness { at, radius } => self.apply_darkness(at, radius), MobEvent::CreakingHurt { home, @@ -1189,12 +1344,14 @@ impl Game<'_> { self.creaking_tear_down(center, spread) } MobEvent::CureZombieVillager { mob } => self.cure_zombie_villager(mob), + MobEvent::Reinforcements { mob, target } => self.call_reinforcements(mob, target), MobEvent::VillagerMeet { mob, other } => self.villager_meet(mob, other), MobEvent::VillagerBirth { parent, partner, child, } => self.villager_birth(parent, partner, child), + MobEvent::WorkAtComposter { mob, pos } => self.villager_work_at_composter(mob, pos), MobEvent::GolemCheck { mob, needed } => self.villager_golem_check(mob, needed), MobEvent::Firework { at, color, flight } => { self.villager_firework(at, color, flight) @@ -1215,19 +1372,51 @@ impl Game<'_> { m.ai.aggressive |= aggressive; } } - MobEvent::GiftLoot { table, at } => { - let drops = - self.res - .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); + MobEvent::GiftLoot { mob, table, at } => { + // Turtle.ageBoundaryReached: only with mob loot on. + if table == "minecraft:gameplay/turtle_grow" && !self.ui.rules.bool("mob_drops") + { + continue; } + self.drop_gift_loot(mob, table, at); } } } Ok(()) } + /// `TurtleEggBlock.randomTick` at the last hatch stage: one baby turtle + /// per egg, a day from grown, with the egg as its home (the sound, the + /// crumbs and the block's removal came from the level). + pub(super) fn hatch_turtles( + &mut self, + pos: [i32; 3], + state: horizon_world::registry::BlockStateId, + ) { + let eggs = self + .pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("eggs")) + .and_then(|v| v.parse::().ok()) + .unwrap_or(1); + for i in 0..eggs { + let at = [ + f64::from(pos[0]) + 0.3 + f64::from(i) * 0.2, + f64::from(pos[1]), + f64::from(pos[2]) + 0.3, + ]; + if let Some(id) = self.spawn_mob("minecraft:turtle", at, true) + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) + { + m.extra.age = -24000; + m.extra.home = Some(pos); + m.yaw = 0.0; + m.body_yaw = 0.0; + m.head_yaw = 0.0; + } + } + } fn apply_setup(&mut self, id: u32, setup: &SpawnSetup) { let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) else { return; @@ -1261,6 +1450,13 @@ impl Game<'_> { m.extra.egg_time = life; } } + /// `Animal.finalizeSpawnChildFromBreeding`'s experience orb: only when the + /// `mob_drops` game rule is on. + fn spawn_breeding_orb(&mut self, at: [f64; 3], amount: u32) { + if self.ui.rules.bool("mob_drops") { + self.spawn_orbs(at, amount); + } + } /// Animal.spawnChildFromBreeding fn breed( &mut self, @@ -1283,6 +1479,8 @@ impl Game<'_> { .unwrap_or_else(|| parent.clone()); let mut child = parent.clone(); child.baby = true; + // TurtleBreedGoal.breed triggers it without a child. + let turtle = p.species() == Species::Turtle; if matches!( ( p.species(), @@ -1295,7 +1493,7 @@ impl Game<'_> { ) { child.kind = "minecraft:mule".into(); } - self.trigger_bred(&parent, &partner_view, Some(&child)); + self.trigger_bred(&parent, &partner_view, (!turtle).then_some(&child)); } if let Some(q) = self.mobs.iter_mut().find(|m| m.id == partner) { q.extra.age = 6000; @@ -1307,6 +1505,19 @@ impl Game<'_> { self.lay_sniffer_egg(&p); return; } + // TurtleBreedGoal.breed: the goal gave the mother her egg; only the + // experience is left, and only with mob loot on. + if p.species() == Species::Turtle { + // One `new ExperienceOrb` of 1 to 7 from the mother's random (not + // split up as `ExperienceOrb.award` does). + if self.ui.rules.bool("mob_drops") + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == parent) + { + let xp = 1 + m.random.next_int_bound(7).unwrap_or(0) as u32; + self.add_orb([p.position.x, p.position.y, p.position.z], xp); + } + return; + } let coin = self.world.random.next_int_bound(2).unwrap_or(0) == 0; let coin2 = self.world.random.next_int_bound(2).unwrap_or(0) == 0; // A horse and a donkey have a mule. @@ -1354,7 +1565,7 @@ impl Game<'_> { } self.world.random = r; let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32; - self.spawn_orbs([p.position.x, p.position.y, p.position.z], xp); + self.spawn_breeding_orb([p.position.x, p.position.y, p.position.z], xp); return; } if p.species() == Species::Cat { @@ -1375,7 +1586,7 @@ impl Game<'_> { }; } let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32; - self.spawn_orbs([p.position.x, p.position.y, p.position.z], xp); + self.spawn_breeding_orb([p.position.x, p.position.y, p.position.z], xp); return; } if p.species() == Species::Wolf { @@ -1397,7 +1608,7 @@ impl Game<'_> { }; } let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32; - self.spawn_orbs([p.position.x, p.position.y, p.position.z], xp); + self.spawn_breeding_orb([p.position.x, p.position.y, p.position.z], xp); return; } // Nautilus.getBreedOffspring: a tame parent's baby is tame too. @@ -1413,7 +1624,7 @@ impl Game<'_> { } } let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32; - self.spawn_orbs([p.position.x, p.position.y, p.position.z], xp); + self.spawn_breeding_orb([p.position.x, p.position.y, p.position.z], xp); } /// `MobEffectUtil.addEffectToPlayersAround` for an elder guardian: /// mining fatigue III for five minutes unless a stronger or longer one @@ -1470,11 +1681,34 @@ impl Game<'_> { pub(super) fn mob_hits_player_kind(&mut self, amount: f32, from: [f64; 3], kind: &str) { self.mob_hits_player(amount, from, kind); } + /// Damage whose causing mob is known (`cause`, or none): not guessed + /// from the mob nearest to `from`. + pub(super) fn mob_hits_player_caused( + &mut self, + amount: f32, + from: [f64; 3], + kind: &str, + cause: Option, + ) { + self.hurt_player_from(amount, Some(from), kind, Some(cause)); + } pub(super) fn mob_hits_player( &mut self, amount: f32, from: [f64; 3], damage_type: &str, + ) -> bool { + self.hurt_player_from(amount, Some(from), damage_type, None) + } + /// `hurtServer` on the player. `from` is the source's position (none: no + /// direction), `known`: the causing mob when it is given (`/damage`), + /// else the melee attacker is the mob nearest to `from`. + pub(super) fn hurt_player_from( + &mut self, + amount: f32, + from: Option<[f64; 3]>, + damage_type: &str, + known: Option>, ) -> bool { // ServerPlayer.canHarmPlayer refused another player's projectile. if self.creative || self.combat.refuse_player_hit { @@ -1487,37 +1721,44 @@ impl Game<'_> { .damage_tags .get("minecraft:is_projectile") .is_some_and(|t| t.contains(damage_type)); - let blocking = self.player_blocking(Some(from), damage_type, false); + let blocking = self.player_blocking(from, damage_type, false); let raised = blocking.is_some(); // Melee: the attacker stands at `from` (another player's hit has no mob behind it). - let attacker = (!projectile && damage_type != "minecraft:player_attack") - .then(|| { - self.mobs - .iter() - .filter(|m| m.alive()) - .min_by(|a, b| { - let d = |m: &horizon_client::mobs::Mob| { - (m.position.x - from[0]).powi(2) + (m.position.z - from[2]).powi(2) - }; - d(a).total_cmp(&d(b)) - }) - .map(|m| m.id) - }) - .flatten(); + let attacker = match known { + Some(known) => known, + None => from + .filter(|_| !projectile && damage_type != "minecraft:player_attack") + .and_then(|from| { + self.mobs + .iter() + .filter(|m| m.alive()) + .min_by(|a, b| { + let d = |m: &horizon_client::mobs::Mob| { + (m.position.x - from[0]).powi(2) + (m.position.z - from[2]).powi(2) + }; + d(a).total_cmp(&d(b)) + }) + .map(|m| m.id) + }), + }; // The causing entity for the death message. let owner = self.combat.projectile_owner.take(); if let Some(a) = attacker.or(owner) { self.note_attacker(damage_type, a); } + // DamageSource.scalesWithDifficulty: a mob (or its projectile's + // owner) caused the hit, not a player. + let living_cause = attacker.or(owner).is_some(); let mut outcome = horizon_client::health::BlockOutcome::default(); if let Some(player) = self.player.as_mut() && let Some(id) = self.motion.health.damage.id(damage_type) - && let Ok(o) = player.hurt_blocking( + && let Ok(o) = player.hurt_caused_by( &self.motion.health, self.world.health_rules, id, amount, blocking, + living_cause, ) && { outcome = o; @@ -1527,7 +1768,10 @@ impl Game<'_> { // LivingEntity.hurtServer's dealDefaultKnockback: not inside the // hurt cooldown (a stronger hit there only adds its difference). if o.knockback { - let (xd, zd) = (from[0] - player.position.x, from[2] - player.position.z); + // No source position: a random direction. + let (xd, zd) = from.map_or((0.0, 0.0), |from| { + (from[0] - player.position.x, from[2] - player.position.z) + }); self.knock_back_player(f64::from(0.4_f32), xd, zd); if let Some(p) = self.player.as_mut() && let Some(r) = p.hurt_log.last_mut() @@ -1535,8 +1779,10 @@ impl Game<'_> { r.knockback = Some([p.velocity.x, p.velocity.y, p.velocity.z]); } } - self.hurt_armor(amount); - self.thorns(from); + // The thorns hurt the entity that caused the hit, if there is one. + if let Some(a) = attacker.or(owner) { + self.thorns(a); + } } if raised { self.after_block(outcome, amount, attacker, projectile); @@ -1863,6 +2109,33 @@ impl Game<'_> { None => self.projectile_hit(p, hit), } } + /// What an arrow or a thrown trident hits an entity of type `victim` + /// for (`AbstractArrow.onHitEntity`, `ThrownTrident.onHitEntity`): a + /// trident's 8 through `EnchantmentHelper.modifyDamage` of the trident + /// (Impaling's `minecraft:damage` on `#sensitive_to_impaling`). + fn shot_damage(&mut self, shot: &mut Projectile, victim: Option<&str>) -> f32 { + if !matches!(shot.kind, ProjectileKind::Trident) { + return arrow_damage(shot, &mut self.world.random) + shot.bonus.damage; + } + let Some(trident) = shot.arrow.as_ref().map(|a| a.pickup_item.clone()) else { + return 8.0; + }; + let ctx = horizon_client::enchant::EffectContext { + this: victim, + attacker: (shot.owner == Some(Who::Player)).then_some("minecraft:player"), + direct_attacker: Some("minecraft:trident"), + damage_type: Some("minecraft:trident"), + items: Some(self.res.items()), + ..Default::default() + }; + self.res.stations().enchantments.modify_value( + Some(&trident), + "minecraft:damage", + &ctx, + &mut self.world.random, + 8.0, + ) + } /// What an arrow's tick asked for: its particles and sounds. fn arrow_event(&mut self, at: Vec3, event: horizon_client::arrows::ArrowEvent) { use horizon_client::arrows::{ArrowEvent, ArrowParticle, ArrowSound, BlockReaction}; @@ -1891,6 +2164,8 @@ impl Game<'_> { ArrowSound::Splash => "minecraft:entity.generic.splash", ArrowSound::HitGround => "minecraft:entity.arrow.hit", ArrowSound::Extinguish => "minecraft:entity.generic.extinguish_fire", + ArrowSound::TridentHitGround => "minecraft:item.trident.hit_ground", + ArrowSound::TridentHit => "minecraft:item.trident.hit", }; self.audio .play(name, Some([at.x, at.y, at.z]), volume, pitch); @@ -1987,6 +2262,23 @@ impl Game<'_> { self.creatures.projectiles.push(arrow); } } + /// `TargetBlock.onProjectileHit`: a target block takes its power from + /// where the projectile landed and resets after 20 ticks for an arrow, 8 + /// for any other projectile. A player's shot counts as a target hit. + fn target_block_hit(&mut self, p: &Projectile, pos: [i32; 3], at: Vec3, face: [i32; 3]) { + let block = BlockPos::new(pos[0], pos[1], pos[2]); + let arrow = p.arrow.is_some(); + let location = [at.x, at.y, at.z]; + let hit = self.with_level(|b, level, ticks| { + b.target_projectile_hit(level, ticks, block, location, face, arrow) + }); + if hit.is_some() { + let _ = self.process_level_events(); + if p.owner == Some(Who::Player) { + self.stats.custom("target_hit", 1); + } + } + } pub(super) fn projectile_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> { self.combat.projectile_owner = match p.owner { Some(Who::Mob(id)) => Some(id), @@ -1996,6 +2288,13 @@ impl Game<'_> { Hit::Entity { at, .. } | Hit::Block { at, .. } => at, Hit::None => return Ok(()), }; + // Projectile.onHitBlock: BlockState.onProjectileHit, for every + // projectile (a wind charge out of the world's top has no face). + if let Hit::Block { pos, face, .. } = hit + && face != [0; 3] + { + self.target_block_hit(p, pos, at, face); + } if let Hit::Entity { who: Who::Mob(id), at, @@ -2016,11 +2315,11 @@ impl Game<'_> { && id >= super::dragon::SPECIAL { let by_player = p.owner == Some(Who::Player); - if let ProjectileKind::Arrow { .. } = p.kind { + if p.arrow.is_some() { // AbstractArrow.onHitEntity: spent if the part or crystal took // it, else turned back (a perched dragon sets it alight first). let mut arrow = p.clone(); - let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage; + let amount = self.shot_damage(&mut arrow, None); let outcome = match self.hit_special(id, amount, by_player, true) { super::dragon::Hurt::Landed { .. } => EntityHit::Hurt, super::dragon::Hurt::Refused => EntityHit::Refused, @@ -2041,17 +2340,15 @@ impl Game<'_> { self.hit_special(id, amount, by_player, false); return Ok(()); } - if let ( - ProjectileKind::Arrow { .. }, - Hit::Entity { + if p.arrow.is_some() + && let Hit::Entity { who: Who::Mob(id), .. - }, - ) = (&p.kind, hit) + } = hit && let Some(i) = self.carts.iter().position(|c| c.id == id) { // AbstractArrow.onHitEntity on a minecart. let mut arrow = p.clone(); - let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage; + let amount = self.shot_damage(&mut arrow, None); let burning = p.arrow.as_ref().is_some_and(|a| a.on_fire()); let creative = p.owner == Some(Who::Player) && self.creative; self.arrow_hits_cart(i, amount, p.velocity, burning, creative); @@ -2062,7 +2359,7 @@ impl Game<'_> { // Projectile.onHit: the landing is heard. self.projectile_event("minecraft:projectile_land", p.owner, atp); let source_kind = match p.kind { - ProjectileKind::Arrow { .. } => DamageKind::Arrow, + ProjectileKind::Arrow { .. } | ProjectileKind::Trident => DamageKind::Arrow, ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } => { DamageKind::Fireball } @@ -2074,6 +2371,40 @@ impl Game<'_> { from: Some([p.previous.x, p.previous.y, p.previous.z]), }; match (&p.kind, hit) { + // ThrownTrident.onHitEntity: 8 damage (Impaling on aquatic mobs), + // dealt whether or not the hurt lands, then it bounces off. + (ProjectileKind::Trident, Hit::Entity { who, .. }) => { + let mut trident = p.clone(); + let victim = match who { + Who::Mob(id) => self + .mobs + .iter() + .find(|m| m.id == id) + .map(|m| m.kind.id.clone()), + Who::Player => Some("minecraft:player".to_owned()), + }; + let amount = self.shot_damage(&mut trident, victim.as_deref()); + let hurt = match who { + Who::Player => self.mob_hits_player( + amount, + [p.previous.x, p.previous.y, p.previous.z], + "minecraft:trident", + ), + Who::Mob(id) => self + .mobs + .iter_mut() + .find(|m| m.id == id) + .is_some_and(|m| m.damage(amount, source)), + }; + let outcome = if hurt { + EntityHit::Hurt + } else { + EntityHit::Refused + }; + self.finish_arrow_hit(trident, outcome); + } + // AbstractArrow.onHitBlock plays its sound itself (ArrowEvent). + (ProjectileKind::Trident, Hit::Block { .. }) => {} (ProjectileKind::Arrow { effect, .. }, Hit::Entity { who, .. }) => { let mut arrow = p.clone(); let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage; @@ -2295,14 +2626,30 @@ impl Game<'_> { if d2 < 16.0 && !self.creative { let scale = 1.0 - d2.sqrt() / 4.0; let t = (f64::from(*ticks) * scale + 0.5) as i32; - if let Some(owner) = self.combat.projectile_owner { - self.note_attacker("minecraft:indirect_magic", owner); - } match *effect { - "minecraft:instant_damage" => self.hurt_player_by( - "minecraft:indirect_magic", - 6.0 * (1 << *amplifier) as f32 * scale as f32, - ), + "minecraft:instant_damage" => { + // indirectMagic(potion, owner), built where the + // hurt happens: the thrower, or the potion + // itself when it has none. A status effect + // deals no damage, so it records no source. + let owner = self + .combat + .projectile_owner + .filter(|id| self.mob_display_name(*id).is_some()); + match owner { + Some(owner) => { + self.note_attacker("minecraft:indirect_magic", owner) + } + None => self.note_direct_entity( + "minecraft:indirect_magic", + Text::translate("entity.minecraft.splash_potion", &[]), + ), + } + self.hurt_player_by( + "minecraft:indirect_magic", + 6.0 * (1 << *amplifier) as f32 * scale as f32, + ) + } e if t > 20 => self.give_player_effect(e, t, *amplifier), _ => {} } @@ -2358,12 +2705,14 @@ impl Game<'_> { // ShulkerBullet.onHitEntity: 4 damage, then levitation for 10 s. (ProjectileKind::ShulkerBullet { .. }, Hit::Entity { who, .. }) => match who { Who::Player => { - if !self.creative { - self.mob_hits_player( + // Only a hit that hurt (`wasHurt`) brings the levitation. + if !self.creative + && self.mob_hits_player( 4.0, [p.previous.x, p.previous.y, p.previous.z], "minecraft:mob_projectile", - ); + ) + { self.give_player_effect("minecraft:levitation", 200, 0); } } @@ -2372,6 +2721,8 @@ impl Game<'_> { && m.damage(4.0, source) { m.extra.levitation = 200; + // Shulker.hurtServer: a shulker hit by a bullet. + horizon_client::mobs::shulker::hit_by_bullet(m); } } }, @@ -2453,21 +2804,22 @@ impl Game<'_> { .as_ref() .map(|h| h.item.to_string()) .unwrap_or_default(); + // Bucketable.bucketMobPickup: a water bucket scoops up a fish, a + // tadpole or an axolotl, with the data its bucket carries. if item == "minecraft:water_bucket" - && self.mobs[index].species() == Species::Axolotl && self.mobs[index].alive() + && let Some((bucket, sound)) = bucketable(self.mobs[index].species()) { - let mut filled = ItemStack::new("minecraft:axolotl_bucket", 1); + let mut filled = ItemStack::new(bucket, 1); filled.extra = Some(Box::new(horizon_client::entity_nbt::bucket_components( &self.mobs[index], ))); - self.audio.play( - "minecraft:item.bucket.fill_axolotl", - Some(self.mobs[index].center()), - 1.0, - 1.0, - ); + self.audio + .play(sound, Some(self.mobs[index].center()), 1.0, 1.0); self.trigger_item("minecraft:filled_bucket", &filled); + // Leashable.dropLeash, then discard. + let id = self.mobs[index].id; + self.break_leash(id, true, false); self.mobs[index].removed = true; if self.creative { if let Some(rest) = self.give(filled) { @@ -2521,6 +2873,19 @@ impl Game<'_> { } return Ok(true); } + // Creeper.mobInteract: any item in #creeper_igniters, damaged when it + // is damageable and used up otherwise. + let creeper_igniter = self + .res + .items() + .item_tags + .get("minecraft:creeper_igniters") + .is_some_and(|t| t.contains(&*item)); + let damageable = self + .res + .items() + .get(&item) + .is_some_and(|i| i.max_damage > 0); let m = &mut self.mobs[index]; if !m.alive() { return Ok(false); @@ -2536,6 +2901,7 @@ impl Game<'_> { let mut handled = true; let mut drops: Vec<(String, u32)> = Vec::new(); let is_food = m.kind.food.contains(&item); + let baby_turtle = species == Species::Turtle && m.is_baby(); match species { Species::Cow | Species::Mooshroom if item == "minecraft:bucket" && !m.is_baby() => { give = Some("minecraft:milk_bucket"); @@ -2761,10 +3127,21 @@ impl Game<'_> { consume = true; sound = Some("entity.iron_golem.repair"); } - Species::Creeper if item == "minecraft:flint_and_steel" => { + Species::Creeper if creeper_igniter => { m.extra.flag = true; - sound = Some("item.flintandsteel.use"); - self.damage_held_tool(); + // FIRECHARGE_USE for a fire charge, else FLINTANDSTEEL_USE, + // at the creeper's feet with a pitch from its own random. + let event = if item == "minecraft:fire_charge" { + "item.firecharge.use" + } else { + "item.flintandsteel.use" + }; + eat = Some((event, 1.0, m.random.next_float() * 0.4 + 0.8)); + if damageable { + self.damage_held_tool(); + } else { + consume = true; + } } // Parrot.mobInteract: parrot food may tame a wild one (one time in // ten); a parrot never takes it as Animal food (isFood is false). @@ -2814,6 +3191,14 @@ impl Game<'_> { if !handled { return Ok(false); } + // Turtle.ageBoundaryReached: food that finishes a baby's growth. + if baby_turtle && !self.mobs[index].is_baby() { + self.handle_mob_events(vec![MobEvent::GiftLoot { + mob: self.mobs[index].id, + table: "minecraft:gameplay/turtle_grow", + at: feet, + }])?; + } self.swing_arm(); if let Some(s) = sound { let pitch = @@ -3173,6 +3558,30 @@ impl Game<'_> { } continue; } + // ThrownTridentRenderer. + if matches!(a.kind, ProjectileKind::Trident) { + let Some(model) = self.trident_model.as_ref() else { + continue; + }; + let Some(r) = atlas.sprites.get("entity/trident/trident").copied() else { + continue; + }; + let m = glam::Mat4::from_translation(c) + * glam::Mat4::from_rotation_y((a.yaw - 90.0).to_radians()) + * glam::Mat4::from_rotation_z((a.pitch + 90.0).to_radians()); + let poses = horizon_client::mobs::anim::Poses::new(model); + horizon_client::mobs::render::draw( + model, + m, + &poses, + [r.u0, r.v0, r.u1, r.v1], + 0xFFFF_FFFF, + packed, + 0, + out, + ); + continue; + } // WindChargeRenderer. if matches!( a.kind, @@ -3247,6 +3656,26 @@ impl Game<'_> { } } } +/// `Bucketable.getBucketItemStack` and `getPickupSound` of a mob that a water +/// bucket picks up. +fn bucketable(species: Species) -> Option<(&'static str, &'static str)> { + let fish = "minecraft:item.bucket.fill_fish"; + Some(match species { + Species::Cod => ("minecraft:cod_bucket", fish), + Species::Salmon => ("minecraft:salmon_bucket", fish), + Species::Pufferfish => ("minecraft:pufferfish_bucket", fish), + Species::TropicalFish => ("minecraft:tropical_fish_bucket", fish), + Species::Tadpole => ( + "minecraft:tadpole_bucket", + "minecraft:item.bucket.fill_tadpole", + ), + Species::Axolotl => ( + "minecraft:axolotl_bucket", + "minecraft:item.bucket.fill_axolotl", + ), + _ => return None, + }) +} /// Mob.getBaseExperienceReward /// The damage type id of a Horizon damage kind. pub(super) fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static str { @@ -3266,6 +3695,7 @@ pub(super) fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) K::InFire => "minecraft:in_fire", K::Lava => "minecraft:lava", K::Drown => "minecraft:drown", + K::DryOut => "minecraft:dry_out", K::Magic => "minecraft:magic", K::Sting => "minecraft:sting", K::Cactus => "minecraft:cactus", @@ -3291,6 +3721,7 @@ fn to_loot(stack: &ItemStack) -> horizon_world::loot::LootStack { map: false, exploration: None, ominous_amplifier: None, + stew_effects: Vec::new(), } } /// A generated loot stack as a Horizon item stack. diff --git a/crates/horizon-client/src/game/crossbow.rs b/crates/horizon-client/src/game/crossbow.rs index 70ccba8d3..bc49c4b90 100644 --- a/crates/horizon-client/src/game/crossbow.rs +++ b/crates/horizon-client/src/game/crossbow.rs @@ -6,6 +6,7 @@ //! finds the ammo for bows and crossbows. use super::{Game, shield::OFFHAND_SLOT, view_vector}; use horizon_client::{ + enchant::EffectContext, items::ItemStack, mobs::Who, projectiles::{Projectile, ProjectileKind}, @@ -152,6 +153,20 @@ impl Game<'_> { }; let charged = std::mem::take(&mut bow.data_mut().charged); bow.tidy(); + let weapon = bow.clone(); + // AbstractArrow's constructor: `getPiercingCount` of the weapon. + let pierce = self + .res + .stations() + .enchantments + .modify_value( + Some(&weapon), + "minecraft:projectile_piercing", + &EffectContext::default(), + &mut self.world.random, + 0.0, + ) + .clamp(0.0, 127.0) as u8; let count = charged.len(); // getShootingPower: a rocket among them slows every shot. let power = if charged.iter().any(|s| &*s.item == FIREWORK_ROCKET) { @@ -204,6 +219,7 @@ impl Game<'_> { if let Some(a) = arrow.arrow.as_mut() { a.set_item(ammo); a.set_owner(Some(Who::Player)); + a.pierce = pierce; } arrow.shoot(&mut self.world.random, dir.to_array(), power, 1.0); self.creatures.projectiles.push(arrow); diff --git a/crates/horizon-client/src/game/cushions.rs b/crates/horizon-client/src/game/cushions.rs new file mode 100644 index 000000000..0847321d6 --- /dev/null +++ b/crates/horizon-client/src/game/cushions.rs @@ -0,0 +1,494 @@ +//! Cushions: `CushionItem.useOn` placement on the top face of a block, +//! `Cushion.canBePlacedAt`/`survives`, `Cushion.interact` (sit), +//! `BlockAttachedEntity.hurtServer` (break, dropping the matching colour), +//! `BlockAttachedEntity.tick` and `CushionRenderer`. +//! +//! A cushion is a `BlockAttachedEntity`, not a block: it has no block state, +//! only an entity whose `Pos` is the click point's height. Placement uses +//! outline bounds, collision shapes and suffocation predicates. +use super::{Game, Hit, view_vector}; +use horizon_client::entities::{Cushion, dye_index}; +use horizon_client::items::ItemStack; +use horizon_client::mobs::anim::Poses; +use horizon_core::geometry::{Aabb, Vec3}; +use winit::keyboard::KeyCode; + +/// `Direction.fromYRot(yaw).toYRot()`: the nearest 90 degree step. +pub(crate) fn snap_yaw(yaw: f32) -> f32 { + (((f64::from(yaw) / 90.0 + 0.5).floor() as i64) & 3) as f32 * 90.0 +} + +fn aabb(bounds: ([f64; 3], [f64; 3])) -> Aabb { + Aabb::new( + Vec3::new(bounds.0[0], bounds.0[1], bounds.0[2]), + Vec3::new(bounds.1[0], bounds.1[1], bounds.1[2]), + ) +} + +fn overlaps(a: Aabb, b: Aabb) -> bool { + a.intersects(b) +} +use horizon_client::cushion::blocks_in; + +struct PlacementWorld<'a, 'r>(&'a Game<'r>); +impl horizon_client::cushion::World for PlacementWorld<'_, '_> { + fn outline_bounds(&self, p: [i32; 3]) -> Option { + let boxes = self.0.outline_boxes(p); + let mut shape = *boxes.first()?; + for b in &boxes[1..] { + for k in 0..3 { + shape[k] = shape[k].min(b[k]); + shape[k + 3] = shape[k + 3].max(b[k + 3]); + } + } + Some(Aabb::new( + Vec3::new(shape[0], shape[1], shape[2]), + Vec3::new(shape[3], shape[4], shape[5]), + )) + } + + fn collision_shapes(&self, bounds: Aabb) -> Vec { + let binding = self.0.res.collision(); + let mut world = horizon_client::collisions::SceneCollisions { + world: &self.0.world, + binding, + subject: None, + }; + // Include neighbour blocks whose collision shape can reach outside their cell. + blocks_in(bounds.inflate(Vec3::new(1.0, 1.0, 1.0))) + .filter_map(|p| { + let state = self.0.world.block(p[0], p[1], p[2]); + binding + .collision_shape(&mut world, state, p) + .ok() + .map(|s| s.moved(Vec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2])))) + }) + .collect() + } + fn suffocating(&self, p: [i32; 3]) -> bool { + let state = self.0.world.block(p[0], p[1], p[2]); + let facts = self.0.res.facts().get(state); + let name = facts.name.as_ref(); + // Blocks' explicit predicates, then the default causes_suffocation/full-shape rule. + match name { + "minecraft:dirt_path" + | "minecraft:farmland" + | "minecraft:mud" + | "minecraft:soul_sand" => true, + "minecraft:piston" | "minecraft:sticky_piston" => self + .0 + .pack + .assets + .registry + .state(state) + .is_some_and(|s| s.properties.get("extended").is_some_and(|p| p == "false")), + "minecraft:mangrove_roots" | "minecraft:moving_piston" => false, + _ if name.ends_with("_leaves") + || name.ends_with("glass") + || name.ends_with("copper_grate") => + { + false + } + // ShulkerBoxBlock: suffocating while closed; a box seen open + // here is rare enough to count as closed. + _ if name.ends_with("shulker_box") => true, + _ => { + facts.full_collision + && self + .0 + .res + .items() + .block_in_tag("minecraft:causes_suffocation", name) + } + } + } +} + +impl Game<'_> { + /// The cushion under the crosshair, its distance and the hit point. + pub(super) fn cushion_hit(&self) -> Option<(usize, f64, [f64; 3])> { + let eye = self.eye_position()?; + let dir = view_vector(self.yaw, self.pitch); + let reach: f64 = if self.creative { 5.0 } else { 3.0 }; + let mut best: Option<(usize, f64, [f64; 3])> = None; + for (i, c) in self.cushions.iter().enumerate() { + let Some(d) = super::ray_box(eye, dir, reach, aabb(c.bounds())) else { + continue; + }; + if best.is_none_or(|b| d < b.1) { + best = Some((i, d, std::array::from_fn(|k| eye[k] + dir[k] * d))); + } + } + best + } + + pub(super) fn cushion_survives(&self, c: &Cushion) -> bool { + horizon_client::cushion::survives(&PlacementWorld(self), aabb(c.bounds())) + } + + /// `Cushion.destroyIfInFire`: a fire-tagged block inside the deflated box. + fn cushion_in_fire(&self, c: &Cushion) -> bool { + let bounds = aabb(c.bounds()).next_deflated(); + blocks_in(bounds).any(|p| { + let facts = self.res.facts().get(self.world.block(p[0], p[1], p[2])); + self.res.items().block_in_tag("minecraft:fire", &facts.name) + }) + } + + /// `CushionItem.useOn`: on the top face only, spawning at the click's + /// height above the clicked block (or the replaceable block itself). + pub(super) fn place_cushion(&mut self, hit: &Hit, stack: &ItemStack) -> bool { + let Some(info) = self.res.items().get(&stack.item).cloned() else { + return false; + }; + let Some(default_color) = info.cushion_color.as_deref() else { + return false; + }; + let color_override = stack + .data() + .and_then(|d| d.other("minecraft:cushion/color")) + .and_then(|tag| match tag { + horizon_world::nbt::Tag::String(s) => Some(s.to_string_lossy()), + _ => None, + }); + let color = dye_index(color_override.as_deref().unwrap_or(default_color)); + // CushionItem.recalculateContextForSpecialCollisionShapes: open containers + // (cauldrons, hoppers and composters) use the collision ray's actual height. + let mut adjusted = Hit { + pos: hit.pos, + face: hit.face, + point: hit.point, + }; + let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); + if self.res.items().block_in_tag( + "minecraft:cushion_uses_collision_shape", + &self.res.facts().get(state).name, + ) && let Some(eye) = self.eye_position() + { + let start = Vec3::new(eye[0], eye[1], eye[2]); + let point = Vec3::new(hit.point[0], hit.point[1], hit.point[2]); + let end = point.add_vector(point.subtract(start).normalize().scale(0.001)); + let binding = self.res.collision(); + let mut world = horizon_client::collisions::SceneCollisions { + world: &self.world, + binding, + subject: None, + }; + if let Ok(shape) = binding.collision_shape(&mut world, state, hit.pos) + && let Some(result) = shape.clip( + start, + end, + horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]), + ) + { + adjusted.face = result.direction.normal(); + adjusted.point = [result.location.x, result.location.y, result.location.z]; + } + } + let hit = &adjusted; + if hit.face != [0, 1, 0] { + return false; + } + // BlockPlaceContext: a replaceable clicked block is replaced. + let clicked = self + .res + .facts() + .get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2])); + let pos = if clicked.replaceable { + hit.pos + } else { + std::array::from_fn(|i| hit.pos[i] + hit.face[i]) + }; + // `Vec3.atCenterOfWithY(clickedPos, clickLocation.y)`. + let y = hit.point[1]; + let position = Vec3::new(f64::from(pos[0]) + 0.5, y, f64::from(pos[2]) + 0.5); + let bounds = aabb(( + [position.x - 0.5, position.y, position.z - 0.5], + [position.x + 0.5, position.y + 0.25, position.z + 0.5], + )); + if !horizon_client::cushion::can_place(&PlacementWorld(self), bounds) { + return false; + } + // `getEntitiesOfClass(Cushion.class, spawnAABB).isEmpty()`. + if self + .cushions + .iter() + .any(|c| overlaps(aabb(c.bounds()), bounds)) + { + return false; + } + self.next_entity += 1; + let id = self.next_entity; + // `BlockAttachedEntity.setPos`: `BlockPos.containing(position)`. + let attached = [ + position.x.floor() as i32, + position.y.floor() as i32, + position.z.floor() as i32, + ]; + self.cushions.push(Cushion { + id, + position, + pos: attached, + yaw: snap_yaw(self.yaw), + color, + check_interval: 0, + }); + self.world + .modified + .insert((attached[0] >> 4, attached[2] >> 4)); + // `destroyIfInFire`: placed into fire, it breaks at once. + let placed = self.cushions.len() - 1; + if self.cushion_in_fire(&self.cushions[placed]) { + self.break_cushion(placed, false); + } + self.audio.play( + "minecraft:entity.cushion.place", + Some([position.x, position.y, position.z]), + 0.75, + 0.8, + ); + let ctx = self.who_context(Some(horizon_client::mobs::Who::Player), None); + self.post_game_event( + "minecraft:entity_place", + [position.x, position.y, position.z], + ctx, + ); + if !self.creative { + self.consume_held(); + } + true + } + + /// `Cushion.interact`: sit down unless sneaking or already occupied. + pub(super) fn interact_cushion(&mut self) -> bool { + let Some((i, d, _)) = self.cushion_hit() else { + return false; + }; + if !self.before_block(d) { + return false; + } + // isSecondaryUseActive. + if self.keys.contains(&KeyCode::ShiftLeft) { + return false; + } + let id = self.cushions[i].id; + let occupied = self.riding == Some(id) + || self + .lan + .as_ref() + .is_some_and(|h| h.hub.guests.iter().any(|g| g.vehicle == Some(id))); + // `Cushion.interact`: an occupied cushion (`isVehicle`) passes. + if occupied { + return false; + } + // `Player.startRiding` gives up the vehicle it already has; the + // client never sends that click, so pass instead. + if self.riding.is_some() { + return false; + } + self.riding = Some(id); + let p = self.cushions[i].position; + self.audio.play( + "minecraft:entity.cushion.sit", + Some([p.x, p.y, p.z]), + 1.0, + 1.0, + ); + self.swing_arm(); + true + } + + /// `Cushion.hurtServer` from a player: killed, then the item dropped. + pub(super) fn attack_cushion(&mut self) -> bool { + let Some((i, d, _)) = self.cushion_hit() else { + return false; + }; + if !self.before_block(d) || self.mob_hit().is_some_and(|m| m.1 < d) { + return false; + } + // `skipAttackInteraction` when `mayInteract` is false. + if !self.may_build() { + return true; + } + self.break_cushion(i, true); + true + } + + /// `Cushion.dropItem`: the break sound and particles, then the coloured + /// item unless drops are off or the breaker has infinite materials. + pub(super) fn break_cushion(&mut self, index: usize, by_player: bool) { + let c = self.cushions.remove(index); + let p = c.position; + self.world.modified.insert((c.pos[0] >> 4, c.pos[2] >> 4)); + if self.riding == Some(c.id) { + self.riding = None; + } + self.audio.play( + "minecraft:entity.cushion.break", + Some([p.x, p.y, p.z]), + 1.0, + 1.0, + ); + self.cushion_break_particles(&c); + if !self.ui.rules.bool("entity_drops") || (by_player && self.creative) { + return; + } + let stack = ItemStack { + item: std::sync::Arc::from(c.item()), + count: 1, + damage: 0, + extra: None, + }; + self.spawn_item(stack, [p.x, p.y, p.z], [0.0; 3], 10); + } + + /// `Cushion.showBreakingParticles`: ten of the matching wool block. + fn cushion_break_particles(&mut self, c: &Cushion) { + let name = format!("minecraft:{}_wool", c.color_name()); + let Some(state) = self.pack.assets.registry.default_state(&name) else { + return; + }; + let at = [ + c.position.x.floor() as i32, + c.position.y.floor() as i32, + c.position.z.floor() as i32, + ]; + let Some((sprite, tint)) = self.particle_sprite(state, at) else { + return; + }; + let options = horizon_client::particles::ParticleOptions::block( + horizon_client::particles::ParticleType::Block, + sprite, + tint, + ); + let p = c.position; + self.particles.send_particles( + &options, + [p.x, p.y + 0.666_666_7, p.z], + [0.25, 0.0625, 0.25], + 0.05, + 10, + ); + } + + /// `BlockAttachedEntity.tick`: survive and burn checks after the post-increment reaches 100. + pub(super) fn tick_cushions(&mut self) { + let ticking = self.entity_ticking_area(); + let mut i = 0; + while i < self.cushions.len() { + let p = self.cushions[i].position; + if !ticking(p.x.floor() as i32, p.z.floor() as i32) { + i += 1; + continue; + } + let previous = self.cushions[i].check_interval; + self.cushions[i].check_interval += 1; + if previous < 100 { + i += 1; + continue; + } + self.cushions[i].check_interval = 0; + let c = self.cushions[i].clone(); + if self.cushion_in_fire(&c) || !self.cushion_survives(&c) { + self.break_cushion(i, false); + continue; + } + i += 1; + } + } + + /// `Player.rideTick` on a cushion: hold the seat, and get up on sneak. + pub(super) fn tick_cushion_riding(&mut self, keys: super::Keys) -> bool { + let Some(c) = self + .cushions + .iter() + .find(|c| Some(c.id) == self.riding) + .cloned() + else { + return false; + }; + if keys.shift { + let at = c.dismount(); + self.riding = None; + if let Some(p) = self.player.as_mut() { + self.previous_position = p.position; + p.position = at; + p.velocity = Vec3::ZERO; + p.fall_distance = 0.0; + } + // `Cushion.removePassenger`: the get-up sound for a rider that + // left rather than one whose cushion was killed. + self.audio.play( + "minecraft:entity.cushion.get_up", + Some([c.position.x, c.position.y, c.position.z]), + 1.0, + 1.0, + ); + return true; + } + let seat = c.seat(); + if let Some(p) = self.player.as_mut() { + self.previous_position = p.position; + p.position = seat; + p.velocity = Vec3::ZERO; + p.fall_distance = 0.0; + } + true + } + + /// `CushionRenderer`: the coloured model, rotated to the nearest + /// direction, with its bottom on the cushion's position. + pub(super) fn cushion_geometry( + &self, + camera: glam::DVec3, + out: &mut Vec, + ) { + let Some(model) = self.cushion_model.as_ref() else { + return; + }; + let sprites = &self.gui.atlas.sprites; + for c in &self.cushions { + let entity_start = out.len(); + let a = aabb(c.bounds()); + let (lo, hi) = (a.min_position(), a.max_position()); + let (lo, hi) = ( + glam::DVec3::new(lo.x, lo.y, lo.z), + glam::DVec3::new(hi.x, hi.y, hi.z), + ); + 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(uv) = sprites + .get(&format!("entity/cushion/{}_cushion", c.color_name())) + .map(|r| [r.u0, r.v0, r.u1, r.v1]) + else { + continue; + }; + let p = glam::DVec3::new(c.position.x, c.position.y, c.position.z) - camera; + let base = glam::Mat4::from_translation(p.as_vec3()) + * glam::Mat4::from_rotation_y((180.0 - snap_yaw(c.yaw)).to_radians()) + * glam::Mat4::from_rotation_x(std::f32::consts::PI) + * glam::Mat4::from_translation(glam::Vec3::new(0.0, -0.25, 0.0)); + // `EntityRenderer.getPackedLightCoords` probes at the eye height. + let l = self.world.light( + c.position.x.floor() as i32, + (c.position.y + 0.2125).floor() as i32, + c.position.z.floor() as i32, + ); + let packed = (u32::from(l >> 4) * 16) | ((u32::from(l & 15) * 16) << 8); + horizon_client::mobs::render::draw( + model, + base, + &Poses::new(model), + uv, + 0xFFFF_FFFF, + packed, + 0, + out, + ); + self.cull_entity_vertices(out, entity_start); + } + } +} diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index fa5365195..49b653ae1 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -654,6 +654,9 @@ impl Game<'_> { // DedicatedServer.initServer ends with saveEverything(false, true, true). self.save_game()?; self.log_saved_levels(); + if let Some(host) = self.lan.as_mut() { + host.hub.entity_range_percent = props.entity_broadcast_range_percentage; + } let mut state = ServerState { lists, console, diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index 267f323c3..33da8b5ce 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -725,6 +725,11 @@ impl Game<'_> { match self.world.block_entities.get_mut(&p) { Some(BlockEntity::Jukebox(j)) => j.record = stack, Some(BlockEntity::Lectern(l)) => l.book = stack, + Some(BlockEntity::Campfire(c)) => { + if let Some(cell) = c.items.get_mut(slot) { + *cell = stack; + } + } Some(e) => { if let Some(cell) = e.slots_mut().get_mut(slot) { *cell = stack; @@ -1126,14 +1131,18 @@ impl Game<'_> { let (p, v) = (b.position, b.velocity); out.push(line(&kind, [p.x, p.y, p.z], [v.x, v.y, v.z], "")); } + // A merged orb prints once per count, as the oracle does: whether orbs + // merge depends on entity ids, which differ from vanilla's. for o in &self.orbs { let (p, v) = (o.position, o.velocity); - out.push(line( - "minecraft:experience_orb", - [p.x, p.y, p.z], - [v.x, v.y, v.z], - "", - )); + for _ in 0..o.count.max(1) { + out.push(line( + "minecraft:experience_orb", + [p.x, p.y, p.z], + [v.x, v.y, v.z], + "", + )); + } } for c in &self.carts { let (p, v) = (c.position, c.velocity); diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index 61725c6ab..f902f1c05 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -982,7 +982,7 @@ impl Game<'_> { | "minecraft:lingering_potion" => { let mut shot = Projectile::new(ProjectileKind::Snowball, at, None); shot.shoot(&mut own, dir, power, uncertainty); - self.launch_thrown(one, at, shot.velocity); + self.launch_thrown(one, at, shot.velocity, None); } "minecraft:firework_rocket" => { let mut shot = Projectile::new(ProjectileKind::Snowball, at, None); diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index c83018c82..e063b913c 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -12,11 +12,13 @@ use horizon_client::{ hud_layout, hud_overlays, mesher::Vertex, particles::{ParticleOptions, ParticleType}, + text::Text, }; use horizon_core::{ geometry::{Aabb, Vec3}, random::{LegacyRandom, RandomSource}, }; +use horizon_protocol::entity_data::Value; use horizon_world::nbt::Tag; /// Mob ids from here on are dragon parts (`SPECIAL + part`) and crystals @@ -1558,6 +1560,7 @@ impl Game<'_> { y -= 1.0; } self.breath_clouds.push(Breath { + id: 0, at: [x, y.floor() + 1.0, z], radius: 5.0, age: 0, @@ -1684,32 +1687,17 @@ impl Game<'_> { .play("minecraft:entity.ender_dragon.growl", Some(at), 2.5, pitch); } } - // checkCrystals: heal 1 every 10 ticks from the nearest crystal within 32. + // checkCrystals: heal 1 every 10 ticks from the nearest crystal, found + // among those touching the dragon's box grown by 32. let d = self.dragon.as_mut().expect("dragon"); if d.nearest_crystal.is_some() && d.ticks % 10 == 0 && d.health < MAX_HEALTH { - d.health += 1.0; + // LivingEntity.setHealth clamps to the maximum. + d.health = (d.health + 1.0).min(MAX_HEALTH); } if d.random.next_int_bound(10).unwrap_or(1) == 0 { let p = d.position; - d.nearest_crystal = self - .crystals - .iter() - .enumerate() - .filter(|(_, c)| { - (c.position.x - p.x).abs() <= 32.0 - && (c.position.y - p.y).abs() <= 32.0 - && (c.position.z - p.z).abs() <= 32.0 - }) - .min_by(|a, b| { - let da = (a.1.position.x - p.x).powi(2) - + (a.1.position.y - p.y).powi(2) - + (a.1.position.z - p.z).powi(2); - let db = (b.1.position.x - p.x).powi(2) - + (b.1.position.y - p.y).powi(2) - + (b.1.position.z - p.z).powi(2); - da.total_cmp(&db) - }) - .map(|(i, _)| i); + let nearest = self.nearest_crystal_to(p); + self.dragon.as_mut().expect("dragon").nearest_crystal = nearest; } let d = self.dragon.as_mut().expect("dragon"); d.yaw = wrap(d.yaw); @@ -1870,7 +1858,7 @@ impl Game<'_> { pl.velocity.z += zd / dd * 4.0; } if !sitting { - g.hurt_player_by("minecraft:mob_attack", 5.0); + g.dragon_hurts_player("minecraft:mob_attack", 5.0); } }); } @@ -1879,7 +1867,7 @@ impl Game<'_> { for h in heads { if h.inflate(Vec3::new(1.0, 1.0, 1.0)).intersects(p.bounds) { self.as_fight_player(p.who, |g| { - g.hurt_player_by("minecraft:mob_attack", 10.0); + g.dragon_hurts_player("minecraft:mob_attack", 10.0); }); } } @@ -2037,6 +2025,7 @@ impl Game<'_> { // assignDirectionalMovement: the direction times the acceleration power 0.1. let velocity = Vec3::new(v.x * 0.1, v.y * 0.1, v.z * 0.1); self.dragon_fireballs.push(DragonFireball { + id: 0, position: at, previous: at, velocity, @@ -2083,6 +2072,7 @@ impl Game<'_> { }); if hit_block || hit_player || b.age > 600 { self.breath_clouds.push(Breath { + id: 0, at: [next.x, next.y, next.z], radius: 3.0, age: 0, @@ -2166,10 +2156,23 @@ impl Game<'_> { self.breath_clouds.append(&mut clouds); for (who, amount) in harmed { self.as_fight_player(who, |g| { - g.hurt_player_by("minecraft:indirect_magic", amount); + g.dragon_hurts_player("minecraft:indirect_magic", amount); }); } } + /// Damage from the dragon, which is its causing entity + /// (`DamageSources.mobAttack(dragon)`, `indirectMagic(cloud, dragon)`): the + /// death message names it, or the cloud once the dragon is gone. + fn dragon_hurts_player(&mut self, damage_type: &str, amount: f32) { + if let Some(id) = self.dragon.as_ref().map(|d| d.id) { + let name = Text::translate("entity.minecraft.ender_dragon", &[]); + self.note_named_attacker(damage_type, id, name); + } else if damage_type == "minecraft:indirect_magic" { + let name = Text::translate("entity.minecraft.area_effect_cloud", &[]); + self.note_direct_entity(damage_type, name); + } + self.hurt_player_by(damage_type, amount); + } /// `BossHealthOverlay.extractRenderState`: whatever `publish_boss_bars` /// (or a server's packets) put on this client's overlay. pub(super) fn draw_boss_bars(&self, batch: &mut HudBatch) { @@ -2207,15 +2210,58 @@ impl Game<'_> { } } pub(super) struct DragonFireball { - position: Vec3, - previous: Vec3, - velocity: Vec3, + /// Its entity id once a server's players track it (0 until then). + pub(super) id: u32, + pub(super) position: Vec3, + pub(super) previous: Vec3, + pub(super) velocity: Vec3, age: i32, } +impl DragonFireball { + /// One a server sent (`handleAddEntity`). + pub(super) fn remote(id: u32, at: Vec3, velocity: Vec3) -> Self { + Self { + id, + position: at, + previous: at, + velocity, + age: 0, + } + } + /// `AbstractHurtingProjectile.tick` on a server's client: `applyInertia` + /// first (power 0.1, inertia 0.95 or 0.8 in water), then the move; only + /// the server decides what it hits. + pub(super) fn remote_step(&mut self, water: bool) { + self.previous = self.position; + self.age += 1; + let v = self.velocity; + // Vec3.normalize: a vector shorter than 1e-5 stays zero. + let l = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt(); + let n = if l < 1.0e-5 { + Vec3::new(0.0, 0.0, 0.0) + } else { + Vec3::new(v.x / l, v.y / l, v.z / l) + }; + let inertia = f64::from(if water { 0.8f32 } else { 0.95f32 }); + let v = Vec3::new( + (v.x + n.x * 0.1) * inertia, + (v.y + n.y * 0.1) * inertia, + (v.z + n.z * 0.1) * inertia, + ); + self.velocity = v; + self.position = Vec3::new( + self.position.x + v.x, + self.position.y + v.y, + self.position.z + v.z, + ); + } +} pub(super) struct Breath { - at: [f64; 3], - radius: f32, - age: i32, + /// Its entity id once a server's players track it (0 until then). + pub(super) id: u32, + pub(super) at: [f64; 3], + pub(super) radius: f32, + pub(super) age: i32, duration: i32, from_dragon: bool, } @@ -2560,7 +2606,9 @@ impl Game<'_> { } pub(super) fn fight_ready(&mut self) -> bool { self.load_fight(); - self.fight.loaded + // spawnExitPortal runs from scanState and the dragon's death, both + // only with players in the fight. + self.fight.loaded && self.fight.players } pub(super) fn exit_portal(&self) -> Option<[i32; 3]> { self.fight.exit_portal @@ -3137,6 +3185,212 @@ impl Game<'_> { let _ = self.activate_exit_portal(); self.fight.dirty = true; } + /// `EnderDragon.checkCrystals`' search: the nearest crystal whose box + /// meets the dragon's box grown by 32. + fn nearest_crystal_to(&self, p: Vec3) -> Option { + // The dragon's 16 by 8 box. + let reach = Aabb::new( + Vec3::new(p.x - 8.0, p.y, p.z - 8.0), + Vec3::new(p.x + 8.0, p.y + 8.0, p.z + 8.0), + ) + .inflate(Vec3::new(32.0, 32.0, 32.0)); + self.crystals + .iter() + .enumerate() + .filter(|(_, c)| { + // An end crystal's 2 by 2 box. + reach.intersects(Aabb::new( + Vec3::new(c.position.x - 1.0, c.position.y, c.position.z - 1.0), + Vec3::new(c.position.x + 1.0, c.position.y + 2.0, c.position.z + 1.0), + )) + }) + .min_by(|a, b| { + let da = (a.1.position.x - p.x).powi(2) + + (a.1.position.y - p.y).powi(2) + + (a.1.position.z - p.z).powi(2); + let db = (b.1.position.x - p.x).powi(2) + + (b.1.position.y - p.y).powi(2) + + (b.1.position.z - p.z).powi(2); + da.total_cmp(&db) + }) + .map(|(i, _)| i) + } +} + +/// The dragon on a server's client (`ClientPacketListener.handleAddEntity` +/// and the client side of `EnderDragon.aiStep`): the server flies it and +/// sends its moves, health and phase; the client flaps its wings, keeps +/// its flight history and places its parts, so it can be drawn and hit. +impl Game<'_> { + /// `handleAddEntity` for `minecraft:ender_dragon`. Its constructor + /// sets the full health and the hovering phase until the server's + /// synched data says otherwise. + pub(super) fn spawn_remote_dragon(&mut self, id: i32, position: [f64; 3], yaw: f32) { + let at = Vec3::new(position[0], position[1], position[2]); + let mut d = Dragon::new(at, yaw, i64::from(id)); + d.id = id as u32; + d.phase = Phase::from_id(10); + self.dragon = Some(d); + self.place_dragon_parts(); + if let Some(d) = self.dragon.as_mut() { + for part in &mut d.parts { + part.1 = part.0; + } + } + } + /// The remote dragon, if `id` is it. + fn remote_dragon_mut(&mut self, id: i32) -> Option<&mut Dragon> { + self.dragon.as_mut().filter(|d| d.id as i32 == id) + } + /// `handleSetEntityData`: LivingEntity.DATA_HEALTH_ID and + /// EnderDragon.DATA_PHASE (`onSyncedDataUpdated` sets the phase). + pub(super) fn remote_dragon_data(&mut self, id: i32, values: &[(u8, i32, Value)]) { + let Some(d) = self.remote_dragon_mut(id) else { + return; + }; + for (index, _, value) in values { + match (index, value) { + (9, Value::Float(health)) => d.health = *health, + (16, Value::Int(phase)) => d.set_phase(Phase::from_id(*phase)), + _ => {} + } + } + } + /// `handleSetEntityMotion`: the velocity its wings flap by. + pub(super) fn remote_dragon_motion(&mut self, id: i32, velocity: [f64; 3]) { + if let Some(d) = self.remote_dragon_mut(id) { + d.velocity = Vec3::new(velocity[0], velocity[1], velocity[2]); + } + } + /// `handleHurtAnimation` and `handleDamageEvent`: the red flash. + pub(super) fn remote_dragon_hurt(&mut self, id: i32) { + if let Some(d) = self.remote_dragon_mut(id) { + d.hurt_time = 10; + } + } + /// `handleRemoveEntities`, or a crystal removed: the healing beam + /// keeps pointing at the same crystal. + pub(super) fn remove_remote_dragon(&mut self, id: i32) { + if self.remote_dragon_mut(id).is_some() { + self.dragon = None; + return; + } + let Some(index) = self.crystals.iter().position(|c| c.id as i32 == id) else { + return; + }; + if let Some(d) = self.dragon.as_mut() { + match d.nearest_crystal { + Some(n) if n == index => d.nearest_crystal = None, + Some(n) if n > index => d.nearest_crystal = Some(n - 1), + _ => {} + } + } + } + /// One client tick of the dragon. `lerp`: the step toward its last + /// sent position and yaw (LivingEntity's interpolation), and the + /// steps left including this one. + pub(super) fn tick_remote_dragon(&mut self, lerp: Option<([f64; 3], Option, u32)>) { + let Some(d) = self.dragon.as_mut() else { + return; + }; + d.previous = d.position; + d.previous_yaw = d.yaw; + d.old_flap = d.flap; + d.ticks += 1; + d.hurt_time = (d.hurt_time - 1).max(0); + for part in &mut d.parts { + part.1 = part.0; + } + if let Some((target, yaw, steps)) = lerp { + let n = f64::from(steps.max(1)); + d.position = Vec3::new( + d.position.x + (target[0] - d.position.x) / n, + d.position.y + (target[1] - d.position.y) / n, + d.position.z + (target[2] - d.position.z) / n, + ); + if let Some(yaw) = yaw { + d.yaw += wrap(yaw - d.yaw) / steps.max(1) as f32; + } + } + if !d.alive() { + // EnderDragon.tickDeath on a client: it rises, and bursts + // from tick 180 to 200; the server removes it. + d.death_time += 1; + let (t, p) = (d.death_time, d.position); + if (180..=200).contains(&t) { + let r = &mut d.random; + let o = [ + f64::from((r.next_float() - 0.5) * 8.0), + f64::from((r.next_float() - 0.5) * 4.0), + f64::from((r.next_float() - 0.5) * 8.0), + ]; + self.particles.add( + &ParticleOptions::simple(ParticleType::ExplosionEmitter), + [p.x + o[0], p.y + 2.0 + o[1], p.z + o[2]], + [0.0; 3], + ); + } + if let Some(d) = self.dragon.as_mut() { + d.position.y += 0.1; + for part in &mut d.parts { + part.0.y += 0.1; + } + } + return; + } + // processFlappingMovement and onFlap: its wing beats, and their sound. + let flap_was = (d.old_flap * std::f32::consts::TAU).cos(); + let v = d.velocity; + let mut flap_speed = 0.2 / ((v.x.hypot(v.z) as f32) * 10.0 + 1.0); + flap_speed *= 2f32.powf(v.y as f32); + d.flap += if d.phase.sitting() { 0.1 } else { flap_speed }; + let flap_now = (d.flap * std::f32::consts::TAU).cos(); + let at = [d.position.x, d.position.y, d.position.z]; + if flap_was <= -0.3 && flap_now >= -0.3 { + let pitch = 0.8 + self.world.random.next_float() * 0.3; + self.audio + .play("minecraft:entity.ender_dragon.flap", Some(at), 5.0, pitch); + } + let d = self.dragon.as_mut().expect("dragon"); + if !d.phase.sitting() { + d.growl -= 1; + if d.growl < 0 { + d.growl = 200 + d.random.next_int_bound(200).unwrap_or(0); + let pitch = 0.8 + self.world.random.next_float() * 0.3; + self.audio + .play("minecraft:entity.ender_dragon.growl", Some(at), 2.5, pitch); + } + } + // checkCrystals' search runs on a client too (the healing beam). + let d = self.dragon.as_mut().expect("dragon"); + if d.random.next_int_bound(10).unwrap_or(1) == 0 { + let p = d.position; + let nearest = self.nearest_crystal_to(p); + self.dragon.as_mut().expect("dragon").nearest_crystal = nearest; + } + let d = self.dragon.as_mut().expect("dragon"); + d.yaw = wrap(d.yaw); + d.record(); + self.place_dragon_parts(); + } + /// The dragon's parts as a server's client attacks them: the server's + /// ids for `EnderDragonPart`s follow the dragon's. + pub(super) fn remote_dragon_part_hit( + &self, + eye: [f64; 3], + dir: [f64; 3], + reach: f64, + ) -> Option<(i32, f64, [f64; 3])> { + let d = self.dragon.as_ref().filter(|d| d.alive() && d.id != 0)?; + (0..8) + .filter_map(|i| { + let b = d.part_box(i); + let p = d.parts[i].0; + super::ray_box(eye, dir, reach, b) + .map(|t| ((d.id + 1 + i as u32) as i32, t, [p.x, p.y, p.z])) + }) + .min_by(|a, b| a.1.total_cmp(&b.1)) + } } #[cfg(test)] diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index aa9f75e06..b24a62520 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -3,10 +3,14 @@ //! unbreaking (`minecraft:item_damage`), sharpness/smite/bane and power //! (`minecraft:damage`), knockback, fire aspect, infinity (`minecraft:ammo_use`), //! thorns (`minecraft:post_attack`), mending (`minecraft:repair_with_xp`) and -//! the armor attribute effects (respiration, depth strider, ...). +//! the armor attribute effects (respiration, depth strider, ...) and Soul +//! Speed's `location_changed` and `tick` effects. use super::Game; -use horizon_client::{enchant::EffectContext, items::ItemStack}; -use horizon_core::random::RandomSource; +use horizon_client::{ + enchant::{EffectContext, Enchantments, level_value}, + items::ItemStack, +}; +use horizon_core::{position::BlockPos, random::RandomSource}; /// Where Mending found a damaged item (`EnchantedItemInUse.inSlot`). #[derive(Clone, Copy)] @@ -255,23 +259,26 @@ impl Game<'_> { let _ = self.wind_burst(feet, radius, knockback, false, false); } } - /// Thorns on worn armor when a mob at `from` hits the player. - pub(super) fn thorns(&mut self, from: [f64; 3]) { - let attacker = self - .mobs - .iter() - .enumerate() - .filter(|(_, m)| m.alive()) - .min_by(|a, b| { - let d = |m: &horizon_client::mobs::Mob| { - (m.position.x - from[0]).powi(2) - + (m.position.y - from[1]).powi(2) - + (m.position.z - from[2]).powi(2) - }; - d(a.1).total_cmp(&d(b.1)) - }) - .map(|(i, _)| i); - let Some(attacker) = attacker else { return }; + /// Thorns on worn armor when the mob `attacker` hits the player: the + /// `affected: attacker` effect of `Enchantment.doPostAttack` hurts the + /// entity that caused the hit. + pub(super) fn thorns(&mut self, attacker: u32) { + let Some(index) = self.mobs.iter().position(|m| m.id == attacker && m.alive()) else { + return; + }; + for damage in self.thorns_damage() { + let m = &mut self.mobs[index]; + m.hurt(damage, None, &mut self.world.random); + let center = [m.position.x, m.position.y, m.position.z]; + self.audio + .play("minecraft:enchant.thorns.hit", Some(center), 1.0, 1.0); + } + } + /// The victim's side of thorns: for each worn piece whose chance comes up, + /// the damage to deal the attacker (`DamageEntity` min 1, max 5) and the + /// piece's wear (`ChangeItemDamage` 2). + pub(super) fn thorns_damage(&mut self) -> Vec { + let mut hits = Vec::new(); for slot in 0..4 { let Some(stack) = self.armor[slot].clone() else { continue; @@ -299,15 +306,7 @@ impl Game<'_> { if !ok { continue; } - // DamageEntity(min 1, max 5) and ChangeItemDamage(2). - let damage = 1.0 + self.world.random.next_float() * 4.0; - let center = { - let m = &mut self.mobs[attacker]; - m.hurt(damage, None, &mut self.world.random); - [m.position.x, m.position.y, m.position.z] - }; - self.audio - .play("minecraft:enchant.thorns.hit", Some(center), 1.0, 1.0); + hits.push(1.0 + self.world.random.next_float() * 4.0); if let Some(s) = self.armor[slot].as_mut() { s.damage += 2; if self @@ -320,6 +319,7 @@ impl Game<'_> { } } } + hits } /// `ExperienceOrb.repairPlayerItems`: returns the experience left over. pub(super) fn mending(&mut self, amount: u32) -> u32 { @@ -388,7 +388,9 @@ impl Game<'_> { } } /// Bow enchantments at release: (extra base damage, infinity keeps the arrow). - pub(super) fn bow_enchantments(&mut self) -> (f64, bool) { + /// `ammo` is the item being fired: `Enchantment.itemContext` hands it to the + /// `ammo_use` conditions as the tool, so Infinity only frees plain arrows. + pub(super) fn bow_enchantments(&mut self, ammo: &str) -> (f64, bool) { let Some(bow) = self.inventory[self.selected].clone() else { return (0.0, false); }; @@ -407,7 +409,7 @@ impl Game<'_> { 0.0, ); let ammo_ctx = EffectContext { - tool: Some("minecraft:arrow"), + tool: Some(ammo), items: Some(self.res.items()), ..Default::default() }; @@ -460,6 +462,134 @@ impl Game<'_> { } ignite } + /// Soul Speed (`data/minecraft/enchantment/soul_speed.json`), the parts of + /// `Enchantment.runLocationChangedEffects` and `tick` that file uses. The + /// `location_changed` effects run when the player enters a new block, lands, + /// or its boots change: + /// - the speed and movement efficiency modifiers turn on over a soul speed + /// block (not flying, not riding) and stay on while airborne, then off + /// (`enchantment_active_check`); + /// - the boots lose 1 durability with a 4% chance when on such a block. + /// + /// Every fifth tick the player walking on one also gets a soul particle + /// (returned as its position and velocity, for the caller to show or send + /// to the players around) and sometimes a sound. Runs for the window's own + /// player and for each guest on the server (`guest_server_tick`); a remote + /// client leaves it to its server. + pub(super) fn tick_soul_speed(&mut self) -> Option<([f64; 3], [f64; 3])> { + const ID: &str = "minecraft:soul_speed"; + let player = self.player.as_mut()?; + if player.client_side { + return None; + } + let level = self.armor[3] + .as_ref() + .map_or(0, |s| s.enchantment_level(ID)); + let position = player.position; + let (on_ground, flying) = (player.ground.on_ground, player.flying); + let moved = position.subtract(player.old_position); + let (tick, width) = (player.health.tick_count, player.dimensions.width); + let fx = &mut player.location_effects; + let on_soul = fx.on_soul_speed_block; + let block = BlockPos::containing(position); + let changed_block = fx.block.replace(block) != Some(block); + let landed = std::mem::take(&mut fx.landed); + // Changed boots: `stopLocationBasedEffects`, then the effects run again. + let equipped = std::mem::replace(&mut fx.boots_level, level) != level; + let was_active = fx.applied_level; + let mut active = was_active > 0 && !equipped; + let mut wear = false; + if level > 0 && (changed_block || landed || equipped) { + let riding = self.riding.is_some(); + let wanted = !riding && !flying && (on_soul || (active && !on_ground)); + active = wanted; + // `random_chance` is the first term of the wear's `all_of`: it + // draws from the level random before the block is looked at. + let roll = self.world.random.next_float() < 0.04; + wear = roll && on_ground && on_soul; + } + fx.applied_level = if active { level } else { 0 }; + // `Entity.getKnownMovement` horizontal speed of at least 1.0E-5. + let walking = moved.x * moved.x + moved.z * moved.z >= 1.0e-10; + let tick_effects = level > 0 && !flying && on_ground && walking && on_soul && tick % 5 == 0; + // The attribute effects were applied to the player before: swap them. + if was_active > 0 && (!active || equipped) { + for (attribute, id, _, op) in + soul_speed_modifiers(&self.res.stations().enchantments, was_active) + { + let _ = player.set_modifier(&attribute, &id, 0.0, &op, false); + } + } + if active && (was_active == 0 || equipped) { + for (attribute, id, amount, op) in + soul_speed_modifiers(&self.res.stations().enchantments, level) + { + let _ = player.set_modifier(&attribute, &id, amount, &op, true); + } + } + if wear && !self.creative { + self.wear_boots(1); + } + if level == 0 { + return None; + } + let r = &mut self.world.random; + // `spawn_particles`: in the bounding box, 0.1 above the feet, thrown + // back against the movement (-0.2) and up (0.1). + let particle = tick_effects.then(|| { + let x = position.x + (r.next_double() - 0.5) * f64::from(width); + let z = position.z + (r.next_double() - 0.5) * f64::from(width); + ( + [x, position.y + 0.1, z], + [moved.x * -0.2, 0.1, moved.z * -0.2], + ) + }); + // `play_sound`: its `random_chance` (35%) comes first in its `all_of`, + // so the level random is drawn every tick the boots are worn; volume + // 0.6, pitch 0.6 to 1.0. + if r.next_float() < 0.35 && tick_effects { + let pitch = r.next_float() * 0.4 + 0.6; + self.audio.play( + "minecraft:particle.soul_escape", + Some([position.x, position.y, position.z]), + 0.6, + pitch, + ); + } + particle + } + /// `ItemStack.hurtAndBreak` on the worn boots (`change_item_damage`): + /// Unbreaking applies, and they break when worn out. + fn wear_boots(&mut self, amount: u32) { + let Some(stack) = self.armor[3].clone() else { + return; + }; + let loss = self.durability_loss(&stack, amount); + let max = self + .res + .items() + .get(&stack.item) + .map_or(0, |info| info.max_damage); + if max == 0 { + return; + } + let Some(boots) = self.armor[3].as_mut() else { + return; + }; + boots.damage += loss; + if boots.damage >= max { + self.armor[3] = None; + if let Some(eye) = self.eye_position() { + self.audio.play( + "minecraft:entity.item.break", + Some(eye), + 0.8, + 0.8 + self.world.random.next_float() * 0.4, + ); + } + self.apply_equipment(); + } + } /// Enchantment attribute modifiers of worn armor (respiration, depth strider...). /// Each piece's modifier id ends with its slot (`EnchantmentAttributeEffect.idForSlot`), /// so the same enchantment on two pieces stacks instead of replacing itself. @@ -483,3 +613,28 @@ impl Game<'_> { self.potions.enchant_modifiers = wanted; } } + +/// Soul Speed's `attribute` effects at `level` (attribute, id, amount, operation), +/// the id taking the boots slot like `EnchantmentAttributeEffect.idForSlot`. +fn soul_speed_modifiers( + enchantments: &Enchantments, + level: u32, +) -> Vec<(String, String, f64, String)> { + let Some(e) = enchantments.get("minecraft:soul_speed") else { + return Vec::new(); + }; + e.effects["minecraft:location_changed"][0]["effect"]["effects"] + .as_array() + .into_iter() + .flatten() + .filter(|a| a["type"] == "minecraft:attribute") + .map(|a| { + ( + a["attribute"].as_str().unwrap_or("").to_owned(), + format!("{}/feet", a["id"].as_str().unwrap_or("")), + f64::from(level_value(&a["amount"], level)), + a["operation"].as_str().unwrap_or("add_value").to_owned(), + ) + }) + .collect() +} diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index 904c035c5..32d5113b0 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -129,15 +129,32 @@ impl EndState { survive: false, }); } - /// One tick of a server's client: `step` moves each toward where the - /// server put it. - pub(super) fn step_remote_eyes(&mut self, mut step: impl FnMut(u32, [f64; 3]) -> [f64; 3]) { + /// `EyeOfEnder.tick` on a server's client: it moves by its last known + /// motion; only the server steers it. + pub(super) fn step_remote_eyes(&mut self) { for e in &mut self.eyes { e.previous = e.position; e.life += 1; - e.position = glam::DVec3::from_array(step(e.id, e.position.to_array())); + e.position += e.velocity; } } + /// A server's move: an eye has no interpolation handler, so + /// `moveOrInterpolateTo` puts it there at once. False when `id` isn't one. + pub(super) fn move_remote_eye(&mut self, id: u32, at: [f64; 3]) -> bool { + let Some(e) = self.eyes.iter_mut().find(|e| e.id == id) else { + return false; + }; + e.position = glam::DVec3::from_array(at); + true + } + /// `handleSetEntityMotion` for an eye. False when `id` isn't one. + pub(super) fn remote_eye_motion(&mut self, id: u32, velocity: [f64; 3]) -> bool { + let Some(e) = self.eyes.iter_mut().find(|e| e.id == id) else { + return false; + }; + e.velocity = glam::DVec3::from_array(velocity); + true + } pub(super) fn remove_remote_eye(&mut self, id: u32) { self.eyes.retain(|e| e.id != id); } @@ -1099,6 +1116,7 @@ impl Game<'_> { /// EyeOfEnder.tick: fly, then drop (4 in 5) or shatter after 80 ticks. fn tick_eyes(&mut self) { let mut eyes = std::mem::take(&mut self.end.eyes); + let mut shattered = Vec::new(); eyes.retain_mut(|eye| { eye.previous = eye.position; let next = eye.position + eye.velocity; @@ -1122,10 +1140,44 @@ impl Game<'_> { extra: None, }; self.spawn_item(stack, at, [vx, 0.2, vz], 0); + } else { + shattered.push(at.map(|v| v.floor() as i32)); } false }); self.end.eyes = eyes; + for pos in shattered { + self.level_event_at(2003, pos, 0); + } + } + + /// `LevelEventHandler` 2003: a shattered eye's item crumbs and two rings + /// of portal particles drawn in towards it. + pub(super) fn eye_break_particles(&mut self, pos: [i32; 3]) { + let (x, y, z) = ( + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + ); + let crumbs = self.item_particle(&ItemStack::new("minecraft:ender_eye", 1)); + for _ in 0..8 { + let r = self.particles.random(); + let v = [ + r.next_gaussian() * 0.15, + r.next_double() * 0.2, + r.next_gaussian() * 0.15, + ]; + self.particles.add(&crumbs, [x, y, z], v); + } + let portal = ParticleOptions::simple(ParticleType::Portal); + let mut angle = 0.0f64; + while angle < std::f64::consts::PI * 2.0 { + let (c, s) = (angle.cos(), angle.sin()); + let at = [x + c * 5.0, y - 0.4, z + s * 5.0]; + self.particles.add(&portal, at, [c * -5.0, 0.0, s * -5.0]); + self.particles.add(&portal, at, [c * -7.0, 0.0, s * -7.0]); + angle += std::f64::consts::PI / 20.0; + } } /// `EyeOfEnder.tick` on a client: behind each eye (a quarter of its last diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 6ecba3a54..b2191aa9f 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -296,12 +296,14 @@ impl Game<'_> { if !creative && !spectator && hurtable - && let Ok(o) = p.hurt_blocking( + && let Ok(o) = p.hurt_caused_by( &self.motion.health, self.world.health_rules, id, amount, blocking, + // The exploding mob is the causing entity. + exploding.is_some(), ) { outcome = o; @@ -314,9 +316,6 @@ impl Game<'_> { ); } } - if outcome.hurt && !creative { - self.hurt_armor(amount); - } if raised { self.after_block(outcome, amount, None, false); } @@ -391,9 +390,11 @@ impl Game<'_> { [feet[0] - w, feet[1], feet[2] - w], [feet[0] + w, feet[1] + h, feet[2] + w], ); + // The exploding mob is the damage source's entity, so victims + // it kills drop its charged-creeper loot (`Creeper.killedEntity`). let source = horizon_client::mobs::Damage { kind: horizon_client::mobs::DamageKind::Explosion, - attacker: None, + attacker: exploding.map(horizon_client::mobs::Who::Mob), from: Some(center), }; if hurtable && !m.damage(damage(dist, exposure), source) { @@ -571,16 +572,16 @@ impl Game<'_> { let pitch = (1.0 + (client_float() - client_float()) * 0.2) * 0.7; self.audio .play("minecraft:entity.generic.explode", Some(center), 4.0, pitch); - let block_count = if interaction == BlockInteraction::Keep { - 0 - } else { - targets.len() - }; + // ServerLevel.explode sends toBlow.size() whatever the interaction, and + // `ServerExplosion.isSmall` also covers an explosion that keeps blocks. + let block_count = targets.len(); + let small = radius < 2.0 || interaction == BlockInteraction::Keep; 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])) - }); - self.lan_explode(center, radius, block_count); + self.particles + .explosion(center, small, block_count, radius, &|b| { + facts.is_air(world.block(b[0], b[1], b[2])) + }); + self.lan_explode(center, small, radius, block_count); Ok(()) } /// `BlockBehaviour.onExplosionHit` (TNT: `wasExploded` primes a short fuse). @@ -597,6 +598,11 @@ impl Game<'_> { } let name = self.res.facts().get(state).name.clone(); let is_tnt = &*name == "minecraft:tnt"; + // CreakingHeartBlock.onExplosionHit: its creaking dies (no + // experience, as Horizon does not track a TNT's owner). + if &*name == "minecraft:creaking_heart" { + self.creaking_heart_broken(pos, false); + } // Block.onExplosionHit: the drops copy from the block entity, which // then spills its contents as the block turns to air. let key = (pos[0], pos[1], pos[2]); @@ -620,6 +626,7 @@ impl Game<'_> { &mut self.world.random, Some((&mut self.rand_sequences, self.level.seed)), decay, + false, ); for mut stack in drops { if &*stack.item == "minecraft:air" || stack.count == 0 { diff --git a/crates/horizon-client/src/game/falling_damage.rs b/crates/horizon-client/src/game/falling_damage.rs index 8eec28d1d..41c714561 100644 --- a/crates/horizon-client/src/game/falling_damage.rs +++ b/crates/horizon-client/src/game/falling_damage.rs @@ -64,6 +64,25 @@ impl Game<'_> { pos: BlockPos::new(pos[0], pos[1], pos[2]), data: 0, }); + } else if self + .res + .facts() + .get(block.state) + .name + .starts_with("minecraft:suspicious_") + { + // BrushableBlock.onBrokenAfterFall. + let at = BlockPos::new(pos[0], pos[1], pos[2]); + self.level_events.push(LevelEvent::LevelEvent { + id: 2001, + pos: at, + data: block.state.0 as i32, + }); + self.level_events.push(LevelEvent::GameEvent { + pos: at, + event: "minecraft:block_destroy", + state: None, + }); } return; } @@ -108,16 +127,10 @@ impl Game<'_> { } else { amount }; - let hurt = if let Some(p) = self.player.as_mut() + if let Some(p) = self.player.as_mut() && let Some(id) = self.motion.health.damage.id(kind) { - p.hurt(&self.motion.health, self.world.health_rules, id, amount) - .unwrap_or(false) - } else { - false - }; - if hurt { - self.hurt_armor(amount); + let _ = p.hurt(&self.motion.health, self.world.health_rules, id, amount); } } } diff --git a/crates/horizon-client/src/game/fangs.rs b/crates/horizon-client/src/game/fangs.rs index cdf2d17a5..6c20ccf93 100644 --- a/crates/horizon-client/src/game/fangs.rs +++ b/crates/horizon-client/src/game/fangs.rs @@ -7,12 +7,13 @@ use std::sync::Arc; #[derive(Clone, Debug)] pub(super) struct Fangs { - pos: [f64; 3], - yaw: f32, + pub id: u32, + pub pos: [f64; 3], + pub yaw: f32, warmup: i32, - life: i32, + pub life: i32, owner: u32, - started: bool, + pub started: bool, } #[derive(Default)] pub(super) struct FangState { @@ -21,6 +22,11 @@ pub(super) struct FangState { } impl Game<'_> { pub(super) fn add_fangs(&mut self, at: [f64; 3], yaw: f32, delay: i32, owner: u32) { + self.next_entity += 1; + self.insert_fangs(self.next_entity, at, yaw, delay, owner); + } + + pub(super) fn insert_fangs(&mut self, id: u32, at: [f64; 3], yaw: f32, delay: i32, owner: u32) { if self.fangs.model.is_none() { self.fangs.model = horizon_client::mobs::load_model( &self.options.resources, @@ -29,6 +35,7 @@ impl Game<'_> { .map(Arc::new); } self.fangs.list.push(Fangs { + id, pos: at, yaw, warmup: delay, @@ -37,6 +44,30 @@ impl Game<'_> { started: false, }); } + /// `EvokerFangs.handleEntityEvent`: only event 4 starts a client attack. + pub(super) fn remote_fangs_event(&mut self, id: u32, event: i8) { + if event == 4 + && let Some(f) = self.fangs.list.iter_mut().find(|f| f.id == id) + { + f.started = true; + self.audio.play_unshared( + "minecraft:entity.evoker_fangs.attack", + Some(f.pos), + 1.0, + 1.0, + ); + } + } + + /// `EvokerFangs.tick`: clients only advance animation, never damage or discard. + pub(super) fn tick_remote_fangs(&mut self) { + for f in &mut self.fangs.list { + if f.started { + f.life -= 1; + } + } + } + /// `EvokerFangs.tick`. pub(super) fn tick_fangs(&mut self) { let mut list = std::mem::take(&mut self.fangs.list); @@ -50,7 +81,8 @@ impl Game<'_> { } if !f.started { f.started = true; - self.audio.play( + self.lan_entity_event(f.id as i32, 4, f.pos); + self.audio.play_unshared( "minecraft:entity.evoker_fangs.attack", Some(f.pos), 1.0, @@ -71,26 +103,49 @@ impl Game<'_> { let b = horizon_core::geometry::Aabb::new(lo, hi); // Every player in the box, the server's players too. let pos = f.pos; + // `EvokerFangs.dealDamageTo`: indirectMagic(fangs, owner) while the + // owner lives, plain magic (nobody to name) once it is gone. + let owner = self + .mobs + .iter() + .any(|m| m.id == f.owner && m.alive()) + .then_some(f.owner); let bite = move |g: &mut Self| { if let Some(p) = g.player_view() && p.alive && p.bounds.intersects(b) { - g.mob_hits_player_kind(6.0, pos, "minecraft:indirect_magic"); + let kind = match owner { + Some(_) => "minecraft:indirect_magic", + None => "minecraft:magic", + }; + g.mob_hits_player_caused(6.0, pos, kind, owner); } }; bite(self); self.each_guest_hit(bite); + // `AbstractIllager.considersEntityAsAlly`: with no teams, the illager + // tag is allied; `Evoker.considersEntityAsAlly` adds a vex whose + // owner is allied (itself or another illager). Teams are not modelled. + let illager = |s: Species| { + matches!( + s, + Species::Evoker | Species::Illusioner | Species::Pillager | Species::Vindicator + ) + }; + let illagers: Vec = self + .mobs + .iter() + .filter(|m| illager(m.species())) + .map(|m| m.id) + .collect(); + // A missing owner hurts everyone (`currentOwner == null`). + let owner_known = illagers.contains(&f.owner); for m in &mut self.mobs { - let ally = matches!( - m.species(), - Species::Evoker - | Species::Illusioner - | Species::Vex - | Species::Pillager - | Species::Vindicator - | Species::Witch - ); + let ally = owner_known + && (illager(m.species()) + || m.species() == Species::Vex + && illagers.contains(&(m.extra.counter2 as u32))); if m.id != f.owner && !ally && m.alive() && m.bounds().intersects(b) { m.damage( 6.0, diff --git a/crates/horizon-client/src/game/fireworks.rs b/crates/horizon-client/src/game/fireworks.rs index e6b4eb136..38fd74ed8 100644 --- a/crates/horizon-client/src/game/fireworks.rs +++ b/crates/horizon-client/src/game/fireworks.rs @@ -17,6 +17,8 @@ use horizon_core::{ random::RandomSource, }; +pub(super) const FIREWORK_EXPLODE_EVENT: i8 = 17; + pub(super) struct Rocket { /// The entity id a server tracks it by (0 until it is tracked). pub id: u32, @@ -261,6 +263,14 @@ impl Game<'_> { /// `FireworkRocketEntity.explode` and `dealExplosionDamage`. fn explode_rocket(&mut self, r: &Rocket) { let at = [r.position.x, r.position.y, r.position.z]; + // FireworkRocketEntity.explode broadcasts before discard. Send now: + // tick_lan removes missing tracked entities before flushing effects. + if r.id != 0 + && let Some(host) = &self.lan + { + host.hub + .entity_event(r.id as i32, FIREWORK_EXPLODE_EVENT, at); + } if !r.explosions.is_empty() { let damage = 5.0 + r.explosions.len() as f32 * 2.0; let from = r.position; @@ -322,6 +332,16 @@ impl Game<'_> { self.particles .fireworks(at, v, r.explosions.clone(), camera); } + /// FireworkRocketEntity.handleEntityEvent: use the synchronized item data. + pub(super) fn remote_firework_explosion(&mut self, id: i32) { + let camera = self.eye_position(); + if let Some(r) = self.rockets.iter().find(|r| r.id == id as u32) { + let at = [r.position.x, r.position.y, r.position.z]; + let v = [r.velocity.x, r.velocity.y, r.velocity.z]; + self.particles + .fireworks(at, v, r.explosions.clone(), camera.unwrap_or(at)); + } + } /// `dealExplosionDamage` on a player that is not the rocket's /// `attachedToEntity`: within 5 blocks, when the rocket sees its feet or /// its middle (`ClipContext.Block.COLLIDER`, no fluids). @@ -352,17 +372,11 @@ impl Game<'_> { if self.creative || self.spectator() { return; } - let hurt = if let Some(p) = self.player.as_mut() + if let Some(p) = self.player.as_mut() && !p.health.dead_or_dying() && let Some(id) = self.motion.health.damage.id("minecraft:fireworks") { - p.hurt(&self.motion.health, self.world.health_rules, id, amount) - .unwrap_or(false) - } else { - false - }; - if hurt { - self.hurt_armor(amount); + let _ = p.hurt(&self.motion.health, self.world.health_rules, id, amount); } } /// `FireworkEntityRenderer.submit`: the item (GROUND) facing the camera, diff --git a/crates/horizon-client/src/game/fishing.rs b/crates/horizon-client/src/game/fishing.rs index d454df406..39f9e5ffe 100644 --- a/crates/horizon-client/src/game/fishing.rs +++ b/crates/horizon-client/src/game/fishing.rs @@ -154,37 +154,54 @@ impl Game<'_> { let mut damage = 0; if let State::Hooked(id) = hook.state { // pullEntity: 0.1 of the way to the owner. + let d = Vec3::new( + owner.x - hook.position.x, + owner.y - hook.position.y, + owner.z - hook.position.z, + ); + let pulled = |v: Vec3| Vec3::new(v.x + d.x * 0.1, v.y + d.y * 0.1, v.z + d.z * 0.1); + let mut hooked_item = false; if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { - let d = Vec3::new( - owner.x - hook.position.x, - owner.y - hook.position.y, - owner.z - hook.position.z, - ); - m.velocity = Vec3::new( - m.velocity.x + d.x * 0.1, - m.velocity.y + d.y * 0.1, - m.velocity.z + d.z * 0.1, - ); + m.velocity = pulled(m.velocity); + } else if let Some(item) = self.dropped.iter_mut().find(|i| i.id == id) { + item.velocity = pulled(item.velocity); + hooked_item = true; } - damage = 5; + // `hookedIn instanceof ItemEntity ? 3 : 5`. + damage = if hooked_item { 3 } else { 5 }; } else if hook.nibble > 0 { let biome = self.biome_name_at(hook.position); let Some(loot) = horizon_client::structure_blocks::loot_data(&self.options.resources) else { return damage; }; + // `withLuck(this.luck + owner.getLuck())`: the rod's Luck of the Sea + // plus the owner's luck attribute (the Luck and Bad Luck effects). + let owner_luck = self + .player + .as_mut() + .and_then(|p| p.attribute("minecraft:luck").ok()) + .unwrap_or(0.0) as f32; let mut random = self.world.random.clone(); let items = loot.roll( "minecraft:gameplay/fishing", &mut random, - hook.luck as f32, + hook.luck as f32 + owner_luck, biome.as_deref(), Some(hook.open_water), ); self.world.random = random; - // FishingHook.retrieve: fish_caught for a catch. - self.stats.custom("fish_caught", 1); for stack in items { + // FishingHook.retrieve: fish_caught for each catch in #minecraft:fishes. + if self + .res + .items() + .item_tags + .get("minecraft:fishes") + .is_some_and(|t| t.contains(stack.item.as_str())) + { + self.stats.custom("fish_caught", 1); + } let mut item = ItemStack { item: Arc::from(stack.item.as_str()), count: stack.count.max(1) as u32, @@ -231,7 +248,7 @@ impl Game<'_> { } damage } - fn biome_name_at(&self, p: Vec3) -> Option { + pub(super) 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( @@ -457,35 +474,47 @@ impl Game<'_> { self.hook = Some(h); return; } - // checkCollision: hook the first living mob it touches. + // checkCollision: hook the first living mob it touches, or (via + // `canHitEntity`) a dropped item. let bb = bounds(h.position); let (lo, hi) = (bb.min_position(), bb.max_position()); - if let Some(m) = self.mobs.iter().find(|m| { - let mb = m.bounds(); - let (a, z) = (mb.min_position(), mb.max_position()); - m.alive() - && a.x < hi.x - && lo.x < z.x - && a.y < hi.y - && lo.y < z.y - && a.z < hi.z - && lo.z < z.z - }) { - h.state = State::Hooked(m.id); + let touches = |b: Aabb| { + let (a, z) = (b.min_position(), b.max_position()); + a.x < hi.x && lo.x < z.x && a.y < hi.y && lo.y < z.y && a.z < hi.z && lo.z < z.z + }; + let hit = self + .mobs + .iter() + .find(|m| m.alive() && touches(m.bounds())) + .map(|m| m.id) + .or_else(|| { + self.dropped + .iter() + .find(|i| touches(i.bounds())) + .map(|i| i.id) + }); + if let Some(id) = hit { + h.state = State::Hooked(id); h.velocity = Vec3::ZERO; self.hook = Some(h); return; } } State::Hooked(id) => { - match self.mobs.iter().find(|m| m.id == id && m.alive()) { - Some(m) => { - h.position = Vec3::new( - m.position.x, - m.position.y + f64::from(m.height()) * 0.8, - m.position.z, - ) - } + // updateHookedEntity: ride the hooked mob or item at 0.8 of its height. + let hooked = self + .mobs + .iter() + .find(|m| m.id == id && m.alive()) + .map(|m| (m.position, f64::from(m.height()))) + .or_else(|| { + self.dropped + .iter() + .find(|i| i.id == id) + .map(|i| (i.position, horizon_client::entities::ItemEntity::WIDTH)) + }); + match hooked { + Some((at, height)) => h.position = Vec3::new(at.x, at.y + height * 0.8, at.z), None => h.state = State::Flying, } self.hook = Some(h); diff --git a/crates/horizon-client/src/game/frames.rs b/crates/horizon-client/src/game/frames.rs index 7f5e6c26a..d08c5f283 100644 --- a/crates/horizon-client/src/game/frames.rs +++ b/crates/horizon-client/src/game/frames.rs @@ -355,12 +355,23 @@ impl Game<'_> { * glam::DMat4::from_rotation_y(y_rot.to_radians()); let light = self.world.light(f.pos[0], f.pos[1], f.pos[2]); let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); + // ItemFrameRenderer.getBlockLightLevel: a glow frame's model is at least 5 bright. + let frame_light = if f.glow { + (light & 0xF0) | (light & 15).max(5) + } else { + light + }; + let frame_packed = + (u32::from(frame_light >> 4) * 16) | ((u32::from(frame_light & 15) * 16) << 8); let mut quad = |m: &glam::DMat4, corners: [[f64; 3]; 4], uv: [[f32; 2]; 4], light: u32| { - for (c, uv) in corners.iter().zip(uv) { - let p = m.transform_point3(glam::DVec3::from_array(*c)); + // The frame model is drawn with the entity shader, lit by its face normal. + let at = corners.map(|c| m.transform_point3(glam::DVec3::from_array(c))); + let n = (at[1] - at[0]).cross(at[2] - at[0]).normalize_or_zero(); + let normal = [0, 1, 2].map(|k| (n[k].clamp(-1.0, 1.0) * 127.0) as i8); + for (p, uv) in at.into_iter().zip(uv) { out.push(Vertex { - normal: [0; 4], + normal: [normal[0], normal[1], normal[2], -127], pos: p.as_vec3().to_array(), uv, layer: 0, @@ -393,7 +404,7 @@ impl Game<'_> { ] }), map_uv(r, *uv), - packed, + frame_packed, ); } } diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index a7218ff3c..d91d3b979 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -151,6 +151,7 @@ impl Game<'_> { before(self.painting_hit().map(|h| h.1)) || before(self.frame_hit().map(|h| h.1)) || before(self.armor_stand_hit().map(|h| h.1)) + || before(self.cushion_hit().map(|h| h.1)) || before(self.boat_hit().map(|h| h.1)) || before(self.cart_hit().map(|h| h.1)) || before(self.dragon_hit().map(|h| h.1)) diff --git a/crates/horizon-client/src/game/initial_spawn.rs b/crates/horizon-client/src/game/initial_spawn.rs index 3f7a071bb..c1149b26a 100644 --- a/crates/horizon-client/src/game/initial_spawn.rs +++ b/crates/horizon-client/src/game/initial_spawn.rs @@ -20,7 +20,8 @@ use horizon_core::{ }; use horizon_world::{ block_collision::BlockCollisionRegistry, collision_context::CollisionContext, - heightmap::HeightmapType, worldgen::terrain::TerrainBlockStates, + heightmap::HeightmapType, level::flags::UPDATE_CLIENTS, registry::BlockStateId, + worldgen::terrain::TerrainBlockStates, }; /// The loaded world as the spawn searches query it. @@ -121,33 +122,102 @@ impl Game<'_> { } Ok(Some([ox * 16 + 8, height, oz * 16 + 8])) } + /// MinecraftServer.setInitialSpawn's bonus chest: BonusChestFeature.place + /// in the spawn chunk, a chest with the spawn bonus loot and a torch on + /// each side that can hold one, on the first free column of a shuffled + /// walk over the chunk. Skipped while the chunk is not loaded. + pub(super) fn place_bonus_chest(&mut self, origin: [i32; 3]) -> Result<()> { + use horizon_client::containers::BlockEntity; + let (cx, cz) = (origin[0] >> 4, origin[2] >> 4); + let registry = &self.pack.assets.registry; + let (Some(chest), Some(torch)) = ( + registry.default_state("minecraft:chest"), + registry.default_state("minecraft:torch"), + ) else { + return Ok(()); + }; + if !self.streaming.is_lit(cx, cz) { + return Ok(()); + } + // `level.getRandom()`. Util.toShuffledList of the chunk's x and z. + let random = &mut self.world.random; + let mut shuffled = |min: i32| -> [i32; 16] { + let mut values: [i32; 16] = std::array::from_fn(|i| min + i as i32); + for end in (2..=16usize).rev() { + let other = random.next_int_bound(end as i32).unwrap_or(0) as usize; + values.swap(end - 1, other); + } + values + }; + let (xs, zs) = (shuffled(cx * 16), shuffled(cz * 16)); + for x in xs { + for z in zs { + let y = self + .spawn_columns() + .height(HeightmapType::MotionBlockingNoLeaves, x, z); + if self.world.block(x, y, z) != self.world.air && !self.collision_empty([x, y, z]) { + continue; + } + self.set_block_clients([x, y, z], chest)?; + let seed = self.world.random.next_long(); + self.world + .block_entities + .insert((x, y, z), BlockEntity::Chest(Vec::new())); + self.load_block_entity_nbt( + [x, y, z], + &format!( + "{{LootTable:\"minecraft:chests/spawn_bonus_chest\",LootTableSeed:{seed}L}}" + ), + ); + for [dx, dz] in [[0, -1], [1, 0], [0, 1], [-1, 0]] { + let at = [x + dx, y, z + dz]; + let survives = self.with_level(|b, level, ticks| { + b.can_survive(level, ticks, BlockPos::new(at[0], at[1], at[2]), torch) + }); + if survives { + self.set_block_clients(at, torch)?; + } + } + return Ok(()); + } + } + Ok(()) + } + /// `Level.setBlock(pos, state, UPDATE_CLIENTS)`: no neighbour updates. + fn set_block_clients(&mut self, pos: [i32; 3], state: BlockStateId) -> Result<()> { + self.with_level(|b, level, ticks| { + b.set_block( + level, + ticks, + BlockPos::new(pos[0], pos[1], pos[2]), + state, + UPDATE_CLIENTS, + ); + }); + self.process_level_events() + } + /// The block at `pos` has no collision shape. + fn collision_empty(&self, pos: [i32; 3]) -> bool { + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }; + self.collision + .collision_shape_with_context( + &mut scene, + self.world.block(pos[0], pos[1], pos[2]), + BlockPos::new(pos[0], pos[1], pos[2]), + &CollisionContext::empty(false), + ) + .is_ok_and(|shape| shape.is_empty()) + } /// PlayerSpawnFinder.findSpawn around the world spawn: the feet of a /// player who has no position yet. None while a candidate's chunk loads. pub(super) fn find_player_spawn(&mut self, suggestion: [i32; 3]) -> Result> { let mut finder = match self.player_spawn { Some(finder) => finder, - None if self.level.game_mode == 2 => { - // Adventure mode: the suggestion itself. - let mut finder = PlayerSpawnFinder::new(suggestion, 0, |_| 0); - finder.next_candidate(); - finder - } - None => { - let mut radius = self.ui.rules.int("respawn_radius").max(0); - let to_border = self - .border - .distance(f64::from(suggestion[0]), f64::from(suggestion[2])) - .floor() as i32; - if to_border < radius { - radius = to_border; - } - if to_border <= 1 { - radius = 1; - } - PlayerSpawnFinder::new(suggestion, radius, |n| { - entity_random().next_int_bound(n).unwrap_or(0) - }) - } + None => self.spawn_finder(suggestion), }; let found = loop { let Some(candidate) = finder.next_candidate() else { @@ -176,6 +246,58 @@ impl Game<'_> { self.player_spawn = found.is_none().then_some(finder); Ok(found) } + /// A new PlayerSpawnFinder around `suggestion`: the respawn radius, cut + /// by the world border; the suggestion itself in adventure mode. + fn spawn_finder(&self, suggestion: [i32; 3]) -> PlayerSpawnFinder { + if self.level.game_mode == 2 { + let mut finder = PlayerSpawnFinder::new(suggestion, 0, |_| 0); + finder.next_candidate(); + return finder; + } + let mut radius = self.ui.rules.int("respawn_radius").max(0); + let to_border = self + .border + .distance(f64::from(suggestion[0]), f64::from(suggestion[2])) + .floor() as i32; + if to_border < radius { + radius = to_border; + } + if to_border <= 1 { + radius = 1; + } + PlayerSpawnFinder::new(suggestion, radius, |n| { + entity_random().next_int_bound(n).unwrap_or(0) + }) + } + /// ServerPlayer.adjustSpawnLocation for a server's new player: where + /// PlayerSpawnFinder.findSpawn puts their feet around the world spawn + /// (`spawn`, the feet there), so that players new to a world don't all + /// stand in one spot. Vanilla waits for each candidate's chunk; a server + /// tick can't, so a candidate in a chunk not loaded yet is passed over, + /// and `spawn` stays when the search never reaches a loaded column. + pub(super) fn server_player_spawn(&self, spawn: [f64; 3]) -> [f64; 3] { + let suggestion = spawn.map(|v| v.floor() as i32); + let mut finder = self.spawn_finder(suggestion); + while let Some(candidate) = finder.next_candidate() { + let (x, z) = match candidate { + SpawnCandidate::Column(x, z) => (x, z), + SpawnCandidate::Suggestion => (suggestion[0], suggestion[2]), + }; + if !self.streaming.is_lit(x >> 4, z >> 4) { + continue; + } + let feet = match candidate { + SpawnCandidate::Column(x, z) => level_respawn_pos(&self.spawn_columns(), x, z) + .filter(|&pos| self.player_fits(pos)) + .map(bottom_center), + SpawnCandidate::Suggestion => Some(self.fixup_spawn_height(suggestion)), + }; + if let Some(feet) = feet { + return [feet.x, feet.y, feet.z]; + } + } + spawn + } /// PlayerSpawnFinder.noCollisionNoLiquid: a player's box standing at the /// block's bottom centre touches no block or liquid. fn player_fits(&self, pos: [i32; 3]) -> bool { diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index 14a18caa6..7d81c971d 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -52,6 +52,8 @@ struct Flags { /// server follows while it runs (IntegratedServer.tickServer). render_distance: AtomicI32, simulation_distance: AtomicI32, + /// `MinecraftServer.isCurrentlySaving`: the server is autosaving. + saving: AtomicBool, } /// Work the window hands its server thread (`MinecraftServer.execute`). @@ -69,6 +71,10 @@ impl Integrated { pub fn smoothed_tick_ms(&self) -> f32 { f32::from_bits(self.flags.smoothed_tick_ms.load(Ordering::Relaxed)) } + /// `MinecraftServer.isCurrentlySaving`. + pub fn is_saving(&self) -> bool { + self.flags.saving.load(Ordering::Relaxed) + } /// `IntegratedServer.tickServer` skips the world while the game is paused. pub fn set_paused(&self, paused: bool) { self.flags.paused.store(paused, Ordering::Relaxed); @@ -148,6 +154,12 @@ pub(super) struct Serving { /// is out of its place: applied after the tick. pending: Option, } +impl Serving { + /// The window reads this as `MinecraftServer.isCurrentlySaving`. + pub(super) fn set_saving(&self, saving: bool) { + self.flags.saving.store(saving, Ordering::Relaxed); + } +} enum Publish { Open(TcpListener, LanSettings), Close, @@ -222,7 +234,6 @@ impl Game<'_> { options.report = None; 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()); @@ -292,6 +303,9 @@ impl Game<'_> { launch.create.as_ref(), )?)?; let saved = Box::new(self.level.clone()); + // IntegratedServer runs the server mods; the window the client mods. + self.mods.dev = self.options.dev_mods.clone(); + self.start_mods(); // 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); diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index 1d79f077d..b6b7e2fb7 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -196,13 +196,31 @@ impl Game<'_> { skins: &self.skin_downloads, } } - /// The client level as item models read it. + /// The client level as item models read it: worked out once a frame (a + /// screen of items read the same level, its sky sampled once). pub(super) fn item_level(&self) -> LevelState { let dimension = match self.dim { Dim::Overworld => "minecraft:overworld", Dim::Nether => "minecraft:the_nether", Dim::End => "minecraft:the_end", }; + let key = ( + self.frames, + self.world.game_time, + self.world.day_time, + dimension, + ); + let mut cached = self.item_level_cache.borrow_mut(); + if let Some((at, level)) = cached.as_ref() + && *at == key + { + return level.clone(); + } + let level = self.level_state_now(dimension); + *cached = Some((key, level.clone())); + level + } + fn level_state_now(&self, dimension: &'static str) -> LevelState { let sky = self .dim_environment() .sample(self.world.day_time, None, None); diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 50fa222e6..28ec3fe8a 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -11,10 +11,10 @@ use horizon_client::{ chunks::ChunkEncoder, data::SyncData, entity::{EntityState, States}, - hub::{HostEvent, HostState, Hub, HubConfig, TickCtx}, + hub::{BodyFlags, HostEvent, HostState, Hub, HubConfig, TickCtx}, playerdata, }, - mobs::{Mob, leash::Holder}, + mobs::{Mob, Who, leash::Holder}, text::Text, }; use horizon_core::geometry::Vec3; @@ -24,11 +24,24 @@ use horizon_protocol::{ }; use std::{ collections::HashMap, - sync::{Arc, OnceLock}, + sync::{Arc, Mutex}, }; /// The registries and tags are the same for every world: load them once. -static SYNC: OnceLock, String>> = OnceLock::new(); +static SYNC: Mutex, String>>> = Mutex::new(None); + +/// The registries and tags a server sends, loaded from `root` the first time. +pub(super) fn sync_data(root: &std::path::Path) -> std::result::Result, String> { + let mut sync = SYNC.lock().unwrap_or_else(|e| e.into_inner()); + sync.get_or_insert_with(|| SyncData::load(root).map(Arc::new)) + .clone() +} + +/// Let go of what `sync_data` loaded: for a preload no world used +/// (game/world_loading.rs). +pub(super) fn forget_sync_data() { + *SYNC.lock().unwrap_or_else(|e| e.into_inner()) = None; +} /// The settings of the open world (WorldOptionsScreen's multiplayer section). #[derive(Clone, Copy, Debug)] @@ -71,6 +84,8 @@ pub(super) struct LanHost { /// 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, + /// Mods' quiet commands waiting to run a few a tick (game/lan_quiet.rs). + pub quiet: std::collections::VecDeque, /// The entities the guests track, described again every tick /// (`lan_entities`) over last tick's states. states: lan::entity::States, @@ -145,6 +160,7 @@ pub(super) fn baby_index(kind: &str) -> Option { fn mob_meta( m: &Mob, hub: &Hub, + player_entity: Option, meta: &mut Vec<(u8, i32, Value)>, defaults: &mut Vec<(u8, i32, Value)>, ) { @@ -175,6 +191,17 @@ fn mob_meta( meta.push((9, serializer::FLOAT, Value::Float(health))); } defaults.push((9, serializer::FLOAT, Value::Float(1.0))); + // LivingEntity.DATA_EFFECT_PARTICLES and DATA_EFFECT_AMBIENCE_ID: the + // swirls of its effects (the ones a mob has are visible, not ambient). + meta.extend( + hub.effect_meta( + (m.extra.effects.iter()) + .filter(|e| !m.extra.hidden_effects.contains(&e.0)) + .map(|e| (e.0, false)), + ), + ); + defaults.push((10, serializer::PARTICLES, Value::Particles(Vec::new()))); + defaults.push((11, serializer::BOOLEAN, Value::Bool(false))); // Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2, aggressive 4 (what // draws a vindicator's axe, a skeleton's drawn bow, a piglin's raised // weapon). @@ -194,6 +221,53 @@ fn mob_meta( let e = &m.extra; let id = |registry: &str, name: &str| hub.registry_id(registry, &format!("minecraft:{name}")); match kind { + "minecraft:guardian" | "minecraft:elder_guardian" => { + // Guardian.DATA_ID_MOVING and DATA_ID_ATTACK_TARGET. + if e.flag2 { + meta.push((16, serializer::BOOLEAN, Value::Bool(true))); + } + let target = if e.flag { + m.ai.target.and_then(|who| match who { + Who::Player => player_entity, + Who::Mob(id) => Some(id as i32), + }) + } else { + None + }; + if let Some(target) = target { + meta.push((17, serializer::INT, Value::Int(target))); + } + defaults.push((16, serializer::BOOLEAN, Value::Bool(false))); + defaults.push((17, serializer::INT, Value::Int(0))); + } + // Bat.DATA_ID_FLAGS: resting in bit 0, flying by default. + "minecraft:bat" => { + if e.flag { + meta.push((16, serializer::BYTE, Value::Byte(1))); + } + defaults.push((16, serializer::BYTE, Value::Byte(0))); + } + // SnowGolem.DATA_PUMPKIN_ID: 16 while the pumpkin is on (the default). + "minecraft:snow_golem" => { + if e.sheared { + meta.push((16, serializer::BYTE, Value::Byte(0))); + } + defaults.push((16, serializer::BYTE, Value::Byte(16))); + } + // MushroomCow.DATA_TYPE: 0 red, 1 brown. + "minecraft:mooshroom" => { + if e.variant == 1 { + meta.push((17, serializer::INT, Value::Int(1))); + } + defaults.push((17, serializer::INT, Value::Int(0))); + } + // Piglin.DATA_IS_DANCING (after the baby flag and the crossbow charge). + "minecraft:piglin" => { + if e.scratch[0] > 0 { + meta.push((19, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((19, serializer::BOOLEAN, Value::Bool(false))); + } // Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 when sheared. "minecraft:sheep" => { let value = (e.color & 15) | if e.sheared { 16 } else { 0 }; @@ -308,6 +382,14 @@ fn mob_meta( } defaults.push((17, serializer::BOOLEAN, Value::Bool(false))); } + // PolarBear.DATA_STANDING_ID (after AgeableMob's two): the bear + // rears up; the client animates it. + "minecraft:polar_bear" => { + if e.flag { + meta.push((18, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((18, serializer::BOOLEAN, Value::Bool(false))); + } // SpellcasterIllager.DATA_SPELL_CASTING_ID: the casting pose. "minecraft:evoker" | "minecraft:illusioner" => { if e.variant2 != 0 { @@ -533,10 +615,7 @@ impl Game<'_> { config: HubConfig, host: Option, ) -> Result<()> { - let root = self.options.resources.clone(); - let sync = SYNC - .get_or_init(|| SyncData::load(&root).map(Arc::new)) - .clone()?; + let sync = sync_data(&self.options.resources)?; let biome_names: Vec = self .res .biomes() @@ -596,6 +675,7 @@ impl Game<'_> { waypoint_dead: Default::default(), border_sent: None, commands: Vec::new(), + quiet: std::collections::VecDeque::new(), states: Default::default(), }); self.audio.capture = Some(Vec::new()); @@ -634,6 +714,7 @@ impl Game<'_> { self.world.light_log = None; self.audio.capture = None; self.lan_events.clear(); + self.lan_critical_hits.clear(); self.streaming.extra.clear(); if announce { self.system_message(Text::translate( @@ -804,6 +885,16 @@ impl Game<'_> { living_flags: living_flags(self.using) | if p.auto_spin_attack_ticks > 0 { 4 } else { 0 }, bed: self.sleeping, + body: BodyFlags { + gliding: p.fall_flying, + swimming: p.swimming, + crawling: p.pose == horizon_client::pose::Pose::Swimming && !p.swimming, + crouching: p.pose == horizon_client::pose::Pose::Crouching, + spin_attack: p.auto_spin_attack_ticks > 0, + on_fire: p.fire_ticks > 0, + invisible: self.potions.effects.get("invisibility").is_some(), + glowing: self.potions.effects.get("glowing").is_some(), + }, }) } @@ -820,12 +911,13 @@ impl Game<'_> { for m in self.mobs.iter().filter(|m| !m.removed) { // The lead's holder: the player the mob sees (a guest, else the // host) or another mob. A fence knot isn't an entity here. + let player_entity = mob_players + .get(&m.id) + .and_then(|conn| hub.guest(*conn)) + .map(|g| g.entity_id) + .or(host_entity); let leash = m.extra.leash.and_then(|h| match h { - Holder::Player => mob_players - .get(&m.id) - .and_then(|conn| hub.guest(*conn)) - .map(|g| g.entity_id) - .or(host_entity), + Holder::Player => player_entity, Holder::Mob(id) => Some(id as i32), Holder::Knot(_) => None, }); @@ -835,7 +927,7 @@ impl Game<'_> { e.on_ground = m.on_ground; e.velocity = [m.velocity.x, m.velocity.y, m.velocity.z]; e.needs_sync = m.needs_sync; - mob_meta(m, hub, &mut e.meta, &mut e.defaults); + mob_meta(m, hub, player_entity, &mut e.meta, &mut e.defaults); mob_equipment(m, hub, &mut e.equipment); self.mob_attributes(m, &mut e.attributes); e.leash = leash; @@ -912,7 +1004,24 @@ impl Game<'_> { for m in &mut self.mobs { m.needs_sync = false; } + // `runBlockEvents`' broadcast precedes the tick's block changes + // (`ChunkHolder.broadcastChanges` in `tick_level` below): the + // guest re-runs a piston's `triggerEvent` while its level still + // has the blocks as they were before the move. + for (pos, b0, b1, state) in std::mem::take(&mut self.lan_block_events) { + host.hub.block_event(pos, b0, b1, state); + } let entities = states.as_slice(); + // An entity that left the level since the last tick (a snowball + // that hit) is dropped by the tracker below: its event goes out + // first, as `Level.broadcastEntityEvent` precedes the discard. + let (gone, later): (Vec<_>, Vec<_>) = std::mem::take(&mut self.lan_entity_events) + .into_iter() + .partition(|(id, ..)| !entities.iter().any(|e| e.id == *id)); + self.lan_entity_events = later; + for (id, event, at) in gone { + host.hub.entity_event(id, event, at); + } 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(); @@ -960,6 +1069,9 @@ impl Game<'_> { event @ (HostEvent::Chat { .. } | HostEvent::Warn(_) | HostEvent::Error(_)) => { self.lan_log_event(event); } + HostEvent::PlayerChat { sender, text } => { + self.mod_player_chat(super::server_mods::Who::Uuid(sender), &text); + } HostEvent::Joined(conn) => { self.lan_guest_joined(&mut host, conn, state.as_ref(), entities, spawn); if self.options.dedicated.is_some() @@ -1029,6 +1141,14 @@ impl Game<'_> { } host.states = states; } + if !host.quiet.is_empty() { + self.lan = Some(host); + self.run_quiet_commands(); + host = self + .lan + .take() + .expect("the hub is back after the quiet commands"); + } self.lan_flush_effects(&mut host); if !paused { self.tick_guests(&mut host); @@ -1078,8 +1198,17 @@ impl Game<'_> { g.game_mode = default_mode; } if !known { - g.position = spawn; - g.previous_position = spawn; + // ServerPlayer.adjustSpawnLocation: a player new to the world + // stands where PlayerSpawnFinder puts them, not all on one spot + // (it reads the loaded level, which holds the spawn when it is + // the overworld). + let feet = if self.dim == super::Dim::Overworld { + self.server_player_spawn(spawn) + } else { + spawn + }; + g.position = feet; + g.previous_position = feet; g.health = 20.0; g.food = 20; g.dimension = super::Dim::Overworld.id().to_owned(); @@ -1134,17 +1263,29 @@ impl Game<'_> { return; } for e in events { - if let horizon_world::level::LevelEvent::LevelEvent { id, pos, data } = e { - // The acting guest does not predict the egg's teleport - // particles, bone meal's growth, or anvil result sounds - // (these levelEvent calls name no excluded player). - let except = if matches!(*id, 2015 | 1505 | 1029 | 1030) { - None - } else { - self.lan_acting - }; - self.lan_events - .push((*id, [pos.x, pos.y, pos.z], *data, except)); + match e { + horizon_world::level::LevelEvent::LevelEvent { id, pos, data } => { + // The acting guest does not predict the egg's teleport + // particles, bone meal's growth, or anvil result sounds + // (these levelEvent calls name no excluded player). + let except = if matches!(*id, 2015 | 1505 | 1029 | 1030) { + None + } else { + self.lan_acting + }; + self.lan_events + .push((*id, [pos.x, pos.y, pos.z], *data, except)); + } + // `ServerLevel.runBlockEvents` broadcasts a handled block + // event (`ClientboundBlockEventPacket`): the guest re-runs + // the block's `triggerEvent` — a piston's `moveBlocks` is + // what animates the move there. `state` is the block the + // event named, read before it ran (the packet's `block`). + horizon_world::level::LevelEvent::BlockEntityEvent { pos, state, a, b } => { + self.lan_block_events + .push(([pos.x, pos.y, pos.z], *a, *b, state.0)); + } + _ => {} } } } @@ -1162,8 +1303,33 @@ impl Game<'_> { self.lan_entity_events.push((id, event, at)); } } + /// `ServerPlayer.crit` (or `magicCrit` when `magic`): this window's + /// emitter, and an animation for the attacker's client and observers once + /// the hub is back in place. + pub(super) fn critical_hit( + &mut self, + attacker: Option, + id: i32, + feet: [f64; 3], + width: f64, + height: f64, + magic: bool, + ) { + use horizon_client::particles::{ParticleOptions, ParticleType}; + let particle = if magic { + ParticleType::EnchantedHit + } else { + ParticleType::Crit + }; + self.particles + .tracking_emitter(ParticleOptions::simple(particle), feet, width, height); + if self.audio.capture.is_some() { + self.lan_critical_hits.push((attacker, id, magic)); + } + } /// Send the tick's level events, sounds and mob animations. fn lan_flush_effects(&mut self, host: &mut LanHost) { + let critical_hits = std::mem::take(&mut self.lan_critical_hits); for (kind, pos, data, acting) in std::mem::take(&mut self.lan_events) { if kind == 2001 { host.broken @@ -1236,6 +1402,14 @@ impl Game<'_> { seen.insert(m.id, (m.hurt_time, dead, swing)); } host.mob_state.insert(self.dim, seen); + for (attacker, target, magic) in critical_hits { + let Some(attacker) = attacker.map_or(Some(host.host_entity), |conn| { + host.hub.guest(conn).map(|g| g.entity_id) + }) else { + continue; + }; + host.hub.critical_hit(attacker, target, magic); + } } /// Keep the chunks around every guest loaded. @@ -1317,6 +1491,13 @@ impl Game<'_> { .each_ref() .map(|s| s.as_ref().map(|s| s.item.clone())); m.extra.crouching = g.sneaking; + m.extra.sprinting = g.sprinting; + // LivingEntity.DATA_EFFECT_PARTICLES: the swirls of its visible effects. + let visible = || g.effects.list.iter().filter(|e| e.visible); + m.extra.effect_particles = visible() + .filter_map(|e| super::client_ambient::effect_particle(e.id, e.ambient)) + .collect(); + m.extra.effect_ambient = visible().all(|e| e.ambient); // Lying in its bed (LivingEntity.getBedOrientation). m.extra.ints[1] = g.bed.map_or(0, |b| self.bed_facing(b)); // LivingEntity.updateSwingTime: the arm swing lan_swings started. @@ -1403,7 +1584,11 @@ impl Game<'_> { let tag = if secure { "" } else { "[Not Secure] " }; super::dedicated::log("INFO", &format!("{tag}{line}")); } - HostEvent::Chat { line, .. } => self.system_message(Text::literal(line)), + // Player chat (and `/say`'s or `/me`'s, which are chat messages + // too): the host's Chat option decides, as `ChatListener` does + // for the guests' packets. Command feedback is a system message + // and takes the system-message permission instead. + HostEvent::Chat { line, .. } => self.player_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), diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index bbb0c37c0..8c51a3f2a 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -77,6 +77,10 @@ pub(super) struct GuestPlay { last_inventory: u64, /// `Entity.portalProcess` and `portalCooldown` (game/server_travel.rs). pub(super) portal: horizon_client::nether_portal::PortalState, + /// `ServerPlayer.wonGame`: the End poem is showing, the player waits for + /// its client's PERFORM_RESPAWN (`respawn_requested`). + pub(super) won_game: bool, + pub(super) respawn_requested: bool, /// `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. @@ -94,11 +98,14 @@ pub(super) struct GuestPlay { /// A guest's command waiting for the hub (`LanHost::commands`). pub(super) struct GuestCommand { - conn: u32, - command: String, - permission: u8, + pub(super) conn: u32, + pub(super) command: String, + pub(super) permission: u8, /// An integrated server's: no level teleports (yet). - integrated: bool, + pub(super) integrated: bool, + /// A mod's quiet command (game/lan_quiet.rs): its output suppressed, as + /// `CommandSourceStack.withSuppressedOutput` does. + pub(super) quiet: bool, } /// The game's own state while a guest's is swapped in (`enter_guest`), and @@ -872,7 +879,11 @@ impl Game<'_> { .filter(|g| host.hub.here(g)) .filter(|g| { g.menu.as_ref().is_some_and(|m| { - m.slots.valid(&self.world) && !m.slots.still_valid(&self.world, g, m.pos) + (m.slots.valid(&self.world) && !m.slots.still_valid(&self.world, g, m.pos)) + || m.pos.is_some_and(|k| { + k.1 == super::minecarts::CART_KEY_Y + && !self.chest_vehicle_still_valid(k.2, g) + }) }) }) .map(|g| g.conn) @@ -886,6 +897,35 @@ impl Game<'_> { } } + /// `ContainerEntity.isChestVehicleStillValid`: the chest minecart or chest + /// boat is still there and within the guest's entity interaction range + /// plus 4 of its box. + fn chest_vehicle_still_valid(&self, id: i32, g: &horizon_client::lan::guest::Guest) -> bool { + let bounds = self + .carts + .iter() + .find(|c| c.id as i32 == id) + .map(|c| c.bounds()) + .or_else(|| { + self.boats + .iter() + .find(|b| b.id as i32 == id) + .map(|b| b.bounds()) + }); + let Some(b) = bounds else { + return false; + }; + let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]]; + let (lo, hi) = (b.min_position(), b.max_position()); + let d = [ + eye[0] - eye[0].clamp(lo.x, hi.x), + eye[1] - eye[1].clamp(lo.y, hi.y), + eye[2] - eye[2].clamp(lo.z, hi.z), + ]; + let range = if g.creative() { 5.0 } else { 3.0 } + 4.0; + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < range * range + } + /// A packet from a guest that the hub does not handle itself. pub(super) fn lan_guest_packet(&mut self, host: &mut LanHost, conn: u32, packet: S) { let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { @@ -1176,6 +1216,12 @@ impl Game<'_> { { self.guest_carried_back(host, gi); } + S::SelectBundleItem(p) => { + if !spectator && let Ok(slot) = usize::try_from(p.slot) { + host.hub + .select_bundle_item(conn, slot, p.index, &mut self.world); + } + } S::ContainerClick(p) => { let rules = ItemRules(self.res.items()); let slots = host.hub.guests[gi] @@ -1210,6 +1256,9 @@ impl Game<'_> { self.guest_carried_back(host, gi); } S::ChatCommand(c) => self.guest_chat_command(host, conn, &c.command), + S::CustomPayload(p) if p.channel == horizon_protocol::quiet::CHANNEL => { + self.guest_quiet_commands(host, conn, &p.data) + } 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) { @@ -1308,6 +1357,13 @@ impl Game<'_> { self.guest_suggestions(host, conn, &payload); } S::PlaceRecipe(p) => self.lan_place_recipe(host, conn, &p), + // handleClientCommand: PERFORM_RESPAWN after the poem leaves the End + // (the next server tick sends the player on). + S::ClientCommand(c) + if c.action == 0 && host.play.get(&conn).is_some_and(|p| p.won_game) => + { + host.play.entry(conn).or_default().respawn_requested = true; + } S::ClientCommand(c) if c.action == 0 => self.guest_respawn(host, conn), // ServerStatsCounter.sendStats. S::ClientCommand(c) if c.action == 1 => { @@ -1533,6 +1589,10 @@ impl Game<'_> { ); return; } + // A server mod's command, for every player whatever their level. + if self.guest_server_mod_command(host, conn, command.trim_start_matches('/')) { + return; + } // An integrated server runs every player's commands at their own // permission level (`CommandSourceStack.permissions`); a LAN world // follows its Allow Commands, and a dedicated server leaves it to @@ -1559,6 +1619,7 @@ impl Game<'_> { command: command.trim_start_matches('/').to_owned(), permission, integrated, + quiet: false, }); } @@ -1573,41 +1634,54 @@ impl Game<'_> { 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); - } - // What the command earned is announced before its feedback. - self.announce_guest_advancements(&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, - }), - ); - } - // The other operators hear of it; never the player whose command it was. - self.send_admin_feedback(&mut host, Some(c.conn)); - self.lan = Some(host); + self.run_guest_command(c); } } + /// One guest's command as that guest, its feedback sent to them; false + /// when it failed (or the guest is gone). + pub(super) fn run_guest_command(&mut self, c: GuestCommand) -> bool { + let Some(mut host) = self.lan.take() else { + return false; + }; + let Some(swap) = self.enter_guest(&mut host, c.conn) else { + self.lan = Some(host); + return false; + }; + self.lan = Some(host); + self.chat_capture = Some(Vec::new()); + let level = std::mem::replace(&mut self.ui.registries.permission, c.permission); + let ok = if c.quiet { + self.run_command_quietly(&c.command) + } else { + 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); + } + // What the command earned is announced before its feedback. + self.announce_guest_advancements(&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, + }), + ); + } + // The other operators hear of it; never the player whose command it was. + self.send_admin_feedback(&mut host, Some(c.conn)); + self.lan = Some(host); + ok + } + /// 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 @@ -2115,6 +2189,7 @@ impl Game<'_> { let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height()); let at = g.position; let sneaking = g.sneaking; + let mut soul = None; let events = self.as_guest(host, conn, |game| { let (rules, motion) = (game.world.health_rules, game.motion); let health = &motion.health; @@ -2184,6 +2259,7 @@ impl Game<'_> { w.player.shift_key_down = sneaking; w.player.freeze_immune = freeze_immune; let _ = w.server_block_damage(start); + let _ = w.update_soul_speed_block(); let _ = w.tick_environment_damage(); let _ = w.apply_fire_contact(); let _ = w.server_hazards_tick(in_wall); @@ -2211,6 +2287,9 @@ impl Game<'_> { // LivingEntity.baseTick: outside the world border, then tickEffects. game.border_damage(); game.tick_mob_effects(); + // Soul Speed's effects (LivingEntity.baseTick's location_changed + // and tick effects); its particle goes to the players around. + soul = game.tick_soul_speed(); let Some(player) = game.player.as_mut() else { return (Vec::new(), None); }; @@ -2233,16 +2312,48 @@ impl Game<'_> { let marked = std::mem::take(&mut player.health.sync_velocity); let velocity = marked.then_some(player.velocity); game.record_combat(&events); + game.wear_armor(&events); (events, velocity) }); let Some((events, marked)) = events else { return; }; + if let Some((at, velocity)) = soul { + super::lan_particles::send_soul_particle(host, at, velocity); + } self.as_guest(host, conn, |game| game.tick_player_sculk_events()); for event in events { match event { MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, at), + // LivingEntity.checkFallDamage: the crumbs reach every player. + MotionEvent::Fall(horizon_client::landing::FallEvent::Particles { + state, + position, + count, + speed, + }) => self.landing_dust(Some(host), state, position, count, speed), MotionEvent::Fall(event) => self.landing_block_updates(&event), + // HoneyBlock.maybeDoSlideEffects: the sound reaches the + // others (Player.playSound excludes the player, whose client + // plays it), the entity event 53 everyone around. + MotionEvent::HoneySlide { + sound, particles, .. + } => { + let Some((id, at)) = host.hub.guest(conn).map(|g| (g.entity_id, g.position)) + else { + continue; + }; + if sound { + let name = "minecraft:block.honey_block.slide"; + let source = horizon_client::settings::sound_source(name) as i32; + self.audio.play_unshared(name, Some(at), 1.0, 1.0); + host.hub.sound(name, at, 1.0, 1.0, source, Some(conn)); + } + if particles { + self.honey_slide_particles(at); + host.hub.entity_event(id, 53, at); + } + } _ => {} } } @@ -2326,9 +2437,13 @@ impl Game<'_> { } if (next / 10) % 2 == 0 && !creative - && let Some(elytra) = game.armor[1].as_mut() + && let Some(stack) = game.armor[1].clone() { - elytra.damage += 1; + // `ItemStack.hurtAndBreak`: Unbreaking can save the wear. + let loss = game.durability_loss(&stack, 1); + if let Some(elytra) = game.armor[1].as_mut() { + elytra.damage += loss; + } } let ctx = game.player_context(None); game.post_game_event("minecraft:elytra_glide", at, ctx); @@ -2591,7 +2706,13 @@ impl Game<'_> { .random .next_int_bound(touching.len() as i32) .unwrap_or(0) as usize; - let orb = self.orbs.remove(touching[pick]); + // A merged orb gives its value once per count and goes at zero. + let orb = self.orbs[touching[pick]].clone(); + if orb.count <= 1 { + self.orbs.remove(touching[pick]); + } else { + self.orbs[touching[pick]].count -= 1; + } play.xp_delay = 2; host.hub.take_item(orb.id as i32, id, 1, at); // ClientPacketListener.handleTakeItemEntity's sound, at the orb. diff --git a/crates/horizon-client/src/game/lan_chat.rs b/crates/horizon-client/src/game/lan_chat.rs index f678480ab..621955967 100644 --- a/crates/horizon-client/src/game/lan_chat.rs +++ b/crates/horizon-client/src/game/lan_chat.rs @@ -28,7 +28,11 @@ impl Game<'_> { /// 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)> { + pub(super) 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; diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index cd4ba2fb8..665710be2 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -245,6 +245,16 @@ impl Game<'_> { } out.push(e); } + for c in &self.cushions { + let p = c.position; + let mut e = state(c.id, "minecraft:cushion", [p.x, p.y, p.z], c.yaw, false); + // Cushion.DATA_COLOR, set unless it is the default white. + if c.color != 0 { + e.meta + .push((8, serializer::DYE_COLOR, Value::Id(i32::from(c.color)))); + } + out.push(e); + } self.lan_projectile_states(host_entity, hub, out); for o in &self.others { let p = o.position; @@ -279,6 +289,10 @@ impl Game<'_> { self.bolts.iter_mut().for_each(|b| give(&mut b.id)); self.potions.thrown_ids().for_each(&mut give); self.end.eye_ids().for_each(&mut give); + self.breath_clouds.iter_mut().for_each(|b| give(&mut b.id)); + self.dragon_fireballs + .iter_mut() + .for_each(|b| give(&mut b.id)); } /// Primed TNT, falling blocks, projectiles, tridents, firework rockets and @@ -290,6 +304,9 @@ impl Game<'_> { None => 0, }; let at = |p: horizon_core::geometry::Vec3| [p.x, p.y, p.z]; + for f in &self.fangs.list { + out.push(state(f.id, "minecraft:evoker_fangs", f.pos, f.yaw, false)); + } // LightningBolt: each client draws and flashes its own. for b in self.bolts.iter().filter(|b| b.id != 0) { out.push(state(b.id, "minecraft:lightning_bolt", b.at, 0.0, false)); @@ -340,6 +357,20 @@ impl Game<'_> { a.is_some_and(|a| a.in_ground) || p.stuck, )); } + // ThrownTrident.ID_LOYALTY (none for a mob's) and ID_FOIL, on + // AbstractArrow's flags. + K::Trident => { + let a = p.arrow.as_deref(); + e.meta.extend(arrow_meta( + false, + a.is_some_and(|a| a.no_physics), + 0, + a.is_some_and(|a| a.in_ground) || p.stuck, + )); + if a.is_some_and(|a| a.pickup_item.has_any_enchantments()) { + e.meta.push((12, serializer::BOOLEAN, Value::Bool(true))); + } + } // WitherSkull.DATA_DANGEROUS. K::WitherSkull { dangerous: true } => { e.meta.push((8, serializer::BOOLEAN, Value::Bool(true))); @@ -435,6 +466,35 @@ impl Game<'_> { } out.push(e); } + // The dragon's breath clouds (AreaEffectCloud's DATA_RADIUS, + // DATA_WAITING for its 20-tick wait, and DATA_PARTICLE): the + // client draws them from these (`tick_remote_clouds`). + let breath = self.network_particle( + &horizon_client::particles::ParticleOptions::simple( + horizon_client::particles::ParticleType::DragonBreath, + ), + None, + ); + for b in self.dragon_fireballs.iter().filter(|b| b.id != 0) { + let p = b.position; + let mut e = state(b.id, "minecraft:dragon_fireball", at(p), 0.0, false); + e.velocity = [b.velocity.x, b.velocity.y, b.velocity.z]; + out.push(e); + } + for b in self.breath_clouds.iter().filter(|b| b.id != 0) { + let mut e = state(b.id, "minecraft:area_effect_cloud", b.at, 0.0, false); + e.meta.push((8, serializer::FLOAT, Value::Float(b.radius))); + if b.age < 20 { + e.meta.push((9, serializer::BOOLEAN, Value::Bool(true))); + } + if let Some(p) = &breath { + e.meta + .push((10, serializer::PARTICLE, Value::Particle(p.clone()))); + } + e.defaults + .push((9, serializer::BOOLEAN, Value::Bool(false))); + out.push(e); + } out.extend(self.lan_dragon_state()); } } diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 4f53cec60..6527f1015 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -370,6 +370,7 @@ mod tests { velocity: Vec3::ZERO, yaw: 0.0, hero: false, + effects: Vec::new(), uuid: [0; 4], allies: Default::default(), remote: false, diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs index 0e35392bf..648cef962 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -1,7 +1,8 @@ //! Particles a server sends its players and its clients draw: //! `ClientboundLevelParticlesPacket` (`ServerLevel.sendParticles`, which //! `/particle` uses) and `ClientboundExplodePacket` (`ServerLevel.explode`). -use super::Game; +use super::{Game, lan::LanHost}; +use horizon_client::lan::hub::Hub; use horizon_client::particles::{ParticleOptions, ParticleType}; use horizon_core::{geometry::Vec3, random::RandomSource}; use horizon_protocol::{ @@ -24,7 +25,123 @@ fn rgb(c: [f32; 4]) -> [f32; 3] { [c[0], c[1], c[2]] } +/// `ServerLevel.sendParticles` of one soul particle moving by `velocity` +/// (Soul Speed's `spawn_particles`): sent to the players within 32 blocks. +pub(super) fn send_soul_particle(host: &super::lan::LanHost, at: [f64; 3], velocity: [f64; 3]) { + let Some(id) = host + .hub + .registry_id("minecraft:particle_type", "minecraft:soul") + else { + return; + }; + let packet = C::LevelParticles(play::LevelParticles { + particle: Particle { id, data: None }, + override_limiter: false, + always_show: false, + pos: at, + dist: velocity.map(|v| v as f32), + max_speed: [1.0; 3], + count: 0, + randomization: 0, + }); + for g in host.hub.guests.iter().filter(|g| host.hub.here(g)) { + let distance: f64 = (0..3) + .map(|k| (g.position[k].floor() + 0.5 - at[k]).powi(2)) + .sum(); + if distance < 32.0 * 32.0 { + g.send(&packet); + } + } +} + impl Game<'_> { + /// `SonicBoom.tick` uses `ServerLevel.sendParticles` for each ray point. + /// Keep the local event's rendering; connected players receive one at rest. + pub(super) fn lan_sonic_boom(&self, options: &ParticleOptions, at: [f64; 3]) { + let (Some(host), Some(particle)) = (&self.lan, self.network_particle(options, None)) else { + return; + }; + let packet = C::LevelParticles(play::LevelParticles { + particle, + override_limiter: false, + always_show: false, + pos: at, + dist: [0.0; 3], + max_speed: [0.0; 3], + count: 0, + randomization: 0, + }); + for g in host.hub.guests.iter().filter(|g| host.hub.here(g)) { + // ServerLevel compares the player's block centre, strictly within 32. + let distance: f64 = (0..3) + .map(|k| (g.position[k].floor() + 0.5 - at[k]).powi(2)) + .sum(); + if distance < 32.0 * 32.0 { + g.send(&packet); + } + } + } + + /// `LivingEntity.checkFallDamage`'s `ServerLevel.sendParticles` of the + /// landing block's crumbs: drawn in this window, when it has one, and + /// sent to each player within 32 blocks. `host` is the hub of a guest's + /// turn, which is out of `self.lan` meanwhile. + pub(super) fn landing_dust( + &mut self, + host: Option<&LanHost>, + state: BlockStateId, + at: Vec3, + count: i32, + speed: f64, + ) { + let at = [at.x, at.y, at.z]; + if self.serving.is_none() && self.options.dedicated.is_none() { + let block = [ + at[0].floor() as i32, + (at[1] - 0.2).floor() as i32, + at[2].floor() as i32, + ]; + if let Some((sprite, tint)) = self.particle_sprite(state, block) { + self.particles.send_particles( + &ParticleOptions::block(ParticleType::Block, sprite, tint), + at, + [0.0; 3], + speed, + count as u32, + ); + } + } + let Some(hub) = host.or(self.lan.as_ref()).map(|h| &h.hub) else { + return; + }; + let Some(particle) = Self::hub_particle( + hub, + &ParticleOptions::simple(ParticleType::Block), + Some(state), + ) else { + return; + }; + let packet = C::LevelParticles(play::LevelParticles { + particle, + override_limiter: false, + always_show: false, + pos: at, + dist: [0.0; 3], + max_speed: [speed as f32; 3], + count, + randomization: 0, + }); + for g in hub.guests.iter().filter(|g| hub.here(g)) { + // ServerLevel compares the player's block centre, strictly within 32. + let distance: f64 = (0..3) + .map(|k| (g.position[k].floor() + 0.5 - at[k]).powi(2)) + .sum(); + if distance < 32.0 * 32.0 { + g.send(&packet); + } + } + } + /// `ParticleTypes.STREAM_CODEC`'s value for `options`: the type's /// network id and the data it carries (`state` for the block particles). /// None while not serving, or for a particle whose data isn't sent from @@ -33,13 +150,19 @@ impl Game<'_> { &self, options: &ParticleOptions, state: Option, + ) -> Option { + Self::hub_particle(&self.lan.as_ref()?.hub, options, state) + } + + /// `network_particle` for a hub that is out of `self.lan` meanwhile (a + /// guest's turn). + fn hub_particle( + hub: &Hub, + options: &ParticleOptions, + state: Option, ) -> Option { let name = format!("minecraft:{}", options.ty.name()); - let id = self - .lan - .as_ref()? - .hub - .registry_id("minecraft:particle_type", &name)?; + let id = hub.registry_id("minecraft:particle_type", &name)?; use ParticleType as T; let c = options.color; let data = match options.ty { @@ -68,7 +191,11 @@ impl Game<'_> { /// The options a server's particle stands for (None for a type or data /// this client doesn't draw). - fn received_particle(&mut self, p: &Particle, at: [f64; 3]) -> Option { + pub(super) fn received_particle( + &mut self, + p: &Particle, + at: [f64; 3], + ) -> Option { let name = self .remote .as_ref()? @@ -194,8 +321,14 @@ impl Game<'_> { /// `ServerLevel.explode`'s packet to each player within 64 blocks. The /// sound and the push reach them on their own (the level's sounds, the /// motion a hurt player is sent), so the packet carries neither. - pub(super) fn lan_explode(&self, center: [f64; 3], radius: f32, block_count: usize) { - let emitter = if radius < 2.0 { + pub(super) fn lan_explode( + &self, + center: [f64; 3], + small: bool, + radius: f32, + block_count: usize, + ) { + let emitter = if small { "minecraft:explosion" } else { "minecraft:explosion_emitter" diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index 467c4537c..65520221a 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -32,9 +32,13 @@ pub(super) enum Victim { /// The attacker's side of the hit. pub(super) struct Strike { + /// The attacking guest, kept after their turn through `as_guest` ends. + attacker: Option, amount: f32, scale: f32, crit: bool, + /// `Player.attack`'s `magicBoost > 0`: the enchantments added damage. + magic: bool, from: [f64; 3], sweep: Option<[f64; 3]>, /// `causeExtraKnockback`: its strength and direction (the attacker's @@ -107,7 +111,7 @@ impl Game<'_> { pub(super) fn pvp_strike(&mut self) -> Option { let p = self.player.as_ref()?; let from = [p.position.x, p.position.y, p.position.z]; - let (amount, scale, crit) = self.melee_damage("minecraft:player"); + let (amount, scale, crit, magic) = self.melee_damage("minecraft:player"); let sweep = self.sweep_attack_position(scale, crit); let (strength, knockback_attack) = self.extra_knockback("minecraft:player", scale); let (xd, zd) = self.extra_knockback_direction(); @@ -119,9 +123,11 @@ impl Game<'_> { } self.swing_arm(); Some(Strike { + attacker: self.lan_acting, amount, scale, crit, + magic, from, sweep, knockback: (strength, xd, zd), @@ -242,14 +248,50 @@ impl Game<'_> { if hurt && strength > 0.0 { g.knock_back_player(f64::from(strength), xd, zd); } - hurt + // The victim's thorns, dealt to the attacker below. + let thorns = if hurt { g.thorns_damage() } else { Vec::new() }; + (hurt, thorns) }; - let hurt = self.ui.rules.bool("pvp") - && harm - && match victim { + let (hurt, thorns) = if self.ui.rules.bool("pvp") && harm { + match victim { Victim::Host => land(self), - Victim::Guest(conn) => self.guest_struck_by(host, conn, land).unwrap_or(false), + Victim::Guest(conn) => self.guest_struck_by(host, conn, land).unwrap_or_default(), + } + } else { + Default::default() + }; + if hurt && (s.crit || s.magic) { + let target = match victim { + Victim::Host => self.player.as_ref().map(|p| (host.host_entity, p)), + Victim::Guest(conn) => host + .hub + .guest(conn) + .and_then(|g| g.motion.as_deref().map(|p| (g.entity_id, p))), }; + if let Some((id, p)) = target { + let d = p.dimensions; + let (feet, width, height) = ( + [p.position.x, p.position.y, p.position.z], + f64::from(d.width), + f64::from(d.height), + ); + if s.crit { + self.critical_hit(s.attacker, id, feet, width, height, false); + } + if s.magic { + self.critical_hit(s.attacker, id, feet, width, height, true); + } + } + } + // `Enchantment.doPostAttack`: thorns hurt the attacking player. + for damage in thorns { + match s.attacker { + None => self.hurt_player_by("minecraft:thorns", damage), + Some(conn) => { + self.guest_hit_by(host, conn, |g| g.hurt_player_by("minecraft:thorns", damage)); + } + } + } let sound = match (hurt, s.crit, s.scale > 0.9) { (false, ..) => "minecraft:entity.player.attack.nodamage", (true, true, _) => "minecraft:entity.player.attack.crit", diff --git a/crates/horizon-client/src/game/lan_quiet.rs b/crates/horizon-client/src/game/lan_quiet.rs new file mode 100644 index 000000000..63d382c02 --- /dev/null +++ b/crates/horizon-client/src/game/lan_quiet.rs @@ -0,0 +1,165 @@ +//! Quiet commands (`horizon_protocol::quiet`): a Horizon client's mod sends a +//! batch of command lines in one payload, and the server runs each exactly as +//! that player typing it would (`guest_command`'s checks, the player's own +//! permission level, at the time it runs) with its output suppressed, as +//! vanilla's functions run (`CommandSourceStack.withSuppressedOutput`): no +//! feedback and no failure in anyone's chat. A batch waits in a queue and runs +//! [`PER_TICK`] lines a player a tick, so a mod can't flood a server; each +//! finished batch is one line in the server's log. +use super::{Game, lan::LanHost, lan_actions::GuestCommand}; +use horizon_protocol::quiet; +use std::collections::{HashMap, VecDeque}; + +/// Lines a player may have waiting at most; a batch past it loses the rest. +pub(super) const PENDING: usize = 4096; +/// Lines run a player a tick at most. +pub(super) const PER_TICK: usize = 64; + +/// A batch waiting to run. +pub(super) struct QuietBatch { + conn: u32, + mod_id: String, + lines: VecDeque, + ran: usize, + failed: usize, + /// Lines past [`PENDING`], never run. + dropped: usize, +} + +impl Game<'_> { + /// A `horizon:quiet_commands` payload from `conn`: queued (or logged as + /// refused when it breaks the payload's caps). + pub(super) fn guest_quiet_commands(&mut self, host: &mut LanHost, conn: u32, data: &[u8]) { + let Some(name) = host.hub.guest(conn).map(|g| g.name.clone()) else { + return; + }; + let batch = match quiet::decode(data) { + Ok(b) => b, + Err(e) => { + super::dedicated::log( + "WARN", + &format!("{name} sent quiet commands that were refused: {e}"), + ); + return; + } + }; + let waiting: usize = host + .quiet + .iter() + .filter(|b| b.conn == conn) + .map(|b| b.lines.len()) + .sum(); + let room = PENDING.saturating_sub(waiting); + let dropped = batch.lines.len().saturating_sub(room); + host.quiet.push_back(QuietBatch { + conn, + mod_id: batch.mod_id, + lines: batch.lines.into_iter().take(room).collect(), + ran: 0, + failed: 0, + dropped, + }); + } + + /// The waiting batches, [`PER_TICK`] lines a player this tick, in order. + pub(super) fn run_quiet_commands(&mut self) { + let mut left: HashMap = HashMap::new(); + let mut i = 0; + loop { + let Some(host) = self.lan.as_mut() else { + return; + }; + let Some(batch) = host.quiet.get_mut(i) else { + return; + }; + let conn = batch.conn; + let budget = left.entry(conn).or_insert(PER_TICK); + let gone = host.hub.guest(conn).is_none(); + if gone || batch.lines.is_empty() { + let batch = host.quiet.remove(i).expect("got it above"); + if !gone { + let name = host + .hub + .guest(conn) + .map_or(String::new(), |g| g.name.clone()); + super::dedicated::log("INFO", &summary(&name, &batch)); + } + continue; + } + if *budget == 0 { + i += 1; + continue; + } + *budget -= 1; + let line = batch.lines.pop_front().expect("not empty"); + let ok = self.run_quiet_line(conn, &line); + if let Some(batch) = self.lan.as_mut().and_then(|h| h.quiet.get_mut(i)) { + batch.ran += 1; + batch.failed += usize::from(!ok); + } + } + } + + /// One line as `guest_command` would run it for `conn`, quietly. False + /// when it is refused or fails. A command that carries a chat message + /// (`say`, `msg`...) is refused: it would need the player's signature. + fn run_quiet_line(&mut self, conn: u32, line: &str) -> bool { + let allowed = self.options.dedicated.is_some() || self.allow_commands(); + let Some(host) = self.lan.as_ref() else { + return false; + }; + let integrated = host.hub.config.integrated; + if !integrated && (!host.settings.guest_commands || !allowed) { + return false; + } + let Some(permission) = host.hub.guest(conn).map(|g| g.permission) else { + return false; + }; + let command = line.trim_start_matches('/'); + if !self.signable_arguments(permission, command).is_empty() { + return false; + } + self.run_guest_command(GuestCommand { + conn, + command: command.to_owned(), + permission, + integrated, + quiet: true, + }) + } +} + +/// The batch's line in the server's log. +fn summary(name: &str, b: &QuietBatch) -> String { + let mut line = format!( + "{name} ran {} quiet command(s) from mod {}: {} failed", + b.ran, b.mod_id, b.failed + ); + if b.dropped > 0 { + line += &format!(", {} dropped (more than {PENDING} waiting)", b.dropped); + } + line +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_log_line_counts_the_batch() { + let b = QuietBatch { + conn: 1, + mod_id: "orbital".into(), + lines: VecDeque::new(), + ran: 12, + failed: 3, + dropped: 0, + }; + assert_eq!( + summary("Alex", &b), + "Alex ran 12 quiet command(s) from mod orbital: 3 failed" + ); + let b = QuietBatch { dropped: 5, ..b }; + assert!(summary("Alex", &b).ends_with(", 5 dropped (more than 4096 waiting)")); + } +} diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index 1bec9809d..7beeeba2f 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -144,15 +144,16 @@ impl Game<'_> { .offers .iter() .filter_map(|o| { - let cost = - |st: &ItemStack, hub: &mut horizon_client::lan::hub::Hub| play::NetCost { - item: hub.item_id(&st.item), - count: st.count as i32, - }; + let cost = |st: &ItemStack, hub: &mut horizon_client::lan::hub::Hub| { + hub.stack(&Some(st.clone())).map(play::NetCost::from) + }; Some(play::NetOffer { - cost_a: cost(&o.base_cost_a.stack, &mut host.hub), + cost_a: cost(&o.base_cost_a.stack, &mut host.hub)?, result: host.hub.stack(&Some(o.result.clone()))?, - cost_b: o.cost_b.as_ref().map(|b| cost(&b.stack, &mut host.hub)), + cost_b: match &o.cost_b { + Some(b) => Some(cost(&b.stack, &mut host.hub)?), + None => None, + }, out_of_stock: o.out_of_stock(), uses: o.uses, max_uses: o.max_uses, diff --git a/crates/horizon-client/src/game/lan_vehicles.rs b/crates/horizon-client/src/game/lan_vehicles.rs index f16a1e37d..00795aa62 100644 --- a/crates/horizon-client/src/game/lan_vehicles.rs +++ b/crates/horizon-client/src/game/lan_vehicles.rs @@ -56,6 +56,13 @@ impl Game<'_> { let (lo, hi) = corners(a.bounds()); return Some((lo, hi, at(a.position))); } + if let Some(c) = self.cushions.iter().find(|c| c.id == id) { + let (lo, hi) = corners(Aabb::new( + Vec3::new(c.position.x - 0.5, c.position.y, c.position.z - 0.5), + Vec3::new(c.position.x + 0.5, c.position.y + 0.25, c.position.z + 0.5), + )); + return Some((lo, hi, at(c.position))); + } if let Some(f) = self.item_frames.iter().find(|f| f.id == id) { let (lo, hi) = f.bounds(); return Some((lo, hi, centre(f.pos))); @@ -98,9 +105,10 @@ impl Game<'_> { let boat = self.boats.iter().position(|b| b.id == vehicle); let cart = self.carts.iter().any(|c| c.id == vehicle); let mount = self.mobs.iter().any(|m| m.id == vehicle); + let cushion = self.cushions.iter().any(|c| c.id == vehicle); // The vehicle is gone (broken, in another level) or the rider died: // its client drops it with the entity or the death screen. - if dead || (boat.is_none() && !cart && !mount) { + if dead || (boat.is_none() && !cart && !mount && !cushion) { let g = &mut host.hub.guests[gi]; (g.vehicle, g.vehicle_good) = (None, None); return; @@ -115,6 +123,17 @@ impl Game<'_> { // Getting out goes through leave_guest, which tells the client and // teleports it (ServerPlayer.dismountTo). let seat = self.as_guest(host, conn, |game| { + // A cushion does not move: the rider sits on it until it sneaks + // (`Cushion.removePassenger` plays the get-up sound). + if game.cushions.iter().any(|c| Some(c.id) == game.riding) { + if keys.shift { + game.tick_cushion_riding(keys); + return None; + } + let c = game.cushions.iter().find(|c| Some(c.id) == game.riding)?; + let p = c.seat(); + return Some([p.x, p.y, p.z]); + } if let Some(i) = game.boats.iter().position(|b| Some(b.id) == game.riding) { if keys.shift { game.dismount(i); @@ -168,6 +187,12 @@ impl Game<'_> { .iter() .find(|c| c.id == vehicle) .map(|c| (c.position, c.position.add_vector(Vec3::new(0.0, SEAT, 0.0)))) + }) + .or_else(|| { + self.cushions + .iter() + .find(|c| c.id == vehicle) + .map(|c| (c.position, c.seat())) }); if let Some((p, seat)) = at { let g = &mut host.hub.guests[gi]; diff --git a/crates/horizon-client/src/game/leads.rs b/crates/horizon-client/src/game/leads.rs index 8867157ee..ca70351c6 100644 --- a/crates/horizon-client/src/game/leads.rs +++ b/crates/horizon-client/src/game/leads.rs @@ -104,6 +104,9 @@ impl Game<'_> { }; let m = &mut self.mobs[i]; if let Some(h) = holder { + if h == Holder::Player { + m.extra.leash_player = Some(player_uuid); + } m.extra.leash = Some(h); m.extra.leash_pending = None; } else if m.age > 100 { @@ -201,7 +204,9 @@ impl Game<'_> { if self.mobs[index].extra.leash.is_some() { self.break_leash(id, true, false); } + let holder = self.acting_player_uuid(); self.mobs[index].extra.leash = Some(Holder::Player); + self.mobs[index].extra.leash_player = Some(holder); self.lead_sound("tied", at); // The lead is always used up. if let Some(stack) = self.held_mut().as_mut() { diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index e6593e7b9..e73cfdb01 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -4,6 +4,7 @@ //! off (3004) and scraping (3005), plus the smoke, drips, egg and dragon //! fireball particles of 1501, 1502, 1504, 2006, 2009, 2012 and 3009. use super::Game; +use horizon_client::items::ItemStack; use horizon_client::particles::{self, ParticleOptions, ParticleType}; use horizon_core::{geometry::trig, position::BlockPos, random::RandomSource}; use horizon_world::level::LevelEvent; @@ -309,6 +310,68 @@ impl Game<'_> { // Each guest plays it from the global packet. self.audio.play_unshared(sound, at, volume, 1.0); } + /// `LevelEventHandler.potionSplashParticles` (2002 with `Effect`, 2007 + /// with `InstantEffect`): eight splash potion crumbs, and a hundred + /// spell particles in the potion's colour `data`, flung out in a disc. + pub(super) fn potion_splash_particles(&mut self, pos: BlockPos, data: i32, instant: bool) { + let ty = if instant { + ParticleType::InstantEffect + } else { + ParticleType::Effect + }; + // Vec3.atBottomCenterOf. + let at = [ + f64::from(pos.x) + 0.5, + f64::from(pos.y), + f64::from(pos.z) + 0.5, + ]; + let crumb = self.item_particle(&ItemStack::new("minecraft:splash_potion", 1)); + let r = self.particles.level_random(); + let crumbs: Vec<[f64; 3]> = (0..8) + .map(|_| { + [ + r.next_gaussian() * 0.15, + r.next_double() * 0.2, + r.next_gaussian() * 0.15, + ] + }) + .collect(); + for v in crumbs { + self.particles.add(&crumb, at, v); + } + let channel = |shift: i32| ((data >> shift) & 0xFF) as f32 / 255.0; + let color = [channel(16), channel(8), channel(0)]; + for _ in 0..100 { + let r = self.particles.level_random(); + let dist = r.next_double() * 4.0; + let angle = r.next_double() * std::f64::consts::PI * 2.0; + let velocity = [ + angle.cos() * dist, + 0.01 + r.next_double() * 0.5, + angle.sin() * dist, + ]; + let brightness = 0.75 + r.next_float() * 0.25; + let options = ParticleOptions { + color: [ + color[0] * brightness, + color[1] * brightness, + color[2] * brightness, + 1.0, + ], + scale: dist as f32, + ..ParticleOptions::simple(ty) + }; + self.particles.add( + &options, + [ + at[0] + velocity[0] * 0.1, + at[1] + 0.3, + at[2] + velocity[2] * 0.1, + ], + velocity, + ); + } + } /// Queue and play level event `id` at `pos` (`Level.levelEvent`). pub(super) fn level_event_at(&mut self, id: i32, pos: [i32; 3], data: i32) { self.level_events.push(LevelEvent::LevelEvent { diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index e8a8cfb59..5f0286d02 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -3,8 +3,8 @@ //! The game's tick code reads one level: the one in place, held in `Game`'s //! own fields (the world, its streaming and save, block ticks, entities). //! A server (the dedicated server and single player's server thread) keeps -//! the other dimensions' levels here and ticks each one that has players by -//! swapping it into place (`enter_level`), the way `as_guest` swaps a player +//! the other dimensions' levels here and ticks each one with players or forced +//! chunks by swapping it into place (`enter_level`), the way `as_guest` swaps a player //! in, so the tick code runs unchanged, one level at a time. The in-frame //! game holds one level, which follows its player (`enter_dimension`). //! @@ -50,6 +50,7 @@ pub(super) struct Parked { paintings: Vec, item_frames: Vec, armor_stands: Vec, + cushions: Vec, others: Vec, boats: Vec, carts: Vec, @@ -74,6 +75,7 @@ pub(super) struct Parked { lan_events: Vec<(i32, [i32; 3], i32, Option)>, lan_block_events: Vec<([i32; 3], i32, i32, u32)>, lan_entity_events: Vec<(i32, i8, [f64; 3])>, + lan_critical_hits: Vec<(Option, i32, bool)>, /// Only the per-level parts of these are used (`swap_level`). anims: BlockEntityAnims, raiding: Raiding, @@ -107,6 +109,19 @@ pub(super) struct Levels { parked: HashMap, } +impl Levels { + /// The chunks of each level not in place (capability `world` lends + /// them to server mods for a call). + #[cfg_attr(not(feature = "mods"), allow(dead_code))] + pub(super) fn parked_chunks( + &mut self, + ) -> impl Iterator { + self.parked + .iter_mut() + .map(|(d, p)| (*d, &mut p.world.chunks)) + } +} + impl Game<'_> { /// A new level for `dim`, opened from the save (`MinecraftServer.createLevels`). fn open_level(&self, dim: Dim) -> Result { @@ -135,6 +150,7 @@ impl Game<'_> { paintings: Vec::new(), item_frames: Vec::new(), armor_stands: Vec::new(), + cushions: Vec::new(), others: Vec::new(), boats: Vec::new(), carts: Vec::new(), @@ -159,6 +175,7 @@ impl Game<'_> { lan_events: Vec::new(), lan_block_events: Vec::new(), lan_entity_events: Vec::new(), + lan_critical_hits: Vec::new(), anims: Default::default(), raiding: Default::default(), sculk: Default::default(), @@ -175,6 +192,7 @@ impl Game<'_> { let mut locator = self.end.locator(); swap(&mut locator, &mut p.locator); self.end.set_locator(locator); + self.share_spawn_conditions(); 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); @@ -185,6 +203,7 @@ impl Game<'_> { swap(&mut self.paintings, &mut p.paintings); swap(&mut self.item_frames, &mut p.item_frames); swap(&mut self.armor_stands, &mut p.armor_stands); + swap(&mut self.cushions, &mut p.cushions); swap(&mut self.others, &mut p.others); swap(&mut self.boats, &mut p.boats); swap(&mut self.carts, &mut p.carts); @@ -209,6 +228,7 @@ impl Game<'_> { swap(&mut self.lan_events, &mut p.lan_events); swap(&mut self.lan_block_events, &mut p.lan_block_events); swap(&mut self.lan_entity_events, &mut p.lan_entity_events); + swap(&mut self.lan_critical_hits, &mut p.lan_critical_hits); let (a, b) = (&mut self.be_anims, &mut p.anims); swap(&mut a.chests, &mut b.chests); swap(&mut a.books, &mut b.books); @@ -219,6 +239,7 @@ impl Game<'_> { swap(&mut a.pots, &mut b.pots); swap(&mut a.gateways, &mut b.gateways); swap(&mut a.gateway_servers, &mut b.gateway_servers); + swap(&mut a.conduit_servers, &mut b.conduit_servers); self.raiding.swap_level(&mut p.raiding); self.sculk.swap_level(&mut p.sculk); self.creaking.swap_level(&mut p.creaking); @@ -287,8 +308,8 @@ impl Game<'_> { } /// One server tick (`MinecraftServer.tickServer`): each level with - /// players in turn (`tickChildren`), its chunks streamed and loaded and - /// its world ticked. The first pass reads the network and runs the + /// players or forced chunks in turn (`tickChildren`), its chunks streamed + /// and loaded and its world ticked. The first pass reads the network and runs the /// tick's shared parts (the clock, the weather, functions, the autosave); /// the next ones only their level. While `paused`, only the connections /// run. @@ -307,6 +328,8 @@ impl Game<'_> { }; self.update_dedicated_streaming(); self.update_world(); + // What server mods set in this level since its last tick. + self.apply_mod_block_writes(); result = if paused { self.tick_lan(true); Ok(()) @@ -377,7 +400,8 @@ impl Game<'_> { } *next += self.clock.tick_duration(); if *next > now { - // A `/pregen` task keeps the workers fed until the next tick. + // A `/pregen` task or force-loaded chunks keep the workers fed + // until the next tick. self.pump_pregen(*next); let now = Instant::now(); if *next > now { @@ -390,7 +414,7 @@ impl Game<'_> { /// The levels this server tick runs, in `MinecraftServer.levels` order /// (the Overworld, the Nether, the End): every level with a player in - /// it or a `/pregen` task, or the Overworld while nobody is online. + /// it, forced chunks or a `/pregen` task, or the Overworld while idle. pub(super) fn levels_to_tick(&self) -> Vec { let guests = self .lan @@ -399,7 +423,17 @@ impl Game<'_> { let mut dims: Vec = [Dim::Overworld, Dim::Nether, Dim::End] .into_iter() .filter(|d| { - guests.iter().any(|g| g.dimension == d.id()) || self.pregen_level() == Some(*d) + let forced = if *d == self.dim { + !self.streaming.forced.is_empty() + } else { + self.levels + .parked + .get(d) + .is_some_and(|p| !p.streaming.forced.is_empty()) + }; + guests.iter().any(|g| g.dimension == d.id()) + || forced + || self.pregen_level() == Some(*d) }) .collect(); if dims.is_empty() { diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 916bd2a0a..8a3ac2745 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -74,14 +74,74 @@ impl Game<'_> { self.spawn_bolt(at, trap); } } - /// `findLightningTargetAround`: a living entity under open sky in the - /// column (3 blocks around), else the top of the column. + /// `ServerLevel.findLightningRod`: `PoiManager.findClosest` over the + /// lightning rod points of interest within 128 blocks of `center` whose + /// block is the top (`WORLD_SURFACE`) of its column; the strike lands one + /// above it. Horizon keeps no point-of-interest index, so this scans the + /// loaded chunks the way `/locate poi` does. + fn find_lightning_rod(&self, center: [i32; 3]) -> Option<[i32; 3]> { + const RANGE: i32 = 128; + let facts = self.res.facts(); + let mut is_rod: std::collections::HashMap = std::collections::HashMap::new(); + let mut best: Option<(i64, [i32; 3])> = None; + let (cx0, cz0) = ((center[0] - RANGE) >> 4, (center[2] - RANGE) >> 4); + let (cx1, cz1) = ((center[0] + RANGE) >> 4, (center[2] + RANGE) >> 4); + for cx in cx0..=cx1 { + for cz in cz0..=cz1 { + let Some(chunk) = self.world.chunks.get(&(cx, cz)) else { + continue; + }; + for (i, section) in chunk.sections.iter().enumerate() { + let mut rod = |state: u32| { + *is_rod.entry(state).or_insert_with(|| { + facts + .get(horizon_world::registry::BlockStateId(state)) + .name + .ends_with("lightning_rod") + }) + }; + if !section.blocks.maybe_has(&mut rod) { + continue; + } + let base_y = horizon_client::chunk::MIN_Y + 16 * i as i32; + for j in 0..4096 { + if !rod(section.get(j)) { + continue; + } + let p = [ + cx * 16 + (j & 15) as i32, + base_y + (j >> 8) as i32, + cz * 16 + ((j >> 4) & 15) as i32, + ]; + let d = [p[0] - center[0], p[1] - center[1], p[2] - center[2]] + .map(|d| i64::from(d) * i64::from(d)) + .iter() + .sum::(); + if d > i64::from(RANGE * RANGE) || best.is_some_and(|(b, _)| d >= b) { + continue; + } + let surface = self.world.world_surface(p[0], p[2], |s| facts.is_air(s)); + if p[1] == surface - 1 { + best = Some((d, p)); + } + } + } + } + } + best.map(|(_, p)| [p[0], p[1] + 1, p[2]]) + } + /// `findLightningTargetAround`: the closest lightning rod, else a living + /// entity under open sky in the column (3 blocks around), else the top of + /// the column. fn lightning_target(&mut self, x: i32, z: i32) -> Option<[i32; 3]> { if !self.world.loaded(x, z) { return None; } let top = self.with_level(|b, level, _| b.motion_blocking_top(level, BlockPos::new(x, 0, z))); + if let Some(rod) = self.find_lightning_rod([x, top.y, z]) { + return Some(rod); + } let sees_sky = |g: &Self, p: [i32; 3]| g.world.light(p[0], p[1], p[2]) >> 4 == 15; let mut candidates: Vec<[i32; 3]> = self .mobs @@ -162,11 +222,9 @@ impl Game<'_> { converted: Vec::new(), }); } - /// `spawnFire`: fire at the strike point and `extra` random neighbours. + /// `spawnFire`: fire at the strike point and `extra` random neighbours, + /// wherever `BaseFireBlock.getState` fire can survive. fn bolt_fire(&mut self, at: [f64; 3], extra: i32) { - if self.ui.difficulty < 2 { - return; - } let base = [ at[0].floor() as i32, at[1].floor() as i32, @@ -183,18 +241,13 @@ impl Game<'_> { 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 name = if matches!(&*below.name, "minecraft:soul_soil" | "minecraft:soul_sand") { - "minecraft:soul_fire" - } else { - "minecraft:fire" - }; - // FireBlock.canSurvive: a sturdy floor (flammable neighbours aside). - if below.sturdy_full >> 1 & 1 == 0 { - continue; - } - if let Some(fire) = self.pack.assets.registry.default_state(name) { + // BaseFireBlock.getState and FireBlock/SoulFireBlock.canSurvive. + let at = BlockPos::new(p[0], p[1], p[2]); + let fire = self.with_level(|b, level, ticks| { + let fire = b.fire_state_for(level, ticks, at); + b.can_survive(level, ticks, at, fire).then_some(fire) + }); + if let Some(fire) = fire { let _ = self.level_set(p, fire); } } @@ -219,7 +272,10 @@ impl Game<'_> { pitch, ); if !b.visual_only { - self.bolt_fire(b.at, 4); + // Only Normal and Hard start fires with the strike itself. + if self.ui.difficulty >= 2 { + self.bolt_fire(b.at, 4); + } self.strike_rod(b.at); } } diff --git a/crates/horizon-client/src/game/mace.rs b/crates/horizon-client/src/game/mace.rs index 8ad5e76c3..34c968980 100644 --- a/crates/horizon-client/src/game/mace.rs +++ b/crates/horizon-client/src/game/mace.rs @@ -24,7 +24,7 @@ const KNOCKBACK_POWER: f32 = 0.7; /// `Entity.isAlliedTo` between the player (`player` its UUID) and a mob /// without teams: `TamableAnimal.considersEntityAsAlly` (a pet it tamed) and /// `Allay.considersEntityAsAlly` (an allay that likes it). -fn ally_of_player(m: &Mob, player: Option<[i32; 4]>) -> bool { +pub(super) fn ally_of_player(m: &Mob, player: Option<[i32; 4]>) -> bool { let tamable = matches!( m.species(), Species::Wolf diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index 8742962e9..bb936744b 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -159,8 +159,10 @@ impl Containers<'_> { }); } let entity = self.world.block_entities.get(&pos)?; - // A beehive keeps bees, not items: it is no `Container`. - if matches!(entity, BlockEntity::Beehive(_)) { + // A beehive keeps bees, not items, and a campfire cooks its own: neither + // is a `Container` (HopperBlockEntity.getContainerAt), so a dropper drops + // in front of them and a hopper leaves them alone. + if matches!(entity, BlockEntity::Beehive(_) | BlockEntity::Campfire(_)) { return None; } let kind = match (entity, name) { diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index a19b6df73..072059e49 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -87,9 +87,12 @@ pub(super) struct Minecart { pub fuse: i32, /// Hopper minecarts: an unpowered activator rail enables them. pub enabled: bool, + /// Chest minecarts: the loot table rolled into `items` on load, saved + /// again while the items are still that roll. + pub loot: Option, } -const WIDTH: f64 = 0.98; -const HEIGHT: f64 = 0.7; +pub(super) const WIDTH: f64 = 0.98; +pub(super) const HEIGHT: f64 = 0.7; /// AbstractMinecart.getDefaultDisplayOffset, in sixteenths of a block. fn display_offset(kind: CartKind) -> f64 { if kind == CartKind::Hopper { 1.0 } else { 6.0 } @@ -97,7 +100,7 @@ fn display_offset(kind: CartKind) -> f64 { /// The minecart's passenger attachment minus Player.DEFAULT_VEHICLE_ATTACHMENT. pub(super) const SEAT: f64 = 0.1875 - 0.6; /// The placeholder container key under which an open cart's items live. -pub(super) const CART_KEY_Y: i32 = -100_000; +pub(super) const CART_KEY_Y: i32 = horizon_client::lan::menu::VEHICLE_KEY_Y; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(super) enum Shape { @@ -182,6 +185,7 @@ impl Minecart { push: [0.0; 2], fuse: -1, enabled: true, + loot: None, } } pub fn bounds(&self) -> Aabb { @@ -1527,6 +1531,12 @@ impl Minecart { } CartKind::Rideable => {} } + // A loaded loot table goes back while the items are still its roll; + // otherwise the items replace it, as vanilla's unpackLootTable does. + if !self.loot.as_ref().is_some_and(|l| l.restore(map)) { + map.remove(&JavaString::from("LootTable")); + map.remove(&JavaString::from("LootTableSeed")); + } } tag } diff --git a/crates/horizon-client/src/game/mob_blocks.rs b/crates/horizon-client/src/game/mob_blocks.rs index 083c96a66..a0ce5e9db 100644 --- a/crates/horizon-client/src/game/mob_blocks.rs +++ b/crates/horizon-client/src/game/mob_blocks.rs @@ -1,6 +1,7 @@ //! Blocks mobs carry: block items in a hand (`ItemInHandLayer`) and the //! block an enderman holds (`CarriedBlockLayer`), drawn as shaded cubes like -//! dropped block items. +//! dropped block items. Also the block models mobs wear (`SnowGolemHeadLayer`, +//! `MushroomCowMushroomLayer`). use super::Game; use horizon_client::{ items::ItemStack, @@ -218,6 +219,7 @@ impl Game<'_> { ) { self.captain_banner_geometry(mob, camera, alpha, light, out); self.held_item_geometry(mob, camera, alpha, light, true, out); + self.worn_block_geometry(mob, camera, alpha, light, out); if mob.species() == Species::Enderman && let Some(state) = mob.extra.carried && let Some((sprite, tint)) = self.block_face_sprite(state) @@ -244,6 +246,76 @@ impl Game<'_> { ); } } + /// `SnowGolemHeadLayer` and `MushroomCowMushroomLayer`: the carved pumpkin + /// on a snow golem's head, and the mushrooms on an adult mooshroom's back + /// and head, as baked block models. + fn worn_block_geometry( + &self, + mob: &Mob, + camera: glam::DVec3, + alpha: f64, + light: u32, + out: &mut Vec, + ) { + use glam::{Mat4, Vec3}; + let species = mob.species(); + let on_head = match species { + Species::SnowGolem => !mob.extra.sheared, + Species::Mooshroom => !mob.is_baby(), + _ => false, + }; + // The layers draw nothing on an invisible mob (the glow outline is not drawn). + if !on_head || horizon_client::mobs::trader::is_invisible(mob) { + return; + } + let registry = &self.pack.assets.registry; + let block = match species { + Species::SnowGolem => "minecraft:carved_pumpkin", + _ if mob.extra.variant == 1 => "minecraft:brown_mushroom", + _ => "minecraft:red_mushroom", + }; + let Some(state) = registry.default_state(block) else { + return; + }; + let alpha = alpha as f32; + let Some(head) = render::part_transform(mob, alpha, camera, self.res.mob_data(), "head") + else { + return; + }; + let unit = Mat4::from_translation(Vec3::splat(-0.5)); + let flip = Mat4::from_scale(Vec3::new(-1.0, -1.0, 1.0)); + let at = |x: f32, y: f32, z: f32| Mat4::from_translation(Vec3::new(x, y, z)); + let spin = |degrees: f32| Mat4::from_rotation_y(degrees.to_radians()); + let transforms = if species == Species::SnowGolem { + vec![ + head * at(0.0, -0.34375, 0.0) + * spin(180.0) + * Mat4::from_scale(Vec3::new(0.625, -0.625, -0.625)) + * unit, + ] + } else { + let base = render::base_transform(mob, alpha, camera); + vec![ + base * at(0.2, -0.35, 0.5) * spin(-48.0) * flip * unit, + base * at(0.2, -0.35, 0.5) + * spin(42.0) + * at(0.1, 0.0, -0.6) + * spin(-48.0) + * flip + * unit, + head * at(0.0, -0.7, -0.2) * spin(-78.0) * flip * unit, + ] + }; + // The hurt tint reaches these blocks as it does the body. + let overlay = horizon_client::overlay::living(0.0, mob.hurt_time > 0 || mob.death_time > 0); + for t in transforms { + let start = out.len(); + self.block_model_vertices(state, 0, t, light, true, out); + for vertex in &mut out[start..] { + vertex.layer = overlay; + } + } + } /// `ItemInHandLayer`: both hands through the item model pipeline; `lit` /// applies the level's diffuse lighting (off for GUI previews, which /// light the projected quads themselves). diff --git a/crates/horizon-client/src/game/mod_browser.rs b/crates/horizon-client/src/game/mod_browser.rs new file mode 100644 index 000000000..645415ccb --- /dev/null +++ b/crates/horizon-client/src/game/mod_browser.rs @@ -0,0 +1,485 @@ +//! Capability `ui`'s panel beside container screens (WIT `interface +//! browser`, docs/mods.md): the items a recipe viewer mod lists, drawn as +//! the game's own item slots in pages right of the screen's window, with a +//! search box under them. The mod says what the panel holds; the game pages +//! it and tells the mod what the player clicked, typed, and which of the +//! mod's keys went down over an item. With no mod showing a panel, each +//! hook here returns after one check. +use super::Game; +#[cfg(feature = "mods")] +use { + super::Screen, + horizon_client::{ + hud::{HudBatch, rgba}, + items::ItemStack, + ui::EditBox, + }, + horizon_mods::{BrowserClick, BrowserEvent, BrowserStack}, +}; + +#[cfg(not(feature = "mods"))] +impl Game<'_> { + pub(super) fn draw_mod_browser(&mut self, _batch: &mut horizon_client::hud::HudBatch) {} + pub(super) fn mod_browser_press(&mut self, _right: bool) -> bool { + false + } + pub(super) fn mod_browser_typing(&self) -> bool { + false + } + pub(super) fn mod_browser_key(&mut self, _event: &winit::event::KeyEvent) {} + pub(super) fn mod_browser_text(&mut self, _text: Option<&str>, _backspace: bool) {} + pub(super) fn mod_browser_closed(&mut self) {} +} + +/// One slot of the panel, in GUI pixels. +#[cfg(feature = "mods")] +const SLOT: f32 = 18.0; +/// The most columns the panel takes, and the fewest it shows with. +#[cfg(feature = "mods")] +const COLUMNS: (usize, usize) = (12, 2); +/// The gap between the window and the panel, and the screen's edges. +#[cfg(feature = "mods")] +const MARGIN: f32 = 8.0; + +/// The panel's state in the game. +#[cfg(feature = "mods")] +#[derive(Default)] +pub(super) struct Browser { + /// The items' owner and version they were made from. + of: Option<(usize, u64)>, + /// The mod's items as stacks; `None` for an item the game doesn't have. + stacks: Vec>, + page: usize, + search: Option, + /// The search text the mod last heard. + sent: String, + /// `set-recipes`' recipes, shown instead of the items. + pub(super) recipes: Option, +} + +/// Where the panel's parts are this frame. +#[cfg(feature = "mods")] +pub(super) struct Layout { + /// The panel's whole area, for clicks that hit none of its parts. + pub(super) area: [f32; 4], + /// The grid's top left corner, its columns and rows. + pub(super) grid: (f32, f32), + pub(super) columns: usize, + pub(super) rows: usize, + /// The page arrows' row. + pub(super) arrows_y: f32, + pub(super) search: [f32; 4], +} +#[cfg(feature = "mods")] +impl Layout { + fn per_page(&self) -> usize { + self.columns * self.rows + } + pub(super) fn width(&self) -> f32 { + self.columns as f32 * SLOT + } + fn slot(&self, n: usize) -> (f32, f32) { + ( + self.grid.0 + (n % self.columns) as f32 * SLOT, + self.grid.1 + (n / self.columns) as f32 * SLOT, + ) + } + /// The page arrows: backward, then forward. + pub(super) fn arrows(&self) -> [(f32, f32); 2] { + [ + (self.grid.0, self.arrows_y), + (self.grid.0 + self.width() - 12.0, self.arrows_y), + ] + } +} + +#[cfg(feature = "mods")] +pub(super) fn inside(p: (f32, f32), [x, y, w, h]: [f32; 4]) -> bool { + p.0 >= x && p.1 >= y && p.0 < x + w && p.1 < y + h +} + +#[cfg(feature = "mods")] +impl Game<'_> { + fn browser_batch(&self) -> Option { + let r = self.renderer.as_ref()?; + Some(HudBatch::new([r.config.width, r.config.height])) + } + /// The mod showing a panel, with its items made into stacks once per + /// `set-items`; none while no mod shows one or no container screen is up. + fn browser_sync(&mut self) -> Option { + if self.screen != Screen::Inventory || self.title.is_some() { + return None; + } + let Some((owner, version)) = self.mods.mods.browser_items().map(|(o, v, _)| (o, v)) else { + self.mods.browser.of = None; + self.mods.browser.stacks.clear(); + return None; + }; + if self.mods.browser.of != Some((owner, version)) { + let items = self.res.items(); + let stacks = self + .mods + .mods + .browser_items() + .map_or_else(Vec::new, |(_, _, list)| { + list.iter().map(|s| browser_stack(items, s)).collect() + }); + self.mods.browser.stacks = stacks; + // The same title again (the mod updating its buttons) keeps the page. + let old = self.mods.browser.recipes.take(); + self.mods.browser.recipes = self + .mods + .mods + .browser_recipes(owner) + .map(|shown| super::mod_browser_recipes::Pages::new(items, shown, old)); + self.mods.browser.of = Some((owner, version)); + } + Some(owner) + } + /// The panel's parts: right of the window, from the top of the screen to + /// the search box at its foot. None when the screen has no room for it. + fn browser_layout(&self, batch: &HudBatch) -> Option { + let image = self.container_image(batch); + let left = (image.left + image.width) as f32 + MARGIN; + let right = batch.width - MARGIN; + let columns = (((right - left) / SLOT).floor().max(0.0) as usize).min(COLUMNS.0); + if columns < COLUMNS.1 { + return None; + } + let x = (left + (right - left - columns as f32 * SLOT) / 2.0).floor(); + let arrows_y = MARGIN; + let top = arrows_y + 17.0 + 4.0; + let search = [x, batch.height - MARGIN - 16.0, columns as f32 * SLOT, 16.0]; + let rows = ((search[1] - 4.0 - top) / SLOT).floor().max(0.0) as usize; + (rows > 0).then_some(Layout { + area: [left, 0.0, right - left, batch.height], + grid: (x, top), + columns, + rows, + arrows_y, + search, + }) + } + fn browser_pages(&self, layout: &Layout) -> usize { + self.mods + .browser + .stacks + .len() + .div_ceil(layout.per_page()) + .max(1) + } + /// The stack under the pointer on the panel, an item's or a recipe's, + /// as the mod sent it and as a stack. + fn browser_pointed_stack(&self, layout: &Layout) -> Option<(BrowserStack, ItemStack)> { + if self.mods.browser.recipes.is_some() { + if let Some((_, sent, stack)) = self.recipe_tab_hovered(layout) { + return Some((sent, stack)); + } + let (_, _, sent, stack) = self.recipe_slot_hovered(layout)?; + return Some((sent, stack)); + } + let (index, stack) = self.browser_hovered(layout)?; + let (_, _, items) = self.mods.mods.browser_items()?; + Some((items.get(index)?.clone(), stack)) + } + /// The panel's item under the pointer: its index and stack. + fn browser_hovered(&self, layout: &Layout) -> Option<(usize, ItemStack)> { + if self.mods.browser.recipes.is_some() { + return None; + } + let first = self.mods.browser.page * layout.per_page(); + (0..layout.per_page()).find_map(|n| { + let (x, y) = layout.slot(n); + if !inside(self.cursor, [x, y, SLOT, SLOT]) { + return None; + } + let stack = self.mods.browser.stacks.get(first + n)?.clone()?; + Some((first + n, stack)) + }) + } + fn browser_search(&mut self, layout: &Layout) -> &mut EditBox { + let search = self.mods.browser.search.get_or_insert_with(|| { + let mut edit = EditBox::new(0.0, 0.0, 0.0, 0.0); + edit.max_length = 50; + edit.focused = false; + edit + }); + [search.x, search.y, search.width, search.height] = layout.search; + search + } + + /// The items' page arrows and grid. + fn draw_browser_items(&mut self, batch: &mut HudBatch, layout: &Layout) { + let pages = self.browser_pages(layout); + self.mods.browser.page = self.mods.browser.page.min(pages - 1); + let page = self.mods.browser.page; + let cursor = self.cursor; + if pages > 1 { + let labels = [ + self.translate("gui.recipebook.previous_page", "Previous Page"), + self.translate("gui.recipebook.next_page", "Next Page"), + ]; + let shown = [page > 0, page + 1 < pages]; + let atlas = &self.gui.atlas; + for (((x, y), name), (label, shown)) in layout + .arrows() + .into_iter() + .zip(["page_backward", "page_forward"]) + .zip(labels.iter().zip(shown)) + { + if !shown { + continue; + } + let hover = inside(cursor, [x, y, 12.0, 17.0]); + let suffix = if hover { "_highlighted" } else { "" }; + batch.sprite( + atlas, + &format!("gui/sprites/recipe_book/{name}{suffix}"), + x, + y, + ); + horizon_client::widgets::record(label, [x, y, 12.0, 17.0], true); + } + let text = format!("{}/{pages}", page + 1); + let w = HudBatch::text_width(atlas, &text); + let x = (layout.grid.0 + (layout.width() - w) / 2.0).floor(); + batch.text(atlas, &text, x, layout.arrows_y + 5.0, u32::MAX, true); + } + let first = page * layout.per_page(); + for n in 0..layout.per_page() { + let Some(stack) = self.mods.browser.stacks.get(first + n) else { + break; + }; + let Some(stack) = stack.clone() else { + continue; + }; + let (x, y) = layout.slot(n); + self.draw_item(batch, &stack, x + 1.0, y + 1.0); + let rect = [x + 1.0, y + 1.0, 16.0, 16.0]; + if inside(cursor, [x, y, SLOT, SLOT]) { + batch.fill( + &self.gui.atlas, + x + 1.0, + y + 1.0, + 16.0, + 16.0, + rgba(255, 255, 255, 128), + ); + } + let name = self.pack.names.display_item(&stack.item); + horizon_client::widgets::record_as( + &name, + rect, + true, + horizon_client::widgets::Kind::Button, + ); + } + } + /// Draws the panel over the open container screen, then the carried + /// stack or the tooltip again so they stay on top of it. + pub(super) fn draw_mod_browser(&mut self, batch: &mut HudBatch) { + if self.browser_sync().is_none() { + return; + } + let Some(layout) = self.browser_layout(batch) else { + return; + }; + let cursor = self.cursor; + if self.mods.browser.recipes.is_some() { + self.draw_browser_recipes(batch, &layout); + } else { + self.draw_browser_items(batch, &layout); + } + let hint = self.translate("gui.recipebook.search_hint", "Search..."); + let search = self.browser_search(&layout); + // The hint shows in an empty box without focus, as the recipe book's. + search.suggestion = (search.value.is_empty() && !search.focused).then_some(hint); + let mut search = search.clone(); + search.draw(batch, &self.gui.atlas, None); + self.mods.browser.search = Some(search); + if self.carried.is_some() { + self.draw_carried(batch); + } else if let Some(stack) = self.browser_pointed_stack(&layout) { + let lines = self.stack_tooltip(&stack.1); + self.draw_tooltip_lines(batch, &lines, cursor.0, cursor.1); + } else { + self.draw_slot_tooltip(batch); + } + } + + /// A mouse press on a container screen: true when the panel took it + /// (its search box, page arrows, items or empty space; a click there + /// never throws the carried stack). + pub(super) fn mod_browser_press(&mut self, right: bool) -> bool { + let Some(owner) = self.browser_sync() else { + return false; + }; + let Some(batch) = self.browser_batch() else { + return false; + }; + let Some(layout) = self.browser_layout(&batch) else { + return false; + }; + let cursor = self.cursor; + let shift = self.has_shift_down(); + let atlas = &self.gui.atlas; + let search = self.mods.browser.search.get_or_insert_with(|| { + let mut edit = EditBox::new(0.0, 0.0, 0.0, 0.0); + edit.max_length = 50; + edit + }); + [search.x, search.y, search.width, search.height] = layout.search; + if inside(cursor, layout.search) { + search.focused = true; + search.click(atlas, cursor.0, shift, false); + search.reset_blink(); + return true; + } + search.focused = false; + if self.mods.browser.recipes.is_some() { + return self.browser_recipes_press(&layout, owner, right) + || inside(cursor, layout.area); + } + let pages = self.browser_pages(&layout); + let page = self.mods.browser.page; + let [back, forward] = layout.arrows(); + let step = if pages > 1 && page > 0 && inside(cursor, [back.0, back.1, 12.0, 17.0]) { + Some(page - 1) + } else if pages > 1 + && page + 1 < pages + && inside(cursor, [forward.0, forward.1, 12.0, 17.0]) + { + Some(page + 1) + } else { + None + }; + if let Some(to) = step { + self.mods.browser.page = to; + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); + return true; + } + if let Some((index, _)) = self.browser_hovered(&layout) { + let event = BrowserEvent::Clicked(BrowserClick { + index: index as u32, + right, + }); + self.mods.mods.browser_event(owner, event); + return true; + } + inside(cursor, layout.area) + } + + /// Whether keys go to the panel's search box. + pub(super) fn mod_browser_typing(&self) -> bool { + self.screen == Screen::Inventory + && self.mods.browser.of.is_some() + && self.mods.browser.search.as_ref().is_some_and(|s| s.focused) + } + /// A key press while the search box has focus. + pub(super) fn mod_browser_key(&mut self, event: &winit::event::KeyEvent) { + use winit::keyboard::PhysicalKey; + let shortcut = self.edit_shortcut(event); + let ctrl = self.has_control_down(); + let shift = self.has_shift_down(); + let Some(search) = self.mods.browser.search.as_mut() else { + return; + }; + if let Some(shortcut) = shortcut { + search.shortcut(shortcut, &mut self.clipboard); + } else { + let handled = match event.physical_key { + PhysicalKey::Code(code) => search.key(code, ctrl, shift), + _ => false, + }; + if !handled + && !ctrl + && let Some(text) = &event.text + { + let text: String = text.chars().filter(|c| !c.is_control()).collect(); + search.insert_text(&text); + } + } + search.reset_blink(); + self.browser_searched(); + } + /// Text typed (or one backspace) into the search box (`horizon-ctl type`). + pub(super) fn mod_browser_text(&mut self, text: Option<&str>, backspace: bool) { + let Some(search) = self.mods.browser.search.as_mut() else { + return; + }; + if backspace { + search.delete_chars(-1); + } else if let Some(text) = text { + search.insert_text(text); + } + self.browser_searched(); + } + /// The mod hears the search text when it changed. + fn browser_searched(&mut self) { + let (Some((owner, _)), Some(search)) = (self.mods.browser.of, &self.mods.browser.search) + else { + return; + }; + if search.value != self.mods.browser.sent { + let value = search.value.clone(); + self.mods.browser.sent.clone_from(&value); + self.mods.browser.page = 0; + self.mods + .mods + .browser_event(owner, BrowserEvent::Search(value)); + } + } + /// The container screen closed: the search box lets go of the keys. + pub(super) fn mod_browser_closed(&mut self) { + if let Some(search) = self.mods.browser.search.as_mut() { + search.focused = false; + } + } + /// The item under the pointer on a container screen, for the mods' keys + /// (`browser`'s `key` event): the panel's, else a slot's. + pub(super) fn mod_browser_pointed(&mut self) -> Option { + let batch = self.browser_batch()?; + let stack = match self + .browser_sync() + .and_then(|_| self.browser_layout(&batch)) + { + // The panel's stacks as the mod sent them. + Some(layout) if inside(self.cursor, layout.area) => { + return Some(self.browser_pointed_stack(&layout)?.0); + } + _ => { + let slot = self.slot_at(&batch, self.cursor.0, self.cursor.1)?; + self.slot_view(slot)? + } + }; + Some(BrowserStack { + item: stack.item.to_string(), + count: stack.count, + components: super::mod_recipes::components(&stack), + }) + } +} + +/// A mod's item as a stack: an item the game has, its components read as +/// `/give` reads them (ones it can't read are left out). +#[cfg(feature = "mods")] +pub(super) fn browser_stack( + items: &horizon_client::items::Items, + s: &BrowserStack, +) -> Option { + items.get(&s.item)?; + let (damage, extra) = if s.components.is_empty() { + (0, None) + } else { + horizon_client::item_data::command_components(&s.components).map_or((0, None), |tag| { + horizon_client::item_data::decode_components(Some(&tag)) + }) + }; + Some(ItemStack { + item: s.item.as_str().into(), + count: s.count.clamp(1, 99), + damage, + extra, + }) +} diff --git a/crates/horizon-client/src/game/mod_browser_recipes.rs b/crates/horizon-client/src/game/mod_browser_recipes.rs new file mode 100644 index 000000000..557ae9029 --- /dev/null +++ b/crates/horizon-client/src/game/mod_browser_recipes.rs @@ -0,0 +1,523 @@ +//! `browser.set-recipes` (docs/mods.md): a mod's recipes shown in its item +//! panel's place, laid out by the game with its own slots, arrows and +//! buttons, paged to the panel's height, under a title and a back button. +//! The mod hears clicks on their slots, their action buttons, the back +//! button and page turns. +use super::{ + Game, + mod_browser::{Layout, browser_stack, inside}, +}; +use horizon_client::{ + hud::{HudBatch, rgba}, + items::ItemStack, +}; +use horizon_mods::{BrowserEvent, BrowserLayout, BrowserSlotClick, BrowserStack, RecipePage}; +use std::time::Instant; + +const SLOT: f32 = 18.0; +/// The title row's height, and the gap under each recipe. +const TITLE: f32 = 18.0; +/// A tab's step: an 18 px slot and a gap. +const TAB: f32 = 20.0; +const GAP: f32 = 6.0; + +/// One recipe as the game draws it. +pub(super) struct Shown { + layout: BrowserLayout, + width: usize, + height: usize, + /// Each slot's stacks (the result last), as the mod sent them and as + /// stacks; a stack the game doesn't have is left out of the cycle. + slots: Vec>, + note: String, + action: Option, +} + +/// The recipes a panel shows, and its page. +pub(super) struct Pages { + title: String, + /// The tabs' icons and the selected one. + tabs: Vec<(BrowserStack, Option)>, + tab: usize, + recipes: Vec, + page: usize, + since: Instant, +} + +impl Pages { + pub(super) fn new( + items: &horizon_client::items::Items, + shown: &RecipePage, + old: Option, + ) -> Self { + let (title, list, tab) = (&shown.title, &shown.recipes, shown.tab as usize); + let kept = old.filter(|o| o.title == *title && o.tab == tab); + let cycle = |stacks: &[BrowserStack]| -> Vec<(BrowserStack, ItemStack)> { + stacks + .iter() + .filter_map(|s| Some((s.clone(), browser_stack(items, s)?))) + .collect() + }; + let recipes = list + .iter() + .map(|r| { + let mut slots: Vec<_> = r.slots.iter().map(|s| cycle(s)).collect(); + slots.push(cycle(&r.results)); + Shown { + layout: r.layout, + width: r.width as usize, + height: r.height as usize, + slots, + note: r.note.clone(), + action: r.action, + } + }) + .collect(); + Self { + title: title.clone(), + tabs: shown + .tabs + .iter() + .map(|t| (t.clone(), browser_stack(items, t))) + .collect(), + tab, + recipes, + page: kept.as_ref().map_or(0, |o| o.page), + since: kept.map_or_else(Instant::now, |o| o.since), + } + } +} + +impl Shown { + /// The inputs' block: its size and each input slot's place in it. + fn inputs(&self) -> ((f32, f32), Vec<(f32, f32)>) { + let row = |n: usize| (0..n).map(|i| (i as f32 * SLOT, 0.0)).collect(); + match self.layout { + BrowserLayout::Grid => { + let (w, h) = (self.width.max(1), self.height.max(1)); + let at = (0..w * h) + .map(|i| ((i % w) as f32 * SLOT, (i / w) as f32 * SLOT)) + .collect(); + ((w as f32 * SLOT, h as f32 * SLOT), at) + } + // The input over the flame. + BrowserLayout::Cooking => ((SLOT, 2.0 * SLOT), vec![(0.0, 0.0)]), + BrowserLayout::Single => ((SLOT, SLOT), row(1)), + BrowserLayout::Smithing => ((3.0 * SLOT, SLOT), row(3)), + BrowserLayout::Brewing => ((2.0 * SLOT, SLOT), row(2)), + } + } + /// The height of its slots, arrow and button, `room` wide. + fn block(&self, room: f32) -> f32 { + let h = self.inputs().0.1; + let (_, _, action) = self.places(room); + match self.action { + Some(_) => h.max(action.1 + 12.0), + None => h, + } + } + fn height(&self, room: f32) -> f32 { + let note = if self.note.is_empty() { 0.0 } else { 11.0 }; + self.block(room) + note + GAP + } + /// Every slot's place from the recipe's corner (the result last), the + /// arrow's and the action button's: beside the result, or under it + /// when the panel is `room` wide and that doesn't fit. + fn places(&self, room: f32) -> (Vec<(f32, f32)>, (f32, f32), (f32, f32)) { + let ((w, h), mut at) = self.inputs(); + // The mod's slots beyond the layout's are not shown. + at.truncate(self.slots.len() - 1); + let arrow = (w + 4.0, ((h - 16.0) / 2.0).floor()); + let result = (w + 32.0, ((h - SLOT) / 2.0).floor()); + let action = if result.0 + SLOT + 16.0 <= room { + (result.0 + SLOT + 4.0, ((h - 12.0) / 2.0).floor()) + } else { + (result.0 + 3.0, result.1 + SLOT + 2.0) + }; + while at.len() < self.slots.len() - 1 { + at.push((f32::NAN, f32::NAN)); + } + at.push(result); + (at, arrow, action) + } +} + +/// The tabs' places, in rows under the title row. +fn tab_places(pages: &Pages, layout: &Layout) -> Vec<(f32, f32)> { + let per_row = ((layout.width() / TAB).floor() as usize).max(1); + (0..pages.tabs.len()) + .map(|i| { + ( + layout.grid.0 + (i % per_row) as f32 * TAB, + layout.grid.1 + TITLE + 3.0 + (i / per_row) as f32 * TAB, + ) + }) + .collect() +} +/// Where the recipes start: under the title row and the tabs. +fn recipes_top(pages: &Pages, layout: &Layout) -> f32 { + let tabs = tab_places(pages, layout); + tabs.last() + .map_or(layout.grid.1 + TITLE, |&(_, y)| y + TAB + 3.0) +} + +impl Game<'_> { + /// The first recipe of each page, filling the panel from the tabs to + /// the search box. + fn recipe_pages(pages: &Pages, layout: &Layout) -> Vec { + let room = layout.search[1] - 4.0 - recipes_top(pages, layout); + let mut starts = vec![0]; + let mut used = 0.0; + for (i, r) in pages.recipes.iter().enumerate() { + let h = r.height(layout.width()); + if used > 0.0 && used + h > room { + starts.push(i); + used = 0.0; + } + used += h; + } + starts + } + /// The recipes on the open page, each with its corner. + fn recipes_shown(&self, layout: &Layout) -> Vec<(usize, (f32, f32))> { + let Some(pages) = &self.mods.browser.recipes else { + return Vec::new(); + }; + let starts = Self::recipe_pages(pages, layout); + let page = pages.page.min(starts.len() - 1); + let end = starts.get(page + 1).copied().unwrap_or(pages.recipes.len()); + let mut y = recipes_top(pages, layout); + (starts[page]..end) + .map(|i| { + let at = (layout.grid.0, y); + y += pages.recipes[i].height(layout.width()); + (i, at) + }) + .collect() + } + fn back_button(&self, layout: &Layout) -> ([f32; 4], String) { + let label = self.translate("gui.back", "Back"); + let w = HudBatch::text_width(&self.gui.atlas, &label) + 8.0; + ([layout.grid.0, layout.grid.1, w, 14.0], label) + } + /// What a slot of a shown recipe holds now: its stacks cycle once a second. + fn recipe_slot_now(&self, recipe: usize, slot: usize) -> Option<&(BrowserStack, ItemStack)> { + let pages = self.mods.browser.recipes.as_ref()?; + let stacks = pages.recipes.get(recipe)?.slots.get(slot)?; + let n = pages.since.elapsed().as_secs() as usize; + stacks.get(n % stacks.len().max(1)) + } + /// The tab under the pointer: its index and icon. + pub(super) fn recipe_tab_hovered( + &self, + layout: &Layout, + ) -> Option<(usize, BrowserStack, ItemStack)> { + let pages = self.mods.browser.recipes.as_ref()?; + let places = tab_places(pages, layout); + places.iter().enumerate().find_map(|(i, &(x, y))| { + if !inside(self.cursor, [x, y, SLOT, SLOT]) { + return None; + } + let (sent, stack) = pages.tabs.get(i)?; + Some((i, sent.clone(), stack.clone()?)) + }) + } + /// The recipe slot under the pointer: recipe, slot, and its stack now. + pub(super) fn recipe_slot_hovered( + &self, + layout: &Layout, + ) -> Option<(usize, usize, BrowserStack, ItemStack)> { + let pages = self.mods.browser.recipes.as_ref()?; + self.recipes_shown(layout) + .into_iter() + .find_map(|(i, (x, y))| { + let (at, _, _) = pages.recipes[i].places(layout.width()); + at.iter().enumerate().find_map(|(k, &(sx, sy))| { + if !inside(self.cursor, [x + sx, y + sy, SLOT, SLOT]) { + return None; + } + let (mod_stack, stack) = self.recipe_slot_now(i, k)?.clone(); + Some((i, k, mod_stack, stack)) + }) + }) + } + + /// Draws the title row, the page's recipes and the page arrows. + pub(super) fn draw_browser_recipes(&mut self, batch: &mut HudBatch, layout: &Layout) { + let Some(pages) = &self.mods.browser.recipes else { + return; + }; + let cursor = self.cursor; + let starts = Self::recipe_pages(pages, layout); + let page = pages.page.min(starts.len() - 1); + let (title, pages_n) = (pages.title.clone(), starts.len()); + let (back, label) = self.back_button(layout); + let atlas = &self.gui.atlas; + let hover = inside(cursor, back); + let sprite = if hover { + "gui/sprites/widget/button_highlighted" + } else { + "gui/sprites/widget/button" + }; + horizon_client::ui::nine_slice( + batch, + atlas, + sprite, + back[0], + back[1], + back[2], + back[3], + u32::MAX, + ); + batch.text(atlas, &label, back[0] + 4.0, back[1] + 3.0, u32::MAX, true); + horizon_client::widgets::record(&label, back, true); + let room = layout.width() - back[2] - 4.0; + // Cut to the panel with vanilla's ellipsis (CommonComponents.ELLIPSIS). + let shown = if atlas.font.fit(&title, room) >= title.chars().count() { + title + } else { + let fit = atlas.font.fit(&title, room - atlas.font.width("...")); + let kept: String = title.chars().take(fit).collect(); + format!("{}...", kept.trim_end()) + }; + batch.text( + atlas, + &shown, + back[0] + back[2] + 4.0, + back[1] + 3.0, + u32::MAX, + true, + ); + self.draw_recipe_tabs(batch, layout); + if pages_n > 1 { + let labels = [ + self.translate("gui.recipebook.previous_page", "Previous Page"), + self.translate("gui.recipebook.next_page", "Next Page"), + ]; + let visible = [page > 0, page + 1 < pages_n]; + let atlas = &self.gui.atlas; + for (((x, y), name), (label, visible)) in layout + .arrows() + .into_iter() + .zip(["page_backward", "page_forward"]) + .zip(labels.iter().zip(visible)) + { + if !visible { + continue; + } + let suffix = if inside(cursor, [x, y, 12.0, 17.0]) { + "_highlighted" + } else { + "" + }; + batch.sprite( + atlas, + &format!("gui/sprites/recipe_book/{name}{suffix}"), + x, + y, + ); + horizon_client::widgets::record(label, [x, y, 12.0, 17.0], true); + } + let text = format!("{}/{pages_n}", page + 1); + let w = HudBatch::text_width(atlas, &text); + let x = (layout.grid.0 + (layout.width() - w) / 2.0).floor(); + batch.text(atlas, &text, x, layout.arrows_y + 5.0, u32::MAX, true); + } + for (i, (x, y)) in self.recipes_shown(layout) { + let Some(r) = self.mods.browser.recipes.as_ref().map(|p| &p.recipes[i]) else { + break; + }; + let (at, arrow, action) = r.places(layout.width()); + let h = r.block(layout.width()); + let (cooking, note, button) = + (r.layout == BrowserLayout::Cooking, r.note.clone(), r.action); + let atlas = &self.gui.atlas; + for &(sx, sy) in at.iter().filter(|p| p.0.is_finite()) { + batch.sprite(atlas, "gui/sprites/container/slot", x + sx, y + sy); + } + if cooking { + batch.sprite( + atlas, + "gui/sprites/container/furnace/lit_progress", + x + 2.0, + y + SLOT + 2.0, + ); + } + batch.sprite( + atlas, + "gui/sprites/container/furnace/burn_progress", + x + arrow.0, + y + arrow.1, + ); + if let Some(enabled) = button { + let rect = [x + action.0, y + action.1, 12.0, 12.0]; + let sprite = match (enabled, inside(cursor, rect)) { + (false, _) => "gui/sprites/widget/button_disabled", + (true, true) => "gui/sprites/widget/button_highlighted", + (true, false) => "gui/sprites/widget/button", + }; + horizon_client::ui::nine_slice( + batch, + atlas, + sprite, + rect[0], + rect[1], + 12.0, + 12.0, + u32::MAX, + ); + let color = if enabled { + u32::MAX + } else { + rgba(160, 160, 160, 255) + }; + batch.text(atlas, "+", rect[0] + 3.0, rect[1] + 2.0, color, true); + horizon_client::widgets::record(&format!("+ {i}"), rect, enabled); + } + if !note.is_empty() { + batch.text(atlas, ¬e, x, y + h + 2.0, rgba(224, 224, 224, 255), true); + } + for (k, &(sx, sy)) in at.iter().enumerate().filter(|(_, p)| p.0.is_finite()) { + let Some((_, stack)) = self.recipe_slot_now(i, k).cloned() else { + continue; + }; + self.draw_item(batch, &stack, x + sx + 1.0, y + sy + 1.0); + if inside(cursor, [x + sx, y + sy, SLOT, SLOT]) { + batch.fill( + &self.gui.atlas, + x + sx + 1.0, + y + sy + 1.0, + 16.0, + 16.0, + rgba(255, 255, 255, 128), + ); + } + let name = self.pack.names.display_item(&stack.item); + horizon_client::widgets::record_as( + &format!("{name} {i}:{k}"), + [x + sx + 1.0, y + sy + 1.0, 16.0, 16.0], + true, + horizon_client::widgets::Kind::Button, + ); + } + } + } + + /// The tabs, on slots; the selected one framed. + fn draw_recipe_tabs(&mut self, batch: &mut HudBatch, layout: &Layout) { + let Some(pages) = &self.mods.browser.recipes else { + return; + }; + let places = tab_places(pages, layout); + let tabs: Vec> = pages.tabs.iter().map(|t| t.1.clone()).collect(); + let selected = pages.tab; + for (i, (&(x, y), stack)) in places.iter().zip(tabs).enumerate() { + let atlas = &self.gui.atlas; + batch.sprite(atlas, "gui/sprites/container/slot", x, y); + let Some(stack) = stack else { + continue; + }; + self.draw_item(batch, &stack, x + 1.0, y + 1.0); + // The selected tab: a white frame around its slot. + if i == selected { + let white = rgba(255, 255, 255, 255); + let atlas = &self.gui.atlas; + batch.fill(atlas, x - 1.0, y - 1.0, SLOT + 2.0, 1.0, white); + batch.fill(atlas, x - 1.0, y + SLOT, SLOT + 2.0, 1.0, white); + batch.fill(atlas, x - 1.0, y, 1.0, SLOT, white); + batch.fill(atlas, x + SLOT, y, 1.0, SLOT, white); + } + if inside(self.cursor, [x, y, SLOT, SLOT]) { + batch.fill( + &self.gui.atlas, + x + 1.0, + y + 1.0, + 16.0, + 16.0, + rgba(255, 255, 255, 128), + ); + } + let name = self.pack.names.display_item(&stack.item); + horizon_client::widgets::record_as( + &format!("{name} tab"), + [x + 1.0, y + 1.0, 16.0, 16.0], + true, + horizon_client::widgets::Kind::Tab(i == selected), + ); + } + } + + /// A press on the recipes: true when it hit one of their parts. + pub(super) fn browser_recipes_press( + &mut self, + layout: &Layout, + owner: usize, + right: bool, + ) -> bool { + let Some(pages) = &self.mods.browser.recipes else { + return false; + }; + let cursor = self.cursor; + let starts = Self::recipe_pages(pages, layout); + let page = pages.page.min(starts.len() - 1); + let [back_arrow, forward] = layout.arrows(); + let turn = if page > 0 && inside(cursor, [back_arrow.0, back_arrow.1, 12.0, 17.0]) { + Some(page - 1) + } else if page + 1 < starts.len() && inside(cursor, [forward.0, forward.1, 12.0, 17.0]) { + Some(page + 1) + } else { + None + }; + if let Some(to) = turn { + if let Some(p) = self.mods.browser.recipes.as_mut() { + p.page = to; + } + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); + self.mods + .mods + .browser_event(owner, BrowserEvent::Page(starts[to] as u32)); + return true; + } + if let Some((tab, _, _)) = self.recipe_tab_hovered(layout) { + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); + self.mods + .mods + .browser_event(owner, BrowserEvent::Tab(tab as u32)); + return true; + } + if inside(cursor, self.back_button(layout).0) { + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); + self.mods.mods.browser_event(owner, BrowserEvent::Back); + return true; + } + if let Some((recipe, slot, stack, _)) = self.recipe_slot_hovered(layout) { + let event = BrowserEvent::SlotClicked(BrowserSlotClick { + recipe: recipe as u32, + slot: slot as u32, + stack, + right, + }); + self.mods.mods.browser_event(owner, event); + return true; + } + let action = self.recipes_shown(layout).into_iter().find(|&(i, (x, y))| { + let r = &pages.recipes[i]; + let (_, _, (ax, ay)) = r.places(layout.width()); + r.action.is_some() && inside(cursor, [x + ax, y + ay, 12.0, 12.0]) + }); + if let Some((i, _)) = action { + if pages.recipes[i].action == Some(true) { + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); + self.mods + .mods + .browser_event(owner, BrowserEvent::Action(i as u32)); + } + return true; + } + false + } +} diff --git a/crates/horizon-client/src/game/mod_input.rs b/crates/horizon-client/src/game/mod_input.rs index 10faf6a81..3df62c3d4 100644 --- a/crates/horizon-client/src/game/mod_input.rs +++ b/crates/horizon-client/src/game/mod_input.rs @@ -111,6 +111,18 @@ impl Game<'_> { if repeat || !self.mods.mods.has_keys() { return; } + // Over an item on a container screen, the mods' keys are `browser` + // events (a recipe viewer's R and U). + if pressed + && self.screen == Screen::Inventory + && self.title.is_none() + && !self.mod_browser_typing() + && let Some(name) = horizon_client::keybinds::key_name(key) + && let Some(stack) = self.mod_browser_pointed() + { + self.mods.mods.browser_key(name, &stack); + return; + } if pressed && (self.screen != Screen::Playing || self.title.is_some()) { return; } diff --git a/crates/horizon-client/src/game/mod_recipes.rs b/crates/horizon-client/src/game/mod_recipes.rs new file mode 100644 index 000000000..b97944e39 --- /dev/null +++ b/crates/horizon-client/src/game/mod_recipes.rs @@ -0,0 +1,274 @@ +//! Capability `recipes` (docs/mods.md): every item and recipe the game +//! knows, made once for the mods that read them, and the recipe book's +//! known displays. The recipes are the window's own data: the world's in +//! single player, vanilla's on a server (a client is sent no others), while +//! the known displays follow the server's book as the recipe book does. +use super::Game; +use horizon_client::{ + crafting::Ingredient, + items::ItemStack, + recipe_book::{Category, Display}, + stations::Smithing, +}; +use horizon_mods::{Recipe, RecipeItem, RecipeKind, RecipeStack, Recipes}; +use std::{collections::HashMap, sync::Arc}; + +/// Item id -> its index in [`Recipes::items`]. +struct Index(HashMap, u32>); +impl Index { + fn stack(&self, item: &str, count: u32, components: String) -> Option { + Some(RecipeStack { + item: *self.0.get(item)?, + count, + components, + }) + } + fn of(&self, s: &ItemStack) -> Option { + self.stack(&s.item, s.count, components(s)) + } + fn any(&self, i: &Ingredient) -> Vec { + i.1.iter() + .filter_map(|id| self.stack(id, 1, String::new())) + .collect() + } +} + +/// A stack's components beyond its item's, as vanilla's item syntax writes +/// them (`[minecraft:potion_contents={potion:"minecraft:swiftness"}]`), or "". +pub(super) fn components(s: &ItemStack) -> String { + use horizon_world::nbt::Tag; + let Some(Tag::Compound(entries)) = horizon_client::item_data::encode_components(s) else { + return String::new(); + }; + let parts: Vec = entries + .iter() + .map(|(k, v)| { + format!( + "{}={}", + k.to_string_lossy(), + horizon_client::snbt::to_snbt(v) + ) + }) + .collect(); + format!("[{}]", parts.join(",")) +} + +fn recipe(id: String, kind: RecipeKind) -> Recipe { + Recipe { + id, + kind, + category: String::new(), + group: String::new(), + width: 0, + height: 0, + slots: Vec::new(), + results: Vec::new(), + cooking_time: 0, + experience: 0.0, + book_id: -1, + } +} + +impl Game<'_> { + /// `recipes.give`: a creative player takes the stack as from the + /// creative inventory; a server hears it as `SetCreativeModeSlot` + /// through the inventory's sync, and refuses it unless creative. + pub(super) fn mod_give(&mut self, item: &str, count: u32, components: &str) { + let Some(max) = self.res.items().get(item).map(|i| i.max_stack) else { + return; + }; + if !self.creative { + return; + } + let (damage, extra) = horizon_client::item_data::command_components(components) + .map_or((0, None), |tag| { + horizon_client::item_data::decode_components(Some(&tag)) + }); + let _ = self.give(ItemStack { + item: item.into(), + // One stack at most, as the creative inventory hands out. + count: count.min(max), + damage, + extra, + }); + } + /// Capability `recipes`'s tables and known displays for this tick's + /// snapshot; nothing while no running mod reads them. + pub(super) fn mod_recipes(&mut self) -> (Option>, Arc<[i32]>) { + if !self.mods.mods.wants_recipes() { + return (None, Arc::from([])); + } + if self.mods.recipes.is_none() { + self.mods.recipes = Some(Arc::new(self.make_mod_recipes())); + } + let (version, known) = self.recipe_book_displays(); + if self.mods.known_recipes.0 != Some(version) { + self.mods.known_recipes = (Some(version), known.into()); + } + (self.mods.recipes.clone(), self.mods.known_recipes.1.clone()) + } + + fn make_mod_recipes(&mut self) -> Recipes { + let names = &self.pack.names; + let items = self.res.items(); + let mut tags: HashMap<&str, Vec> = HashMap::new(); + for (tag, members) in &items.item_tags { + for m in members { + tags.entry(m).or_default().push(tag.clone()); + } + } + let table: Vec = items + .registry_order + .iter() + .map(|id| RecipeItem { + id: id.to_string(), + name: names.display_item(id), + tags: tags.remove(&**id).map_or_else(Vec::new, |mut t| { + t.sort(); + t + }), + }) + .collect(); + let index = Index( + items + .registry_order + .iter() + .enumerate() + .map(|(i, id)| (id.clone(), i as u32)) + .collect(), + ); + let mut out = Vec::new(); + let cooking: HashMap = self + .res + .recipes() + .cooking + .iter() + .map(|c| (format!("minecraft:{}", c.id), (c.time, c.experience))) + .collect(); + for e in self.recipe_book_entries() { + let furnace = |c: Category| match c.name().split('_').next() { + Some("blast") => RecipeKind::Blasting, + Some("smoker") => RecipeKind::Smoking, + _ => RecipeKind::Smelting, + }; + let kind = match &e.display { + Display::Shaped { .. } => RecipeKind::CraftingShaped, + Display::Shapeless(_) => RecipeKind::CraftingShapeless, + Display::Furnace(_) => furnace(e.category), + }; + let mut r = recipe(e.id.clone(), kind); + r.category = e.category.name().to_owned(); + r.group = e.group.clone().unwrap_or_default(); + r.book_id = e.display_id; + r.slots = match &e.display { + Display::Shaped { + width, + height, + cells, + } => { + (r.width, r.height) = (*width as u32, *height as u32); + cells + .iter() + .map(|c| c.as_ref().map_or_else(Vec::new, |i| index.any(i))) + .collect() + } + Display::Shapeless(list) => list.iter().map(|i| index.any(i)).collect(), + Display::Furnace(i) => vec![index.any(i)], + }; + // Requirements shown as other stacks (an arrow's potions): the + // requirement's index counts the filled slots only. + let filled: Vec = (0..r.slots.len()) + .filter( + |&k| !matches!(&e.display, Display::Shaped { cells, .. } if cells[k].is_none()), + ) + .collect(); + for (req, stacks) in &e.stacks { + if let Some(&k) = filled.get(*req) { + r.slots[k] = stacks.iter().filter_map(|s| index.of(s)).collect(); + } + } + r.results = e.results().iter().filter_map(|s| index.of(s)).collect(); + if let Some(&(time, xp)) = cooking.get(&e.id) { + (r.cooking_time, r.experience) = (time, xp); + } + out.push(r); + } + for c in &self.res.recipes().cooking { + if c.kind == "minecraft:campfire_cooking" { + let mut r = recipe(format!("minecraft:{}", c.id), RecipeKind::Campfire); + r.group = c.group.clone(); + r.slots = vec![index.any(&c.ingredient)]; + r.results = index.of(&c.result).into_iter().collect(); + (r.cooking_time, r.experience) = (c.time, c.experience); + out.push(r); + } + } + let stations = self.res.stations(); + for s in &stations.recipes.stonecutting { + let mut r = recipe(s.id.clone(), RecipeKind::Stonecutting); + r.slots = vec![index.any(&s.input)]; + r.results = index.of(&s.result).into_iter().collect(); + out.push(r); + } + for s in &stations.recipes.smithing { + let (id, template, base, addition, results) = match s { + Smithing::Transform { + id, + template, + base, + addition, + result, + } => ( + id, + template, + base, + addition, + index.stack(result, 1, String::new()).into_iter().collect(), + ), + Smithing::Trim { + id, + template, + base, + addition, + .. + } => (id, template, base, addition, index.any(base)), + }; + let mut r = recipe(id.clone(), RecipeKind::Smithing); + r.slots = vec![index.any(template), index.any(base), index.any(addition)]; + r.results = results; + out.push(r); + } + for b in &stations.brewing.recipes { + let potion = |p: &horizon_client::brewing::PotionIngredient| -> Vec { + let mut item_ids: Vec<&String> = p.items.iter().collect(); + item_ids.sort(); + let mut potions: Vec<&String> = p.potions.iter().flatten().collect(); + potions.sort(); + item_ids + .into_iter() + .flat_map(|item| { + let one = |c: String| index.stack(item, 1, c); + if potions.is_empty() { + one(String::new()).into_iter().collect::>() + } else { + potions + .iter() + .filter_map(|p| { + one(format!("[minecraft:potion_contents={{potion:\"{p}\"}}]")) + }) + .collect() + } + }) + .collect() + }; + let mut r = recipe(b.id.clone(), RecipeKind::Brewing); + r.slots = vec![potion(&b.input), potion(&b.reagent)]; + r.results = index.of(&b.output).into_iter().collect(); + out.push(r); + } + Recipes { + items: table, + recipes: out, + } + } +} diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index a83277376..52dc46fe0 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -17,6 +17,7 @@ use std::{path::PathBuf, time::Duration}; #[cfg(feature = "mods")] use { super::Screen, + super::{execution_role::ExecutionRole, lan::LanHost, server_mods::ModEvent}, horizon_client::{ extras::Corner, extras_hud, @@ -28,7 +29,8 @@ use { ui, }, horizon_mods::{ - Clock, ModKey, Mods, Output, Player, Runs, Snapshot, Status, UiScreen, UiWidget, + Clock, ModKey, Mods, Output, Player, Runs, ServerPlayer, Snapshot, Status, UiScreen, + UiWidget, }, std::time::Instant, winit::{event::MouseButton, keyboard::KeyCode}, @@ -52,11 +54,32 @@ pub(super) struct ModsState { /// The chat's command tree while a running mod owns commands. #[cfg(feature = "mods")] tree: Option, + /// A server mod runs here: what players do is queued for it. + #[cfg(feature = "mods")] + pub(super) server: bool, + /// The players server mods saw last tick, for joins and leaves. + #[cfg(feature = "mods")] + pub(super) players: Vec, + /// What players did this tick, for server mods at its end. + #[cfg(feature = "mods")] + pub(super) events: Vec, + /// A running server mod has capability `world`: its calls get the + /// levels' chunks to read. + #[cfg(feature = "mods")] + pub(super) world: bool, + /// Blocks server mods set, by dimension, made before that level's next + /// tick. + #[cfg(feature = "mods")] + pub(super) block_writes: Vec<(String, horizon_mods::BlockChange)>, /// `command.run` lines for this window's own world, run on the next tick: /// run at once, their chat lines would reach the mods while their output /// is still being shown, and a mod answering its own lines would recurse. #[cfg(feature = "mods")] commands: Vec, + /// `command.run-quiet` batches for this window's own world, by mod id, + /// run on the next tick as `commands` are. + #[cfg(feature = "mods")] + quiet: Vec<(String, Vec)>, /// The server's command tree with the running mods' commands added. #[cfg(feature = "mods")] remote_tree: Option, @@ -66,6 +89,15 @@ pub(super) struct ModsState { /// The HUD font's advances for `render.text-width`, made once. #[cfg(feature = "mods")] font_widths: std::sync::Arc<[f32]>, + /// Capability `recipes`'s tables, made once a mod reads them. + #[cfg(feature = "mods")] + pub(super) recipes: Option>, + /// The recipe book's known displays, and the book's version they are of. + #[cfg(feature = "mods")] + pub(super) known_recipes: (Option, std::sync::Arc<[i32]>), + /// Capability `ui`'s item panel beside container screens. + #[cfg(feature = "mods")] + pub(super) browser: super::mod_browser::Browser, /// Extras that are official mods now, being installed. #[cfg(feature = "mods")] pub(super) moved: super::moved_extras::MovedState, @@ -272,18 +304,31 @@ impl Game<'_> { .collect(); let enabled = &self.settings.mods.enabled; let on = |id: &str| enabled.contains(id) || dev_ids.iter().any(|d| d == id); - let mods = Mods::load_for(Runs::Client, &paths, on, vanilla_command); + let mods = Mods::load_for(self.mod_runs(), &paths, on, vanilla_command); self.mods.mods = mods; let chosen = &self.settings.mods; self.mods.mods.set_bindings(|id| chosen.keys_of(id)); // Entries were replaced wholesale: a screen's owner index is stale. self.mods.screen = None; + // Content mods may have changed the items: remade on the next read. + self.mods.recipes = None; self.list_mods(); self.sync_mod_commands(); self.show_mod_output(); } + /// Which mods this game runs: a server the server mods, the window + /// client mods, and both when it simulates the world itself (in-frame). + fn mod_runs(&self) -> Runs { + match self.options.execution_role { + ExecutionRole::IntegratedServer | ExecutionRole::DedicatedServer => Runs::Server, + ExecutionRole::Client if self.options.server_thread => Runs::Client, + ExecutionRole::Client => Runs::Both, + } + } /// The Mods page's rows, from what loaded. fn list_mods(&mut self) { + self.mods.server = self.mods.mods.runs_server(); + self.mods.world = self.mods.mods.wants_world(); let dev = &self.mods.dev; self.settings.mods.installed = self .mods @@ -326,7 +371,10 @@ impl Game<'_> { } /// The chat's tree after the running mods changed. fn sync_mod_commands(&mut self) { - let mut names = self.mods.mods.commands().peekable(); + // In-frame, the window runs server mods too: their names, free text + // here (the server parses their arguments). + let server = self.mods.mods.server_commands().map(|c| c.name.as_str()); + let mut names = self.mods.mods.commands().chain(server).peekable(); self.mods.tree = names .peek() .is_some() @@ -369,8 +417,18 @@ impl Game<'_> { self.start_mods(); } } - /// What mods read this tick (or frame, for mods with a `frame` hook). + /// What mods read this tick (or frame, for mods with a `frame` hook): the + /// server's players as they were at the last tick's end. fn mod_snapshot(&mut self) -> Snapshot { + let players = if self.mods.server { + self.mods.players.clone() + } else { + Vec::new() + }; + self.mod_snapshot_with(players) + } + /// What mods read, with these players on the server. + pub(super) fn mod_snapshot_with(&mut self, players: Vec) -> Snapshot { let player = self.player.as_ref().map(|p| Player { x: p.position.x, y: p.position.y, @@ -405,6 +463,7 @@ impl Game<'_> { .map(|c| char::from_u32(c).map_or(6.0, |c| atlas.glyph_cell(c).1)) .collect(); } + let (recipes, known_recipes) = self.mod_recipes(); Snapshot { player, clock, @@ -414,9 +473,115 @@ impl Game<'_> { mappings, cps, font_widths: self.mods.font_widths.clone(), - players: Vec::new(), + players, + view_hit: self.mod_view_hit(), + recipes, + known_recipes, + placing: self.mod_recipe_screen(), + creative: self.creative, } } + /// The first block along the player's view within + /// [`horizon_mods::RAYCAST_MAX`] and its distance from the eye + /// (`game.raycast`): through the loaded chunks as the crosshair's ray + /// goes (fluids pass), then across the distant terrain's ground heights, + /// a block at a time. + fn mod_view_hit(&self) -> Option<(f32, horizon_mods::Hit)> { + if !self.mods.mods.wants_raycast() { + return None; + } + let eye = self.eye_position()?; + let dir = super::view_vector(self.yaw, self.pitch); + let reach = f64::from(horizon_mods::RAYCAST_MAX); + let (pos, point, state) = match self.clip_ray(eye, dir, reach) { + Some(hit) => ( + hit.pos, + hit.point, + self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]), + ), + None => self.lod_ray(eye, dir, reach)?, + }; + let distance = (0..3).map(|i| (point[i] - eye[i]).powi(2)).sum::(); + let hit = horizon_mods::Hit { + block_x: pos[0], + block_y: pos[1], + block_z: pos[2], + x: point[0], + y: point[1], + z: point[2], + block: self.res.facts().get(state).name.to_string(), + }; + Some((distance.sqrt() as f32, hit)) + } + /// Past the resident chunks: the view walked across the distant + /// terrain's ground heights (`Lod::ground`), a block at a time. Columns in + /// loaded chunks are left to `clip_ray`, which has already missed them. + fn lod_ray( + &self, + eye: [f64; 3], + dir: [f64; 3], + reach: f64, + ) -> Option<([i32; 3], [f64; 3], horizon_world::registry::BlockStateId)> { + let lod = self.lod.as_ref()?; + let mut t = 0.0; + while t <= reach { + let p = [0, 1, 2].map(|i| eye[i] + dir[i] * t); + let (x, z) = (p[0].floor() as i32, p[2].floor() as i32); + if !self.world.loaded(x, z) + && let Some((height, state)) = lod.ground(x, z) + && p[1] <= f64::from(height) + { + return Some(([x, height - 1, z], [p[0], f64::from(height), p[2]], state)); + } + t += 1.0; + } + None + } + /// A mod's `command.run-quiet` lines (vanilla's commands only, as + /// `command.run`): to a server that runs them quietly as one payload + /// (`horizon_protocol::quiet`), to any other as chat commands, or for this + /// window's own world next tick. + fn mod_quiet_commands(&mut self, mod_id: String, lines: Vec) { + let lines: Vec = lines + .into_iter() + .filter(|l| vanilla_command(l.split(' ').next().unwrap_or_default())) + .collect(); + match self.remote.as_ref().map(|r| r.quiet_commands) { + Some(true) => { + for data in horizon_protocol::quiet::encode(&mod_id, &lines) { + self.send(horizon_protocol::packets::play::Serverbound::CustomPayload( + horizon_protocol::packets::configuration::CustomPayload { + channel: horizon_protocol::quiet::CHANNEL.into(), + data, + }, + )); + } + } + // The server checks the player's permissions; its feedback shows. + Some(false) => { + for line in lines { + self.send_chat(&format!("/{line}")); + } + } + None => self.mods.quiet.push((mod_id, lines)), + } + } + /// A quiet batch in this window's own world, as a server runs one + /// (game/lan_quiet.rs): each line as the player typing it, no chat, a + /// chat message refused; one line in the log. + fn run_quiet_batch(&mut self, mod_id: &str, lines: &[String]) { + let permission = self.ui.registries.permission; + let mut failed = 0; + for line in lines { + let ok = self.signable_arguments(permission, line).is_empty() + && self.run_command_quietly(line); + failed += usize::from(!ok); + } + log::info!( + "[mod {mod_id}] ran {} quiet command(s): {failed} failed", + lines.len() + ); + } /// A game tick. pub(super) fn tick_mods(&mut self) { // Here, at the player's level: shown inside a console call (a control @@ -424,6 +589,9 @@ impl Game<'_> { for line in std::mem::take(&mut self.mods.commands) { self.run_command(&line); } + for (mod_id, lines) in std::mem::take(&mut self.mods.quiet) { + self.run_quiet_batch(&mod_id, &lines); + } if !self.mods.mods.is_running() { return; } @@ -433,23 +601,32 @@ impl Game<'_> { self.mods.mods.tick(self.ticks); self.show_mod_output(); } - /// Once per frame: the frame hook, and dev mods' rebuilds. - pub(super) fn mods_frame(&mut self, elapsed: Duration) { - if !self.mods.dev.is_empty() - && self + /// Restarts the dev mods rebuilt since the last check, once a second. + pub(super) fn reload_dev_mods(&mut self) { + if self.mods.dev.is_empty() + || self .mods .checked - .is_none_or(|t| t.elapsed() >= RELOAD_CHECK) + .is_some_and(|t| t.elapsed() < RELOAD_CHECK) { - self.mods.checked = Some(Instant::now()); - if self.mods.mods.reload_changed(vanilla_command) { - let chosen = &self.settings.mods; - self.mods.mods.set_bindings(|id| chosen.keys_of(id)); - self.list_mods(); - self.sync_mod_commands(); + return; + } + self.mods.checked = Some(Instant::now()); + if self.mods.mods.reload_changed(vanilla_command) { + let chosen = &self.settings.mods; + self.mods.mods.set_bindings(|id| chosen.keys_of(id)); + self.list_mods(); + self.sync_mod_commands(); + if self.options.execution_role.is_client() { self.system_message(Text::literal("Mods reloaded").with_color(text::GRAY)); + } else { + log::info!("Horizon: mods reloaded"); } } + } + /// Once per frame: the frame hook, and dev mods' rebuilds. + pub(super) fn mods_frame(&mut self, elapsed: Duration) { + self.reload_dev_mods(); if !self.mods.mods.is_running() { return; } @@ -480,8 +657,13 @@ impl Game<'_> { self.mods.mods.chat(line); self.show_mod_output(); } - /// Chat lines, command feedback and stopped mods, into the chat. - fn show_mod_output(&mut self) { + /// What mods showed: client mods' lines into the chat, server mods' + /// to their players. + pub(super) fn show_mod_output(&mut self) { + self.route_mod_output(None); + } + /// [`Game::show_mod_output`], with the hub when it is out of `self.lan`. + pub(super) fn route_mod_output(&mut self, mut host: Option<&mut LanHost>) { for output in self.mods.mods.drain() { let line = match output { Output::Chat { name, text } => { @@ -504,12 +686,27 @@ impl Game<'_> { } continue; } + Output::QuietCommands { mod_id, lines } => { + self.mod_quiet_commands(mod_id, lines); + continue; + } Output::Stopped { name, reason } => { // Its screen goes with it: the entry's run is gone, so // `mod_ui_view` finds no widgets and the screen closes. self.list_mods(); self.sync_mod_commands(); - Text::literal(format!("Mod {name} stopped: {reason}")).with_color(text::RED) + let line = format!("Mod {name} stopped: {reason}"); + if self.options.dedicated.is_some() { + super::dedicated::log("WARN", &line); + } + Text::literal(line).with_color(text::RED) + } + server @ (Output::Tell { .. } + | Output::Broadcast { .. } + | Output::Reply { .. } + | Output::SetBlocks { .. }) => { + self.route_server_output(host.as_deref_mut(), server); + continue; } Output::OpenScreen { owner } => { self.open_mod_screen(owner, false); @@ -519,26 +716,26 @@ impl Game<'_> { self.mods.shake.add(strength, seconds); continue; } + Output::PlaceRecipe { book_id, all } => { + self.mod_place_recipe(book_id, all); + continue; + } + Output::Give { + item, + count, + components, + } => { + self.mod_give(&item, count, &components); + continue; + } Output::CloseScreen { owner } => { if self.mods.screen.as_ref().is_some_and(|s| s.owner == owner) { self.close_mod_screen(false); } continue; } - // Server mods' lines: this game runs no server mod yet. - Output::Tell { .. } | Output::Broadcast { .. } | Output::Reply { .. } => continue, }; - // Not through system_message: a mod must not hear its own lines. - // Written by this client, so the Chat option doesn't hide it. - let focused = self.screen == Screen::Chat; - self.ui.chat.add( - &self.gui.atlas, - line, - None, - horizon_client::chat::ChatSource::Client, - self.ticks, - focused, - ); + self.add_mod_chat_line(line); } // A mod may set or clear its settings page in any call, not only // while loading: its row's Settings button follows. @@ -547,6 +744,20 @@ impl Game<'_> { row.has_settings = e.has_ui_settings(); } } + /// A mod's line in the window's chat; not through system_message: a mod + /// must not hear its own lines. + /// Written by this client, so the Chat option doesn't hide it. + pub(super) fn add_mod_chat_line(&mut self, line: Text) { + let focused = self.screen == Screen::Chat; + self.ui.chat.add( + &self.gui.atlas, + line, + None, + horizon_client::chat::ChatSource::Client, + self.ticks, + focused, + ); + } /// The mods' HUD panels, stacked with the extras in their corners. pub(super) fn draw_mod_panels(&self, batch: &mut HudBatch, corners: &mut Corners) { for panel in self.mods.mods.panels() { diff --git a/crates/horizon-client/src/game/music.rs b/crates/horizon-client/src/game/music.rs index 6f8b5e7ae..97ca3763e 100644 --- a/crates/horizon-client/src/game/music.rs +++ b/crates/horizon-client/src/game/music.rs @@ -3,7 +3,7 @@ use super::Game; use horizon_client::{ blocks::Fluid, - music::{BackgroundMusic, Music, Situation}, + music::{BackgroundMusic, Music, MusicFrequency, Situation}, sound_engine::TickContext, }; @@ -11,6 +11,11 @@ impl Game<'_> { /// `Minecraft.tick` -> `MusicManager.tick`, once per client tick. pub(super) fn tick_music(&mut self) { let (music, volume) = self.situational_music(); + // Options.musicFrequency's listener: MusicManager.setMinutesBetweenSongs. + let frequency = MusicFrequency::parse(&self.settings.file.name("musicFrequency")); + if frequency != self.music.frequency { + self.music.set_frequency(frequency, music.as_ref()); + } // LevelLoadingScreen: no new track before the player is in the world. let loading = self.title.is_none() && self.player.is_none() && self.win.is_none(); self.music @@ -91,7 +96,7 @@ 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 { + pub(super) 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)); if f.fluid != Fluid::Water { diff --git a/crates/horizon-client/src/game/names.rs b/crates/horizon-client/src/game/names.rs index f249bd01f..9f7561e53 100644 --- a/crates/horizon-client/src/game/names.rs +++ b/crates/horizon-client/src/game/names.rs @@ -86,6 +86,10 @@ impl Game<'_> { .iter() .filter_map(|m| Some((m, m.custom_name.clone()?, false))); let players = players.into_iter().map(|(m, name)| (m, name, true)); + // Who is riding whom: asked once per tag below, and rescanning every mob + // for each tag made this quadratic in the number of loaded mobs. + let ridden: std::collections::HashSet = + self.mobs.iter().filter_map(|o| o.extra.mount).collect(); for (m, name, player) in named.chain(players) { if !m.alive() { continue; @@ -134,7 +138,7 @@ impl Game<'_> { invisible_to_viewer: invisible, hud_hidden: self.ui.hide_gui, is_camera: false, - is_vehicle: self.mobs.iter().any(|o| o.extra.mount == Some(m.id)), + is_vehicle: ridden.contains(&m.id), }; // MobRenderer.shouldShowName: a visible name, or the mob under the // crosshair; players (LivingEntityRenderer) need neither. @@ -310,7 +314,7 @@ impl Game<'_> { } /// The lines of one name tag, `o` from the camera: the text at /// `text_alpha` in its layer, on the translucent black background - /// (unlit, a hair behind) when `background`. + /// (in `text_layer` like the glyphs, a hair behind) when `background`. #[allow(clippy::too_many_arguments)] fn name_tag_quads( &self, @@ -382,7 +386,7 @@ impl Game<'_> { [white.u0, white.v0, white.u1, white.v1], BACKGROUND, true, - 2, + text_layer, ); } let mut x = x0; diff --git a/crates/horizon-client/src/game/net_harness.rs b/crates/horizon-client/src/game/net_harness.rs index 1ec573e7c..468f1db71 100644 --- a/crates/horizon-client/src/game/net_harness.rs +++ b/crates/horizon-client/src/game/net_harness.rs @@ -3,7 +3,10 @@ //! window, waits until it stands in the world with the chunks around it, //! sends a chat message and `/list`, collects the chat it is shown, leaves //! and writes a JSON report (position, chunks, chat lines, whether the -//! server kept it connected throughout). +//! server kept it connected throughout). With `HORIZON_NET_QUIET` (lines +//! split by `;`) it then sends them as one batch of a mod's quiet commands +//! (`horizon_protocol::quiet`, `tools/quiet_commands_e2e.py`) and waits two +//! seconds for any chat they bring. use super::Game; use horizon_client::Result; use serde_json::json; @@ -23,6 +26,9 @@ impl Game<'_> { let mut step_at = Instant::now(); let mut chat_at = 0; let mut position = None; + let quiet: Vec = std::env::var("HORIZON_NET_QUIET") + .map(|v| v.split(';').map(str::to_owned).collect()) + .unwrap_or_default(); let mut chunks = 0; let mut error = None; while Instant::now() < deadline { @@ -71,6 +77,22 @@ impl Game<'_> { step_at = now; chat_at = shown; } + 2 if answered && !quiet.is_empty() => { + for data in horizon_protocol::quiet::encode("net_harness", &quiet) { + self.send(horizon_protocol::packets::play::Serverbound::CustomPayload( + horizon_protocol::packets::configuration::CustomPayload { + channel: horizon_protocol::quiet::CHANNEL.into(), + data, + }, + )); + } + step = 4; + step_at = now; + } + 4 if now - step_at > Duration::from_secs(2) => { + step = 3; + break; + } 2 if answered => { step = 3; break; diff --git a/crates/horizon-client/src/game/nether_portal.rs b/crates/horizon-client/src/game/nether_portal.rs index 353ad216c..87ba81c93 100644 --- a/crates/horizon-client/src/game/nether_portal.rs +++ b/crates/horizon-client/src/game/nether_portal.rs @@ -454,11 +454,24 @@ impl Game<'_> { for m in &self.mobs { self.portals.before.insert(m.id, m.position); } + for b in &self.boats { + self.portals.before.insert(b.id, b.position); + } + for c in &self.carts { + self.portals.before.insert(c.id, c.position); + } let ids: Vec<(u32, bool)> = self .dropped .iter() .map(|e| (e.id, true)) .chain(self.mobs.iter().map(|m| (m.id, self.mob_can_use_portal(m)))) + .chain( + self.boats + .iter() + .map(|b| b.id) + .chain(self.carts.iter().map(|c| c.id)) + .map(|id| (id, !self.vehicle_occupied(id))), + ) .collect(); let present: std::collections::HashSet = ids.iter().map(|(id, _)| *id).collect(); self.portals.entities.retain(|id, _| present.contains(id)); @@ -501,8 +514,15 @@ impl Game<'_> { && self.riding != Some(m.id) && m.species() != Species::Wither } - /// `NetherPortalBlock.entityInside` for the items and mobs that moved this - /// tick: the portal blocks their box swept through. + /// Whether the player, a server player or a mob rides vehicle `id`. + fn vehicle_occupied(&self, id: u32) -> bool { + self.riding == Some(id) + || self.ridden_by_guest(id) + || self.mobs.iter().any(|m| m.extra.mount == Some(id)) + } + /// `NetherPortalBlock.entityInside` for the items, mobs and empty boats + /// and minecarts that moved this tick: the portal blocks their box swept + /// through. pub(super) fn find_entity_portals(&mut self) { if self.remote.is_some() { return; @@ -519,8 +539,23 @@ impl Game<'_> { .filter(|m| self.mob_can_use_portal(m)) .map(|m| (m.id, m.position, m.width(), m.height())) .collect(); + let vehicles: Vec<(u32, Vec3, f32, f32)> = self + .boats + .iter() + .map(|b| (b.id, b.position, super::boats::WIDTH, super::boats::HEIGHT)) + .chain(self.carts.iter().map(|c| { + ( + c.id, + c.position, + super::minecarts::WIDTH, + super::minecarts::HEIGHT, + ) + })) + .filter(|(id, ..)| !self.vehicle_occupied(*id)) + .map(|(id, at, w, h)| (id, at, w as f32, h as f32)) + .collect(); let mut portal_sections = std::mem::take(&mut self.portals.sections); - for (id, to, width, height) in items.into_iter().chain(mobs) { + for (id, to, width, height) in items.into_iter().chain(mobs).chain(vehicles) { 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)); @@ -678,6 +713,44 @@ impl Game<'_> { } self.portals.arrivals.push(Arrival { plan, tag }); self.portals.dirty = true; + } else if let Some(i) = self.boats.iter().position(|b| b.id == id) { + let b = &self.boats[i]; + let (width, height) = (super::boats::WIDTH as f32, super::boats::HEIGHT as f32); + let plan = self.portal_plan(entry, b.position, width, height, false); + if !self.may_enter(plan.dim) { + return; + } + let uuid = self.uuid_for(id); + let b = &self.boats[i]; + let tag = horizon_client::entity_nbt::boat_to_nbt( + &b.entity_type(), + b.position, + b.velocity, + b.yaw, + uuid, + self.persist_raw(id), + b.chest.then_some(&b.items[..]), + ); + self.boats.remove(i); + self.forget_entity(id); + self.portals.arrivals.push(Arrival { plan, tag }); + self.portals.dirty = true; + } else if let Some(i) = self.carts.iter().position(|c| c.id == id) { + let c = &self.carts[i]; + let (width, height) = ( + super::minecarts::WIDTH as f32, + super::minecarts::HEIGHT as f32, + ); + let plan = self.portal_plan(entry, c.position, width, height, false); + if !self.may_enter(plan.dim) { + return; + } + let uuid = self.uuid_for(id); + let tag = self.carts[i].to_nbt(uuid, self.persist_raw(id)); + self.carts.remove(i); + self.forget_entity(id); + self.portals.arrivals.push(Arrival { plan, tag }); + self.portals.dirty = true; } } /// Entities waiting for the loaded dimension whose exit area is loaded: diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index 243eced5c..7ac4ae98b 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -257,6 +257,7 @@ impl Game<'_> { lang::set(lang::Language::load(&[&root], code)); self.refresh_remote_language(); self.ui.chat.rescale(&self.gui.atlas); + self.creative_screen.forget_items(); } /// Settings that Horizon applies beyond render distance, volume and GUI scale. pub(super) fn apply_ui_settings(&mut self) { @@ -268,6 +269,11 @@ impl Game<'_> { r.animated_textures = s.horizon.animated_textures; r.set_mipmap_levels(s.mipmap_levels.max(0) as u32); r.set_world_post(s.horizon.resolution_scale as f32 / 100.0, s.horizon.fxaa); + r.set_hdr( + s.horizon.hdr, + s.horizon.hdr_paper_white as f32, + s.horizon.hdr_peak as f32, + ); } // Window.updateFullscreenIfChanged: only a changed option asks the // window to change, so applying settings never undoes a fullscreen diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index ee57e9f2b..569c63083 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -163,7 +163,7 @@ impl Game<'_> { self.pack.context.biomes.clone(), self.pack.context.light.clone(), )?; - // Keep the working GPU resources, but release its exclusive window surface. + // Keep the working GPU resources, and hand its window surface over. if let Some(renderer) = &mut self.renderer { renderer.release_surface(); } @@ -221,6 +221,8 @@ impl Game<'_> { self.apply_ui_settings(); } self.ui.chat.rescale(&self.gui.atlas); + // The creative screen survives the reload; item names may not. + self.creative_screen.forget_items(); Ok(()) } } diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 45ef8801f..9e727d35d 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -279,7 +279,8 @@ impl Game<'_> { k if super::minecarts::CartKind::from_id(k).is_some() => { let kind = super::minecarts::CartKind::from_id(k).unwrap(); let id = self.next_entity + 1; - if let Some(c) = super::minecarts::Minecart::from_nbt(&tag, id, kind) { + if let Some(mut c) = super::minecarts::Minecart::from_nbt(&tag, id, kind) { + self.roll_cart_loot(&mut c, &tag); self.next_entity = id; self.remember(id, uuid, tag); self.carts.push(c); @@ -314,6 +315,13 @@ impl Game<'_> { self.item_frames.push(f); } } + "minecraft:cushion" => { + self.next_entity += 1; + if let Some(c) = entity_nbt::cushion_from_nbt(&tag, self.next_entity) { + self.remember(c.id, uuid, tag); + self.cushions.push(c); + } + } "minecraft:painting" => { if let Some((pos, facing, variant)) = entity_nbt::painting_from_nbt(&tag) && let Some(v) = self.painting_variants.get(&variant).cloned() @@ -349,7 +357,8 @@ impl Game<'_> { pub(super) fn load_mob(&mut self, tag: Tag, mount: Option) -> Option { self.next_entity += 1; let uuid = entity_nbt::uuid(&tag); - // Structure entities placed with finalizeEntities. + // Structure mobs that generation left to finish: saves from before + // they were finalized at placement, or a placement that could not. let mut tag = tag; let mut finalize = false; if let Tag::Compound(c) = &mut tag { @@ -441,7 +450,8 @@ impl Game<'_> { } } /// An entity of a type Horizon does not simulate, kept as its compound. - fn load_other(&mut self, tag: Tag, kind: &str) -> Option { + fn load_other(&mut self, mut tag: Tag, kind: &str) -> Option { + strip_finalize(&mut tag); let position = entity_nbt::position(&tag)?; let rotation = match tag.get("Rotation") { Some(Tag::List(l)) => { @@ -527,6 +537,30 @@ impl Game<'_> { pub(super) fn persist_raw(&self, id: u32) -> Option<&Tag> { self.persist.raw.get(&id) } + /// A loaded chest minecart with a loot table and no items: the table + /// rolled now, as generated containers are (Horizon does not unpack on + /// first open), and kept to save it again while unchanged. + fn roll_cart_loot(&self, cart: &mut super::minecarts::Minecart, tag: &Tag) { + let Some(table) = horizon_client::save::text(tag.get("LootTable")) else { + return; + }; + if cart.items.is_empty() || cart.items.iter().any(Option::is_some) { + return; + } + let loot = horizon_client::structure_blocks::loot_data(&self.options.resources); + let p = cart.position; + let pos = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); + let biome = self.biome_name_at(p).unwrap_or_default(); + let seed = horizon_client::structure_blocks::loot_seed(tag); + cart.loot = Some(horizon_client::structure_blocks::roll_container( + &mut cart.items, + loot.as_deref(), + table, + seed, + pos, + &biome, + )); + } fn remember(&mut self, id: u32, uuid: Option<[i32; 4]>, tag: Tag) { self.restore_portal_cooldown(id, &tag); if let Some(u) = uuid { @@ -776,6 +810,18 @@ impl Game<'_> { out.entry(chunk_of(at)).or_default().push(tag); } } + for c in &self.cushions { + if keys.contains(&chunk_of(c.position)) { + let uuid = self + .persist + .uuids + .get(&c.id) + .copied() + .unwrap_or_else(random_uuid); + let tag = entity_nbt::cushion_to_nbt(c, uuid, self.persist.raw.get(&c.id)); + out.entry(chunk_of(c.position)).or_default().push(tag); + } + } for p in &self.paintings { let at = painting_center(p); if keys.contains(&chunk_of(at)) { @@ -868,6 +914,13 @@ impl Game<'_> { } keep }); + self.cushions.retain(|c| { + let keep = !gone(c.position); + if !keep { + removed.push(c.id); + } + keep + }); // Riders leave with their root vehicle, a boat's with the boat. let leaving: HashSet = (0..self.mobs.len()) .filter(|&i| { @@ -934,6 +987,7 @@ impl Game<'_> { .chain(self.boats.iter().map(|e| e.id)) .chain(self.carts.iter().map(|e| e.id)) .chain(self.armor_stands.iter().map(|e| e.id)) + .chain(self.cushions.iter().map(|e| e.id)) .chain(self.item_frames.iter().map(|e| e.id)) .chain(self.paintings.iter().map(|e| e.id)) .chain(self.others.iter().map(|e| e.id)) @@ -962,3 +1016,9 @@ impl Game<'_> { self.save.save_entities(chunks) } } +/// Only a mob is finalized; another entity drops the request. +fn strip_finalize(tag: &mut Tag) { + if let Tag::Compound(c) = tag { + c.remove(&"horizon:finalize".into()); + } +} diff --git a/crates/horizon-client/src/game/pickups.rs b/crates/horizon-client/src/game/pickups.rs index 1e19bcfc3..040a6f01b 100644 --- a/crates/horizon-client/src/game/pickups.rs +++ b/crates/horizon-client/src/game/pickups.rs @@ -155,6 +155,8 @@ mod tests { value: 1, age: 0, on_ground: false, + count: 1, + ticks: 0, })) } diff --git a/crates/horizon-client/src/game/piglins.rs b/crates/horizon-client/src/game/piglins.rs index bcf9e6ab5..edfd9a3a0 100644 --- a/crates/horizon-client/src/game/piglins.rs +++ b/crates/horizon-client/src/game/piglins.rs @@ -4,18 +4,172 @@ use super::Game; use horizon_client::{ items::ItemStack, - mobs::{Species, Who, piglin::ADMIRE}, + mobs::{ + Mob, Species, Who, + finalize::{ + SLOT_NAMES, set_drop_chance, set_item, set_slot_enchantments, slot_enchantments, + stored_drop_chance, + }, + piglin::{ADMIRE, ATE_RECENTLY}, + }, }; use horizon_core::{geometry::Vec3, random::RandomSource}; impl Game<'_> { - fn piglin_loved(&self, item: &str) -> bool { + fn item_in_tag(&self, tag: &str, item: &str) -> bool { self.res .items() .item_tags - .get("minecraft:piglin_loved") + .get(tag) .is_some_and(|t| t.contains(item)) } + fn piglin_loved(&self, item: &str) -> bool { + self.item_in_tag("minecraft:piglin_loved", item) + } + /// `PiglinAi.isLovedItem` or a preferred weapon (`Piglin.canReplaceCurrentItem`). + fn piglin_wanted(&self, item: &str) -> bool { + self.piglin_loved(item) || self.item_in_tag("minecraft:piglin_preferred_weapons", item) + } + /// The `SLOT_NAMES` index `getEquipmentSlotForItem` picks: armour goes + /// to its slot, anything else to the main hand. + fn piglin_slot(&self, item: &str) -> usize { + let slot = self + .res + .items() + .get(item) + .and_then(|i| i.equip_slot.as_deref()) + .filter(|s| matches!(*s, "head" | "chest" | "legs" | "feet")) + .unwrap_or("mainhand"); + SLOT_NAMES.iter().position(|n| *n == slot).unwrap_or(0) + } + /// `Piglin.canReplaceCurrentItem`: an empty slot takes anything, a wanted + /// item replaces an unwanted one and never the other way round. Vanilla's + /// armour and weapon comparison for two equal-interest items is left out + /// (the piglin keeps what it has). + fn piglin_can_replace(&self, m: &Mob, item: &str, slot: usize) -> bool { + let Some(current) = horizon_client::mobs::finalize::item(m, slot) else { + return true; + }; + self.piglin_wanted(item) && !self.piglin_wanted(¤t) + } + /// `SimpleContainer.canAddItem` on the piglin's eight slots. + fn piglin_can_add(&self, m: &Mob, stack: &ItemStack) -> bool { + m.extra.inventory.len() < 8 + || m.extra.inventory.iter().any(|s| { + s.same_item_same_components(stack) && s.count < self.piglin_max_stack(&s.item) + }) + } + fn piglin_max_stack(&self, item: &str) -> u32 { + self.res.items().get(item).map_or(64, |i| i.max_stack) + } + /// `PiglinAi.wantsToPickup` (an adult that is not hurt-shy), without + /// the baby rule, which babies skip entirely here. + fn piglin_wants(&self, m: &Mob, stack: &ItemStack) -> bool { + let item = &*stack.item; + if self.item_in_tag("minecraft:piglin_repellents", item) { + return false; + } + let holds_loved = m + .extra + .off_hand + .as_deref() + .is_some_and(|o| self.piglin_loved(o)); + if item == "minecraft:gold_ingot" { + return !holds_loved; + } + let space = self.piglin_can_add(m, stack); + if item == "minecraft:gold_nugget" { + space + } else if self.item_in_tag("minecraft:piglin_food", item) { + m.extra.ints[0] <= 0 && space + } else if !self.piglin_loved(item) { + self.piglin_can_replace(m, item, self.piglin_slot(item)) + } else { + !holds_loved && space + } + } + /// `Mob.equipItemIfPossible` for a piglin: put it in its slot when that + /// slot takes it (an armour piece that cannot replace what is worn goes + /// to an empty main hand), dropping what it replaces by drop chance. + fn piglin_equip(&mut self, index: usize, stack: &ItemStack) -> bool { + let item = &*stack.item; + let mut slot = self.piglin_slot(item); + let m = &self.mobs[index]; + let mut replace = self.piglin_can_replace(m, item, slot); + if slot > 1 && !replace { + slot = 0; + replace = m.extra.main_hand.is_none(); + } + if !replace { + return false; + } + let m = &mut self.mobs[index]; + let old = horizon_client::mobs::finalize::item(m, slot); + let chance = stored_drop_chance(m, slot); + let drop_old = old.is_some() && (m.random.next_float() - 0.1).max(0.0) < chance; + let old_enchantments = slot_enchantments(m, slot); + set_item(m, slot, item); + // The piglin keeps what the stack carried (Protection IV stays on). + set_slot_enchantments(m, slot, stack.enchantments().to_vec()); + // setItemSlotAndDropWhenKilled, then persistenceRequired. + set_drop_chance(m, slot, 2.0); + m.persistent = true; + let at = [m.position.x, m.position.y, m.position.z]; + if let (true, Some(old)) = (drop_old, old) { + let mut dropped = ItemStack::new(&old, 1); + dropped.set_crafting_enchantments(old_enchantments); + self.spawn_item(dropped, at, super::dispenser::new_item_motion(), 10); + } + true + } + /// `PiglinAi.putInInventory`: what does not fit is thrown at a random + /// spot nearby. + fn piglin_stash(&mut self, index: usize, mut stack: ItemStack) { + let max = self.piglin_max_stack(&stack.item); + let m = &mut self.mobs[index]; + for s in &mut m.extra.inventory { + if stack.count > 0 && s.same_item_same_components(&stack) && s.count < max { + let n = (max - s.count).min(stack.count); + s.count += n; + stack.count -= n; + } + } + while stack.count > 0 && m.extra.inventory.len() < 8 { + let n = stack.count.min(max); + m.extra.inventory.push(ItemStack { + count: n, + ..stack.clone() + }); + stack.count -= n; + } + if stack.count == 0 { + return; + } + let from = [m.position.x, m.position.y + 1.3, m.position.z]; + let r = &mut self.world.random; + let to = [ + from[0] + f64::from(r.next_float() * 8.0 - 4.0), + from[1], + from[2] + f64::from(r.next_float() * 8.0 - 4.0), + ]; + self.piglin_throw(from, to, stack); + } + /// `PiglinAi.stopHoldingOffHandItem` for something that is not + /// bartering currency: wear it if it can, else keep it in the inventory. + fn piglin_keep(&mut self, index: usize, stack: ItemStack) { + // Nuggets keep their whole stack in the inventory (a hand slot here + // holds one item id only). + if &*stack.item == "minecraft:gold_nugget" || !self.piglin_equip(index, &stack) { + self.piglin_stash(index, stack); + } + } + /// `BehaviorUtils.throwItem`: toss a stack from a point toward another. + fn piglin_throw(&mut self, from: [f64; 3], to: [f64; 3], stack: ItemStack) { + let d = [to[0] - from[0], to[1] - from[1], to[2] - from[2]]; + let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1e-6); + let v = [d[0] / len * 0.3, d[1] / len * 0.3 + 0.1, d[2] / len * 0.3]; + self.spawn_item(stack, from, v, 40); + } /// `PiglinAi.isWearingSafeArmor`. pub(super) fn wearing_gold(&self) -> bool { let tag = self @@ -28,15 +182,13 @@ impl Game<'_> { .flatten() .any(|s| tag.is_some_and(|t| t.contains(&*s.item))) } - /// Piglins notice gold on the ground within 9 blocks, walk to it and - /// take it (`GoToWantedItem`, `Piglin.pickUpItem`). + /// Piglins notice wanted items on the ground within 9 blocks (`PiglinAi.wantsToPickup`: + /// gold and other loved items, nuggets, food, gear), walk to them and + /// take them (`GoToWantedItem`, `Piglin.pickUpItem`). pub(super) fn piglin_pickups(&mut self) { if !self.ui.rules.bool("mob_griefing") { return; } - // Whether each item is piglin-loved, kept until an item is added or - // removed (added ones are pushed at the end under a new id). - let mut loved: (Option<(usize, Option)>, Vec) = (None, Vec::new()); for i in 0..self.mobs.len() { let m = &self.mobs[i]; if m.species() != Species::Piglin @@ -44,27 +196,17 @@ impl Game<'_> { || m.is_baby() || m.extra.using_item > 0 || m.extra.egg_time > 0 - || m.extra.off_hand.is_some() { continue; } let pos = m.position; - let key = (self.dropped.len(), self.dropped.last().map(|e| e.id)); - if loved.0 != Some(key) { - loved.0 = Some(key); - loved.1 = self - .dropped - .iter() - .map(|e| self.piglin_loved(&e.stack.item)) - .collect(); - } let best = self .dropped .iter() .enumerate() - .filter(|&(j, _)| loved.1[j]) .map(|(j, e)| (j, e.position.distance_squared(pos))) .filter(|(_, d)| *d <= 81.0) + .filter(|&(j, _)| self.piglin_wants(m, &self.dropped[j].stack)) .min_by(|a, b| a.1.total_cmp(&b.1)); let Some((j, _)) = best else { self.mobs[i].extra.point = None; @@ -79,24 +221,38 @@ impl Game<'_> { continue; } // Nuggets come whole, anything else one at a time. - let item = e.stack.item.clone(); let (taken_item, id) = (e.clone(), self.mobs[i].id); + let item = e.stack.item.clone(); self.add_pickup( super::pickups::Taken::Item(Box::new(taken_item)), super::pickups::Collector::Mob(id), ); - let taken = if &*item == "minecraft:gold_nugget" { - self.dropped.remove(j).stack.count + let stack = if &*item == "minecraft:gold_nugget" { + self.dropped.remove(j).stack } else { let e = &mut self.dropped[j]; e.stack.count -= 1; + let one = ItemStack { + count: 1, + ..e.stack.clone() + }; if e.stack.count == 0 { self.dropped.remove(j); } - 1 + one }; - let _ = taken; - self.start_admiring(i, item); + if self.piglin_loved(&item) { + self.start_admiring(i, item); + } else if self.item_in_tag("minecraft:piglin_food", &item) + && self.mobs[i].extra.ints[0] <= 0 + { + // PiglinAi.eat: the food is gone and it will not eat for a while. + self.mobs[i].extra.ints[0] = ATE_RECENTLY; + self.mobs[i].nav_stop(); + } else { + self.mobs[i].nav_stop(); + self.piglin_keep(i, stack); + } } } fn start_admiring(&mut self, index: usize, item: std::sync::Arc) { @@ -109,14 +265,15 @@ impl Game<'_> { self.audio .play("minecraft:entity.piglin.admiring_item", Some(at), 1.0, 1.0); } - /// `PiglinAi.mobInteract`: hand a piglin something it loves. + /// `PiglinAi.mobInteract`: hand a piglin a gold ingot (only piglin + /// currency is accepted from the hand; other loved items are passed over). pub(super) fn give_piglin(&mut self, index: usize, item: &str) -> bool { let m = &self.mobs[index]; if m.species() != Species::Piglin || m.is_baby() || m.extra.using_item > 0 || m.extra.egg_time > 0 - || !self.piglin_loved(item) + || item != "minecraft:gold_ingot" { return false; } @@ -124,7 +281,8 @@ impl Game<'_> { true } /// `PiglinAi.stopHoldingOffHandItem` after admiring: gold ingots buy a - /// roll of the bartering table, thrown toward the player. + /// roll of the bartering table, thrown toward the player; any other loved + /// item it picked up is kept (worn if it can be, else stored). pub(super) fn finish_admiring(&mut self, mob: u32) { let Some(i) = self.mobs.iter().position(|m| m.id == mob) else { return; @@ -132,9 +290,13 @@ impl Game<'_> { let Some(item) = self.mobs[i].extra.off_hand.take() else { return; }; + if &*item != "minecraft:gold_ingot" { + self.piglin_keep(i, ItemStack::new(&item, 1)); + return; + } 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() { + let items = if !m.is_baby() { self.res.items().loot_table( "minecraft:gameplay/piglin_bartering", false, @@ -176,10 +338,7 @@ impl Game<'_> { from[2] + f64::from(r.next_float() * 8.0 - 4.0), ] }); - let d = [to[0] - from[0], to[1] - from[1], to[2] - from[2]]; - let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1e-6); - let v = [d[0] / len * 0.3, d[1] / len * 0.3 + 0.1, d[2] / len * 0.3]; - self.spawn_item(stack, from, v, 40); + self.piglin_throw(from, to, stack); } } /// `PiglinAi.angerNearbyPiglins`. diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index b28c2fb4d..4dd8cdb05 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -12,6 +12,7 @@ use horizon_client::{ hud_layout, hud_overlays, inventory_effects, items::ItemStack, mesher::Vertex, + text::Text, }; use horizon_core::{geometry::Vec3, random::RandomSource}; @@ -26,6 +27,9 @@ pub(super) struct ThrownPotion { position: Vec3, velocity: Vec3, age: u32, + /// `Projectile.getOwner`'s display name: the player who threw it (none + /// for a dispenser's). + owner: Option, } /// A mob's effect ids carry the `minecraft:` namespace. fn mob_effect_id(id: &str) -> Option<&'static str> { @@ -47,7 +51,13 @@ fn mob_effect_id(id: &str) -> Option<&'static str> { impl Game<'_> { /// A splash potion, lingering potion or experience bottle in flight (the /// player's throws and dispensers both end up here). - pub(super) fn launch_thrown(&mut self, stack: ItemStack, position: Vec3, velocity: Vec3) { + pub(super) fn launch_thrown( + &mut self, + stack: ItemStack, + position: Vec3, + velocity: Vec3, + owner: Option, + ) { self.potions.thrown.push(ThrownPotion { id: 0, stack, @@ -55,6 +65,7 @@ impl Game<'_> { position, velocity, age: 0, + owner, }); } } @@ -71,6 +82,8 @@ pub(super) struct BodyPotions { pub(super) struct PotionState { pub(super) effects: PlayerEffects, thrown: Vec, + /// The area effect clouds a server tracks (game/remote_projectiles.rs). + pub(super) clouds: Vec, applied: Vec<(&'static str, &'static str, f64, &'static str)>, /// Armor the protection table was computed for. protection_for: Option>>, @@ -133,6 +146,7 @@ impl PotionState { position: at, velocity, age: 0, + owner: None, }); } /// ThrowableItemProjectile.DATA_ITEM_STACK: the potion it shows. @@ -141,14 +155,22 @@ impl PotionState { t.stack = stack; } } - /// One tick of a server's client: `step` moves each toward where the - /// server put it. - pub(super) fn step_remote_thrown(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) { - for t in &mut self.thrown { - t.previous = t.position; - t.age += 1; - t.position = step(t.id, t.position); - } + /// A server's move: thrown potions have no interpolation handler, so + /// `moveOrInterpolateTo` puts them there at once. False when `id` isn't one. + pub(super) fn move_remote_thrown(&mut self, id: u32, at: Vec3) -> bool { + let Some(t) = self.thrown.iter_mut().find(|t| t.id == id) else { + return false; + }; + t.position = at; + true + } + /// `handleSetEntityMotion` for a thrown potion. False when `id` isn't one. + pub(super) fn remote_thrown_motion(&mut self, id: u32, velocity: Vec3) -> bool { + let Some(t) = self.thrown.iter_mut().find(|t| t.id == id) else { + return false; + }; + t.velocity = velocity; + true } pub(super) fn remove_remote_thrown(&mut self, id: u32) { self.thrown.retain(|t| t.id != id); @@ -227,6 +249,7 @@ impl Game<'_> { }, Vec3::new(eye[0], eye[1] - 0.1, eye[2]), v, + Some(self.player_display_text()), ); self.swing_arm(); self.consume_held(); @@ -266,7 +289,8 @@ impl Game<'_> { } else if let Some(rest) = self.give(filled) && let Some(eye) = self.eye_position() { - self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40); + // `player.drop(stack, false)`. + self.throw_from_eyes(rest, eye, false); } } /// Drinking a potion while right-click is held; true when handled. @@ -390,8 +414,28 @@ impl Game<'_> { for action in actions { self.apply_effect_action(action); } + self.turtle_helmet_tick(); self.apply_effect_status(); } + /// `Player.tick` -> `turtleHelmetTick`: with a turtle helmet on the head + /// and the eyes out of the water, Water Breathing for 200 ticks (no + /// particles, an icon). + fn turtle_helmet_tick(&mut self) { + let Some(p) = self.player.as_ref() else { + return; + }; + let eye_y = p.position.y + f64::from(p.dimensions.eye_height); + if !p.health.dead_or_dying() + && self.armor[0] + .as_ref() + .is_some_and(|s| &*s.item == "minecraft:turtle_helmet") + && !self.eye_in_water(p.position.x, eye_y, p.position.z) + { + let mut effect = EffectInstance::new("water_breathing", 200, 0); + effect.visible = false; + self.potions.effects.add(effect); + } + } /// A client's own effects (`LivingEntity.tickEffects` on the client, /// `MobEffectInstance.tickClient`): they count down, and the server /// removes them. Their modifiers and flags move the predicted player. @@ -484,6 +528,7 @@ impl Game<'_> { thrown.retain_mut(|t| { t.age += 1; t.previous = t.position; + self.thrown_potion_motion(t); let next = Vec3::new( t.position.x + t.velocity.x, t.position.y + t.velocity.y, @@ -516,29 +561,71 @@ impl Game<'_> { } } if let Some(p) = hit { - landed.push((t.stack.clone(), p)); + landed.push((t.stack.clone(), p, t.owner.clone())); return false; } t.position = next; - // ThrowableItemProjectile: drag 0.99 then gravity 0.05. - // ThrownExperienceBottle.getDefaultGravity is 0.07. - let gravity = if &*t.stack.item == "minecraft:experience_bottle" { - 0.07 - } else { - 0.05 - }; - t.velocity = Vec3::new( - t.velocity.x * 0.99, - t.velocity.y * 0.99 - gravity, - t.velocity.z * 0.99, - ); t.age < 1200 && t.position.y > -128.0 }); self.potions.thrown = thrown; - for (stack, at) in landed { - self.splash(&stack, at); + for (stack, at, owner) in landed { + self.splash(&stack, at, owner); } } + /// `ThrowableProjectile.tick`'s `applyGravity` and `applyInertia`, which + /// come before the move: gravity 0.05 (0.07 for an experience bottle), + /// then drag 0.99 (0.8 in water). + fn thrown_potion_motion(&self, t: &mut ThrownPotion) { + let gravity = if &*t.stack.item == "minecraft:experience_bottle" { + 0.07 + } else { + 0.05 + }; + let at = t.position; + let water = self + .res + .facts() + .get(self.world.block( + at.x.floor() as i32, + at.y.floor() as i32, + at.z.floor() as i32, + )) + .fluid + == horizon_client::blocks::Fluid::Water; + let inertia = if water { 0.8 } else { 0.99 }; + t.velocity = Vec3::new( + t.velocity.x * inertia, + (t.velocity.y - gravity) * inertia, + t.velocity.z * inertia, + ); + } + /// `ThrowableProjectile.tick` on a server's client: it falls and moves + /// by itself between the server's updates and stops at a block; only + /// the server breaks it. + pub(super) fn step_remote_thrown(&mut self) { + let mut thrown = std::mem::take(&mut self.potions.thrown); + for t in &mut thrown { + t.previous = t.position; + t.age += 1; + self.thrown_potion_motion(t); + let next = Vec3::new( + t.position.x + t.velocity.x, + t.position.y + t.velocity.y, + t.position.z + t.velocity.z, + ); + let state = self.world.block( + next.x.floor() as i32, + next.y.floor() as i32, + next.z.floor() as i32, + ); + if self.res.facts().get(state).full_collision { + t.velocity = Vec3::ZERO; + } else { + t.position = next; + } + } + self.potions.thrown = thrown; + } /// `ThrownItemRenderer` for thrown splash and lingering potions and /// experience bottles: the item (GROUND) facing the camera at scale 1, /// lit at the light probe (the eye, 0.85 of the 0.25 height). @@ -590,6 +677,7 @@ impl Game<'_> { effects: &'static [(&'static str, i32, i32)], at: Vec3, scale: f64, + source: &Text, ) { if let Some(p) = self.player.as_ref() { let center = Vec3::new( @@ -605,6 +693,18 @@ impl Game<'_> { let instant = brewing::effect(id).is_some_and(|e| e.instant); if instant { if let Some(a) = horizon_client::effects::instant(id, *amp, intensity) { + // HealOrHarmMobEffect.applyInstantaneousEffect with + // a source: indirectMagic, not plain magic. + let a = match a { + EffectAction::Hurt("minecraft:magic", amount) => { + self.note_direct_entity( + "minecraft:indirect_magic", + source.clone(), + ); + EffectAction::Hurt("minecraft:indirect_magic", amount) + } + a => a, + }; self.apply_effect_action(a); } } else { @@ -620,68 +720,47 @@ impl Game<'_> { } } /// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash). - fn splash(&mut self, stack: &ItemStack, at: Vec3) { + fn splash(&mut self, stack: &ItemStack, at: Vec3, owner: Option) { + let block = [at.x, at.y, at.z].map(|v| v.floor() as i32); if &*stack.item == "minecraft:experience_bottle" { // ThrownExperienceBottle.onHit: the water-coloured splash (level - // event 2002) and 3 to 11 experience. - let pitch = self.world.random.next_float() * 0.1 + 0.9; - self.audio.play( - "minecraft:entity.splash_potion.break", - Some([at.x, at.y, at.z]), - 1.0, - pitch, - ); - for _ in 0..8 { - let v = [ - f64::from(self.world.random.next_float() - 0.5) * 0.3, - 0.2, - f64::from(self.world.random.next_float() - 0.5) * 0.3, - ]; - let p = horizon_client::particles::Particle::terrain( - &mut self.world.random, - [at.x, at.y, at.z], - v, - "item/splash_potion".into(), - 0x38_5DC6, - ); - self.particles.push(p); - } + // event 2002, its sound 1053) and 3 to 11 experience. + self.level_event_at(2002, block, 0xFF38_5DC6u32 as i32); + self.level_event_at(1053, block, 0); let r = &mut self.world.random; let value = 3 + r.next_int_bound(5).unwrap_or(0) + r.next_int_bound(5).unwrap_or(0); self.spawn_orbs([at.x, at.y, at.z], value as u32); return; } let lingering = &*stack.item == "minecraft:lingering_potion"; - let event = if lingering { - "minecraft:entity.lingering_potion.break" - } else { - "minecraft:entity.splash_potion.break" - }; - let pitch = self.world.random.next_float() * 0.1 + 0.9; - self.audio.play(event, Some([at.x, at.y, at.z]), 1.0, pitch); + // AbstractThrownPotion.onHit: level event 2007 and sound 1054 for a + // potion with instant effects, 2002 and 1053 otherwise. + let potion = stack.potion().and_then(brewing::potion); + let instant = potion.is_some_and(|d| { + d.effects + .iter() + .any(|(id, ..)| brewing::effect(id).is_some_and(|e| e.instant)) + }); let color = brewing::potion_color(stack.potion()); - for _ in 0..8 { - let v = [ - f64::from(self.world.random.next_float() - 0.5) * 0.3, - 0.2, - f64::from(self.world.random.next_float() - 0.5) * 0.3, - ]; - let p = horizon_client::particles::Particle::terrain( - &mut self.world.random, - [at.x, at.y, at.z], - v, - "item/splash_potion".into(), - color, - ); - self.particles.push(p); - } + self.level_event_at(if instant { 2007 } else { 2002 }, block, color as i32); + self.level_event_at(if instant { 1054 } else { 1053 }, block, 0); let scale = if lingering { 0.25 } else { 1.0 }; - let Some(def) = stack.potion().and_then(brewing::potion) else { + let Some(def) = potion else { return; }; // Every player in range (`ThrownSplashPotion.applySplash` over // `LivingEntity`s, the players among them). - self.for_each_player(|g| g.splash_on_player(def.effects, at, scale)); + // Instant damage is indirectMagic(potion or cloud, owner), which the + // death message names by the owner, else by the potion or cloud. + let source = owner.unwrap_or_else(|| { + let entity = if lingering { + "entity.minecraft.area_effect_cloud" + } else { + "entity.minecraft.splash_potion" + }; + Text::translate(entity, &[]) + }); + self.for_each_player(|g| g.splash_on_player(def.effects, at, scale, &source)); // Mobs take the instant effects (undead invert healing and harming). let undead = &self.res.stations().enchantments.entity_tags; let mut hits = Vec::new(); diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index bedca5708..da7c79394 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -235,7 +235,7 @@ impl Game<'_> { } out } - fn difficulty_id(&self) -> i32 { + pub(super) fn difficulty_id(&self) -> i32 { use horizon_world::food::Difficulty; match self.world.health_rules.difficulty { Difficulty::Peaceful => 0, @@ -796,6 +796,8 @@ impl Game<'_> { let s = m.extra.raider.get_or_insert_with(Box::default); s.rider = has_rider; s.in_village = in_village; + // Vindicator.customServerAiStep: `ServerLevel.isRaided`. + s.raided = species == Species::Vindicator && raids.nearby(block).is_some(); if s.raid_id.is_some_and(|id| raids.get(id).is_none()) { s.raid_id = None; s.ticks_outside_raid = 0; diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 96e12d79b..024d45734 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -338,6 +338,25 @@ impl Game<'_> { ui.client_known = Some(known.clone()); ui.client_version += 1; } + /// Every entry of the book, in its order (capability `recipes`). + #[cfg(feature = "mods")] + pub(super) fn recipe_book_entries(&mut self) -> Vec { + self.ensure_book(); + self.recipe_ui + .book + .as_ref() + .map_or_else(Vec::new, |b| b.entries.clone()) + } + /// The display ids the player's book holds, and a number that changes + /// whenever they do (capability `recipes`). + #[cfg(feature = "mods")] + pub(super) fn recipe_book_displays(&mut self) -> (u64, Vec) { + self.sync_client_book(); + ( + self.recipe_ui.client_version, + self.recipe_ui.client.displays(), + ) + } fn ensure_book(&mut self) { if self.recipe_ui.book.is_none() { let mut book = Book::build(self.res.recipes(), self.res.items()); @@ -826,6 +845,34 @@ impl Game<'_> { self.recipe_ui.ghost.clear(); self.place_recipe(book_type, entry_index, use_max); } + /// Whether the open screen takes `recipes.place`: a crafting grid's + /// book (the inventory's or a crafting table's). + #[cfg(feature = "mods")] + pub(super) fn mod_recipe_screen(&self) -> bool { + self.screen == Screen::Inventory + && self.active_book() == Some(BookType::Crafting) + && !self.spectator() + } + /// `recipes.place`: the book's click on the recipe with this display + /// id, refused as `handlePlaceRecipe` refuses it (no crafting screen, + /// not in the player's book; an impossible one in `place_recipe`). + #[cfg(feature = "mods")] + pub(super) fn mod_place_recipe(&mut self, display_id: i32, all: bool) { + if !self.mod_recipe_screen() || !self.recipe_ui.client.displays().contains(&display_id) { + return; + } + self.ensure_book(); + let Some(index) = self + .recipe_ui + .book + .as_ref() + .and_then(|b| b.entries.iter().position(|e| e.display_id == display_id)) + else { + return; + }; + self.recipe_ui.ghost.clear(); + self.place_recipe(BookType::Crafting, index, all); + } /// `ServerboundPlaceRecipePacket`: the server places the recipe /// (`ServerPlaceRecipe` on the menu engine) and answers with a ghost /// recipe when the items are missing. diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5651647b7..8d54f017f 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -11,7 +11,7 @@ use super::{Dim, Game, Mining, Screen}; use horizon_client::first_person::{Hand, SwingAnimation}; use horizon_client::{ Result, - chunk::{Chunk, SECTIONS}, + chunk::Chunk, containers::{BlockEntity, Furnace, FurnaceKind}, entities::{Experience, ExperienceOrb, ItemEntity}, hud::{HudBatch, rgba}, @@ -109,6 +109,8 @@ enum Received { pub(super) struct Remote { pub session: Session, pub brand: String, + /// The server announced it runs mods' quiet commands. + pub quiet_commands: bool, pub(super) builtin: Arc, lang: Arc, pub(super) registries: Arc, @@ -419,6 +421,7 @@ impl Game<'_> { self.remote = Some(Remote { session, brand: "unknown".into(), + quiet_commands: false, builtin: Arc::new(builtin), lang, registries: Arc::new(Dynamic::default()), @@ -839,7 +842,15 @@ impl Game<'_> { remote.brand = brand; } } - Event::Reconfigured(registries) => self.set_registries(registries), + Event::QuietCommands => { + if let Some(remote) = &mut self.remote { + remote.quiet_commands = true; + } + } + Event::Reconfigured(registries) => { + self.boss_overlay.reset(); + self.set_registries(registries); + } // handleTransfer: "Cannot transfer to server from // singleplayer" (no ServerData), so the world just closes. Event::Transfer { host, port } => { @@ -998,6 +1009,9 @@ impl Game<'_> { self.world.day_time, self.world.weather, ); + let old = std::mem::take(&mut self.world.chunks); + let count = old.len(); + horizon_client::chunk::free_columns(old, count); self.world = World::new(self.res.facts().air, spawn.seed); self.world.game_time = time; self.world.day_time = day; @@ -1059,14 +1073,14 @@ impl Game<'_> { if gone.is_empty() { return; } + let mut freed = Vec::with_capacity(gone.len()); for &(x, z) in &gone { - self.streaming.forget(&mut self.world, x, z); - if let Some(renderer) = self.renderer.as_mut() { - for sy in 0..SECTIONS as i32 { - renderer.remove((x, sy, z)); - } - } + freed.extend(self.streaming.forget(&mut self.world, x, z)); } + if let Some(renderer) = self.renderer.as_mut() { + renderer.remove_columns(gone.iter().copied()); + } + horizon_client::chunk::free_columns(freed, gone.len()); // One pass for all of them. self.world .block_entities @@ -1255,6 +1269,9 @@ impl Game<'_> { } else { self.res.mob_types().get(kind).cloned() }; + if kind == "minecraft:ender_dragon" { + self.spawn_remote_dragon(id, position, yaw); + } if kind == "minecraft:experience_orb" { // Its value (ExperienceOrb.DATA_VALUE) follows in SetEntityData. self.orbs.retain(|o| o.id != id as u32); @@ -1266,6 +1283,8 @@ impl Game<'_> { value: 1, age: 0, on_ground: false, + count: 1, + ticks: 0, }); } if let Some(t) = mob_type { @@ -1361,13 +1380,17 @@ impl Game<'_> { m.on_ground = on_ground; return; } - if let Some(p) = self.creatures.projectiles.iter_mut().find(|p| { - p.id == id as u32 - && matches!( - p.kind, - horizon_client::projectiles::ProjectileKind::LargeFireball { .. } - ) - }) { + // Projectiles keep Entity's NO_OP InterpolationHandler too: the + // server's position replaces theirs at once and their own tick + // flies them on (`tick_remote_projectiles`). Eased towards it + // instead, they only moved when an update came, every 10 to 20 + // ticks. + if let Some(p) = self + .creatures + .projectiles + .iter_mut() + .find(|p| p.id == id as u32) + { if path.is_some() { p.position = Vec3::new(position[0], position[1], position[2]); } @@ -1377,6 +1400,22 @@ impl Game<'_> { } return; } + if path.is_some() + && (self.potions.move_remote_thrown( + id as u32, + Vec3::new(position[0], position[1], position[2]), + ) || self.end.move_remote_eye(id as u32, position)) + { + return; + } + // A dragon fireball keeps Entity's NO_OP InterpolationHandler too: + // the server's position replaces its own at once. + if let Some(b) = self.dragon_fireballs.iter_mut().find(|b| b.id == id as u32) { + if path.is_some() { + b.position = Vec3::new(position[0], position[1], position[2]); + } + return; + } if let Some(p) = r.pending_items.get_mut(&id) { p.0 = position; } @@ -1423,6 +1462,8 @@ impl Game<'_> { 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); + // Before the crystals go: the dragon's beam index follows them. + self.remove_remote_dragon(id); self.remove_remote_object(id as u32); self.remove_remote_projectile(id as u32); if let Some(r) = self.remote.as_mut() { @@ -1519,7 +1560,7 @@ impl Game<'_> { } } /// Find a game slot in the menu's complete, contiguous slot mapping. - fn menu_slot_index(menu: &str, internal: usize) -> Option { + pub(super) fn menu_slot_index(menu: &str, internal: usize) -> Option { (0..) .map_while(|slot| Self::menu_slot(menu, slot)) .position(|slot| slot == internal) @@ -1631,9 +1672,7 @@ impl Game<'_> { .block_entities .retain(|k, _| (k.0 >> 4, k.2 >> 4) != (x, z)); if let Some(renderer) = self.renderer.as_mut() { - for sy in 0..SECTIONS as i32 { - renderer.remove((x, sy, z)); - } + renderer.remove_columns([(x, z)]); } } C::ChunkBatchFinished(_) => { @@ -1660,19 +1699,30 @@ impl Game<'_> { } } C::BlockChangedAck(p) => self.end_predictions(p.sequence), - // ClientLevel.blockEvent: BlockEntity.triggerEvent (chest lids, - // shulker boxes, bells) when the block is still the one it names. + // Level.blockEvent on the client level: the block's triggerEvent + // runs on the client's copy of whatever is at pos (a piston's + // moveBlocks builds the moving block entities it animates, a note + // block plays); what it doesn't handle reaches the client copy of + // the block entity (chest lids, shulker boxes). 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 named = self.remote.as_ref().and_then(|r| { - r.builtin - .get("minecraft:block")? - .name(p.block) - .map(str::to_owned) + let pos = horizon_core::position::BlockPos::new(p.pos[0], p.pos[1], p.pos[2]); + let triggered = self.with_level(|b, level, ticks| { + b.client_block_event(level, ticks, pos, i32::from(p.b0), i32::from(p.b1)) }); - if named.as_deref() == Some(&**block) { - self.block_entity_event(p.pos, i32::from(p.b0), i32::from(p.b1)); + self.sync_moving_pistons(); + self.process_level_events()?; + if !triggered { + let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]); + let block = &self.res.facts().get(state).name; + let named = self.remote.as_ref().and_then(|r| { + r.builtin + .get("minecraft:block")? + .name(p.block) + .map(str::to_owned) + }); + if named.as_deref() == Some(&**block) { + self.block_entity_event(p.pos, i32::from(p.b0), i32::from(p.b1)); + } } } // ClientLevel.levelEvent: LevelEventHandler, as this client's own @@ -1691,7 +1741,17 @@ impl Game<'_> { f64::from(p.y) / 8.0, f64::from(p.z) / 8.0, ]; - self.audio.play(&name, Some(at), p.volume, p.pitch); + // ClientPacketListener.handleSoundEvent plays with packet.getSource(). + match usize::try_from(p.source) + .ok() + .filter(|s| *s < horizon_client::settings::SOUND_SOURCES.len()) + { + Some(source) => { + self.audio + .play_on(source, &name, Some(at), p.volume, p.pitch) + } + None => self.audio.play(&name, Some(at), p.volume, p.pitch), + } } } C::StopSound(p) => self @@ -1925,9 +1985,9 @@ impl Game<'_> { } } } - // Entity.DATA_SHARED_FLAGS_ID's crouching bit: another - // player's or a mannequin's crouch (their model and - // Entity.isDiscrete's name tag). + // Entity.DATA_SHARED_FLAGS_ID's crouching and sprinting bits: + // another player's or a mannequin's crouch (their model and + // Entity.isDiscrete's name tag), and the dust a runner raises. if (mannequin || self .remote @@ -1938,6 +1998,7 @@ impl Game<'_> { for (index, _, value) in &p.values { if let (0, Value::Byte(flags)) = (index, value) { m.extra.crouching = flags & 2 != 0; + m.extra.sprinting = flags & 8 != 0; } } } @@ -1957,6 +2018,7 @@ impl Game<'_> { } self.remote_object_data(p.id, &p.values); self.remote_projectile_data(p.id, &p.values); + self.remote_dragon_data(p.id, &p.values); } // ClientPacketListener.handleSetEquipment: what a mob or another // player holds and wears (EquipmentSlot ordinals). @@ -2015,7 +2077,10 @@ impl Game<'_> { { self.add_pickup(super::pickups::Taken::Orb(Box::new(orb)), collector); } - self.remove_entity(p.item); + // An orb stays: the server may still hold merged ones in it. + if !orb { + self.remove_entity(p.item); + } } // ClientPacketListener.handleSetEntityMotion: knockback on this player. C::SetEntityMotion(p) if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) => { @@ -2038,6 +2103,8 @@ impl Game<'_> { } else 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; + } else { + self.remote_dragon_hurt(p.id); } } C::HurtAnimation(p) => { @@ -2047,9 +2114,15 @@ impl Game<'_> { } } else if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { m.hurt_time = 10; + } else { + self.remote_dragon_hurt(p.id); } } C::EntityEvent(p) => { + if p.event == super::fireworks::FIREWORK_EXPLODE_EVENT { + self.remote_firework_explosion(p.id); + } + self.remote_fangs_event(p.id as u32, p.event); // LocalPlayer.setPermissions also refreshes an open World Options screen. if (24..=28).contains(&p.event) && self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) @@ -2063,15 +2136,44 @@ impl Game<'_> { { horizon_client::mobs::rabbit::hop_event(m); } + if p.event == 19 + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) + { + horizon_client::mobs::aquatic::squid_cycle_event(m); + } // EntityEvent.DEATH: start the death animation. if p.event == 3 && let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { m.health = 0.0; } + // LivingEntity.handleEntityEvent 60: the poof as the dead body goes. + if p.event == 60 + && let Some(m) = self.mobs.iter().find(|m| m.id == p.id as u32) + { + let (at, w, h) = (m.position, f64::from(m.width()), f64::from(m.height())); + self.death_poof([at.x, at.y, at.z], w, h); + } if p.event == super::totem::TOTEM_EVENT { self.remote_totem(p.id); } + // Entity event 53: the honey slide particles of a player + // sliding down a honey block (HoneyBlock.showSlideParticles). + if p.event == 53 { + let at = if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) { + self.player + .as_ref() + .map(|q| [q.position.x, q.position.y, q.position.z]) + } else { + self.mobs + .iter() + .find(|m| m.id == p.id as u32) + .map(|m| [m.position.x, m.position.y, m.position.z]) + }; + if let Some(at) = at { + self.honey_slide_particles(at); + } + } } C::Animate(p) => self.remote_animate(p.id, p.action), // ClientPacketListener.handleSwingAnimation: the entity swings @@ -2935,8 +3037,12 @@ impl Game<'_> { /// entities whose own tick moves them on a client: dropped items, falling /// blocks and primed TNT. fn remote_motion(&mut self, id: i32, velocity: [f64; 3]) { + self.remote_dragon_motion(id, velocity); let v = Vec3::new(velocity[0], velocity[1], velocity[2]); - if let Some(d) = self.dropped.iter_mut().find(|d| d.id == id as u32) { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) { + // Squid.aiStep derives its body pitch and roll from network motion. + m.velocity = v; + } else if let Some(d) = self.dropped.iter_mut().find(|d| d.id == id as u32) { d.velocity = v; } else if let Some(f) = self.falling.iter_mut().find(|f| f.id == id as u32) { f.velocity = v; @@ -2949,12 +3055,16 @@ impl Game<'_> { .find(|p| p.id == id as u32) { p.velocity = v; + } else if let Some(b) = self.dragon_fireballs.iter_mut().find(|b| b.id == id as u32) { + b.velocity = v; } else if let Some(p) = self .remote .as_mut() .and_then(|r| r.pending_items.get_mut(&id)) { p.1 = v; + } else if !self.potions.remote_thrown_motion(id as u32, v) { + self.end.remote_eye_motion(id as u32, velocity); } } fn apply_remote_health(&mut self) { @@ -3061,6 +3171,14 @@ impl Game<'_> { fn tick_remote_level(&mut self) -> Result<()> { self.ticks += 1; self.track_experience_display(); + // Player.tick's ItemCooldowns.tick: this path replaces `tick_world`'s + // for a server's client (multiplayer and the default single player), + // so the entries advance here or the slot stays shaded until the + // server says the entry ended. `onCooldownEnded` is the plain + // ItemCooldowns' no-op on a client. + self.cooldowns.tick(); + // Leaving a slot clears its bundle's selection here and on the server. + self.tick_bundle_hover(); // Options.broadcastOptions: a changed render distance or Chat option // is sent again. let view = client_view_distance(self.settings.render_distance); @@ -3098,8 +3216,14 @@ impl Game<'_> { self.border.tick(); self.player_border(); self.tick_remote_entities(running); - // ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells. + // ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells, + // and the moving pistons a block event's client-side moveBlocks made + // (their progress advances between the server's block updates). self.tick_block_entity_anims(); + self.with_level(|b, level, ticks| { + b.client_tick_block_entities(level, ticks); + }); + self.sync_moving_pistons(); self.tick_hand(); self.tick_particles(); self.tick_client_ambient(); @@ -3209,6 +3333,11 @@ impl Game<'_> { resources: self.motion, } .controlled_simulation_tick(keys)?; + } else { + // LivingEntity.baseTick counts hurtTime down for a dead or riding + // player too (controlled_simulation_tick does it otherwise): left + // at 10, the hurt tilt restarted every frame and shook the camera. + player.health.advance_clock(); } // LocalPlayer.onUpdateAbilities: flight turned on or off (a double // jump, a spectator, landing) is sent to the server. @@ -3245,6 +3374,13 @@ impl Game<'_> { horizon_client::motion::MotionEvent::InsidePortal { .. } => { self.client_inside_nether_portal(); } + // HoneyBlock.maybeDoSlideEffects on the client's own level: + // the slide sound, heard here (LocalPlayer.playSound); the + // particles come from the server's event 53. + horizon_client::motion::MotionEvent::HoneySlide { sound: true, .. } => { + self.audio + .play("minecraft:block.honey_block.slide", Some(feet), 1.0, 1.0); + } _ => {} } } @@ -3421,9 +3557,30 @@ impl Game<'_> { if m.species() == horizon_client::mobs::Species::Rabbit { horizon_client::mobs::rabbit::base_tick(m); } + if matches!( + m.species(), + horizon_client::mobs::Species::Horse + | horizon_client::mobs::Species::Donkey + | horizon_client::mobs::Species::Mule + | horizon_client::mobs::Species::SkeletonHorse + | horizon_client::mobs::Species::ZombieHorse + ) { + horizon_client::mobs::equine::tail_tick(m); + } if m.species() == horizon_client::mobs::Species::Creeper { horizon_client::mobs::hostile::creeper_client_tick(m); } + if matches!( + m.species(), + horizon_client::mobs::Species::Guardian + | horizon_client::mobs::Species::ElderGuardian + ) { + horizon_client::mobs::guardian::client_tick(m); + } + // PolarBear.tick: the stand animation follows the synched flag. + if m.species() == horizon_client::mobs::Species::PolarBear { + horizon_client::mobs::polar_bear::client_tick(m); + } if m.hurt_time > 0 { m.hurt_time -= 1; } @@ -3483,6 +3640,8 @@ impl Game<'_> { } else if m.alive() { m.body_rotation_tick(); } + // Squid.aiStep follows LivingEntity's interpolation and head turn. + horizon_client::mobs::aquatic::squid_client_step(m); // 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); @@ -3491,6 +3650,9 @@ impl Game<'_> { if m.species() == horizon_client::mobs::Species::Rabbit { horizon_client::mobs::rabbit::post_tick(m); } + if m.species() == horizon_client::mobs::Species::Bat { + horizon_client::mobs::bat::setup_animation_states(m); + } } for o in self.orbs.iter_mut().filter(|_| running) { o.previous = o.position; @@ -3519,6 +3681,18 @@ impl Game<'_> { self.remote_player_eating(&item, ticks, at, eye, pitch, yaw); } if running { + // The dragon: LivingEntity's interpolation, inside its aiStep. + let dragon_lerp = self + .dragon + .as_ref() + .and_then(|d| lerps.get_mut(&(d.id as i32))) + .filter(|l| l.steps > 0) + .map(|l| { + let steps = l.steps; + l.steps -= 1; + (l.target, l.rotation.map(|r| r.0), steps) + }); + self.tick_remote_dragon(dragon_lerp); // 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)) { @@ -3681,6 +3855,15 @@ impl Game<'_> { /// MultiPlayerGameMode.startDestroyBlock / continueDestroyBlock. fn remote_mining(&mut self, start: bool) { + if !self + .res + .items() + .can_destroy_block(self.held(), self.creative) + { + self.stop_remote_mining(); + self.mining = None; + return; + } let Some(r) = self.remote.as_mut() else { return; }; @@ -3820,19 +4003,25 @@ 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 at = [ - f64::from(pos[0]) + 0.5, - f64::from(pos[1]) + 0.5, - f64::from(pos[2]) + 0.5, - ]; - self.audio.play( - &s.break_sound, - Some(at), - (s.volume + 1.0) / 2.0, - s.pitch * 0.8, - ); - self.destroy_particles(pos, state); + // Block.playerWillDestroy's destroy event (particles and the break + // sound), which BaseFireBlock skips: the server's extinguish sound + // is all a player hears. + let facts = self.res.facts().get(state); + if !facts.has_class("BaseFireBlock") { + let s = facts.sounds.clone(); + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + self.audio.play( + &s.break_sound, + Some(at), + (s.volume + 1.0) / 2.0, + s.pitch * 0.8, + ); + self.destroy_particles(pos, state); + } // The server's block update follows (waterlogged blocks leave water). let air = self.world.air; if self.world.set(pos[0], pos[1], pos[2], air).is_ok() { @@ -3931,15 +4120,11 @@ impl Game<'_> { world_border: false, sequence: seq, })); - let target = [ - hit.pos[0] + hit.face[0], - hit.pos[1] + hit.face[1], - hit.pos[2] + hit.face[2], - ]; - let ticks = self.ticks; + // Only a predicted placement (predict_place) marks a cell whose + // resend plays a place sound: an empty hand or a non-block item + // places nothing (BlockItem.place is where the sound comes from). if let Some(r) = self.remote.as_mut() { r.use_target = Some(hit.pos); - r.placing = Some((target, ticks)); } if reacts { self.predict_use(&changes, seq); @@ -4506,6 +4691,7 @@ impl Game<'_> { } KeyCode::KeyE => { // The inventory opens without telling the server. + self.recipe_ui.reset_screen(); self.screen = if self.creative { Screen::Creative } else { @@ -4580,7 +4766,7 @@ impl Game<'_> { } /// The server's open menu: its window id and menu type (0, "inventory" /// when none is open). - fn remote_menu(&self) -> (i32, String) { + pub(super) 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()), @@ -4670,26 +4856,6 @@ impl Game<'_> { })); } } - /// 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) = self.remote_menu(); - let slot = Self::menu_slot_index(&menu, internal); - let Some(slot) = slot else { return false }; - let carried = self.to_network(&self.carried).map(|s| Hashed::of(&s)); - let state = self.remote.as_ref().map_or(0, |r| r.state_id); - self.send(S::ContainerClick(play::ContainerClick { - container, - state, - slot: slot as i16, - button, - input, - changed: Vec::new(), - carried, - })); - true - } /// The server's open menu is the inventory or a chest-like container /// (chests, barrels, ender chests: `generic_9xN`; shulker boxes). pub(super) fn remote_storage_open(&self) -> bool { @@ -4772,6 +4938,7 @@ impl Game<'_> { self.remote_close_local(); } fn remote_close_local(&mut self) { + self.recipe_ui.reset_screen(); if let Some(r) = self.remote.as_mut() { r.menu = None; r.menu_title = None; @@ -4807,16 +4974,20 @@ impl Game<'_> { if self.open_menu_name(p.container) != "minecraft:merchant" { return; } - let cost = |g: &Self, c: &play::NetCost| horizon_client::merchant::ItemCost { - stack: ItemStack::new(&g.item_name(c.item), c.count.max(0) as u32), + let cost = |g: &Self, c: &play::NetCost| { + g.to_stack(&Some(c.clone().into())) + .map(|stack| horizon_client::merchant::ItemCost { stack }) }; let offers: Vec<_> = p .offers .iter() .filter_map(|o| { let mut offer = horizon_client::merchant::MerchantOffer { - base_cost_a: cost(self, &o.cost_a), - cost_b: o.cost_b.as_ref().map(|b| cost(self, b)), + base_cost_a: cost(self, &o.cost_a)?, + cost_b: match &o.cost_b { + Some(b) => Some(cost(self, b)?), + None => None, + }, result: self.to_stack(&Some(o.result.clone()))?, uses: o.uses, max_uses: o.max_uses, @@ -4842,6 +5013,9 @@ impl Game<'_> { } /// ClientboundOpenScreenPacket for the menus Horizon draws. fn remote_open_screen(&mut self, p: play::OpenScreen) { + // A new RecipeBookComponent owns fresh ghost slots and an overlay, + // even when the server replaces a menu without a close packet. + self.recipe_ui.reset_screen(); let menu = self .remote .as_ref() diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index fbfc5a4fb..65bbbfbbe 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -4,14 +4,15 @@ //! own simulation, which a client of a server doesn't run. use super::Game; use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES}; -use horizon_client::mobs::{Mob, Species, tame}; -use horizon_protocol::entity_data::Value; +use horizon_client::mobs::{Mob, Species, Who, bat, tame}; +use horizon_client::particles::{ParticleOptions, ParticleType}; +use horizon_protocol::entity_data::{Particle, ParticleData, Value}; use horizon_protocol::registry::Builtin; /// The values `apply` takes from one SetEntityData packet, by vanilla's entry /// indices (Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses). /// `builtin` names the ids of built-in registries. -fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin) { +fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_entity: i32) { let species = m.species(); let baby = super::lan::baby_index(&m.kind.id); for (index, _, value) in values { @@ -34,6 +35,10 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin) { // LivingEntity.DATA_HEALTH_ID: the boss bars and the death // animation follow it. (9, Value::Float(health)) => m.health = *health, + // LivingEntity.DATA_EFFECT_PARTICLES and DATA_EFFECT_AMBIENCE_ID: + // the swirls of its effects (`tickEffects` draws them). + (10, Value::Particles(list)) => m.extra.effect_particles = swirls(list, builtin), + (11, Value::Bool(ambient)) => m.extra.effect_ambient = *ambient, // Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2, aggressive 4. // Mob.isAggressive draws the illagers' and skeletons' attack // poses and the vindicator's axe. @@ -46,11 +51,36 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin) { _ => {} } match (species, *index, value) { + (Species::Guardian | Species::ElderGuardian, 16, Value::Bool(moving)) => { + m.extra.flag2 = *moving; + } + (Species::Guardian | Species::ElderGuardian, 17, Value::Int(target)) => { + // Guardian.onSyncedDataUpdated resets the visual charge clock. + m.extra.counter2 = 0; + m.extra.flag = *target != 0; + m.ai.target = (*target != 0).then_some(if *target == local_entity { + Who::Player + } else { + Who::Mob(*target as u32) + }); + } + // PolarBear.DATA_STANDING_ID: the client animates the rearing. + (Species::PolarBear, 18, Value::Bool(standing)) => m.extra.flag = *standing, + // Bat.DATA_ID_FLAGS: resting in bit 0. + (Species::Bat, 16, Value::Byte(flags)) => bat::set_resting(m, flags & 1 != 0), // Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 sheared. (Species::Sheep, 18, Value::Byte(wool)) => { m.extra.color = (*wool & 15) as u8; m.extra.sheared = wool & 16 != 0; } + // SnowGolem.DATA_PUMPKIN_ID: 16 while the pumpkin is on. + (Species::SnowGolem, 16, Value::Byte(flags)) => m.extra.sheared = flags & 16 == 0, + // MushroomCow.DATA_TYPE: 0 red, 1 brown. + (Species::Mooshroom, 17, Value::Int(variant)) => { + m.extra.variant = (*variant == 1) as u8 + } + // Piglin.DATA_IS_DANCING: the dance pose. + (Species::Piglin, 19, Value::Bool(dancing)) => m.extra.scratch[0] = i32::from(*dancing), // TamableAnimal.DATA_FLAGS_ID: sitting 1, tame 4. (Species::Wolf | Species::Cat | Species::Parrot, 18, Value::Byte(flags)) => { m.extra.sitting = flags & 1 != 0; @@ -85,6 +115,30 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin) { } } +/// The options of a synched particle list: an entity effect carries its ARGB +/// colour, the omens none. +fn swirls(list: &[Particle], builtin: &Builtin) -> Vec { + let channel = |argb: i32, shift: u32| ((argb >> shift) & 255) as f32 / 255.0; + list.iter() + .filter_map(|p| { + let name = builtin.get("minecraft:particle_type")?.name(p.id)?; + let ty = ParticleType::from_name(name)?; + Some(match p.data { + Some(ParticleData::Color(argb)) => ParticleOptions::colored( + ty, + [ + channel(argb, 16), + channel(argb, 8), + channel(argb, 0), + channel(argb, 24), + ], + ), + _ => ParticleOptions::simple(ty), + }) + }) + .collect() +} + /// VillagerData as the network sends it: the type and the profession by /// their built-in registry ids, then the level. fn villager_data(m: &mut Mob, data: &[i32], builtin: &Builtin) { @@ -114,7 +168,7 @@ impl Game<'_> { return; }; if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) { - apply(m, values, &r.builtin); + apply(m, values, &r.builtin, r.entity_id); } } } @@ -126,6 +180,10 @@ pub(super) fn client_defaults(m: &mut Mob) { if matches!(m.species(), Species::Wolf | Species::Cat) { m.extra.color = tame::RED; } + if m.species() == Species::Bat { + // Bat's constructor sets resting only on the server; the data default is 0. + bat::set_resting(m, false); + } } #[cfg(test)] @@ -147,7 +205,7 @@ mod tests { } fn apply(m: &mut Mob, values: &[(u8, i32, Value)]) { - super::apply(m, values, &builtin()); + super::apply(m, values, &builtin(), 99); } fn mob(kind: &str) -> Option { @@ -158,6 +216,49 @@ mod tests { Some(m) } + #[test] + fn guardian_charge_follows_target_updates_and_caps_at_its_duration() { + use horizon_client::mobs::guardian::{beam, client_tick}; + for (kind, duration) in [("guardian", 80), ("elder_guardian", 60)] { + let Some(mut m) = mob(&format!("minecraft:{kind}")) else { + return; + }; + assert!(beam(&m, 0.0).is_none()); + apply( + &mut m, + &[ + (16, s::BOOLEAN, Value::Bool(true)), + (17, s::INT, Value::Int(99)), + ], + ); + assert!(m.extra.flag2); + assert_eq!(m.ai.target, Some(Who::Player)); + assert_eq!(beam(&m, 0.0), Some((0.0, 0.0))); + for _ in 0..duration + 10 { + client_tick(&mut m); + } + assert_eq!(beam(&m, 0.0), Some((duration as f32, 1.0))); + // Another player or a mob retains its network entity id. + apply(&mut m, &[(17, s::INT, Value::Int(42))]); + assert_eq!(m.ai.target, Some(Who::Mob(42))); + assert_eq!(m.extra.counter2, 0); + client_tick(&mut m); + assert_eq!(m.extra.counter2, 1); + apply( + &mut m, + &[ + (16, s::BOOLEAN, Value::Bool(false)), + (17, s::INT, Value::Int(0)), + ], + ); + client_tick(&mut m); + assert!(!m.extra.flag2); + assert_eq!(m.ai.target, None); + assert_eq!(m.extra.counter2, 0); + assert!(beam(&m, 0.0).is_none()); + } + } + #[test] fn a_sheep_takes_its_wool_and_a_calf_its_size() { let Some(mut m) = mob("minecraft:sheep") else { @@ -174,6 +275,69 @@ mod tests { assert!(!calf.is_baby()); } + #[test] + fn bat_flags_select_continuous_client_clocks_without_changing_motion() { + use horizon_client::mobs::{MobTypes, anim, keyframes::Animation}; + use horizon_core::geometry::Vec3; + use serde_json::json; + use std::{collections::HashMap, fs, sync::Arc}; + + // Original minimal resources keep this regression runnable without vanilla data. + let root = + std::env::temp_dir().join(format!("horizon-bat-animation-{}", std::process::id())); + fs::create_dir(&root).unwrap(); + fs::write(root.join("entity-types.json"), r#"{"minecraft:bat": {}}"#).unwrap(); + fs::write( + root.join("entity-models.json"), + r#"{"minecraft:bat#main": {"children": {"right_wing": {}, "head": {}}}}"#, + ) + .unwrap(); + let mut types = MobTypes::load(&root).unwrap(); + fs::remove_dir_all(root).unwrap(); + let position = Vec3::new(1.0, 2.25, 3.0); + let velocity = Vec3::new(0.2, 0.3, 0.4); + let mut m = Mob::new( + 1, + Arc::new(types.types.remove("minecraft:bat").unwrap()), + position, + 0.0, + ); + assert!(bat::resting(&m)); + client_defaults(&mut m); + assert!(!bat::resting(&m)); + m.velocity = velocity; + m.age = 1; + bat::setup_animation_states(&mut m); + m.age = 4; + apply(&mut m, &[(16, s::BYTE, Value::Byte(2))]); + bat::setup_animation_states(&mut m); + assert_eq!(m.anim.states[0].started, Some(1.0)); + + let curve = Animation::parse(&json!({"length": 1, "looping": true, + "bones": {"right_wing": [{"target": "rotation", "keyframes": + [[0,[0,0,0],[0,0,0],"linear"],[1,[0,1,0],[0,1,0],"linear"]]}]}})); + let animations = HashMap::from([("BatAnimation.BAT_FLYING".into(), curve)]); + let wing = |partial| { + let mut poses = anim::Poses::new(&m.kind.model); + anim::setup(&m, &anim::state(&m, partial), &mut poses, &animations); + poses.get("right_wing")[4] + }; + assert!(wing(0.5) > wing(0.0)); + + m.age = 5; + apply(&mut m, &[(16, s::BYTE, Value::Byte(3))]); + bat::setup_animation_states(&mut m); + assert!(bat::resting(&m)); + assert_eq!(m.anim.states[0].started, None); + assert_eq!(m.anim.states[1].started, Some(5.0)); + m.age = 7; + apply(&mut m, &[(16, s::BYTE, Value::Byte(0))]); + bat::setup_animation_states(&mut m); + assert_eq!(m.anim.states[0].started, Some(7.0)); + assert_eq!(m.anim.states[1].started, None); + assert_eq!((m.position, m.velocity), (position, velocity)); + } + #[test] fn a_wolf_takes_its_owner_flags_and_collar() { let Some(mut m) = mob("minecraft:wolf") else { diff --git a/crates/horizon-client/src/game/remote_objects.rs b/crates/horizon-client/src/game/remote_objects.rs index 251d277f3..05b1a2b9e 100644 --- a/crates/horizon-client/src/game/remote_objects.rs +++ b/crates/horizon-client/src/game/remote_objects.rs @@ -3,7 +3,7 @@ //! `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_client::entities::{ArmorStand, Cushion, ItemFrame, Painting}; use horizon_core::geometry::Vec3; use horizon_protocol::entity_data::Value; use std::sync::Arc; @@ -57,6 +57,16 @@ impl Game<'_> { invisible: false, check_interval: 0, }); + } else if kind == "minecraft:cushion" { + // BlockAttachedEntity.pos: `BlockPos.containing` of the spawn. + self.cushions.push(Cushion { + id, + position: at, + pos: block, + yaw: super::cushions::snap_yaw(yaw), + color: 0, + check_interval: 0, + }); } else if kind == "minecraft:lightning_bolt" { self.spawn_remote_bolt(id, position); } else if kind == "minecraft:painting" { @@ -152,6 +162,11 @@ impl Game<'_> { } _ => {} } + } else if let Some(c) = self.cushions.iter_mut().find(|c| c.id == id) { + // Cushion.DATA_COLOR (DyeColor, a byte-backed id). + if let (8, Value::Id(color)) = (index, value) { + c.color = (*color).clamp(0, 15) as u8; + } } 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) { @@ -267,6 +282,12 @@ impl Game<'_> { 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 c in &self.cushions { + out.push( + json!({"id": c.id, "kind": "minecraft:cushion", "position": at(c.position), + "yaw": c.yaw, "color": c.color_name()}), + ); + } for f in &self.item_frames { out.push( json!({"id": f.id, "kind": f.kind(), "position": f.pos, "facing": f.facing, @@ -286,6 +307,7 @@ impl Game<'_> { self.carts.clear(); self.boats.clear(); self.armor_stands.clear(); + self.cushions.clear(); self.item_frames.clear(); self.paintings.clear(); } @@ -295,6 +317,7 @@ impl Game<'_> { self.carts.retain(|c| c.id != id); self.boats.retain(|b| b.id != id); self.armor_stands.retain(|a| a.id != id); + self.cushions.retain(|c| c.id != id); self.item_frames.retain(|f| f.id != id); self.paintings.retain(|p| p.id != id); self.bolts.retain(|b| b.id != id); diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index a117b1b7c..55c233ca0 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -3,11 +3,26 @@ //! and `handleSetEntityData`): the server simulates them, the client draws //! them where it says and interpolates their moves. use super::{FallStep, FallingBlock, Game, fireworks::fireworks_of, view_vector}; -use horizon_client::projectiles::{Projectile, ProjectileKind}; -use horizon_core::{geometry::Vec3, position::BlockPos}; +use horizon_client::particles::{ParticleOptions, ParticleType}; +use horizon_client::projectiles::{Hit, Projectile, ProjectileKind, ProjectileWorld}; +use horizon_core::{geometry::Vec3, position::BlockPos, random::RandomSource}; use horizon_protocol::entity_data::Value; use horizon_world::registry::BlockStateId; +/// An `AreaEffectCloud` a server tracks: what its client tick reads. +pub(super) struct RemoteCloud { + id: u32, + at: [f64; 3], + radius: f32, + waiting: bool, + particle: ParticleOptions, +} + +/// `AreaEffectCloud.DEFAULT_PARTICLE`: a white entity effect. +fn default_cloud_particle() -> ParticleOptions { + ParticleOptions::colored(ParticleType::EntityEffect, [1.0; 4]) +} + /// The projectile a type id names, as Horizon models it. fn projectile_kind(kind: &str) -> Option { Some(match kind { @@ -37,6 +52,32 @@ fn projectile_kind(kind: &str) -> Option { }) } +/// `AbstractArrow.tick` on a client: water drag before the move, air drag +/// after it, then gravity; a block it reaches holds it (`inGround`). +fn remote_arrow_tick(p: &mut Projectile, w: &impl ProjectileWorld) { + p.previous = p.position; + p.age += 1; + if p.stuck { + return; + } + let water = w.in_water(p.position); + if water { + p.velocity = p.velocity.scale(0.6); + } + let to = p.position.add_vector(p.velocity); + if let Some((at, _, _)) = w.clip(p.position, to) { + p.position = at; + p.velocity = Vec3::ZERO; + p.stuck = true; + return; + } + p.position = to; + if !water { + p.velocity = p.velocity.scale(0.99); + } + p.velocity.y -= 0.05; +} + impl Game<'_> { /// `handleAddEntity` for these types; false when `kind` isn't one. pub(super) fn spawn_remote_projectile( @@ -54,6 +95,7 @@ impl Game<'_> { let (yaw, pitch) = rotation; self.remove_remote_projectile(id); match kind { + "minecraft:evoker_fangs" => self.insert_fangs(id, position, yaw, 0, 0), "minecraft:tnt" => self.tnts.push(super::tnt::PrimedTnt { id, position: at, @@ -92,6 +134,16 @@ impl Game<'_> { | "minecraft:experience_bottle" => { self.potions.add_remote_thrown(id, kind, at, velocity); } + "minecraft:dragon_fireball" => self + .dragon_fireballs + .push(super::dragon::DragonFireball::remote(id, at, velocity)), + "minecraft:area_effect_cloud" => self.potions.clouds.push(RemoteCloud { + id, + at: position, + radius: 3.0, + waiting: false, + particle: default_cloud_particle(), + }), "minecraft:eye_of_ender" => { self.end .add_remote_eye(id, position, [velocity.x, velocity.y, velocity.z]) @@ -110,6 +162,10 @@ impl Game<'_> { let Some(k) = projectile_kind(kind) else { return false; }; + if k == ProjectileKind::LlamaSpit { + self.particles + .llama_spit_burst(position, [velocity.x, velocity.y, velocity.z]); + } let mut p = Projectile::new(k, at, None); p.id = id; p.velocity = velocity; @@ -125,6 +181,31 @@ impl Game<'_> { pub(super) fn remote_projectile_data(&mut self, id: i32, values: &[(u8, i32, Value)]) { let id = id as u32; self.remote_hook_data(id, values); + if let Some(at) = self + .potions + .clouds + .iter() + .find(|c| c.id == id) + .map(|c| c.at) + { + // AreaEffectCloud.DATA_RADIUS, DATA_WAITING and DATA_PARTICLE. + for (index, _, value) in values { + let particle = match (index, value) { + (10, Value::Particle(p)) => self.received_particle(p, at), + _ => None, + }; + let Some(c) = self.potions.clouds.iter_mut().find(|c| c.id == id) else { + return; + }; + match (index, value) { + (8, Value::Float(r)) => c.radius = *r, + (9, Value::Bool(w)) => c.waiting = *w, + (10, _) => c.particle = particle.unwrap_or_else(default_cloud_particle), + _ => {} + } + } + return; + } if self.rockets.iter().any(|r| r.id == id) { for (index, _, value) in values { match (index, value) { @@ -220,6 +301,7 @@ impl Game<'_> { /// One tick of interpolation, as `tick_remote_objects`. pub(super) fn tick_remote_projectiles(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) { + self.tick_remote_fangs(); // PrimedTnt.tick runs on a client too: it falls, bounces and burns its // fuse down (the swell and flash follow it) between the server's // updates (every 10 ticks), and a client discards it when the fuse @@ -246,29 +328,34 @@ impl Game<'_> { } } self.falling = falling; - for p in &mut self.creatures.projectiles { - p.previous = p.position; - p.age += 1; - if matches!(p.kind, ProjectileKind::LargeFireball { .. }) { - // AbstractHurtingProjectile.tick advances on the client between - // the tracker updates (ten ticks apart for a ghast's fireball). - let at = p.position; - let water = self - .res - .facts() - .get(self.world.block( - at.x.floor() as i32, - at.y.floor() as i32, - at.z.floor() as i32, - )) - .fluid - == horizon_client::blocks::Fluid::Water; - p.apply_hurting_inertia(water); - p.position = p.position.add_vector(p.velocity); - } else { - p.position = step(p.id, p.position); + // Projectiles tick on the client too and fly on between the tracker's + // updates (10 to 20 ticks apart); a block stops them there, and only + // the server decides what they hit. + let mut projectiles = std::mem::take(&mut self.creatures.projectiles); + { + let w = self.mob_world_base(&[]); + let world = super::creatures::ProjWorld { + w: &w, + targets: Vec::new(), + }; + for p in &mut projectiles { + match p.kind { + ProjectileKind::Arrow { .. } => remote_arrow_tick(p, &world), + // ShulkerBullet.tick: only the server steers it. + ProjectileKind::ShulkerBullet { .. } => { + p.previous = p.position; + p.age += 1; + p.position = p.position.add_vector(p.velocity); + } + _ => { + if !matches!(p.tick(&world).1, Hit::None) { + p.velocity = Vec3::ZERO; + } + } + } } } + self.creatures.projectiles = projectiles; for t in &mut self.tridents { let id = t.id; t.remote_step(|at| step(id, at)); @@ -302,15 +389,82 @@ impl Game<'_> { c.time += 1; c.position = step(c.id, c.position); } - self.potions.step_remote_thrown(&mut step); + self.step_remote_thrown(); self.step_remote_hooks(&mut step); - self.end.step_remote_eyes(|id, at| { - let at = step(id, Vec3::new(at[0], at[1], at[2])); - [at.x, at.y, at.z] - }); + self.end.step_remote_eyes(); + self.tick_remote_clouds(); + // The dragon's fireballs fly on between the tracker's updates, with + // their dragon_breath trail (`AbstractHurtingProjectile.getTrailParticle`). + let trail = ParticleOptions::simple(ParticleType::DragonBreath); + for b in &mut self.dragon_fireballs { + let at = b.position; + let water = self + .res + .facts() + .get(self.world.block( + at.x.floor() as i32, + at.y.floor() as i32, + at.z.floor() as i32, + )) + .fluid + == horizon_client::blocks::Fluid::Water; + b.remote_step(water); + let p = b.position; + self.particles.add(&trail, [p.x, p.y + 0.5, p.z], [0.0; 3]); + } + } + + /// `AreaEffectCloud.clientTick`: while waiting, now and then two + /// particles near the middle; then about one per square block of the + /// disc, drifting (an entity effect stays still). + fn tick_remote_clouds(&mut self) { + for c in &self.potions.clouds { + let r = self.particles.random(); + if c.waiting && r.next_boolean() { + continue; + } + let (count, spread) = if c.waiting { + (2, 0.2) + } else { + ( + (std::f32::consts::PI * c.radius * c.radius).ceil() as i32, + c.radius, + ) + }; + for _ in 0..count { + let r = self.particles.random(); + let angle = r.next_float() * std::f32::consts::TAU; + let distance = r.next_float().sqrt() * spread; + let at = [ + c.at[0] + f64::from(angle.cos() * distance), + c.at[1], + c.at[2] + f64::from(angle.sin() * distance), + ]; + let (options, velocity) = if c.particle.ty == ParticleType::EntityEffect { + let default = c.waiting && r.next_boolean(); + let options = if default { + default_cloud_particle() + } else { + c.particle.clone() + }; + (options, [0.0; 3]) + } else if c.waiting { + (c.particle.clone(), [0.0; 3]) + } else { + let v = [ + (0.5 - r.next_double()) * 0.15, + f64::from(0.01f32), + (0.5 - r.next_double()) * 0.15, + ]; + (c.particle.clone(), v) + }; + self.particles.add(&options, at, velocity); + } + } } pub(super) fn remove_remote_projectile(&mut self, id: u32) { + self.fangs.list.retain(|f| f.id != id); self.tnts.retain(|t| t.id != id); self.falling.retain(|f| f.id != id); self.creatures.projectiles.retain(|p| p.id != id); @@ -318,19 +472,26 @@ impl Game<'_> { self.rockets.retain(|r| r.id != id); self.crystals.retain(|c| c.id != id); self.potions.remove_remote_thrown(id); + self.potions.clouds.retain(|c| c.id != id); + self.dragon_fireballs.retain(|b| b.id != id); self.end.remove_remote_eye(id); self.remove_remote_hook(id); } /// Every one a server sent (a new connection, level or dimension). pub(super) fn clear_remote_projectiles(&mut self) { + self.fangs.list.clear(); self.tnts.clear(); self.falling.clear(); self.creatures.projectiles.clear(); self.tridents.clear(); self.rockets.clear(); self.crystals.clear(); + // The dragon a server sent goes with its crystals. + self.dragon = None; self.potions.clear_thrown(); + self.potions.clouds.clear(); + self.dragon_fireballs.clear(); self.end.clear_remote_eyes(); self.clear_remote_hooks(); } @@ -340,6 +501,12 @@ impl Game<'_> { use serde_json::json; let at = |p: Vec3| [p.x, p.y, p.z]; let mut out = Vec::new(); + for f in &self.fangs.list { + out.push( + json!({"id": f.id, "kind": "minecraft:evoker_fangs", "position": f.pos, + "yaw": f.yaw, "started": f.started, "life": f.life}), + ); + } for t in &self.tnts { out.push(json!({"id": t.id, "kind": "minecraft:tnt", "position": at(t.position), "fuse": t.fuse})); } diff --git a/crates/horizon-client/src/game/remote_vehicles.rs b/crates/horizon-client/src/game/remote_vehicles.rs index 620aff97c..877ed66e6 100644 --- a/crates/horizon-client/src/game/remote_vehicles.rs +++ b/crates/horizon-client/src/game/remote_vehicles.rs @@ -56,6 +56,11 @@ impl Game<'_> { let p = a.position; hits.push((a.id as i32, d, [p.x, p.y, p.z])); } + if let Some((i, d, _)) = self.cushion_hit() { + let c = &self.cushions[i]; + let p = c.position; + hits.push((c.id as i32, d, [p.x, p.y, p.z])); + } if let Some((i, d)) = self.boat_hit() { let p = self.boats[i].position; hits.push((self.boats[i].id as i32, d, [p.x, p.y, p.z])); @@ -79,6 +84,8 @@ impl Game<'_> { hits.push((c.id as i32, d, [p.x, p.y, p.z])); } } + // EnderDragonPart.isPickable: the server's dragon hurts by part. + hits.extend(self.remote_dragon_part_hit(eye, dir, reach)); } let (id, distance, origin) = hits.into_iter().min_by(|a, b| a.1.total_cmp(&b.1))?; let point = at(distance); @@ -138,7 +145,10 @@ impl Game<'_> { self.position_rider(); return true; } - let seat = if let Some(i) = self.boats.iter().position(|b| b.id == id) { + let seat = if let Some(c) = self.cushions.iter().find(|c| c.id == id) { + // The seat does not move; the rider sits on the cushion. + Some(c.seat()) + } else if let Some(i) = self.boats.iter().position(|b| b.id == id) { // AbstractBoat.tick on the controlling client: steer and move. let mut b = self.boats[i].clone(); b.input = [keys.left, keys.right, keys.forward, keys.backward]; diff --git a/crates/horizon-client/src/game/render_control.rs b/crates/horizon-client/src/game/render_control.rs index 0a2f9b715..7c5ff4b2d 100644 --- a/crates/horizon-client/src/game/render_control.rs +++ b/crates/horizon-client/src/game/render_control.rs @@ -19,33 +19,7 @@ pub const HELP: &[&str] = &[ impl Game<'_> { /// Parse `name[k=v,...]` into a registry state (defaults for missing properties). fn parse_state(&self, text: &str) -> Result { - let (name, props) = match text.split_once('[') { - Some((n, rest)) => (n, rest.trim_end_matches(']')), - None => (text, ""), - }; - let name = if name.contains(':') { - name.to_owned() - } else { - format!("minecraft:{name}") - }; - let registry = &self.pack.assets.registry; - let default = registry - .default_state(&name) - .ok_or_else(|| format!("unknown block {name}"))?; - let mut state = registry - .state(default) - .ok_or("missing default state")? - .clone(); - for pair in props.split(',').filter(|p| !p.is_empty()) { - let (k, v) = pair - .split_once('=') - .ok_or_else(|| format!("bad property {pair}"))?; - if !state.properties.contains_key(k) { - return Err(format!("{name} has no property {k}").into()); - } - state.properties.insert(k.to_owned(), v.to_owned()); - } - Ok(registry.resolve(&state)?) + parse_state(self.pack.assets.registry, text) } pub(super) fn render_command(&mut self, words: &[&str]) -> Result> { let int = |i: usize| -> Result { @@ -137,3 +111,36 @@ impl Game<'_> { } } } + +/// Parse `name[k=v,...]` into a registry state (defaults for missing properties). +pub(super) fn parse_state( + registry: &horizon_world::registry::BlockRegistry, + text: &str, +) -> Result { + let (name, props) = match text.split_once('[') { + Some((n, rest)) => (n, rest.trim_end_matches(']')), + None => (text, ""), + }; + let name = if name.contains(':') { + name.to_owned() + } else { + format!("minecraft:{name}") + }; + let default = registry + .default_state(&name) + .ok_or_else(|| format!("unknown block {name}"))?; + let mut state = registry + .state(default) + .ok_or("missing default state")? + .clone(); + for pair in props.split(',').filter(|p| !p.is_empty()) { + let (k, v) = pair + .split_once('=') + .ok_or_else(|| format!("bad property {pair}"))?; + if !state.properties.contains_key(k) { + return Err(format!("{name} has no property {k}").into()); + } + state.properties.insert(k.to_owned(), v.to_owned()); + } + Ok(registry.resolve(&state)?) +} diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index e013c8d29..3f5862f49 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -7,6 +7,7 @@ use horizon_client::{ biome::Biomes, blocks::{BlockFacts, Fluid}, chunk::{HEIGHT, MIN_Y}, + containers::BlockEntity, particles::{ParticleLevel, ParticleOptions, ParticleType}, world::World, }; @@ -344,6 +345,10 @@ impl Game<'_> { &mut self.particles, &ctx, r.block_entities(), + &|pos| match self.world.block_entities.get(&(pos[0], pos[1], pos[2])) { + Some(BlockEntity::Campfire(c)) => c.items.each_ref().map(Option::is_some), + _ => [false; 4], + }, ); } let level = ParticleLevel { diff --git a/crates/horizon-client/src/game/saving.rs b/crates/horizon-client/src/game/saving.rs index 378ffe9ce..1c6632562 100644 --- a/crates/horizon-client/src/game/saving.rs +++ b/crates/horizon-client/src/game/saving.rs @@ -179,6 +179,7 @@ impl Game<'_> { if keys.is_empty() { self.prune_entity_memory(); self.save_raids(); + self.save.save_forced_chunks(&self.streaming.forced)?; self.save_game_metadata()?; save.stage = Stage::Writes; } diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 81c03e288..72b3ab000 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -132,8 +132,16 @@ impl Game<'_> { 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, + Target::Mob(id) + | Target::Item(id) + | Target::Stand(id) + | Target::Frame(id) + | Target::Painting(id) + | Target::Boat(id) + | Target::Cart(id) + | Target::Other(id) => Some(uuid_text(self.uuid_for(id))), + // Orbs and projectiles are addressed by index and have no UUID here. + Target::Orb(_) | Target::Projectile(_) => None, } } fn holder_for(&mut self, t: Target) -> Option { diff --git a/crates/horizon-client/src/game/server_mods.rs b/crates/horizon-client/src/game/server_mods.rs new file mode 100644 index 000000000..a5a4b0f3f --- /dev/null +++ b/crates/horizon-client/src/game/server_mods.rs @@ -0,0 +1,576 @@ +//! Server mods in the game (`docs/mods.md`, "Server mods"): the game that +//! simulates the world (in-frame single player, the server thread, a LAN +//! host, the dedicated server) runs them. At the end of each tick it tells +//! them who joined and left, then what players said, broke and placed since +//! the last one, then ticks them; a player's command reaches them at once. +//! Their lines go to the players they name. With no server mod on, each hook +//! here is one check. +use super::{Game, lan::LanHost}; +#[cfg(not(feature = "mods"))] +use horizon_world::registry::BlockStateId; + +/// Who did something a server mod hears about, resolved at the tick's end. +#[cfg_attr(not(feature = "mods"), allow(dead_code))] +pub(super) enum Who { + /// The window's own player, in-frame. + Local, + /// A connection's player (the server thread's owner is one). + Conn(u32), + Uuid(u128), +} + +/// What players did during a tick, for the server mods at its end. +#[cfg_attr(not(feature = "mods"), allow(dead_code))] +pub(super) enum ModEvent { + Chat(Who, String), + Block { + who: Who, + pos: [i32; 3], + state: String, + placed: bool, + }, +} + +#[cfg(not(feature = "mods"))] +impl Game<'_> { + pub(super) fn tick_server_mods(&mut self) {} + pub(super) fn mod_block_event(&mut self, _pos: [i32; 3], _state: BlockStateId, _placed: bool) {} + pub(super) fn mod_player_chat(&mut self, _who: Who, _text: &str) {} + pub(super) fn local_server_mod_command(&mut self, _line: &str) -> bool { + false + } + pub(super) fn guest_server_mod_command( + &mut self, + _host: &mut LanHost, + _conn: u32, + _line: &str, + ) -> bool { + false + } + pub(super) fn apply_mod_block_writes(&mut self) {} +} + +#[cfg(feature = "mods")] +mod run { + use super::{Game, LanHost, ModEvent, Who}; + use horizon_client::chunk_map::ChunkMap; + use horizon_client::{ + command::args::GameMode as Mode, + lan::data::component_nbt, + text::{self, Text}, + }; + use horizon_mods::{ + ArgumentKind, BlockPos, GameMode, Output, ServerCommand, ServerPlayer, WorldView, + }; + use horizon_protocol::packets::play::{self, Clientbound as C}; + use horizon_world::registry::{BlockRegistry, BlockStateId}; + use serde_json::{Value, json}; + + /// Blocks queued for levels that don't tick (another dimension, in-frame) + /// are kept up to this many; the oldest go first. + const MAX_QUEUED_WRITES: usize = 1 << 16; + + /// Capability `world`'s view during a call: the levels' chunks, moved out + /// of the game for the call and back after it (no copy). + struct LentWorld { + registry: &'static BlockRegistry, + biomes: std::sync::Arc, + dims: Vec<(&'static str, ChunkMap)>, + } + impl WorldView for LentWorld { + fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option { + let (_, chunks) = self.dims.iter().find(|(d, _)| *d == dimension)?; + let chunk = chunks.get(&(x >> 4, z >> 4))?; + Some(state_string(self.registry, chunk.block(x & 15, y, z & 15))) + } + fn biome(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option { + let (_, chunks) = self.dims.iter().find(|(d, _)| *d == dimension)?; + let chunk = chunks.get(&(x >> 4, z >> 4))?; + Some(self.biomes.get(chunk.biome(x, y, z)).name.clone()) + } + fn has_dimension(&self, dimension: &str) -> bool { + matches!( + dimension, + "minecraft:overworld" | "minecraft:the_nether" | "minecraft:the_end" + ) + } + fn check_state(&self, state: &str) -> Result<(), String> { + crate::game::render_control::parse_state(self.registry, state) + .map(drop) + .map_err(|e| format!("{state}: {e}")) + } + } + + /// Server mods' commands as a root of the commands report + /// (`lan::commands`): a literal per command, then its arguments in a + /// chain, each node runnable where only optional arguments follow. + fn command_tree<'a>(commands: impl Iterator) -> Value { + let mut root = serde_json::Map::new(); + for c in commands { + let mut next: Option<(String, Value)> = None; + for (i, a) in c.arguments.iter().enumerate().rev() { + let executable = c.arguments.get(i + 1).is_none_or(|b| b.optional); + let (parser, properties) = match a.kind { + ArgumentKind::Word => ("brigadier:string", json!({"type": "word"})), + ArgumentKind::Text => ("brigadier:string", json!({"type": "greedy"})), + ArgumentKind::Integer((min, max)) => { + let mut p = serde_json::Map::new(); + if let Some(min) = min { + p.insert("min".into(), min.into()); + } + if let Some(max) = max { + p.insert("max".into(), max.into()); + } + ("brigadier:integer", Value::Object(p)) + } + ArgumentKind::Number => ("brigadier:double", Value::Null), + ArgumentKind::Boolean => ("brigadier:bool", Value::Null), + ArgumentKind::Player => ( + "minecraft:entity", + json!({"amount": "single", "type": "players"}), + ), + ArgumentKind::BlockPos => ("minecraft:block_pos", Value::Null), + }; + let mut node = json!({ + "type": "argument", + "parser": parser, + "properties": properties, + "executable": executable, + }); + if let Some((name, child)) = next.take() { + node["children"] = json!({ name: child }); + } + next = Some((a.name.clone(), node)); + } + let executable = c.arguments.first().is_none_or(|a| a.optional); + let mut literal = json!({"type": "literal", "executable": executable}); + if let Some((name, child)) = next { + literal["children"] = json!({ name: child }); + } + root.insert(c.name.clone(), literal); + } + if root.is_empty() { + return Value::Null; + } + json!({"type": "root", "children": root}) + } + + /// `minecraft:oak_log[axis=y]`. + fn state_string(registry: &BlockRegistry, state: BlockStateId) -> String { + let Some(s) = registry.state(state) else { + return "minecraft:air".into(); + }; + if s.properties.is_empty() { + return s.name.clone(); + } + let props: Vec = s + .properties + .iter() + .map(|(k, v)| format!("{k}={v}")) + .collect(); + format!("{}[{}]", s.name, props.join(",")) + } + + /// `UUID.toString()`. + fn uuid_string(u: u128) -> String { + let h = format!("{u:032x}"); + format!( + "{}-{}-{}-{}-{}", + &h[..8], + &h[8..12], + &h[12..16], + &h[16..20], + &h[20..] + ) + } + + fn mode(id: i32) -> GameMode { + match id { + 1 => GameMode::Creative, + 2 => GameMode::Adventure, + 3 => GameMode::Spectator, + _ => GameMode::Survival, + } + } + + impl Game<'_> { + /// The players on this game's server: the window's own player + /// in-frame, then every connection's. `host` is the hub when it is + /// out of `self.lan`. + pub(in crate::game) fn server_players(&self, host: Option<&LanHost>) -> Vec { + let mut out = Vec::new(); + if self.options.execution_role.is_client() + && self.remote.is_none() + && let Some(p) = &self.player + { + out.push(ServerPlayer { + id: self.player_uuid_string(), + name: crate::game::chat::PLAYER_NAME.to_owned(), + x: p.position.x, + y: p.position.y, + z: p.position.z, + dimension: self.dim.id().to_owned(), + game_mode: match self.mode { + Mode::Survival => GameMode::Survival, + Mode::Creative => GameMode::Creative, + Mode::Adventure => GameMode::Adventure, + Mode::Spectator => GameMode::Spectator, + }, + health: p.health.health(), + }); + } + let guests = host + .or(self.lan.as_ref()) + .into_iter() + .flat_map(|h| &h.hub.guests); + out.extend(guests.filter(|g| g.placed).map(|g| ServerPlayer { + id: uuid_string(g.uuid), + name: g.name.clone(), + x: g.position[0], + y: g.position[1], + z: g.position[2], + dimension: g.dimension.clone(), + game_mode: mode(g.game_mode), + health: g.health, + })); + out + } + + /// Whether what players do now reaches server mods: one is running + /// and this game simulates the world. + fn hears_players(&self) -> bool { + self.mods.server && self.remote.is_none() + } + + /// The tick's end: joins and leaves, the tick's events, the tick hook. + pub(in crate::game) fn tick_server_mods(&mut self) { + if !self.options.execution_role.is_client() { + // A server has no frames to check its dev mods in. + self.reload_dev_mods(); + } + self.send_server_mod_commands(); + if !self.mods.server { + return; + } + let players = self.server_players(None); + let snapshot = self.mod_snapshot_with(players.clone()); + self.mods.mods.set_snapshot(snapshot); + self.lend_world(); + let before = std::mem::take(&mut self.mods.players); + for p in before + .iter() + .filter(|p| !players.iter().any(|q| q.id == p.id)) + { + self.mods.mods.player_left(p); + } + for p in players + .iter() + .filter(|p| !before.iter().any(|q| q.id == p.id)) + { + self.mods.mods.player_joined(p); + } + for event in std::mem::take(&mut self.mods.events) { + let who = |w: &Who| { + let id = match w { + Who::Local => self.player_uuid_string(), + Who::Uuid(u) => uuid_string(*u), + Who::Conn(c) => { + let guests = self.lan.iter().flat_map(|h| &h.hub.guests); + let g = guests.into_iter().find(|g| g.conn == *c); + g.map_or_else(String::new, |g| uuid_string(g.uuid)) + } + }; + players.iter().chain(&before).find(|p| p.id == id).cloned() + }; + match event { + ModEvent::Chat(w, text) => { + if let Some(p) = who(&w) { + self.mods.mods.player_chat(&p, &text); + } + } + ModEvent::Block { + who: w, + pos, + state, + placed, + } => { + let Some(p) = who(&w) else { continue }; + let pos = BlockPos { + x: pos[0], + y: pos[1], + z: pos[2], + }; + if placed { + self.mods.mods.block_placed(&p, pos, &state); + } else { + self.mods.mods.block_broken(&p, pos, &state); + } + } + } + } + self.mods.mods.server_tick(self.ticks); + self.return_world(); + self.mods.players = players; + self.show_mod_output(); + self.apply_mod_block_writes(); + } + + /// Players' command trees list the running server mods' commands + /// after vanilla's, whenever they change (or a hub opens). + fn send_server_mod_commands(&mut self) { + let key = self.mods.mods.generation(); + let Some(host) = self.lan.as_mut() else { + return; + }; + if host.hub.mod_commands_key() == Some(key) { + return; + } + let tree = command_tree(self.mods.mods.server_commands()); + host.hub.set_mod_commands(key, tree); + } + + /// Lends the levels' chunks to capability `world` for the calls up to + /// [`Game::return_world`], when a running server mod has it. + fn lend_world(&mut self) { + if !self.mods.world { + return; + } + let mut dims = vec![(self.dim.id(), std::mem::take(&mut self.world.chunks))]; + for (dim, chunks) in self.levels.parked_chunks() { + dims.push((dim.id(), std::mem::take(chunks))); + } + let registry = self.pack.assets.registry; + let biomes = self.res.biomes().clone(); + self.mods.mods.lend_world(Box::new(LentWorld { + registry, + biomes, + dims, + })); + } + + /// Puts back the chunks [`Game::lend_world`] lent. + fn return_world(&mut self) { + let Some(view) = self.mods.mods.take_world() else { + return; + }; + let view: Box = view; + let Ok(lent) = view.downcast::() else { + return; + }; + let mut dims = lent.dims; + if let Some(i) = dims.iter().position(|(d, _)| *d == self.dim.id()) { + self.world.chunks = dims.swap_remove(i).1; + } + for (dim, chunks) in self.levels.parked_chunks() { + if let Some(i) = dims.iter().position(|(d, _)| *d == dim.id()) { + *chunks = dims.swap_remove(i).1; + } + } + } + + /// Makes the blocks server mods set in the level in place, in order, + /// as `/setblock` does. Those of other dimensions wait for their level. + pub(in crate::game) fn apply_mod_block_writes(&mut self) { + if self.mods.block_writes.is_empty() { + return; + } + let dim = self.dim.id(); + let (now, later): (Vec<_>, Vec<_>) = std::mem::take(&mut self.mods.block_writes) + .into_iter() + .partition(|(d, _)| d == dim); + self.mods.block_writes = later; + let registry = self.pack.assets.registry; + for (_, b) in now { + let state = match crate::game::render_control::parse_state(registry, &b.state) { + Ok(state) => state, + Err(e) => { + log::warn!("Horizon: a server mod set {}: {e}", b.state); + continue; + } + }; + if let Err(e) = self.place_state([b.x, b.y, b.z], state, false) { + log::debug!( + "Horizon: a server mod's block at {} {} {}: {e:?}", + b.x, + b.y, + b.z + ); + } + } + } + + /// A player broke (or placed) `state` at `pos`: the player acting now. + pub(in crate::game) fn mod_block_event( + &mut self, + pos: [i32; 3], + state: BlockStateId, + placed: bool, + ) { + if !self.hears_players() { + return; + } + let who = self.lan_acting.map_or(Who::Local, Who::Conn); + let state = self.state_string(state); + self.mods.events.push(ModEvent::Block { + who, + pos, + state, + placed, + }); + } + + /// A chat message a player sent. + pub(in crate::game) fn mod_player_chat(&mut self, who: Who, text: &str) { + if self.hears_players() { + self.mods.events.push(ModEvent::Chat(who, text.to_owned())); + } + } + + /// `/line` typed by the window's own player in-frame: true when a + /// server mod owns it. + pub(in crate::game) fn local_server_mod_command(&mut self, line: &str) -> bool { + if !self.hears_players() { + return false; + } + let players = self.server_players(None); + let Some(me) = players.first().cloned() else { + return false; + }; + let snapshot = self.mod_snapshot_with(players); + self.mods.mods.set_snapshot(snapshot); + self.lend_world(); + let owned = self.mods.mods.server_command(&me, line); + self.return_world(); + self.show_mod_output(); + self.apply_mod_block_writes(); + owned + } + + /// `/line` typed by a connection's player: true when a server mod + /// owns it, whatever the player's permission level. + pub(in crate::game) fn guest_server_mod_command( + &mut self, + host: &mut LanHost, + conn: u32, + line: &str, + ) -> bool { + if !self.hears_players() { + return false; + } + let Some(g) = host.hub.guest(conn) else { + return false; + }; + let id = uuid_string(g.uuid); + let players = self.server_players(Some(host)); + let Some(me) = players.iter().find(|p| p.id == id).cloned() else { + return false; + }; + let snapshot = self.mod_snapshot_with(players); + self.mods.mods.set_snapshot(snapshot); + self.lend_world(); + let owned = self.mods.mods.server_command(&me, line); + self.return_world(); + if !owned { + return false; + } + self.route_mod_output(Some(host)); + self.apply_mod_block_writes(); + true + } + + /// Sends a server mod's line to the player with this id: the + /// window's own chat for the local player, a system message for a + /// connection's. `host` is the hub when it is out of `self.lan`. + pub(in crate::game) fn tell_server_player( + &mut self, + host: Option<&mut LanHost>, + id: &str, + line: Text, + ) { + let local = self.options.execution_role.is_client() + && self.remote.is_none() + && self.player.is_some(); + if local && self.player_uuid_string() == id { + self.add_mod_chat_line(line); + return; + } + let Some(host) = host.or(self.lan.as_mut()) else { + return; + }; + let to = host + .hub + .guests + .iter() + .find(|g| g.placed && uuid_string(g.uuid) == id); + if let Some(conn) = to.map(|g| g.conn) { + host.hub.send_to( + conn, + &C::SystemChat(play::SystemChat { + content: component_nbt(&line.component()), + overlay: false, + }), + ); + } + } + + /// Routes a server mod's output: `Tell` and `Reply` to their player, + /// `Broadcast` to everyone and the log. + pub(in crate::game) fn route_server_output( + &mut self, + mut host: Option<&mut LanHost>, + output: Output, + ) { + let named = |name: &str, text: String| { + let mut line = Text::literal(format!("[{name}] ")).with_color(text::GRAY); + line.push(Text::literal(text)); + line + }; + match output { + Output::Tell { name, player, text } => { + self.tell_server_player(host, &player, named(&name, text)); + } + Output::Reply { + player, + text, + error, + } => { + let line = Text::literal(text); + let line = if error { + line.with_color(text::RED) + } else { + line + }; + self.tell_server_player(host, &player, line); + } + Output::Broadcast { name, text } => { + let plain = format!("[{name}] {text}"); + if self.options.dedicated.is_some() { + super::super::dedicated::log("INFO", &plain); + } else { + log::info!("{plain}"); + } + for p in self.server_players(host.as_deref()) { + let line = named(&name, text.clone()); + self.tell_server_player(host.as_deref_mut(), &p.id, line); + } + } + Output::SetBlocks { + name, + dimension, + blocks, + } => { + let queued = &mut self.mods.block_writes; + queued.extend(blocks.into_iter().map(|b| (dimension.clone(), b))); + if queued.len() > MAX_QUEUED_WRITES { + let over = queued.len() - MAX_QUEUED_WRITES; + queued.drain(..over); + log::warn!( + "Horizon: mod {name} set more blocks than wait for their level: {over} dropped" + ); + } + } + _ => {} + } + } + } +} diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs index 158b2301e..bcaf37a76 100644 --- a/crates/horizon-client/src/game/server_travel.rs +++ b/crates/horizon-client/src/game/server_travel.rs @@ -13,6 +13,7 @@ use super::respawn_anchor::RespawnConfig; use super::{Dim, Game, lan::LanHost}; use horizon_client::{lan::hub::TickCtx, text::Text}; use horizon_core::{geometry::Vec3, position::BlockPos}; +use horizon_protocol::packets::play::{self, Clientbound as C}; /// A trip under way: the player is in the destination's level, whose /// chunks are loading around `target`. @@ -103,8 +104,35 @@ impl Game<'_> { if let Some(pos) = self.nether_portal_inside(at) { self.portals.player.set_inside(pos, PLAYER_DELAY); } + // `ServerPlayer.showEndCredits`: the player stays out of the world while the + // poem rolls, then PERFORM_RESPAWN takes it to its respawn point. + let play = host.play.entry(conn).or_default(); + if play.won_game { + if std::mem::take(&mut play.respawn_requested) { + play.won_game = false; + self.start_server_trip(host, conn, Dim::Overworld, None); + self.portals.player.cooldown = 10; + } + return; + } let (end_portal, gateway) = self.inside_end_portals(at, WIDTH, HEIGHT); if end_portal { + // EndPortalBlock.entityInside: the first exit from the End shows the credits. + if self.dim == Dim::End && !host.hub.guest(conn).is_some_and(|g| g.seen_credits) { + if let Some(g) = host.hub.guests.iter_mut().find(|g| g.conn == conn) { + g.seen_credits = true; + } + host.play.entry(conn).or_default().won_game = true; + // ClientboundGameEventPacket.WIN_GAME. + host.hub.send_to( + conn, + &C::GameEvent(play::GameEvent { + event: 4, + param: 0.0, + }), + ); + return; + } if self.portals.player.cooldown == 0 { let target = if self.dim == Dim::End { Dim::Overworld diff --git a/crates/horizon-client/src/game/sign_edit.rs b/crates/horizon-client/src/game/sign_edit.rs index 2f50ad9ab..2d010f1f5 100644 --- a/crates/horizon-client/src/game/sign_edit.rs +++ b/crates/horizon-client/src/game/sign_edit.rs @@ -6,9 +6,9 @@ use horizon_client::{ containers::BlockEntity, hud::{HudBatch, rgba}, signs::wood_type, + ui::EditBox, }; use horizon_protocol::packets::play::{self, Clientbound as C, Serverbound as S}; -use std::time::Instant; use winit::{ event::{ElementState, KeyEvent}, keyboard::{KeyCode, PhysicalKey}, @@ -18,7 +18,16 @@ pub(super) struct SignEditor { pub pos: (i32, i32, i32), pub front: bool, pub line: usize, - pub opened: Instant, + /// The line being edited (`AbstractSignEditScreen`'s text field). + edit: EditBox, +} + +fn sign_box() -> EditBox { + let mut edit = EditBox::new(0.0, 0.0, 90.0, 9.0); + edit.bordered = false; + edit.max_length = 384; + edit.focused = true; + edit } impl Game<'_> { @@ -28,8 +37,9 @@ impl Game<'_> { pos, front, line: 0, - opened: Instant::now(), + edit: sign_box(), }); + self.sign_load(); self.keys.clear(); self.right = false; self.capture(false); @@ -140,97 +150,154 @@ impl Game<'_> { /// A key and the text it typed on the sign being edited (the keyboard, /// or a controller's on-screen keyboard). pub(super) fn sign_input(&mut self, key: Option, typed: Option<&str>) { - let Some(edit) = self.sign_edit.as_mut() else { + if self.sign_edit.is_none() { return; - }; - let front = edit.front; - let id = sign_line_id(front, edit.line); + } match key { Some(KeyCode::Escape) => self.close_sign_editor(), - Some(KeyCode::ArrowUp) => edit.line = (edit.line + 3) & 3, + Some(KeyCode::ArrowUp) => self.sign_move_line(3), Some(KeyCode::ArrowDown | KeyCode::Enter | KeyCode::NumpadEnter) => { - edit.line = (edit.line + 1) & 3 + self.sign_move_line(1) } - Some(KeyCode::Backspace) => { - let (line, key) = (edit.line, edit.pos); - if let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&key) { - let text = if front { - &mut sign.front - } else { - &mut sign.back - }; - let value = &mut text.lines[line]; - if !self.text_selection.take(id, value) { - value.pop(); - } - } + Some( + key @ (KeyCode::ArrowLeft + | KeyCode::ArrowRight + | KeyCode::Home + | KeyCode::End + | KeyCode::Backspace + | KeyCode::Delete), + ) => { + let (ctrl, shift) = (self.has_control_down(), self.has_shift_down()); + self.sign_change(|edit| { + edit.key(key, ctrl, shift); + }); } _ => { let Some(typed) = typed else { return; }; - let line = edit.line; - 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; - }; - if let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&key) { - let max = sign.max_line_width(); - let text = if front { - &mut sign.front - } else { - &mut sign.back - }; - self.text_selection.take(id, &mut text.lines[line]); - for ch in typed.chars().filter(|c| !c.is_control()) { - let mut next = text.lines[line].clone(); - next.push(ch); - // TextFieldHelper filter: font.width(s) <= maxTextLineWidth. - if width(&next) <= max { - text.lines[line] = next; - } - } - } + self.sign_change(|edit| edit.insert_text(typed)); } } } - /// `TextFieldHelper.keyPressed`'s shortcuts on the edited line: a paste - /// (formatting and carriage returns removed) is taken whole or not at - /// all, as the line must stay within the sign's width. - fn sign_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) { + /// Up or down a line: the box writes the line it leaves and loads the next. + fn sign_move_line(&mut self, by: usize) { + self.sign_write(); + if let Some(edit) = self.sign_edit.as_mut() { + edit.line = (edit.line + by) & 3; + } + self.sign_load(); + } + /// The edited line's text. + fn sign_current(&self) -> Option { + let edit = self.sign_edit.as_ref()?; + let BlockEntity::Sign(sign) = self.world.block_entities.get(&edit.pos)? else { + return None; + }; + let side = if edit.front { &sign.front } else { &sign.back }; + Some(side.lines[edit.line].clone()) + } + /// `EditBox.setValue` from the line now being edited. + fn sign_load(&mut self) { + let Some(text) = self.sign_current() else { + return; + }; + if let Some(edit) = self.sign_edit.as_mut() { + edit.edit.set_value(&text); + } + } + /// The box's text onto the sign, when it still fits the line. + fn sign_write(&mut self) { let Some(edit) = self.sign_edit.as_ref() else { return; }; - let (key, front, line) = (edit.pos, edit.front, edit.line); - let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&key) else { + let (pos, front, line, value) = (edit.pos, edit.front, edit.line, edit.edit.value.clone()); + if !self.sign_fits(&value) { + return; + } + let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&pos) else { return; }; - let max = sign.max_line_width(); - let text = if front { + let side = if front { &mut sign.front } else { &mut sign.back }; - let atlas = &self.gui.atlas; - self.text_selection.apply( - sign_line_id(front, line), - &mut text.lines[line], - shortcut, - &mut self.clipboard, - |value, pasted| { - let next = format!( - "{value}{}", - horizon_client::clipboard::helper_clipboard_contents(pasted) - ); - HudBatch::text_width(atlas, &next) <= max && { - *value = next; - true - } - }, - ); + side.lines[line] = value; } - /// Done button (`this.width / 2 - 100, this.height / 4 + 144`, 200x20). + /// TextFieldHelper: `font.width(s) <= maxTextLineWidth`. + fn sign_fits(&self, value: &str) -> bool { + let Some(edit) = self.sign_edit.as_ref() else { + return false; + }; + let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&edit.pos) else { + return false; + }; + HudBatch::text_width(&self.gui.atlas, value) <= sign.max_line_width() + } + /// Edit the line, then keep the result only when it still fits. + fn sign_change(&mut self, f: impl FnOnce(&mut EditBox)) { + let before = self + .sign_edit + .as_ref() + .map(|e| (e.edit.value.clone(), e.edit.cursor, e.edit.highlight)); + if let Some(edit) = self.sign_edit.as_mut() { + f(&mut edit.edit); + let clean = horizon_client::clipboard::strip_formatting(&edit.edit.value); + if clean != edit.edit.value { + let n = horizon_client::ui::char_len(&clean); + edit.edit.value = clean; + edit.edit.cursor = edit.edit.cursor.min(n); + edit.edit.highlight = edit.edit.highlight.min(n); + } + } + self.sign_keep(before); + } + /// Write the box when the line still fits; otherwise put the old text back. + fn sign_keep(&mut self, before: Option<(String, usize, usize)>) { + let value = self + .sign_edit + .as_ref() + .map(|e| e.edit.value.clone()) + .unwrap_or_default(); + if self.sign_fits(&value) { + self.sign_write(); + } else if let (Some(edit), Some((value, cursor, highlight))) = + (self.sign_edit.as_mut(), before) + { + edit.edit.value = value; + edit.edit.cursor = cursor; + edit.edit.highlight = highlight; + } + } + /// `TextFieldHelper.keyPressed`'s shortcuts on the edited line. Paste + /// reads `getClipboardContents` before `insertText`. A paste that would + /// pass the sign's width is refused whole. + fn sign_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) { + if shortcut == horizon_client::clipboard::EditShortcut::Paste { + let raw = horizon_client::clipboard::Clipboard::get(&mut self.clipboard); + let text = horizon_client::clipboard::helper_clipboard_contents(&raw); + self.sign_change(|edit| edit.insert_text(&text)); + return; + } + let before = self + .sign_edit + .as_ref() + .map(|e| (e.edit.value.clone(), e.edit.cursor, e.edit.highlight)); + if let Some(edit) = self.sign_edit.as_mut() { + edit.edit.shortcut(shortcut, &mut self.clipboard); + let clean = horizon_client::clipboard::strip_formatting(&edit.edit.value); + if clean != edit.edit.value { + let n = horizon_client::ui::char_len(&clean); + edit.edit.value = clean; + edit.edit.cursor = edit.edit.cursor.min(n); + edit.edit.highlight = edit.edit.highlight.min(n); + } + } + self.sign_keep(before); + } + /// Done button (`this.width / 2 - 100, this.height / 4 + 144`, 200x20), + /// or a click on a line (`EditBox.onClick`). pub(super) fn sign_edit_click(&mut self, size: [u32; 2]) { let b = HudBatch::new(size); let (x, y) = (b.width / 2.0 - 100.0, b.height / 4.0 + 144.0); @@ -238,7 +305,56 @@ impl Game<'_> { if mx >= x && mx < x + 200.0 && my >= y && my < y + 20.0 { self.audio.play_button_click(); self.close_sign_editor(); + return; } + let Some((cx, top, line_height, max_width, lines)) = self.sign_lines(b.width) else { + return; + }; + let shift = self.has_shift_down(); + for i in 0..lines.len() { + let ly = top + i as f32 * line_height; + let left = cx - max_width / 2.0; + if mx < left || mx >= left + max_width || my < ly || my >= ly + line_height { + continue; + } + let current = self.sign_edit.as_ref().map(|e| e.line); + if current != Some(i) { + self.sign_move_line((i + 4 - current.unwrap_or(0)) & 3); + } + let value = self + .sign_edit + .as_ref() + .map(|e| e.edit.value.clone()) + .unwrap_or_default(); + let lw = HudBatch::text_width(&self.gui.atlas, &value); + let text_x = cx - (lw as i32 / 2) as f32; + if let Some(edit) = self.sign_edit.as_mut() { + edit.edit.x = text_x; + edit.edit.y = ly; + edit.edit.width = max_width; + edit.edit.click(&self.gui.atlas, mx, shift, false); + } + self.sign_write(); + return; + } + } + /// Centre x, the first line's y, the line height, the width limit and the four lines. + fn sign_lines(&self, width: f32) -> Option<(f32, f32, f32, f32, Vec)> { + let edit = self.sign_edit.as_ref()?; + let BlockEntity::Sign(sign) = self.world.block_entities.get(&edit.pos)? else { + return None; + }; + let text = if edit.front { &sign.front } else { &sign.back }; + let line_height = sign.line_height(); + let y = if sign.hanging { 125.0 } else { 90.0 }; + let top = y - (4.0 * line_height / 2.0).floor(); + Some(( + width / 2.0, + top, + line_height, + sign.max_line_width(), + text.lines.to_vec(), + )) } pub(super) fn draw_sign_editor(&self, batch: &mut HudBatch) { let Some(edit) = &self.sign_edit else { return }; @@ -304,23 +420,48 @@ impl Game<'_> { let color = rgba((color >> 16) as u8, (color >> 8) as u8, color as u8, 255); let line_height = sign.line_height(); let midpoint = (4.0 * line_height / 2.0).floor(); - let blink = (edit.opened.elapsed().as_millis() / 300) % 2 == 0; for (i, line) in text.lines.iter().enumerate() { - let lw = HudBatch::text_width(atlas, line); + let shown = if i == edit.line { + edit.edit.value.as_str() + } else { + line.as_str() + }; + let lw = HudBatch::text_width(atlas, shown); let x = cx - (lw as i32 / 2) as f32; let ly = y + i as f32 * line_height - midpoint; - batch.text(atlas, line, x, ly, color, false); - if i == edit.line - && self - .text_selection - .covers(sign_line_id(edit.front, i), line) - { - // AbstractSignEditScreen: the selection from its start to its end. - batch.text_highlight(atlas, (x, ly, lw, line_height), true); + batch.text(atlas, shown, x, ly, color, false); + if i != edit.line { + continue; } - if i == edit.line && blink { - // TextCursorUtils.extractAppendCursor: an underscore after the text. - batch.text(atlas, "_", x + lw, ly, color, false); + let value = &edit.edit.value; + if edit.edit.cursor != edit.edit.highlight { + let (a, b) = ( + edit.edit.cursor.min(edit.edit.highlight), + edit.edit.cursor.max(edit.edit.highlight), + ); + let pre: String = value.chars().take(a).collect(); + let sel: String = value.chars().skip(a).take(b - a).collect(); + batch.text_highlight( + atlas, + ( + x + HudBatch::text_width(atlas, &pre), + ly, + HudBatch::text_width(atlas, &sel), + line_height, + ), + true, + ); + } + if edit.edit.cursor_visible() { + let pre: String = value.chars().take(edit.edit.cursor).collect(); + batch.fill( + atlas, + x + HudBatch::text_width(atlas, &pre), + ly, + 1.0, + line_height, + color, + ); } } let (bx, by) = (w / 2.0 - 100.0, h / 4.0 + 144.0); @@ -344,8 +485,3 @@ impl Game<'_> { ); } } - -/// The sign line being edited, for Select All. -fn sign_line_id(front: bool, line: usize) -> horizon_client::clipboard::FieldId { - (if front { "sign.front" } else { "sign.back" }, line) -} diff --git a/crates/horizon-client/src/game/spill.rs b/crates/horizon-client/src/game/spill.rs index b7283c57b..b1953596b 100644 --- a/crates/horizon-client/src/game/spill.rs +++ b/crates/horizon-client/src/game/spill.rs @@ -171,8 +171,8 @@ pub(super) struct Spawn { pub(super) struct Spill { pub(super) spawns: Vec, /// Experience orbs (`ExperienceOrb.award`): where and how much, each - /// having drawn its merge id from the level random. - pub(super) orbs: Vec<([f64; 3], u32)>, + /// and the merge id it drew from the level random. + pub(super) orbs: Vec<([f64; 3], u32, i32)>, /// Block entities the behaviour removed, for the game's own follow-ups /// (open screens, playing songs). pub(super) removed: Vec<([i32; 3], BlockEntity)>, @@ -342,8 +342,8 @@ impl GameLevel<'_> { while amount > 0 { let value = removal::orb_value(amount); amount -= value; - let _merge_id = self.world.random.next_int_bound(40); - self.spill.orbs.push((at, value)); + let merge_id = self.world.random.next_int_bound(40).unwrap_or(0); + self.spill.orbs.push((at, value, merge_id)); } } /// `BlockEntity.preRemoveSideEffects` and `removeBlockEntity` for the block @@ -398,8 +398,12 @@ impl GameLevel<'_> { } } PreRemove::Campfire => { - for _ in 0..4 { - self.drop_item_stack(pos, None); + let items = match &entity { + Some(BlockEntity::Campfire(c)) => c.items.clone(), + _ => Default::default(), + }; + for stack in items { + self.drop_item_stack(pos, stack); } } PreRemove::Jukebox => { @@ -579,8 +583,8 @@ impl Game<'_> { let motion = s.motion.unwrap_or_else(new_item_motion); self.spawn_item(s.stack, s.pos, motion, s.delay); } - for (at, value) in spill.orbs { - self.add_orb(at, value); + for (at, value, merge_id) in spill.orbs { + self.award_orb(at, value, merge_id); } for (pos, entity) in spill.removed { let key = (pos[0], pos[1], pos[2]); diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index f7f05e1c4..361879d2e 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -135,8 +135,10 @@ pub(super) struct Station { pub(super) offers: EnchantOffers, bookcases: i32, pub(super) anvil: AnvilResult, - /// Anvil rename box text. + /// Anvil rename box text (`AnvilMenu.itemName`). pub(super) name: String, + /// The box itself (`AnvilScreen`'s `EditBox` of 50, unbordered). + pub(super) rename: horizon_client::ui::EditBox, /// Stonecutter: the menu's recipe list (horizon_client::menu), its /// `selectedRecipeIndex` and the screen's first shown index. pub(super) stone: horizon_client::menu::Stonecutter, @@ -146,8 +148,6 @@ pub(super) struct Station { anvil_last: Option, /// Anvil on a server: the name last sent (the client menu's `itemName`). pub(super) anvil_sent: Option, - /// When the screen opened: the rename box has the focus from then. - opened: std::time::Instant, pub(super) last_sound: u64, /// Villager trading state. pub(super) merchant: Option>, @@ -169,12 +169,12 @@ impl Station { bookcases: 0, anvil: AnvilResult::default(), name: String::new(), + rename: anvil_box(), stone: Default::default(), selected: None, start: 0, anvil_last: None, anvil_sent: None, - opened: std::time::Instant::now(), last_sound: 0, merchant: None, beacon: [None; 2], @@ -277,6 +277,10 @@ fn argb(c: i32) -> u32 { ) } +/// A text style's `0xRRGGBB` colour from a HUD colour (`rgba`). +fn rgb_of(rgba: u32) -> u32 { + (rgba & 0xFF) << 16 | (rgba >> 8 & 0xFF) << 8 | (rgba >> 16 & 0xFF) +} impl Game<'_> { /// `Component.translatable`: the selected language (which `lang` layers /// over `en_us`), the caller's English text last. @@ -713,7 +717,8 @@ impl Game<'_> { if let Some(rest) = self.give(stack) && let Some(eye) = self.eye_position() { - self.spawn_item(rest, [eye[0], eye[1] - 0.3, eye[2]], [0.0, 0.1, 0.0], 40); + // Inventory.placeItemBackInInventory: `player.drop(stack, false)`. + self.throw_from_eyes(rest, eye, false); } } /// `Player.giveExperienceLevels`. @@ -868,6 +873,9 @@ impl Game<'_> { if kind == Kind::Stonecutter && self.stonecutter_click(local) { return true; } + if kind == Kind::Anvil && !right && self.anvil_name_click(ox, oy) { + return true; + } } let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return true; @@ -894,6 +902,8 @@ impl Game<'_> { .as_ref() .map(|i| stations::hover_name(&|id| self.pack.names.display_item(id), i)) .unwrap_or_default(); + let name = s.name.clone(); + s.rename.set_value(&name); } self.station_changed(); } @@ -960,21 +970,29 @@ impl Game<'_> { let Some(s) = self.station.as_mut() else { return; }; - let cleared = self.text_selection.take(ANVIL_NAME, &mut s.name); if backspace { - if !cleared { - s.name.pop(); - } + s.rename.delete_chars(-1); } else if let Some(t) = text { - for c in t.chars().filter(|c| !c.is_control()) { - if s.name.chars().count() < ANVIL_NAME_CHARS { - s.name.push(c); - } - } + s.rename.insert_text(t); } + s.name.clone_from(&s.rename.value); self.station_changed(); self.remote_anvil_rename(); } + /// `AnvilScreen.keyPressed`: the rename box handles the key. + pub(super) fn station_key(&mut self, key: winit::keyboard::KeyCode) -> bool { + let (ctrl, shift) = (self.has_control_down(), self.has_shift_down()); + let Some(s) = self.station.as_mut() else { + return false; + }; + if !s.rename.key(key, ctrl, shift) { + return false; + } + s.name.clone_from(&s.rename.value); + self.station_changed(); + self.remote_anvil_rename(); + true + } /// Ctrl+A/C/V/X in the anvil's rename box (an `EditBox` of 50) or the /// recipe book's search box. pub(super) fn station_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) { @@ -985,18 +1003,52 @@ impl Game<'_> { let Some(s) = self.station.as_mut() else { return; }; - if Self::append_shortcut( - &mut self.text_selection, - &mut self.clipboard, - ANVIL_NAME, - &mut s.name, - shortcut, - ANVIL_NAME_CHARS, - ) { + if s.rename.shortcut(shortcut, &mut self.clipboard) { + s.name.clone_from(&s.rename.value); self.station_changed(); self.remote_anvil_rename(); } } + /// A click in the anvil's name box (`EditBox.onClick`). + fn anvil_name_click(&mut self, ox: f32, oy: f32) -> bool { + let open = self + .station + .as_ref() + .is_some_and(|s| s.kind == Kind::Anvil && s.inputs[0].is_some()); + if !open { + return false; + } + let (x, y, w, h) = (ox + 62.0, oy + 24.0, 103.0, 12.0); + let (mx, my) = self.cursor; + if mx < x || my < y || mx >= x + w || my >= y + h { + return false; + } + let shift = self.has_shift_down(); + let Some(s) = self.station.as_mut() else { + return false; + }; + s.rename.x = x; + s.rename.y = y; + s.rename.width = w; + s.rename.click(&self.gui.atlas, mx, shift, false); + true + } + /// AnvilScreen's name box, drawn after the station picture. + fn draw_anvil_name(&mut self, batch: &mut HudBatch, ox: f32, oy: f32) { + let Some(s) = self.station.as_mut() else { + return; + }; + let edit = &mut s.rename; + edit.x = ox + 62.0; + edit.y = oy + 24.0; + edit.width = 103.0; + edit.height = 12.0; + edit.bordered = false; + edit.focused = true; + edit.text_color = u32::MAX; + edit.max_length = ANVIL_NAME_CHARS; + edit.draw(batch, &self.gui.atlas, None); + } // ---------------------------------------------------------------- drawing @@ -1094,6 +1146,10 @@ impl Game<'_> { let (ox, oy) = self.inventory_origin(batch); let local = (self.cursor.0 - ox, self.cursor.1 - oy); let mut tooltip: Option> = None; + let mut anvil_name = false; + // Keep item tooltips as stacks until drawing: text alone loses the + // bundle contents component (including in the player's inventory). + let mut tooltip_stack: Option = None; { let atlas = &self.gui.atlas; batch.fill( @@ -1428,18 +1484,8 @@ impl Game<'_> { ); } if s.inputs[0].is_some() { - // AnvilScreen's name box: white, 103 wide, no inverted highlight. - horizon_client::ui::append_field( - batch, - atlas, - &s.name, - (ox + 62.0, oy + 24.0, 103.0), - (u32::MAX, true), - ANVIL_NAME_CHARS, - self.text_selection.covers(ANVIL_NAME, &s.name), - false, - s.opened.elapsed().as_millis(), - ); + // Drawn once this borrow of the station ends. + anvil_name = true; } let cost = s.anvil.cost; if cost > 0 { @@ -1579,13 +1625,16 @@ impl Game<'_> { ); self.draw_item(batch, &result, ox + x, oy + y); if hover { - tooltip = Some(self.stack_tooltip(&result)); + tooltip_stack = Some(result); } } } } } } + if anvil_name { + self.draw_anvil_name(batch, ox, oy); + } let drag = self.drag_view(); for i in self.station_slots().unwrap_or_default() { let Some((sx, sy)) = self.slot_position_any(i) else { @@ -1606,13 +1655,16 @@ impl Game<'_> { ); if self.carried.is_none() && tooltip.is_none() + && tooltip_stack.is_none() && let Some(stack) = self.slot_mut(slot).clone() { - tooltip = Some(self.stack_tooltip(&stack)); + tooltip_stack = Some(stack); } } if self.carried.is_some() { self.draw_carried(batch); + } else if let Some(stack) = tooltip_stack { + self.draw_stack_tooltip(batch, &stack, self.cursor.0, self.cursor.1); } else if let Some(lines) = tooltip { self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1); } @@ -1642,20 +1694,36 @@ impl Game<'_> { &self, stack: &ItemStack, ) -> Vec<(horizon_client::text::Text, u32)> { - let e: &Enchantments = &self.res.stations().enchantments; - let props = e.props(&stack.item); + self.stack_tooltip_lines(stack, false) + } + /// `ItemStack.getRarity`'s colour for the name line and a `[name]` link. + fn rarity_color(&self, stack: &ItemStack) -> u32 { + let props = self.res.stations().enchantments.props(&stack.item); let rarity = horizon_client::item_tooltip::rarity( stack, props.map_or("common", |p| p.rarity.as_str()), ); - let color = match rarity { + match rarity { "uncommon" => rgba(255, 255, 85, 255), "rare" => rgba(85, 255, 255, 255), "epic" => rgba(255, 85, 255, 255), _ => u32::MAX, - }; - let name = if let Some(n) = stack.custom_name() { + } + } + /// `ItemStack.getHoverName`: the custom name, a written book's title, the + /// item name component, else the item's or potion's name. + fn stack_hover_name(&self, stack: &ItemStack) -> String { + if let Some(n) = stack.custom_name() { n.to_owned() + } else if let Some(title) = stack + .data() + .and_then(|d| d.written.as_ref()) + .map(|w| w.title.as_str()) + .filter(|t| !t.trim().is_empty()) + { + title.to_owned() + } else if let Some(n) = stack.item_name() { + n } else if stack.data().is_some_and(|d| d.ominous_banner) { self.translate("block.minecraft.ominous_banner", "Ominous Banner") } else if stack.data().and_then(|d| d.potion.as_ref()).is_some() @@ -1669,20 +1737,53 @@ impl Game<'_> { .unwrap_or_else(|| self.pack.names.display_item(&stack.item)) } else { self.pack.names.display_item(&stack.item) - }; + } + } + /// `ItemStack.getTooltipLines`. A `nested` stack is a crossbow's + /// projectile: `ChargedProjectiles.addProjectileTooltip` takes its details + /// without the name, the player and the advanced flag. + fn stack_tooltip_lines( + &self, + stack: &ItemStack, + nested: bool, + ) -> Vec<(horizon_client::text::Text, u32)> { + let e: &Enchantments = &self.res.stations().enchantments; + let color = self.rarity_color(stack); + let advanced = !nested && self.options_advanced_tooltips(); 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((horizon_client::text::Text::legacy(&name), color)); + if !nested && display.name_visible(self.screen == Screen::Creative) { + // `getStyledHoverName`: a custom name is italic. + let name = self.stack_hover_name(stack); + let name = if stack.custom_name().is_some() { + horizon_client::text::Text::literal(name).italic() + } else { + horizon_client::text::Text::legacy(&name) + }; + lines.push((name, color)); } let translate = |k: &str| self.pack.names.display_get(k); let push = |lines: &mut Vec<(horizon_client::text::Text, u32)>, s: String, c: u32| { lines.push((horizon_client::text::Text::legacy(&s), c)); }; + let gray = rgba(170, 170, 170, 255); + let item_info = self.res.items().get(&stack.item); + // InstrumentComponent.addToTooltip. + if let Some(text) = + horizon_client::item_tooltip::instrument_line(stack, &display, &translate) + { + push(&mut lines, text, gray); + } + // Bees.addToTooltip. + if let Some(text) = horizon_client::item_tooltip::bees_line(stack, &display, &translate) { + push(&mut lines, text, gray); + } // ItemContainerContents.addToTooltip. let hover_name = |s: &ItemStack| { s.custom_name() - .map_or_else(|| self.pack.names.display_item(&s.item), str::to_owned) + .map(str::to_owned) + .or_else(|| s.item_name()) + .unwrap_or_else(|| self.pack.names.display_item(&s.item)) }; if display.shows("minecraft:container") { for text in @@ -1691,6 +1792,70 @@ impl Game<'_> { push(&mut lines, text, u32::MAX); } } + // BannerPatternLayers.addToTooltip: up to six layer names. + 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); + push( + &mut lines, + self.translate(&key, &key), + rgba(170, 170, 170, 255), + ); + } + } + // WrittenBookContent.addToTooltip. + for text in horizon_client::item_tooltip::written_book_lines(stack, &display, &translate) { + push(&mut lines, text, gray); + } + // ChargedProjectiles.addToTooltip: each run of equal projectiles, then + // the projectile's own details indented under it. + if display.shows("minecraft:charged_projectiles") { + let charged = stack.data().map_or(&[][..], |d| &d.charged[..]); + for run in charged.chunk_by(|a, b| a.same_item_same_components(b)) { + let projectile = &run[0]; + let name = self.stack_hover_name(projectile); + let line = if run.len() == 1 { + // `getDisplayName`: `[name]` in the rarity colour. + let mut shown = horizon_client::text::Text::literal(format!("[{name}]")) + .with_color(rgb_of(self.rarity_color(projectile))); + if projectile.custom_name().is_some() { + shown = shown.italic(); + } + horizon_client::text::format_translation( + &self.translate( + "item.minecraft.crossbow.projectile.single", + "Projectile: %s", + ), + &[shown], + ) + } else { + horizon_client::text::format_translation( + &self.translate( + "item.minecraft.crossbow.projectile.multiple", + "Projectile: %s x %s", + ), + &[ + horizon_client::text::Text::literal(run.len().to_string()), + horizon_client::text::Text::literal(name), + ], + ) + }; + lines.push((line, u32::MAX)); + for (text, c) in self.stack_tooltip_lines(projectile, true) { + // `literal(" ").append(line).withStyle(GRAY)`: the line's + // own colours win over the gray. + let rgb = if c == u32::MAX { + horizon_client::text::GRAY + } else { + rgb_of(c) + }; + let indented = horizon_client::text::Text::literal(" ") + .append(text) + .with_color(rgb); + lines.push((indented, u32::MAX)); + } + } + } // Fireworks / FireworkExplosion.addToTooltip. for text in horizon_client::item_tooltip::firework_lines(stack, &translate) { push(&mut lines, text, rgba(170, 170, 170, 255)); @@ -1713,6 +1878,17 @@ impl Game<'_> { }; push(&mut lines, text, c); } + // The attribute modifiers of the effects (`When Applied:`). + for (text, c) in horizon_client::item_tooltip::potion_modifier_lines(stack, &translate) + { + push(&mut lines, text, c); + } + } + // JukeboxPlayable.addToTooltip. + if let Some(text) = + horizon_client::item_tooltip::jukebox_line(stack, item_info, &display, &translate) + { + push(&mut lines, text, gray); } if display.shows("minecraft:trim") && let Some((material, pattern)) = stack.data().and_then(|d| d.trim.clone()) @@ -1760,16 +1936,12 @@ impl Game<'_> { ); } } - // BannerPatternLayers.addToTooltip: up to six layer names. - 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); - push( - &mut lines, - self.translate(&key, &key), - rgba(170, 170, 170, 255), - ); - } + // DyedItemColor.addToTooltip. + if let Some((text, italic)) = + horizon_client::item_tooltip::dyed_line(stack, &display, advanced, &translate) + { + let text = horizon_client::text::Text::legacy(&text); + lines.push((if italic { text.italic() } else { text }, gray)); } // ItemLore.addToTooltip: after the enchantments, before the attributes // (ItemStack.addDetailsToTooltip). @@ -1778,6 +1950,50 @@ impl Game<'_> { lines.push((text, u32::MAX)); } } + if display.shows("minecraft:attribute_modifiers") { + // The item's own modifiers, then its enchantments' for each slot + // group (`ItemStack.forEachModifier`). + let mut modifiers = item_info.map(|i| i.modifiers.clone()).unwrap_or_default(); + modifiers.extend(e.modifier_rows(stack)); + let base = |name: &str, default| { + self.player + .as_ref() + .and_then(|player| { + let key = player.attributes.key(name)?; + let handle = player.attributes.lookup(Some(&key))?; + player + .attributes + .instance(&handle) + .ok() + .map(|value| value.base_value()) + }) + .unwrap_or(default) + }; + let player_base = (!nested).then(|| { + [ + base("minecraft:attack_damage", 1.0), + base( + "minecraft:attack_speed", + horizon_client::attack_strength::BASE_ATTACK_SPEED, + ), + ] + }); + for (text, c) in + horizon_client::item_tooltip::attribute_lines(&modifiers, player_base, &translate) + { + push(&mut lines, text, c); + } + } + // ItemStack.UNBREAKABLE_TOOLTIP. + if let Some(text) = + horizon_client::item_tooltip::unbreakable_line(stack, &display, &translate) + { + push(&mut lines, text, rgba(85, 85, 255, 255)); + } + // BlockItemStateProperties.addToTooltip. + if let Some(text) = horizon_client::item_tooltip::honey_line(stack, &display, &translate) { + push(&mut lines, text, gray); + } // Spawner.appendHoverText: what a spawner or trial spawner item spawns. if display.shows("minecraft:block_entity_data") && matches!( @@ -1801,43 +2017,11 @@ impl Game<'_> { } } } - if display.shows("minecraft:attribute_modifiers") - && let Some(info) = self.res.items().get(&stack.item) - { - let base = |name: &str, default| { - self.player - .as_ref() - .and_then(|player| { - let key = player.attributes.key(name)?; - let handle = player.attributes.lookup(Some(&key))?; - player - .attributes - .instance(&handle) - .ok() - .map(|value| value.base_value()) - }) - .unwrap_or(default) - }; - let player_base = [ - base("minecraft:attack_damage", 1.0), - base( - "minecraft:attack_speed", - horizon_client::attack_strength::BASE_ATTACK_SPEED, - ), - ]; - for (text, c) in horizon_client::item_tooltip::attribute_lines( - &info.modifiers, - Some(player_base), - &translate, - ) { - push(&mut lines, text, c); - } - } if display.shows("minecraft:damage") - && let Some(info) = self.res.items().get(&stack.item) + && let Some(info) = item_info && info.max_damage > 0 && stack.damage > 0 - && self.options_advanced_tooltips() + && advanced { push( &mut lines, @@ -1849,8 +2033,23 @@ impl Game<'_> { u32::MAX, ); } + // ItemStack.addDetailsToTooltipTail: with advanced tooltips the item id + // and how many components the stack has. + if advanced { + let dark_gray = rgba(85, 85, 85, 255); + push(&mut lines, stack.item.to_string(), dark_gray); + let count = horizon_client::item_tooltip::component_count(stack, item_info); + if count > 0 { + let text = self.translate("item.components", "%s component(s)"); + push( + &mut lines, + text.replacen("%s", &count.to_string(), 1), + dark_gray, + ); + } + } // ItemStack.OP_NBT_WARNING, for a player with game master permission. - if self.ui.registries.permission >= 2 && block_entity_item::op_warning(stack) { + if !nested && self.ui.registries.permission >= 2 && block_entity_item::op_warning(stack) { for (key, fallback) in [ ("item.op_warning.line1", "Warning:"), ( @@ -1907,32 +2106,65 @@ impl Game<'_> { if lines.is_empty() { return; } - let lines: Vec<_> = lines + let lines = Self::resolved(lines); + let atlas = &self.gui.atlas; + let (x, y, w, h) = + Self::tooltip_geometry(atlas, &lines, (x, y), (batch.width, batch.height), 0.0); + Self::tooltip_box(batch, atlas, x, y, w, h); + Self::tooltip_text(batch, atlas, &lines, x, y); + } + /// A tooltip's lines with their legacy codes resolved and their colours. + fn resolved>( + lines: &[(T, u32)], + ) -> Vec<(horizon_client::text::Text, u32)> { + lines .iter() .map(|(text, color)| { let text: horizon_client::text::Text = text.clone().into(); (text.resolve_legacy(), *color) }) - .collect(); - let atlas = &self.gui.atlas; + .collect() + } + /// The tooltip's text's top-left corner and the box's size: beside the + /// cursor, kept on screen, `extra` pixels taller than the text. + fn tooltip_geometry( + atlas: &horizon_client::hud::HudAtlas, + lines: &[(horizon_client::text::Text, u32)], + (x, y): (f32, f32), + (width, height): (f32, f32), + extra: f32, + ) -> (f32, f32, f32, f32) { let w = lines .iter() .map(|(t, _)| atlas.font.width_text(t)) - .fold(0.0, f32::max); - let h = if lines.len() == 1 { + .fold(0.0, f32::max) + .max(if extra > 0.0 { 96.0 } else { 0.0 }); + let text_h = if lines.len() == 1 { 8.0 } else { 8.0 + 2.0 + (lines.len() - 1) as f32 * 10.0 }; + let h = text_h + extra; let mut x = x + 12.0; let mut y = y - 12.0; - if x + w > batch.width - 4.0 { + if x + w > width - 4.0 { x = (x - 28.0 - w).max(4.0); } - if y + h + 3.0 > batch.height { - y = batch.height - h - 3.0; + if y + h + 3.0 > height { + y = height - h - 3.0; } y = y.max(4.0); + (x, y, w, h) + } + /// The box and its frame sprites. + fn tooltip_box( + batch: &mut HudBatch, + atlas: &horizon_client::hud::HudAtlas, + x: f32, + y: f32, + w: f32, + h: f32, + ) { batch.fill(atlas, x - 3.0, y - 4.0, w + 6.0, 1.0, rgba(16, 0, 16, 240)); batch.fill( atlas, @@ -1968,12 +2200,155 @@ impl Game<'_> { h + 4.0, rgba(60, 0, 190, 80), ); + } + fn tooltip_text( + batch: &mut HudBatch, + atlas: &horizon_client::hud::HudAtlas, + lines: &[(horizon_client::text::Text, u32)], + x: f32, + y: f32, + ) { let mut ty = y; for (i, (text, color)) in lines.iter().enumerate() { batch.text_styled(atlas, text, x, ty, *color, true); ty += if i == 0 { 12.0 } else { 10.0 }; } } + /// A stack's tooltip: its lines, and under them a bundle's contents + /// (`ClientBundleTooltip`: the 4 wide grid, the `+N` of what it leaves + /// out, and the weight bar). + pub(super) fn draw_stack_tooltip( + &mut self, + batch: &mut HudBatch, + stack: &ItemStack, + x: f32, + y: f32, + ) { + let lines = Self::resolved(&self.stack_tooltip(stack)); + if lines.is_empty() { + return; + } + // The component's height does not depend on where it is drawn, so a + // probe at the origin gives the box its extra height. + let probe = horizon_client::bundle::tooltip_layout(self.res.items(), stack, 0.0, 0.0, 96.0); + let extra = probe.as_ref().map_or(0.0, |l| l.height + 2.0); + let atlas = &self.gui.atlas; + let (x, y, w, h) = + Self::tooltip_geometry(atlas, &lines, (x, y), (batch.width, batch.height), extra); + Self::tooltip_box(batch, atlas, x, y, w, h); + let text_h = h - extra; + Self::tooltip_text(batch, atlas, &lines, x, y); + let Some(layout) = + horizon_client::bundle::tooltip_layout(self.res.items(), stack, x, y + text_h + 2.0, w) + else { + return; + }; + self.draw_bundle_tooltip(batch, &layout); + } + /// `ClientBundleTooltip.extractImage`: the slots, the count past them and + /// the progress bar. + fn draw_bundle_tooltip( + &mut self, + batch: &mut HudBatch, + layout: &horizon_client::bundle::TooltipLayout, + ) { + for (i, (at, stack)) in layout.slots.iter().enumerate() { + let selected = layout.selected == Some(i); + let sprite = |name: &str| format!("gui/sprites/container/bundle/{name}"); + // Each draw takes the atlas on its own: the item's needs `&mut self`. + horizon_client::ui::nine_slice( + batch, + &self.gui.atlas, + &sprite(if selected { + "slot_highlight_back" + } else { + "slot_background" + }), + at[0], + at[1], + 24.0, + 24.0, + u32::MAX, + ); + let stack = stack.clone(); + let [x, y] = *at; + self.draw_item(batch, &stack, x + 4.0, y + 4.0); + if selected { + horizon_client::ui::nine_slice( + batch, + &self.gui.atlas, + &sprite("slot_highlight_front"), + x, + y, + 24.0, + 24.0, + u32::MAX, + ); + } + } + let atlas = &self.gui.atlas; + if let Some((at, hidden)) = layout.overflow { + let label = horizon_client::text::Text::literal(format!("+{hidden}")); + let w = atlas.font.width_text(&label); + batch.text_styled( + atlas, + &label, + at[0] + 12.0 - (w / 2.0).floor(), + at[1] + 10.0, + u32::MAX, + true, + ); + } + if let Some((at, description)) = layout + .empty_description + .zip(Some("item.minecraft.bundle.empty.description")) + { + let text = horizon_client::text::Text::translate(description, &[]); + let mut ty = at[1]; + for line in atlas.font.split_lines(&text, layout.width) { + batch.text_styled(atlas, &line.0, at[0], ty, 0xFFAA_AAAA, false); + ty += 9.0; + } + } + let [bx, by] = layout.bar; + let fill_sprite = if layout.full { + "gui/sprites/container/bundle/bundle_progressbar_full" + } else { + "gui/sprites/container/bundle/bundle_progressbar_fill" + }; + horizon_client::ui::nine_slice( + batch, + atlas, + fill_sprite, + bx + 1.0, + by, + layout.fill, + 13.0, + u32::MAX, + ); + horizon_client::ui::nine_slice( + batch, + atlas, + "gui/sprites/container/bundle/bundle_progressbar_border", + bx, + by, + 96.0, + 13.0, + u32::MAX, + ); + if let Some(key) = layout.label { + let label = horizon_client::text::Text::translate(key, &[]); + let w = atlas.font.width_text(&label); + batch.text_styled( + atlas, + &label, + bx + 48.0 - (w / 2.0).floor(), + by + 3.0, + u32::MAX, + true, + ); + } + } /// Hovered-slot tooltip on the plain inventory, crafting and container screens. pub(super) fn draw_slot_tooltip(&mut self, batch: &mut HudBatch) { if self.carried.is_some() { @@ -1984,8 +2359,7 @@ impl Game<'_> { }; let stack = self.slot_view(slot); if let Some(stack) = stack { - let lines = self.stack_tooltip(&stack); - self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1); + self.draw_stack_tooltip(batch, &stack, self.cursor.0, self.cursor.1); } else if let Some(text) = self.crafter_tooltip(slot) { self.draw_tooltip_lines( batch, @@ -2041,5 +2415,13 @@ impl Game<'_> { } /// The anvil's rename box (`AnvilScreen`: `setMaxLength(50)`). -const ANVIL_NAME: horizon_client::clipboard::FieldId = ("anvil.name", 0); const ANVIL_NAME_CHARS: usize = 50; + +fn anvil_box() -> horizon_client::ui::EditBox { + let mut edit = horizon_client::ui::EditBox::new(0.0, 0.0, 103.0, 12.0); + edit.bordered = false; + edit.max_length = ANVIL_NAME_CHARS; + edit.text_color = u32::MAX; + edit.focused = true; + edit +} diff --git a/crates/horizon-client/src/game/storage.rs b/crates/horizon-client/src/game/storage.rs index 1bcb6a524..e5cb0ab26 100644 --- a/crates/horizon-client/src/game/storage.rs +++ b/crates/horizon-client/src/game/storage.rs @@ -33,6 +33,55 @@ impl Game<'_> { self.container = Some(key); self.ender_open = Some(key); } + /// The block above `key` is a redstone conductor. + fn conductor_above(&self, key: (i32, i32, i32)) -> bool { + let above = self.world.block(key.0, key.1 + 1, key.2); + self.res.behaviours().facts(above).flags + & horizon_world::level::data::state_flags::CONDUCTOR + != 0 + } + /// `ChestBlock.isChestBlockedAt`: a redstone conductor above the chest or + /// a cat sitting on it. + fn chest_blocked_at(&self, key: (i32, i32, i32)) -> bool { + if self.conductor_above(key) { + return true; + } + // isCatSittingOnChest: a cat whose box meets the block above. + let area = horizon_core::geometry::Aabb::new( + horizon_core::geometry::Vec3::new( + f64::from(key.0), + f64::from(key.1 + 1), + f64::from(key.2), + ), + horizon_core::geometry::Vec3::new( + f64::from(key.0 + 1), + f64::from(key.1 + 2), + f64::from(key.2 + 1), + ), + ); + self.mobs.iter().any(|m| { + m.species() == horizon_client::mobs::Species::Cat + && m.alive() + && horizon_client::mobs::tame::cat_sitting(m) + && m.bounds().intersects(area) + }) + } + /// `ChestBlock.getMenuProvider` (`combine(.., false)`) and + /// `EnderChestBlock.useWithoutItem`: a blocked chest, or a double chest + /// with either half blocked, opens no menu. + pub(super) fn chest_menu_blocked(&self, key: (i32, i32, i32), name: &str) -> bool { + match name { + "minecraft:chest" | "minecraft:trapped_chest" => { + self.chest_blocked_at(key) + || self + .chest_partner(key) + .is_some_and(|(other, _)| self.chest_blocked_at(other)) + } + // The ender chest only looks at the block above (no cat check). + "minecraft:ender_chest" => self.conductor_above(key), + _ => false, + } + } /// Closing it copies the items back and leaves no block-entity contents. pub(super) fn close_ender_chest(&mut self) { let Some(key) = self.ender_open.take() else { diff --git a/crates/horizon-client/src/game/text_displays.rs b/crates/horizon-client/src/game/text_displays.rs index f6c946bcc..45bd64fa7 100644 --- a/crates/horizon-client/src/game/text_displays.rs +++ b/crates/horizon-client/src/game/text_displays.rs @@ -210,6 +210,7 @@ impl Game<'_> { if bg != 0 { batch.fill( atlas, + // submitTextBackground(-1, -1, width, height): corners, not a size. -1.0, -1.0, width + 1.0, diff --git a/crates/horizon-client/src/game/titles.rs b/crates/horizon-client/src/game/titles.rs index cbae1f6b4..9bb000314 100644 --- a/crates/horizon-client/src/game/titles.rs +++ b/crates/horizon-client/src/game/titles.rs @@ -21,6 +21,22 @@ impl Game<'_> { draws.extend(self.titles.title(w, h, partial, font, background)); hud_layout::paint(batch, &self.gui.atlas, &draws); } + /// `Hud.extractSavingIndicator`, under the screens: the option, then the + /// fading "Saving world" text. + pub(super) fn draw_saving_indicator(&self, batch: &mut HudBatch) { + if !self.settings.autosave_indicator { + return; + } + let draws = self.saving_indicator.draw( + batch.width as i32, + batch.height as i32, + self.clock.fraction() as f32, + &self.gui.atlas.font, + Text::literal(self.translate("menu.savingLevel", "Saving world")), + self.settings.text_background(0.0), + ); + 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 { let stack = self.inventory.get(self.selected)?.as_ref()?; @@ -44,6 +60,12 @@ impl Game<'_> { /// The title, action bar and selected-item parts of `Hud.tick`. pub(super) fn tick_hud(&mut self) { self.titles.tick(); + // `MinecraftServer.isCurrentlySaving` of single player's server. + let saving = self + .integrated + .as_ref() + .map_or(self.autosaving, |server| server.is_saving()); + self.saving_indicator.tick(saving); let held = self.held_name(); self.tool_highlight .tick(held, f64::from(self.settings.notification_display_time)); diff --git a/crates/horizon-client/src/game/trading.rs b/crates/horizon-client/src/game/trading.rs index 87e0c18c6..6986d8baa 100644 --- a/crates/horizon-client/src/game/trading.rs +++ b/crates/horizon-client/src/game/trading.rs @@ -803,8 +803,7 @@ impl Game<'_> { text.split('\n').map(|l| (l.to_owned(), u32::MAX)).collect(); self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1); } else if let Some(stack) = tooltip { - let lines = self.stack_tooltip(&stack); - self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1); + self.draw_stack_tooltip(batch, &stack, self.cursor.0, self.cursor.1); } true } diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index c31094596..d934e85aa 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -1,7 +1,8 @@ //! Tridents: `TridentItem.releaseUsing` (throw after 10 ticks, or Riptide in //! water or rain) and `ThrownTrident` (arrow flight with 0.99 water inertia, //! 8 damage plus Impaling, the reversed bounce off a hit, sticking, Loyalty's -//! return to the owner, pickup) with `ThrownTridentRenderer`. +//! return to the owner, pickup) with `ThrownTridentRenderer`, and Channeling's +//! lightning on a hit (`channeling.json`). use super::{Game, view_vector}; use horizon_client::{ collisions::SceneCollisions, @@ -10,7 +11,8 @@ use horizon_client::{ mobs::{Damage, DamageKind, Who, anim::Poses}, }; use horizon_core::{ - geometry::{Aabb, Vec3}, + geometry::{Aabb, Vec3, traverse_blocks}, + position::BlockPos, random::RandomSource, }; @@ -154,6 +156,69 @@ impl Game<'_> { p.auto_spin_attack_dmg = 0.0; } } + /// The `summon_entity` and `play_sound` effects of `channeling.json`: in a + /// thunderstorm (`weather_check`) a spot that sees the sky (`can_see_sky`) + /// gets a lightning bolt and the thunder sound. + fn channel_lightning(&mut self, at: [f64; 3]) { + // Level.isThundering: the thunder level, in dimensions with weather. + if self.dim != super::Dim::Overworld || self.world.weather.levels(1.0).1 <= 0.9 { + return; + } + // BlockAndLightGetter.canSeeSky: full sky light. + let (x, y, z) = ( + at[0].floor() as i32, + at[1].floor() as i32, + at[2].floor() as i32, + ); + if self.world.light(x, y, z) >> 4 != 15 { + return; + } + self.spawn_bolt(at, false); + self.audio + .play("minecraft:item.trident.thunder", Some(at), 5.0, 1.0); + } + /// `minecraft:hit_block` of Channeling (`AbstractArrow.hitBlockEnchantmentEffects`): + /// the block the trident's path first hits, if it is a lightning rod, with + /// the hit location clamped into the block (`BlockPos.clampLocationWithin`). + fn channel_rod_hit(&mut self, from: Vec3, velocity: Vec3) { + let to = Vec3::new( + from.x + velocity.x, + from.y + velocity.y, + from.z + velocity.z, + ); + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }; + // ClipContext.Block.COLLIDER with Fluid.NONE. + let hit = traverse_blocks(from, to, 1024, |p: BlockPos| { + let state = self.world.block(p.x, p.y, p.z); + if self.res.facts().is_air(state) { + return None; + } + let shape = self + .collision + .collision_shape(&mut scene, state, [p.x, p.y, p.z]) + .ok()?; + shape.clip(from, to, p) + }); + let Some(hit) = hit.ok().flatten() else { + return; + }; + let state = self.world.block(hit.block.x, hit.block.y, hit.block.z); + if !self.res.facts().get(state).name.ends_with("lightning_rod") { + return; + } + let edge = f64::from(1.0e-5f32); + let clamp = + |v: f64, origin: i32| v.clamp(f64::from(origin) + edge, f64::from(origin) + 1.0 - edge); + self.channel_lightning([ + clamp(hit.location.x, hit.block.x), + clamp(hit.location.y, hit.block.y), + clamp(hit.location.z, hit.block.z), + ]); + } /// `TridentItem.releaseUsing`. pub(super) fn release_trident(&mut self, ticks: u32) { if ticks < 10 { @@ -171,10 +236,11 @@ impl Game<'_> { .as_ref() .map(|p| [p.position.x, p.position.y, p.position.z]); if riptide > 0 { - if !self.in_water_or_rain() { + // `isInWaterOrRain() && !isPassenger()`. + if !self.in_water_or_rain() || self.riding.is_some() { return; } - self.damage_held(1); + self.hurt_held_without_breaking(1); // trident_spin_attack_strength: 1.5 + 0.75 per level above the first. let strength = 1.5 + 0.75 * (riptide as f32 - 1.0); let d = view_vector(self.yaw, self.pitch); @@ -195,12 +261,8 @@ impl Game<'_> { self.audio.play(&sound, at, 1.0, 1.0); return; } - // hurtWithoutBreaking, then the thrown copy. - if !self.creative - && let Some(s) = self.held_mut().as_mut() - { - s.damage += 1; - } + // hurtWithoutBreaking (Unbreaking applies), then the thrown copy. + self.hurt_held_without_breaking(1); let thrown = self.held().cloned().unwrap_or(stack); if !self.creative { *self.held_mut() = None; @@ -311,9 +373,10 @@ impl Game<'_> { }); let damage = 8.0 + if aquatic { 2.5 * impaling } else { 0.0 }; t.dealt_damage = true; + let mut hurt_at = None; if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { let from = Some([t.position.x, t.position.y, t.position.z]); - m.damage( + let hurt = m.damage( damage, Damage { kind: DamageKind::Arrow, @@ -321,6 +384,15 @@ impl Game<'_> { from, }, ); + if hurt { + hurt_at = Some([m.position.x, m.position.y, m.position.z]); + } + } + // `minecraft:post_attack` of Channeling, on the victim. + if let Some(at) = hurt_at + && t.stack.enchantment_level("minecraft:channeling") > 0 + { + self.channel_lightning(at); } self.audio.play( "minecraft:item.trident.hit", @@ -341,6 +413,7 @@ impl Game<'_> { subject: None, }; if let Ok(moved) = scene.resolve(bounds(t.position), t.velocity, 0.0, false) { + let (from, flight) = (t.position, t.velocity); let blocked = (moved.x - t.velocity.x).abs() > 1e-7 || (moved.y - t.velocity.y).abs() > 1e-7 || (moved.z - t.velocity.z).abs() > 1e-7; @@ -350,6 +423,9 @@ impl Game<'_> { t.position.z + moved.z, ); if blocked { + if t.stack.enchantment_level("minecraft:channeling") > 0 { + self.channel_rod_hit(from, flight); + } t.in_ground = true; t.velocity = Vec3::ZERO; self.audio.play( diff --git a/crates/horizon-client/src/game/tweaks.rs b/crates/horizon-client/src/game/tweaks.rs index cec83e248..648073874 100644 --- a/crates/horizon-client/src/game/tweaks.rs +++ b/crates/horizon-client/src/game/tweaks.rs @@ -70,8 +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 = super::remote::input_ordinal(input); - return self.remote_slot_click(slot, button as i8, ordinal); + return self.remote_menu_ops(&[(Some(slot), button, input)]); } if !self.menu_click(Some(slot), button, input) { return false; diff --git a/crates/horizon-client/src/game/villagers.rs b/crates/horizon-client/src/game/villagers.rs index 3cfe8aa1d..c04b18604 100644 --- a/crates/horizon-client/src/game/villagers.rs +++ b/crates/horizon-client/src/game/villagers.rs @@ -21,6 +21,38 @@ impl Game<'_> { fn item_max_stack(&self, item: &str) -> u32 { self.res.items().get(item).map_or(64, |i| i.max_stack) } + /// `WorkAtComposter.useWorkstation`: at a composter the farmer makes + /// bread, then composts seeds. + pub(super) fn villager_work_at_composter(&mut self, id: u32, pos: [i32; 3]) { + let Some(i) = self.villager_index(id) else { + return; + }; + if self.composter_level(pos).is_none() { + return; + } + self.villager_make_bread(i); + self.villager_compost_items(i, pos); + } + /// `WorkAtComposter.makeBread`: up to three loaves from nine wheat while + /// the villager holds at most 36 bread; what does not fit drops. + fn villager_make_bread(&mut self, i: usize) { + let max_stack = self.item_max_stack("minecraft:bread"); + let e = villager::ext_mut(&mut self.mobs[i]); + if e.count_item("minecraft:bread") > 36 { + return; + } + let loaves = (e.count_item("minecraft:wheat") / 3).min(3); + if loaves == 0 { + return; + } + e.remove_item("minecraft:wheat", loaves * 3); + let left = e.add_item(ItemStack::new("minecraft:bread", loaves), max_stack); + if let Some(rest) = left { + // spawnAtLocation(level, stack, 0.5F) + let p = self.mobs[i].position; + self.spawn_item(rest, [p.x, p.y + 0.5, p.z], [0.0, 0.2, 0.0], 10); + } + } /// `BehaviorUtils.throwItem`: toss a stack from a villager's hand toward /// a point. fn villager_throw(&mut self, from: Vec3, eye: f64, to: Vec3, stack: ItemStack) { diff --git a/crates/horizon-client/src/game/world_loading.rs b/crates/horizon-client/src/game/world_loading.rs index 0cea31fd0..73f1820f2 100644 --- a/crates/horizon-client/src/game/world_loading.rs +++ b/crates/horizon-client/src/game/world_loading.rs @@ -46,6 +46,10 @@ impl WorldRequest { options: &Options, settings: &Settings, ) -> Result { + // Before any chunk is read: a loaded container with a loot table is rolled as its chunk + // is decoded (`save::roll_loaded_loot`), and the spawn chunks are read while the world + // opens. Every world opens here: in-frame, on the server thread, on a dedicated server. + horizon_client::structure_blocks::loot_data(&options.resources); let Self { save_root, folder, @@ -192,6 +196,82 @@ impl WorldLoader { } } +/// How long the preloaded world data outlives the world screens: a player +/// who goes back to the title or to Multiplayer and opens no world for this +/// long gets the memory back. +const PRELOAD_KEPT: std::time::Duration = std::time::Duration::from_secs(60); + +enum Preload { + Idle, + /// Read, or being read, on the "World data preload" thread. `left`: when + /// the player last left the world screens. + Started { + thread: std::thread::JoinHandle<()>, + left: Option, + }, + /// A world opened: the data is the world's now, and stays. + Used, +} + +static PRELOAD: std::sync::Mutex = std::sync::Mutex::new(Preload::Idle); + +/// Each frame of the title: read what every world opening loads and keeps +/// for the rest of the process (the worldgen bundle, the loot tables and the +/// registries the server sends) on a helper thread while the player is on the +/// world screens (`on_world_screens`: Singleplayer, Create World and their +/// dialogs), so it overlaps the time spent choosing a world. A world opened +/// meanwhile waits for the part being read instead of reading it again. Not +/// at the title screen itself: many players only go to Multiplayer, and +/// small machines need the memory. Dropped after `PRELOAD_KEPT` away from +/// the world screens without a world opening. +pub(super) fn preload_world_data( + on_world_screens: bool, + resources: &std::path::Path, + registry: &'static horizon_world::registry::BlockRegistry, +) { + let mut preload = PRELOAD.lock().unwrap_or_else(|e| e.into_inner()); + match &mut *preload { + Preload::Used => {} + Preload::Idle if on_world_screens => { + let resources = resources.to_owned(); + let spawned = std::thread::Builder::new() + .name("World data preload".into()) + .spawn(move || { + horizon_threads::behind_server(); + // Errors are left for the world opening to report. + let _ = horizon_client::vanillagen::shared_data( + &resources.join("worldgen"), + registry, + ); + let _ = horizon_client::structure_blocks::loot_data(&resources); + let _ = super::lan::sync_data(&resources); + }); + match spawned { + Ok(thread) => *preload = Preload::Started { thread, left: None }, + Err(e) => log::warn!("Horizon: world data preload: {e}"), + } + } + Preload::Idle => {} + Preload::Started { left, .. } if on_world_screens => *left = None, + Preload::Started { thread, left } => { + let left = *left.get_or_insert_with(std::time::Instant::now); + if left.elapsed() >= PRELOAD_KEPT && thread.is_finished() { + horizon_client::vanillagen::forget_shared_data(); + horizon_client::structure_blocks::forget_loot_data(); + super::lan::forget_sync_data(); + horizon_threads::release_free_memory(); + *preload = Preload::Idle; + log::info!("Horizon: preloaded world data dropped, no world opened"); + } + } + } +} + +/// A world opens: what `preload_world_data` read is the world's from now on. +pub(super) fn world_data_used() { + *PRELOAD.lock().unwrap_or_else(|e| e.into_inner()) = Preload::Used; +} + pub(super) fn make_streaming( res: &Resources, pack: &PackResources, @@ -261,6 +341,7 @@ pub(super) fn make_streaming( res.threads(), ) }; + streaming.forced = save.load_forced_chunks(); streaming.radius = settings.render_distance; streaming.biome_blend = settings.biome_blend; streaming.smooth_lighting = settings.smooth_lighting; diff --git a/crates/horizon-client/src/game/zombie_reinforcements.rs b/crates/horizon-client/src/game/zombie_reinforcements.rs new file mode 100644 index 000000000..4c6100f43 --- /dev/null +++ b/crates/horizon-client/src/game/zombie_reinforcements.rs @@ -0,0 +1,134 @@ +//! `Zombie.hurtServer`'s reinforcements: a hurt zombie on Hard may call +//! another of its kind from 7 to 40 blocks away to fight its target. +use super::Game; +use horizon_client::mobs::{ + MobType, Species, Who, + finalize::{self, Attr, Op}, + spawn_rules::{self, Reason}, + spawn_selection::{self, NaturalLevel}, + spawner::SpawnerLevel, +}; +use horizon_core::random::{LegacyRandom, RandomSource}; +use horizon_world::food::Difficulty; + +/// `Zombie.REINFORCEMENT_ATTEMPTS`. +const ATTEMPTS: usize = 50; +/// `Zombie.REINFORCEMENT_RANGE_MIN` and `REINFORCEMENT_RANGE_MAX`. +const RANGE_MIN: i32 = 7; +const RANGE_MAX: i32 = 40; + +/// One axis of the offset: `Mth.nextInt(random, 7, 40) * Mth.nextInt(random, -1, 1)`. +fn offset(random: &mut LegacyRandom) -> i32 { + let distance = random + .next_int_between_inclusive(RANGE_MIN, RANGE_MAX) + .unwrap_or(RANGE_MIN); + distance * random.next_int_between_inclusive(-1, 1).unwrap_or(0) +} + +impl Game<'_> { + /// `Zombie.hurtServer` after the hit: on Hard, with the zombie's chance + /// and monsters spawning, a copy of it appears out of sight and takes + /// `target`; both then call less often. + pub(super) fn call_reinforcements(&mut self, caller: u32, target: Who) { + let Some(index) = self.mobs.iter().position(|m| m.id == caller) else { + return; + }; + if self.world.health_rules.difficulty != Difficulty::Hard { + return; + } + let zombie = &mut self.mobs[index]; + if f64::from(zombie.random.next_float()) >= zombie.attrs.spawn_reinforcements { + return; + } + // ServerLevel.isSpawningMonsters. + if !self.ui.rules.bool("spawn_mobs") || !self.ui.rules.bool("spawn_monsters") { + return; + } + let kind = zombie.kind.clone(); + let from = [ + zombie.position.x.floor() as i32, + zombie.position.y.floor() as i32, + zombie.position.z.floor() as i32, + ]; + let mut own = std::mem::replace(&mut zombie.random, LegacyRandom::new(0)); + let mut rules = std::mem::replace(&mut self.world.random, LegacyRandom::new(0)); + let spot = self.reinforcement_spot(&kind, from, &mut own, &mut rules); + self.mobs[index].random = own; + self.world.random = rules; + let Some(spot) = spot else { + return; + }; + let Some(id) = self.spawn_mob(&kind.id, spot.map(f64::from), false) else { + return; + }; + if let Some(reinforcement) = self.mobs.iter_mut().find(|m| m.id == id) { + reinforcement.ai.target = Some(target); + // ZOMBIE_REINFORCEMENT_CALLEE_CHARGE. + finalize::add_modifier( + reinforcement, + Attr::SpawnReinforcements, + "minecraft:reinforcement_callee_charge", + -f64::from(0.05f32), + Op::AddValue, + ); + } + // The caller's charge grows by 0.05 each time it calls. + let caller = &mut self.mobs[index]; + let charged = finalize::modifier_amount( + caller, + Attr::SpawnReinforcements, + "minecraft:reinforcement_caller_charge", + ) + .unwrap_or(0.0); + finalize::add_modifier( + caller, + Attr::SpawnReinforcements, + "minecraft:reinforcement_caller_charge", + charged - 0.05, + Op::AddValue, + ); + } + /// The block `Zombie.hurtServer` puts the reinforcement at: the first of + /// 50 random offsets with a valid spawn surface, no alive player within + /// 7 blocks, and room for the zombie standing on the block's corner. + fn reinforcement_spot( + &self, + kind: &MobType, + from: [i32; 3], + own: &mut LegacyRandom, + rules: &mut LegacyRandom, + ) -> Option<[i32; 3]> { + let level = self.natural_level(); + let (width, height) = (kind.width as f32, kind.height as f32); + for _ in 0..ATTEMPTS { + let [x, y, z] = from.map(|v| v + offset(own)); + if !spawn_rules::is_spawn_position_ok(kind.species, &level, x, y, z) + || !spawn_rules::check_spawn_rules( + kind.species, + &level, + Reason::Reinforcement, + rules, + x, + y, + z, + ) + { + continue; + } + // setPos(x, y, z): the box is centred on the block's corner. + let bounds = + spawn_selection::spawn_box(f64::from(x), f64::from(y), f64::from(z), width, height); + // Drowned.canSpawnInLiquids. + let wet_ok = kind.species == Species::Drowned + || !spawn_selection::contains_any_liquid(&level, bounds); + if !level.alive_player_near(f64::from(x), f64::from(y), f64::from(z), 7.0) + && level.unobstructed(bounds) + && level.no_collision(bounds) + && wet_ok + { + return Some([x, y, z]); + } + } + None + } +} diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 5ff14003c..70d882a98 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -32,6 +32,8 @@ fn entity_shader() -> String { crate::overlay::wgsl_constants() + include_str!("entity.wgsl") } +#[cfg(test)] +mod crumbling_tests; mod entity_batch; mod weather; use entity_batch::EntityBatch; @@ -65,8 +67,10 @@ mod arena; mod cull; mod end_sky; mod flat; +mod hdr; pub mod lightning; mod lod; +mod native_material; mod native_pack; mod native_post; mod native_sky; @@ -332,6 +336,10 @@ pub struct Renderer { adapter: wgpu::Adapter, /// The window's swapchain; `None` when rendering offscreen (`--offscreen`). surface: Option>, + /// The surface `release_surface` set aside for the renderer that replaces + /// this one on the same device: reused, not created again, as a new + /// surface for the window can come back lost (Wayland on Mesa). + spare_surface: std::sync::Mutex>>, /// The offscreen colour target, sized like `config`. offscreen: Option, /// Offscreen submissions still on the GPU: at most two frames run ahead. @@ -429,6 +437,8 @@ pub struct Renderer { /// The mipmap levels sampled (the Mipmap Levels option), at most `mip_levels - 1`. mipmaps: u32, terrain_layout: wgpu::BindGroupLayout, + /// terrain.wgsl's `SPRITE_ARRAYS` and `SPRITE_SPLIT`, for a shader pack's terrain. + terrain_sprites: [f64; 2], sprite_sampler: wgpu::Sampler, lightmap_view: wgpu::TextureView, lightmap_sampler: wgpu::Sampler, @@ -460,7 +470,7 @@ pub struct Renderer { lod_retiring: crate::fast_hash::FxHashSet, /// Finished tile meshes `upload_lods` has yet to upload. lod_pending: Option, - detail_columns: HashMap<(i32, i32), u32>, + detail_columns: crate::fast_hash::FxHashMap<(i32, i32), u32>, /// Bumped whenever a column becomes or stops being complete. detail_revision: u64, arena: arena::Arena, @@ -494,13 +504,17 @@ pub struct Renderer { /// The shadow camera's draws by page, in bands of distance from the light. shadow_runs: page_runs::PageRuns, /// Block-entity blocks per meshed section (world position, state id). - block_entities: HashMap>, + block_entities: crate::fast_hash::FxHashMap>, /// 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). world_post: world_post::Post, + /// HDR output (Horizon setting): `Some` while the swapchain is scRGB. + hdr: Option, + /// Whether the window's surface can present scRGB. + hdr_capable: bool, /// The shader pack's post-processing, and the dimension (legacy id) it was loaded for. pack_post: Option<(i32, Option)>, /// The post passes of one of Horizon's own shader packs; never beside `pack_post`'s. @@ -907,15 +921,24 @@ async fn open_device( limits.max_storage_buffer_binding_size, limits.max_texture_array_layers, )); - match adapter - .request_device(&wgpu::DeviceDescriptor { - label: Some("Horizon device"), - required_features: features, - required_limits: limits, - ..Default::default() - }) - .await - { + let desc = wgpu::DeviceDescriptor { + label: Some("Horizon device"), + required_features: features, + required_limits: limits, + ..Default::default() + }; + #[cfg(not(target_os = "macos"))] + let opened = match info.backend { + wgpu::Backend::Vulkan => horizon_hdr::open_vulkan_device(&adapter, &desc), + _ => None, + }; + #[cfg(target_os = "macos")] + let opened = None; + let opened = match opened { + Some(opened) => opened, + None => adapter.request_device(&desc).await, + }; + match opened { Ok((device, queue)) => { return Ok(Opened { instance, @@ -1027,7 +1050,15 @@ impl Renderer { surface: if offscreen { None } else { - Some(renderer.instance.create_surface(window.clone())?) + let spare = renderer + .spare_surface + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take(); + Some(match spare { + Some(surface) => surface, + None => renderer.instance.create_surface(window.clone())?, + }) }, instance: renderer.instance.clone(), adapter: renderer.adapter.clone(), @@ -1040,7 +1071,7 @@ impl Renderer { let info = adapter.get_info(); crate::graphics::suggest_reduced_far_detail(crate::graphics::lod_capped(&info)); let size = window.inner_size(); - let (config, present_modes) = if let Some(surface) = &surface { + let (config, present_modes, hdr_capable) = if let Some(surface) = &surface { let mut config = surface .get_default_config(&adapter, size.width.max(1), size.height.max(1)) .ok_or("surface has no supported configuration")?; @@ -1068,7 +1099,7 @@ impl Renderer { )); } surface.configure(&device, &config); - (config, caps.present_modes.clone()) + (config, caps.present_modes.clone(), hdr::supported(&caps)) } else { let format = wgpu::TextureFormat::Bgra8Unorm; let config = wgpu::SurfaceConfiguration { @@ -1082,7 +1113,7 @@ impl Renderer { view_formats: vec![format], color_space: wgpu::SurfaceColorSpace::default(), }; - (config, Vec::new()) + (config, Vec::new(), false) }; let offscreen = surface .is_none() @@ -1926,14 +1957,20 @@ impl Renderer { compilation_options: Default::default(), targets: &[Some(wgpu::ColorTargetState { format: config.format.remove_srgb_suffix(), - // RenderPipelines.CELESTIAL: additive (src alpha, one). + // RenderPipelines.CELESTIAL: additive (src alpha, one). The + // alpha goes to 0: HDR output (hdr.wgsl) lets the sun and + // moon shine; nothing else reads the frame's alpha. blend: Some(wgpu::BlendState { color: wgpu::BlendComponent { src_factor: wgpu::BlendFactor::SrcAlpha, dst_factor: wgpu::BlendFactor::One, operation: wgpu::BlendOperation::Add, }, - alpha: wgpu::BlendComponent::OVER, + alpha: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::Zero, + dst_factor: wgpu::BlendFactor::Zero, + operation: wgpu::BlendOperation::Add, + }, }), write_mask: wgpu::ColorWrites::ALL, })], @@ -2297,6 +2334,7 @@ impl Renderer { instance, adapter, surface, + spare_surface: std::sync::Mutex::new(None), offscreen, in_flight: std::collections::VecDeque::new(), first_frame: if previous.is_none() { @@ -2370,6 +2408,7 @@ impl Renderer { mip_levels, mipmaps: mip_levels - 1, terrain_layout: bindings, + terrain_sprites: sprite_constants.map(|(_, v)| v), sprite_sampler, lightmap_view, lightmap_sampler, @@ -2391,7 +2430,7 @@ impl Renderer { lod_cutout: Default::default(), lod_retiring: Default::default(), lod_pending: None, - detail_columns: HashMap::new(), + detail_columns: Default::default(), detail_revision: 0, arena, sorted_indices, @@ -2412,10 +2451,12 @@ impl Renderer { solid_runs: page_runs::PageRuns::default(), phase2_runs: page_runs::PageRuns::default(), shadow_runs: page_runs::PageRuns::default(), - block_entities: HashMap::new(), + block_entities: Default::default(), block_entity_revision: next_block_entity_revision(), occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16), world_post, + hdr: None, + hdr_capable, pack_post: None, native: None, pass_timing: pack_timing::PassTiming::logging(), @@ -2473,19 +2514,38 @@ impl Renderer { view_formats: &config.view_formats, }) } - /// Release the window surface before another renderer uses the same window. + /// Hand the window surface over to the renderer that replaces this one on + /// the same device (it takes `spare_surface`). pub fn release_surface(&mut self) { - self.surface = None; + *self + .spare_surface + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner) = self.surface.take(); } /// Reattach a window after surface loss or a failed renderer replacement. pub fn recreate_surface(&mut self) -> Result<()> { if self.offscreen.is_some() { return Ok(()); } - // Wayland allows only one tearing-control object per window surface. - self.release_surface(); - let surface = self.instance.create_surface(self.window.clone())?; - surface.configure(&self.device, &self.config); + // The surface set aside for a replacement that failed, else a new one + // (Wayland allows only one tearing-control object per window surface, + // so the old one goes first). + let spare = self + .spare_surface + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take(); + self.surface = None; + let surface = match spare { + Some(surface) => surface, + None => self.instance.create_surface(self.window.clone())?, + }; + Self::configure( + &self.device, + &surface, + &self.surface_config(), + self.hdr.as_ref(), + ); self.surface = Some(surface); Ok(()) } @@ -2548,7 +2608,12 @@ impl Renderer { && let Some(surface) = &self.surface { self.config.present_mode = mode; - surface.configure(&self.device, &self.config); + Self::configure( + &self.device, + surface, + &self.surface_config(), + self.hdr.as_ref(), + ); } } pub fn resize(&mut self, width: u32, height: u32) { @@ -2559,7 +2624,12 @@ impl Renderer { self.config.width = width; self.config.height = height; if let Some(surface) = &self.surface { - surface.configure(&self.device, &self.config); + Self::configure( + &self.device, + surface, + &self.surface_config(), + self.hdr.as_ref(), + ); } else { self.offscreen = Some(Self::offscreen_target(&self.device, &self.config)); } @@ -2848,20 +2918,106 @@ impl Renderer { self.detail_columns.insert(column, next); } } - pub fn remove(&mut self, key: SectionKey) { - self.set_detail(key, false); - if self.block_entities.remove(&key).is_some() { + /// Every section of these columns goes: one lookup per column where the + /// tables are by column, and the meshes' ranges freed in one batch. A + /// teleport removes a few thousand columns in one frame. + pub fn remove_columns(&mut self, columns: impl IntoIterator) { + let mut released = Vec::new(); + let mut block_entities = false; + for (x, z) in columns { + if self.detail_columns.remove(&(x, z)) == Some(COMPLETE_COLUMN) { + self.detail_revision += 1; + } + self.occlusion.remove_column(x, z); + let retiring = !self.lod_cutout.is_empty() && self.lod_cutout.contains(&(x, z)); + for sy in 0..crate::chunk::SECTIONS as i32 { + let key = (x, sy, z); + block_entities |= self.block_entities.remove(&key).is_some(); + if retiring { + // Distant tiles still leave its column out: drawn until they don't. + self.lod_retiring.insert(key); + } else if let Some(section) = self.sections.remove(key) { + released.push(section); + } + } + } + if block_entities { self.block_entity_revision = next_block_entity_revision(); } - self.occlusion.remove(key); - if !self.lod_cutout.is_empty() && self.lod_cutout.contains(&(key.0, key.2)) { - // Distant tiles still leave its column out: drawn until they don't. - self.lod_retiring.insert(key); - } else { - self.release_section(key); + if let Some(flat) = &mut self.flat { + for id in released.iter().filter_map(|s| s.flat_id) { + flat.remove(id); + } } + self.sorted_indices + .release_all(released.iter().filter_map(|s| { + let (page, start) = s.sorted_indices?; + Some((page, start, u64::from(s.translucent) * 6)) + })); + self.arena.release_all( + released + .iter() + .map(|s| (s.page, s.start, u64::from(s.solid + s.translucent) * 4)), + ); } /// Horizon's resolution scale (world pixels per window pixel) and FXAA. + /// Configures `surface` and, while HDR output is on, sends its HDR metadata + /// again: a new swapchain starts without it. + fn configure( + device: &wgpu::Device, + surface: &wgpu::Surface<'_>, + config: &wgpu::SurfaceConfiguration, + hdr: Option<&hdr::Hdr>, + ) { + surface.configure(device, config); + if let Some(hdr) = hdr { + horizon_hdr::set_metadata(device, surface, hdr.paper_white, hdr.peak); + } + } + fn configure_surface(&self) { + if let Some(surface) = &self.surface { + Self::configure( + &self.device, + surface, + &self.surface_config(), + self.hdr.as_ref(), + ); + } + } + fn send_hdr_metadata(&self) { + if let (Some(surface), Some(hdr)) = (&self.surface, &self.hdr) { + horizon_hdr::set_metadata(&self.device, surface, hdr.paper_white, hdr.peak); + } + } + /// The swapchain's configuration: `config` (what every pipeline draws in), or + /// scRGB while HDR output is on. + fn surface_config(&self) -> wgpu::SurfaceConfiguration { + let mut config = self.config.clone(); + if self.hdr.is_some() { + config.format = hdr::FORMAT; + config.view_formats = vec![hdr::FORMAT]; + config.color_space = hdr::COLOR_SPACE; + config.usage = wgpu::TextureUsages::RENDER_ATTACHMENT; + } + config + } + /// HDR output (Horizon setting): scRGB at `paper_white` nits, the world's + /// highlights expanded up to `peak` nits. Off where the surface can't present it. + pub fn set_hdr(&mut self, on: bool, paper_white: f32, peak: f32) { + let on = on && self.hdr_capable && self.surface.is_some(); + if on != self.hdr.is_some() { + self.hdr = + on.then(|| hdr::Hdr::new(&self.device, self.config.format.remove_srgb_suffix())); + self.configure_surface(); + } + if let Some(hdr) = &mut self.hdr + && (hdr.paper_white, hdr.peak) != (paper_white, peak) + { + hdr.paper_white = paper_white; + hdr.peak = peak; + self.send_hdr_metadata(); + } + } pub fn set_world_post(&mut self, scale: f32, antialias: bool) { self.world_post.scale = scale.clamp(0.25, 2.0); self.world_post.antialias = antialias; @@ -2937,9 +3093,9 @@ impl Renderer { self.native = None; self.pack_atlas = None; } - /// Runs the sky and post stages of one of Horizon's own shader packs from now on (`None`: - /// no pack), with its options' values; replaces a `shaders/` pack. Returns the stages' - /// labels; on an error the pack that ran keeps running. + /// Runs the sky, material and post stages of one of Horizon's own shader packs from now + /// on (`None`: no pack), with its options' values; replaces a `shaders/` pack. Returns the + /// stages' labels; on an error the pack that ran keeps running. pub fn set_native_shader_pack( &mut self, pack: Option<(horizon_shader_api::Report, Vec<(String, f64)>)>, @@ -2948,14 +3104,14 @@ impl Renderer { self.native = None; return Ok(Vec::new()); }; - let format = self.config.format.remove_srgb_suffix(); - let (pack, labels) = native_pack::NativePack::new( - &self.device, - &self.terrain_layout, - report, - &constants, - format, - )?; + let terrain = native_material::TerrainShape { + globals: &self.terrain_layout, + flat: self.flat.as_ref().map(|f| &f.draw_layout), + sprites: self.terrain_sprites, + format: self.config.format.remove_srgb_suffix(), + }; + let (pack, labels) = + native_pack::NativePack::new(&self.device, &terrain, report, &constants)?; self.native = pack.draws().then_some(pack); if self.native.is_some() { self.pack_post = None; @@ -3197,7 +3353,12 @@ impl Renderer { } Some(wgpu::CurrentSurfaceTexture::Outdated) => { if let Some(surface) = &self.surface { - surface.configure(&self.device, &self.config); + Self::configure( + &self.device, + surface, + &self.surface_config(), + self.hdr.as_ref(), + ); } return Ok(false); } @@ -3209,9 +3370,11 @@ impl Renderer { return Err("surface acquisition failed validation".into()); } }; - let target_texture = match &surface_frame { - Some(f) => f.texture.clone(), - None => self.offscreen.clone().ok_or("no offscreen target")?, + let size = [self.config.width, self.config.height]; + let target_texture = match (&surface_frame, &mut self.hdr) { + (Some(_), Some(hdr)) => hdr.frame(&self.device, size), + (Some(f), None) => f.texture.clone(), + (None, _) => self.offscreen.clone().ok_or("no offscreen target")?, }; // One command buffer for the frame, after the section copies staged // since the last one: Metal commits every command buffer wgpu-core @@ -4179,6 +4342,21 @@ impl Renderer { pass.set_bind_group(0, &self.group, &[]); sky.draw(&mut pass, &native.frame); } + // One of Horizon's own packs with a material stage: terrain draws with its pipelines, + // which read the pack's frame at group 3. + let material = self + .native + .as_ref() + .filter(|_| !frame.title) + .and_then(|n| Some((n.material.as_ref()?, &n.frame.group))); + let solid_pipeline = material.map_or(&self.solid, |(m, _)| &m.solid); + let translucent_pipeline = material.map_or(&self.translucent, |(m, _)| &m.translucent); + let pack_flat = material.and_then(|(m, _)| m.flat.as_ref()); + let pack_frame = |pass: &mut wgpu::RenderPass<'_>| { + if let Some((_, group)) = material { + pass.set_bind_group(horizon_shader_api::stages::GROUP, group, &[]); + } + }; { let attachments = [Some(wgpu::RenderPassColorAttachment { view: world_view, @@ -4212,6 +4390,7 @@ impl Renderer { ..Default::default() }); pass.set_bind_group(0, &self.group, &[]); + pack_frame(&mut pass); if frame.title || (sky_visible && (frame.skybox || frame.end_sky)) { if !frame.title && frame.skybox && !pack_draws_sky && !native_sky_pass { match self @@ -4260,7 +4439,7 @@ impl Renderer { pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); } Some(flat) => { - pass.set_pipeline(&flat.solid); + pass.set_pipeline(pack_flat.map_or(&flat.solid, |p| &p.0)); let vertices = |p| self.arena.buffer(p); match cull { // As below: phase 1, the test, then phase 2's draws @@ -4278,7 +4457,8 @@ impl Renderer { pack_reads_world, ); pass.set_bind_group(0, &self.group, &[]); - pass.set_pipeline(&flat.solid); + pack_frame(&mut pass); + pass.set_pipeline(pack_flat.map_or(&flat.solid, |p| &p.0)); flat.draw_phase2(&mut pass, vertices); } None => flat.draw(&mut pass, &flat.calls[..flat.solid_calls], vertices), @@ -4287,7 +4467,7 @@ impl Renderer { pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); } None => { - pass.set_pipeline(&self.solid); + pass.set_pipeline(solid_pipeline); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); pass.set_vertex_buffer(1, self.instances.slice(..)); match cull { @@ -4307,7 +4487,8 @@ impl Renderer { pack_reads_world, ); pass.set_bind_group(0, &self.group, &[]); - pass.set_pipeline(&self.solid); + pack_frame(&mut pass); + pass.set_pipeline(solid_pipeline); pass.set_index_buffer( self.indices.slice(..), wgpu::IndexFormat::Uint32, @@ -4399,7 +4580,7 @@ impl Renderer { // The pack draws translucent terrain after its deferred programs. _ if pack_draws_water => {} Some(flat) => { - pass.set_pipeline(&flat.translucent); + pass.set_pipeline(pack_flat.map_or(&flat.translucent, |p| &p.1)); flat.draw(&mut pass, flat.translucent_calls(), |p| { self.arena.buffer(p) }); @@ -4407,7 +4588,7 @@ impl Renderer { pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); } None => { - pass.set_pipeline(&self.translucent); + pass.set_pipeline(translucent_pipeline); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); pass.set_vertex_buffer(1, self.instances.slice(..)); self.draw_sections( @@ -4591,6 +4772,9 @@ impl Renderer { } else if scaled.is_some() { self.world_post.finish(&mut encoder, &view_target); } + if let Some(hdr) = &self.hdr { + hdr.keep_world(&mut encoder); + } if hand_quads > 0 && !pack_draws_hand { let attachments = [Some(wgpu::RenderPassColorAttachment { view: &view_target, @@ -4745,6 +4929,9 @@ impl Renderer { self.section_copy_bytes = 0; self.section_uploads.finish(&encoder); } + if let (Some(hdr), Some(f)) = (&self.hdr, &surface_frame) { + hdr.present(&self.queue, &mut encoder, &f.texture, !frame.title); + } let commands = crate::spans::time("encode", || encoder.finish()); let first_frame = self.first_frame == FirstFrame::Submit; if first_frame { @@ -4781,7 +4968,12 @@ impl Renderer { } self.queue.present(surface_frame); if reconfigure && let Some(surface) = &self.surface { - surface.configure(&self.device, &self.config); + Self::configure( + &self.device, + surface, + &self.surface_config(), + self.hdr.as_ref(), + ); } } else { // No swapchain paces offscreen frames: keep two on the GPU at most. diff --git a/crates/horizon-client/src/gfx/arena.rs b/crates/horizon-client/src/gfx/arena.rs index 34b4d332d..8f320a408 100644 --- a/crates/horizon-client/src/gfx/arena.rs +++ b/crates/horizon-client/src/gfx/arena.rs @@ -39,6 +39,35 @@ impl FreeList { } self.0.insert(start, len); } + /// `give` for many ranges: one merge of the sorted ranges into the list, + /// where giving them one by one costs a few tree lookups each. + fn give_all(&mut self, mut ranges: Vec<(u64, u64)>) { + if ranges.len() < 64 { + for (start, len) in ranges { + self.give(start, len); + } + return; + } + ranges.sort_unstable(); + let mut free = std::mem::take(&mut self.0).into_iter().peekable(); + let mut given = ranges.into_iter().peekable(); + let mut merged: Vec<(u64, u64)> = Vec::new(); + loop { + let next = match (free.peek(), given.peek()) { + (Some(a), Some(b)) if a.0 <= b.0 => free.next(), + (_, Some(_)) => given.next(), + (Some(_), None) => free.next(), + (None, None) => break, + }; + let (start, len) = next.expect("peeked"); + match merged.last_mut() { + Some(last) if last.0 + last.1 == start => last.1 += len, + _ => merged.push((start, len)), + } + } + // Sorted: the tree is built in one pass. + self.0 = merged.into_iter().collect(); + } } /// One vertex buffer of the arena; only the newest page grows. @@ -237,6 +266,26 @@ impl Arena { .free .give(start, len); } + /// `release` for many ranges (page, start, vertices) at once. + pub fn release_all(&mut self, ranges: impl IntoIterator) { + let mut by_page: Vec> = Vec::new(); + for (page, start, vertices) in ranges { + let page = page as usize; + if by_page.len() <= page { + by_page.resize_with(page + 1, Vec::new); + } + by_page[page].push((start, Self::span(vertices).min(self.page_limit))); + } + for (page, ranges) in by_page.into_iter().enumerate() { + if !ranges.is_empty() { + self.pages[page] + .as_mut() + .expect("live arena page") + .free + .give_all(ranges); + } + } + } /// Moves a page into a larger buffer; false (the page unchanged) when /// there is no memory for it. fn grow( @@ -435,6 +484,44 @@ mod tests { assert_eq!(free, FreeList::new(4 * GRAIN)); } + #[test] + fn many_ranges_given_at_once_coalesce_as_one_by_one() { + let fill = || { + let mut free = FreeList::new(1 << 30); + let taken: Vec<(u64, u64)> = (0..500u64) + .map(|i| { + let len = GRAIN * (1 + i * 7 % 5); + (free.take(len).unwrap(), len) + }) + .collect(); + for &(start, len) in taken.iter().step_by(3) { + free.give(start, len); + } + (free, taken) + }; + // Every other range of those still taken, in a scattered order. + let (mut one_by_one, taken) = fill(); + let (mut at_once, _) = fill(); + let mut given: Vec<(u64, u64)> = (0..taken.len()) + .filter(|i| i % 3 != 0 && i % 2 == 0) + .map(|i| taken[i]) + .collect(); + given.sort_by_key(|&(start, _)| start.wrapping_mul(0x9E37_79B9_7F4A_7C15)); + assert!(given.len() >= 64); + for &(start, len) in &given { + one_by_one.give(start, len); + } + at_once.give_all(given); + assert_eq!(at_once, one_by_one); + // The rest too: everything is free again, in one range. + let rest: Vec<(u64, u64)> = (0..taken.len()) + .filter(|i| i % 3 != 0 && i % 2 != 0) + .map(|i| taken[i]) + .collect(); + at_once.give_all(rest); + assert_eq!(at_once, FreeList::new(1 << 30)); + } + #[test] fn first_fit_reuses_the_lowest_hole() { let mut free = FreeList::new(8 * GRAIN); diff --git a/crates/horizon-client/src/gfx/crumbling_tests.rs b/crates/horizon-client/src/gfx/crumbling_tests.rs new file mode 100644 index 000000000..620a57cf9 --- /dev/null +++ b/crates/horizon-client/src/gfx/crumbling_tests.rs @@ -0,0 +1,191 @@ +use wgpu::util::DeviceExt; + +/// Sample the production WGSL with the production nearest/no-mipmap atlas sampler. +#[test] +#[ignore = "requires a Vulkan/Metal/DX12 adapter"] +fn crack_samples_stay_aligned_between_stages() { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let adapter = + pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) + .unwrap(); + eprintln!("crack sampling adapter: {:?}", adapter.get_info()); + let (device, queue) = + pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).unwrap(); + #[repr(C)] + #[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] + struct Case { + uv: [f32; 2], + stage: u32, + extent: u32, + } + let mut cases = Vec::new(); + let mut expected = Vec::<[u32; 2]>::new(); + // Include exact texel boundaries, their neighbours, negative projected UVs, + // wrapping and the far sprite edge. Origins straddle the packing error's sign change. + for extent in [16, 32] { + for x in [32, 2080, 4064] { + for y in [0, 32] { + for i in -32..=32 { + for delta in [-0.0001, 0.0, 0.0001] { + let uv = [i as f32 / 16.0 + delta, 0.5 - delta]; + cases.push(Case { + uv, + stage: crate::breaking::stage_light([ + x as f32 / 4096.0, + y as f32 / 64.0, + ]), + extent, + }); + expected.push(uv.map(|v| { + (((v - v.floor()) * extent as f32).floor() as u32).min(extent - 1) + })); + } + } + } + } + } + let math = include_str!("../entity.wgsl") + .split("// CRUMBLING_UV_BEGIN") + .nth(1) + .unwrap() + .split("// CRUMBLING_UV_END") + .next() + .unwrap(); + let source = format!( + "{math}\n{}", + r#" +struct Case { uv: vec2, stage: u32, extent: u32 } +@group(0) @binding(0) var cases: array; +@group(0) @binding(1) var results: array>; +@group(0) @binding(2) var atlas: texture_2d; +@group(0) @binding(3) var atlas_sampler: sampler; +@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3) { + if id.x >= arrayLength(&cases) { return; } + let c = cases[id.x]; + let origin = vec2(f32(c.stage & 65535u), f32(c.stage >> 16u)) / 65535.0; + let dimensions = textureDimensions(atlas); + let uv = crumbling_uv(c.uv, origin, vec2(f32(c.extent)) / vec2(dimensions), dimensions); + // Keep the old addressing as a control: the fixture must reproduce its stage jitter. + let old_uv = origin + fract(c.uv) * vec2(f32(c.extent)) / vec2(dimensions); + results[id.x] = vec4( + vec2(round(textureSampleLevel(atlas, atlas_sampler, uv, 0.0).rg * 255.0)), + vec2(round(textureSampleLevel(atlas, atlas_sampler, old_uv, 0.0).rg * 255.0))); +}"# + ); + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Crack sampling regression"), + source: wgpu::ShaderSource::Wgsl(source.into()), + }); + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: None, + module: &shader, + entry_point: Some("main"), + compilation_options: Default::default(), + cache: None, + }); + // Every sprite repeats the same coordinate pattern, so moving a stage's + // atlas origin must leave every sampled local texel unchanged. + let pixels: Vec = (0..64) + .flat_map(|y| (0..4096).flat_map(move |x| [(x % 32) as u8, (y % 32) as u8, 0, 255])) + .collect(); + let atlas = device.create_texture_with_data( + &queue, + &wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { + width: 4096, + height: 64, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }, + wgpu::util::TextureDataOrder::LayerMajor, + &pixels, + ); + let view = atlas.create_view(&Default::default()); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor::default()); + let input = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: None, + contents: bytemuck::cast_slice(&cases), + usage: wgpu::BufferUsages::STORAGE, + }); + let size = (expected.len() * 16) as u64; + let output = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, + mapped_at_creation: false, + }); + let readback = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &pipeline.get_bind_group_layout(0), + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: input.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: output.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::TextureView(&view), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::Sampler(&sampler), + }, + ], + }); + let mut encoder = device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &group, &[]); + pass.dispatch_workgroups((cases.len() as u32).div_ceil(64), 1, 1); + } + encoder.copy_buffer_to_buffer(&output, 0, &readback, 0, size); + queue.submit([encoder.finish()]); + let (tx, rx) = std::sync::mpsc::channel(); + readback.map_async(wgpu::MapMode::Read, .., move |r| tx.send(r).unwrap()); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + rx.recv().unwrap().unwrap(); + let mapped = readback.get_mapped_range(..).unwrap(); + let actual: &[[u32; 4]] = bytemuck::cast_slice(&mapped); + for (i, (actual, expected)) in actual.iter().zip(&expected).enumerate() { + assert_eq!( + &actual[..2], + expected, + "case {i}, uv={:?}, stage={}, extent={}", + cases[i].uv, + cases[i].stage, + cases[i].extent + ); + } + let old_mismatches = actual + .iter() + .zip(&expected) + .filter(|(a, e)| &a[2..] != e.as_slice()) + .count(); + assert!( + old_mismatches > 0, + "fixture must detect the original sampling bug" + ); + eprintln!( + "{} crack texture samples matched; old addressing mismatched {old_mismatches}", + cases.len() + ); +} diff --git a/crates/horizon-client/src/gfx/hdr.rs b/crates/horizon-client/src/gfx/hdr.rs new file mode 100644 index 000000000..11deed546 --- /dev/null +++ b/crates/horizon-client/src/gfx/hdr.rs @@ -0,0 +1,222 @@ +//! HDR output (Horizon setting, off by default): the frame renders exactly as +//! without it, into an 8-bit target in vanilla's gamma space, and one pass +//! (`hdr.wgsl`) writes it to an scRGB swapchain at the player's paper white, +//! expanding the world's highlights towards their peak brightness. The world +//! is copied aside before the hand and HUD so only it is expanded. + +/// The swapchain format and colour space HDR output presents in. +pub const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; +pub const COLOR_SPACE: wgpu::SurfaceColorSpace = wgpu::SurfaceColorSpace::ExtendedSrgbLinear; + +/// Whether `caps` can present scRGB. +pub fn supported(caps: &wgpu::SurfaceCapabilities) -> bool { + caps.color_spaces(FORMAT) + .contains(wgpu::SurfaceColorSpaces::EXTENDED_SRGB_LINEAR) +} + +struct Targets { + size: [u32; 2], + frame: wgpu::Texture, + world: wgpu::Texture, + group: wgpu::BindGroup, +} + +pub struct Hdr { + layout: wgpu::BindGroupLayout, + pipeline: wgpu::RenderPipeline, + params: wgpu::Buffer, + /// The frame's format: what every other pipeline draws in. + format: wgpu::TextureFormat, + targets: Option, + /// `HORIZON_HDR_DEBUG=1`: paint expanded pixels magenta. + debug: bool, + /// Paper white and peak brightness, in nits. + pub paper_white: f32, + pub peak: f32, +} + +impl Hdr { + pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self { + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Horizon HDR"), + source: wgpu::ShaderSource::Wgsl(include_str!("../hdr.wgsl").into()), + }); + let texture = |binding| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }; + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Horizon HDR bindings"), + entries: &[ + texture(0), + texture(1), + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + ], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Horizon HDR"), + bind_group_layouts: &[Some(&layout)], + ..Default::default() + }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Horizon HDR"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_hdr"), + compilation_options: Default::default(), + buffers: &[], + }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_hdr"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: FORMAT, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }); + let params = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Horizon HDR parameters"), + size: 16, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + Self { + layout, + pipeline, + params, + format, + targets: None, + debug: std::env::var_os("HORIZON_HDR_DEBUG").is_some_and(|v| v == "1"), + paper_white: 200.0, + peak: 1000.0, + } + } + + /// The 8-bit frame every pass draws into this frame, sized like the window. + pub fn frame(&mut self, device: &wgpu::Device, size: [u32; 2]) -> wgpu::Texture { + if self.targets.as_ref().is_none_or(|t| t.size != size) { + let texture = |label, usage| { + device.create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: wgpu::Extent3d { + width: size[0].max(1), + height: size[1].max(1), + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: self.format, + usage: usage | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }) + }; + let frame = texture( + "Horizon HDR frame", + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + ); + let world = texture("Horizon HDR world", wgpu::TextureUsages::COPY_DST); + let view = |t: &wgpu::Texture| t.create_view(&Default::default()); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Horizon HDR bindings"), + layout: &self.layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(&view(&frame)), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&view(&world)), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: self.params.as_entire_binding(), + }, + ], + }); + self.targets = Some(Targets { + size, + frame, + world, + group, + }); + } + self.targets.as_ref().unwrap().frame.clone() + } + + /// Keeps the world as drawn so far, before the hand and HUD cover it. + pub fn keep_world(&self, encoder: &mut wgpu::CommandEncoder) { + let Some(t) = &self.targets else { + return; + }; + encoder.copy_texture_to_texture( + t.frame.as_image_copy(), + t.world.as_image_copy(), + t.frame.size(), + ); + } + + /// Writes the finished frame to the swapchain image `target`. + pub fn present( + &self, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + target: &wgpu::Texture, + world: bool, + ) { + let Some(t) = &self.targets else { + return; + }; + let paper = self.paper_white.max(1.0); + let params = [ + paper / 80.0, + (self.peak / paper).max(1.0), + f32::from(u8::from(world)), + f32::from(u8::from(self.debug)), + ]; + queue.write_buffer(&self.params, 0, bytemuck::cast_slice(¶ms)); + let view = target.create_view(&Default::default()); + let attachments = [Some(wgpu::RenderPassColorAttachment { + view: &view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), + store: wgpu::StoreOp::Store, + }, + })]; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Horizon HDR"), + color_attachments: &attachments, + ..Default::default() + }); + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, &t.group, &[]); + pass.draw(0..3, 0..1); + } +} diff --git a/crates/horizon-client/src/gfx/native_material.rs b/crates/horizon-client/src/gfx/native_material.rs new file mode 100644 index 000000000..e7f8f7bf2 --- /dev/null +++ b/crates/horizon-client/src/gfx/native_material.rs @@ -0,0 +1,328 @@ +//! The material stage of Horizon's own shader packs (docs/shaders.md): the pack's `material` +//! function gives the lit colour of each point of a block's surface, before the alpha test and +//! fog. Terrain still draws with Horizon's meshes, culling and draw lists; only its pipelines +//! change. Their shader is the pack's stage (`CheckedStage::source`), then a copy of +//! terrain.wgsl's terrain section whose names all take a `horizon_terrain_` prefix +//! (`wgsl_prefix.rs`), then entries that hand the pack what vanilla's `fs_solid` and +//! `fs_translucent` combine: the texture, the vertex tint, the light levels and the lightmap's +//! colour. They read the terrain's group 0, the flat draws' group 1 where those run, and the +//! pack's frame at group 3. + +use horizon_shader_api::{check::CheckedStage, stages::GROUP}; + +use super::native_post::{NativeFrame, present_constants}; +use super::wgsl_prefix::{TERRAIN, prefixed, section}; + +const PREFIX: &str = "horizon_terrain_"; + +/// The entries around the pack's `material`: vanilla's vertex work without the lightmap +/// product, then the material, the alpha test and fog as `fs_solid` and `fs_translucent` do. +const ENTRIES: &str = " +struct HorizonMaterialOut { + @builtin(position) clip: vec4, + @location(0) uv: vec2, + @location(1) @interpolate(flat) layer: u32, + @location(2) tint: vec4, + @location(3) light: vec2, + @location(4) lightmap: vec3, + @location(5) position: vec3, + @location(6) spherical: f32, + @location(7) cylindrical: f32, +} +fn horizon_material_vertex(position: vec3, uv: vec2, layer: u32, color: vec4, + light: vec2, origin: vec3) -> HorizonMaterialOut { + let pos = position + origin; + var out: HorizonMaterialOut; + out.clip = horizon_terrain_globals.view_proj * vec4(pos, 1.0); + out.uv = uv; + out.layer = layer; + out.tint = vec4(color.rgb, 1.0); + let block = max(f32(light.y), horizon_terrain_dynamic_block_light(pos)); + let sky = f32(light.x); + // 16 per level, 15 levels. + out.light = min(vec2(block, sky) / 240.0, vec2(1.0)); + out.lightmap = horizon_terrain_sample_lightmap(sky / 16.0, block / 16.0).rgb; + out.position = pos; + out.spherical = length(pos); + out.cylindrical = max(length(pos.xz), abs(pos.y)); + return out; +} +@vertex fn horizon_material_vs( + @location(0) position: vec3, @location(1) uv: vec2, + @location(2) layer: u32, @location(3) color: vec4, @location(4) light: vec2, + @location(5) origin: vec4) -> HorizonMaterialOut { + return horizon_material_vertex(position, horizon_terrain_terrain_uv(uv, origin.w), layer, + color, light, origin.xyz); +} +@vertex fn horizon_material_vs_flat( + @builtin(vertex_index) vertex: u32, + @location(0) position: vec3, @location(1) uv: vec2, + @location(2) layer: u32, @location(3) color: vec4, @location(4) light: vec2 +) -> HorizonMaterialOut { + let origin = horizon_terrain_slot_origins[horizon_terrain_block_slots[vertex >> 8u]]; + return horizon_material_vertex(position, horizon_terrain_terrain_uv(uv, origin.w), layer, + color, light, origin.xyz); +} +fn horizon_material_color(in: HorizonMaterialOut, translucent: bool) -> vec4 { + let albedo = horizon_terrain_sprite(in.uv, in.layer & 0x7fffu); + return material(MaterialInput(albedo, in.tint, in.light, in.lightmap, in.position, in.uv, + translucent)).color; +} +@fragment fn horizon_material_fs_solid(in: HorizonMaterialOut) -> @location(0) vec4 { + let color = horizon_material_color(in, false); + // Bit 15 of the layer marks opaque leaves (forceOpaque): no alpha cutout. + if color.a < 0.5 && (in.layer & 0x8000u) == 0u { discard; } + return horizon_terrain_apply_fog(vec4(color.rgb, 1.0), in.spherical, in.cylindrical); +} +@fragment fn horizon_material_fs_translucent(in: HorizonMaterialOut) -> @location(0) vec4 { + let color = horizon_material_color(in, true); + if color.a < 0.01 { discard; } + return horizon_terrain_apply_fog(color, in.spherical, in.cylindrical); +} +"; + +/// What terrain pipelines are built against: the renderer's layouts and constants. +pub struct TerrainShape<'a> { + /// The terrain's group 0. + pub globals: &'a wgpu::BindGroupLayout, + /// The flat draws' group 1, where they run (`flat.rs`). + pub flat: Option<&'a wgpu::BindGroupLayout>, + /// terrain.wgsl's `SPRITE_ARRAYS` and `SPRITE_SPLIT`. + pub sprites: [f64; 2], + /// The world target's colour format. + pub format: wgpu::TextureFormat, +} + +/// The pack's terrain pipelines: solid (with the cutout test) and translucent, for the +/// renderer's instanced draws and, where they run, its flat ones. +pub struct NativeMaterial { + pub solid: wgpu::RenderPipeline, + pub translucent: wgpu::RenderPipeline, + pub flat: Option<(wgpu::RenderPipeline, wgpu::RenderPipeline)>, +} + +/// terrain.wgsl's terrain section (its globals, bindings, sampling, lighting and fog), with +/// every name it declares prefixed. +fn vanilla_terrain() -> String { + prefixed( + section(TERRAIN, "struct Globals {", "// Sky (SkyRenderer)"), + PREFIX, + ) +} + +/// The terrain shader for the pack's material stage `source`. +fn shader_source(source: &str) -> String { + format!( + "{source}\n// Horizon's terrain (terrain.wgsl)\n{}{ENTRIES}", + vanilla_terrain() + ) +} + +/// The material's naga module, its errors in the stage's file. +fn module(stage: &CheckedStage) -> Result { + let text = shader_source(&stage.source); + naga::front::wgsl::parse_str(&text) + .map_err(|e| format!("{}: {}", stage.file, e.emit_to_string(&text))) +} + +impl NativeMaterial { + /// The pipelines of the pack's material `stage` with the option values `constants`. + pub fn new( + device: &wgpu::Device, + shape: &TerrainShape<'_>, + frame: &NativeFrame, + stage: &CheckedStage, + constants: &[(String, f64)], + ) -> Result { + let module = module(stage)?; + let mut constants = present_constants(&module, constants); + let sprite_names = [ + "horizon_terrain_SPRITE_ARRAYS", + "horizon_terrain_SPRITE_SPLIT", + ]; + constants.extend(sprite_names.into_iter().zip(shape.sprites)); + let scope = device.push_error_scope(wgpu::ErrorFilter::Validation); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some(&stage.label), + source: wgpu::ShaderSource::Naga(std::borrow::Cow::Owned(module)), + }); + let layout = |flat: Option<&wgpu::BindGroupLayout>| { + let mut groups: [Option<&wgpu::BindGroupLayout>; GROUP as usize + 1] = + Default::default(); + groups[0] = Some(shape.globals); + groups[1] = flat; + groups[GROUP as usize] = Some(&frame.layout); + device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Native shader pack terrain"), + bind_group_layouts: &groups, + ..Default::default() + }) + }; + let instance_attributes = wgpu::vertex_attr_array![5=>Float32x4]; + let vertices = wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &super::TERRAIN_ATTRIBUTES, + }; + let instances = wgpu::VertexBufferLayout { + array_stride: 16, + step_mode: wgpu::VertexStepMode::Instance, + attributes: &instance_attributes, + }; + // As the renderer's terrain pipelines (gfx.rs): back faces culled, reversed depth. + let pipeline = |layout: &wgpu::PipelineLayout, + vertex: &str, + buffers: &[Option>], + fragment: &str, + blend: Option| { + let options = wgpu::PipelineCompilationOptions { + constants: &constants, + ..Default::default() + }; + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(&stage.label), + layout: Some(layout), + vertex: wgpu::VertexState { + module: &module, + entry_point: Some(vertex), + compilation_options: options.clone(), + buffers, + }, + primitive: wgpu::PrimitiveState { + cull_mode: Some(wgpu::Face::Back), + ..Default::default() + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::GreaterEqual), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some(fragment), + compilation_options: options, + targets: &[Some(wgpu::ColorTargetState { + format: shape.format, + blend, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }) + }; + let blend = Some(wgpu::BlendState::ALPHA_BLENDING); + let instanced = layout(None); + let buffers = [Some(vertices.clone()), Some(instances)]; + let solid = pipeline( + &instanced, + "horizon_material_vs", + &buffers, + "horizon_material_fs_solid", + None, + ); + let translucent = pipeline( + &instanced, + "horizon_material_vs", + &buffers, + "horizon_material_fs_translucent", + blend, + ); + let flat = shape.flat.map(|group| { + let layout = layout(Some(group)); + let buffers = [Some(vertices.clone())]; + let vs = "horizon_material_vs_flat"; + ( + pipeline(&layout, vs, &buffers, "horizon_material_fs_solid", None), + pipeline( + &layout, + vs, + &buffers, + "horizon_material_fs_translucent", + blend, + ), + ) + }); + if let Some(e) = pollster::block_on(scope.pop()) { + return Err(format!("{}: {e}", stage.file)); + } + Ok(Self { + solid, + translucent, + flat, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_shader_api::{MANIFEST, Pack, StageKind, check}; + + fn stage(material: &str) -> CheckedStage { + let manifest = "schema = 1\nid = \"t\"\nname = \"T\"\nversion = \"1\"\napi = \"0.1\"\n\ + [material]\nfile = \"material.wgsl\"\n\ + [[options]]\nid = \"gain\"\nname = \"Gain\"\ntype = \"float\"\n\ + default = 1.0\nmin = 0.0\nmax = 2.0\n"; + let files = [(MANIFEST, manifest), ("material.wgsl", material)] + .map(|(n, t)| (n.to_owned(), t.as_bytes().to_vec())) + .into(); + let mut report = check(&Pack::from_files(files).unwrap()).unwrap(); + assert_eq!(report.stages[0].kind, StageKind::Material); + report.stages.remove(0) + } + + #[test] + fn the_terrain_takes_a_prefix_and_validates_with_a_pack() { + let terrain = vanilla_terrain(); + for name in [ + "Globals", + "globals", + "sprites_7", + "sprite", + "SPRITE_SPLIT", + "block_slots", + "sample_lightmap", + "apply_fog", + ] { + assert!(terrain.contains(&format!("{PREFIX}{name}")), "{name}"); + } + assert!(!terrain.contains("fs_sky"), "the sky stays out"); + // A pack may use any name Horizon's terrain uses unprefixed. + let own = "override gain: f32;\nconst PI: f32 = 3.0;\n\ + fn sprite(c: vec4) -> vec4 { return c * PI; }\n\ + fn apply_fog(c: vec4) -> vec4 { return c * gain; }\n\ + fn material(input: MaterialInput) -> Surface {\n \ + let lit = input.albedo * input.tint * vec4(input.lightmap, 1.0);\n \ + return Surface(apply_fog(sprite(lit)));\n}\n"; + let stage = stage(own); + let module = module(&stage).unwrap(); + let info = naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::all(), + ) + .validate(&module) + .unwrap_or_else(|e| panic!("{}", e.emit_to_string(&shader_source(&stage.source)))); + let entries: Vec<&str> = module + .entry_points + .iter() + .map(|e| e.name.as_str()) + .collect(); + for entry in [ + "horizon_material_vs", + "horizon_material_vs_flat", + "horizon_material_fs_solid", + "horizon_material_fs_translucent", + ] { + assert!(entries.contains(&entry), "{entry}"); + } + drop(info); + assert_eq!( + present_constants(&module, &[("gain".into(), 1.5), ("other".into(), 1.0)]), + [("gain", 1.5)] + ); + } +} diff --git a/crates/horizon-client/src/gfx/native_pack.rs b/crates/horizon-client/src/gfx/native_pack.rs index 3f9206e11..4fb5cdc59 100644 --- a/crates/horizon-client/src/gfx/native_pack.rs +++ b/crates/horizon-client/src/gfx/native_pack.rs @@ -1,8 +1,9 @@ //! One of Horizon's own shader packs while it runs (docs/shaders.md): the frame its stages -//! read, its sky and post stages, and the timer of their passes. +//! read, its sky, material and post stages, and the timer of their passes. use horizon_shader_api::{Report, StageKind}; +use super::native_material::{NativeMaterial, TerrainShape}; use super::native_post::{NativeFrame, NativePost}; use super::native_sky::NativeSky; use super::pack_timing::PassTiming; @@ -10,6 +11,7 @@ use super::pack_timing::PassTiming; pub struct NativePack { pub frame: NativeFrame, pub sky: Option, + pub material: Option, pub post: Option, /// GPU time of each pass, while the renderer asks for it (`pack_timing.rs`). pub timing: Option, @@ -17,16 +19,16 @@ pub struct NativePack { impl NativePack { /// The pack of the checked stages `report` with the option values `constants`, drawing - /// onto targets of `format`; `globals` is the terrain's group 0, which the sky reads. + /// onto the world's targets as `terrain` describes; the sky reads the terrain's group 0. /// Also returns its stages' labels, in the order they draw. Errors name the stage wgpu /// refused. pub fn new( device: &wgpu::Device, - globals: &wgpu::BindGroupLayout, + terrain: &TerrainShape<'_>, report: Report, constants: &[(String, f64)], - format: wgpu::TextureFormat, ) -> Result<(Self, Vec), String> { + let (globals, format) = (terrain.globals, terrain.format); let frame = NativeFrame::new(device); let (post, others): (Vec<_>, Vec<_>) = report .stages @@ -37,16 +39,28 @@ impl NativePack { .find(|s| s.kind == StageKind::Sky) .map(|stage| NativeSky::new(device, globals, &frame, stage, constants, format)) .transpose()?; + let material = others + .iter() + .find(|s| s.kind == StageKind::Material) + .map(|stage| NativeMaterial::new(device, terrain, &frame, stage, constants)) + .transpose()?; let post = (!post.is_empty()) .then(|| NativePost::new(device, post, constants, format, &frame)) .transpose()?; let mut labels: Vec = sky.iter().map(|s| s.label.clone()).collect(); + labels.extend( + others + .iter() + .filter(|s| material.is_some() && s.kind == StageKind::Material) + .map(|s| s.label.clone()), + ); if let Some(post) = &post { labels.extend(post.labels().into_iter().map(str::to_owned)); } let pack = Self { frame, sky, + material, post, timing: None, }; @@ -55,6 +69,6 @@ impl NativePack { /// Whether the pack draws anything the game runs today. pub fn draws(&self) -> bool { - self.sky.is_some() || self.post.is_some() + self.sky.is_some() || self.material.is_some() || self.post.is_some() } } diff --git a/crates/horizon-client/src/gfx/occlusion.rs b/crates/horizon-client/src/gfx/occlusion.rs index e17ba87d1..22e2f3c81 100644 --- a/crates/horizon-client/src/gfx/occlusion.rs +++ b/crates/horizon-client/src/gfx/occlusion.rs @@ -522,16 +522,27 @@ impl Occlusion { } 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); - } + self.changed(key, vis); } } - pub fn remove(&mut self, key: SectionKey) { - self.set(key, ALL_VISIBLE); + fn changed(&mut self, key: SectionKey, vis: u64) { + self.edits.push(Edit::Set(key, vis)); + self.dirty = true; + self.changed.push(key); + if self.running.is_some() { + self.changed_late.push(key); + } + } + /// Every section of the column `x`, `z` goes (sees through every face). + pub fn remove_column(&mut self, x: i32, z: i32) { + let Some(column) = self.columns.map.remove(&(x, z)) else { + return; + }; + for (y, &vis) in column.iter().enumerate() { + if vis != ALL_VISIBLE { + self.changed((x, y as i32, z), ALL_VISIBLE); + } + } } pub fn clear(&mut self) { self.columns.map.clear(); diff --git a/crates/horizon-client/src/gfx/pack_atlas.rs b/crates/horizon-client/src/gfx/pack_atlas.rs index 42a2abee1..c7a67a50b 100644 --- a/crates/horizon-client/src/gfx/pack_atlas.rs +++ b/crates/horizon-client/src/gfx/pack_atlas.rs @@ -169,6 +169,7 @@ impl PackAtlas { ]; let columns = self.columns; // UVs past a sprite (models up to 2, distant tiles) cannot repeat in an atlas: clamped. + // The colour's alpha holds HDR's emission level (`mesher::EMISSION_BITS`): packs get 1. let body = format!( " vec4 hz_origin = {origin};\n \ uint hz_layer = hz_v_layer & 32767u;\n \ @@ -178,7 +179,7 @@ impl PackAtlas { hz_MultiTexCoord0 = vec4((hz_cell + clamp(vec2(hz_v_uv) * hz_origin.w, 0.0, 1.0)) * hz_scale, 0.0, 1.0);\n \ hz_MultiTexCoord1 = vec4(float(hz_v_light.y), float(hz_v_light.x), 0.0, 1.0);\n \ hz_MultiTexCoord2 = hz_MultiTexCoord1;\n \ - hz_Color = hz_v_color;\n \ + hz_Color = vec4(hz_v_color.rgb, 1.0);\n \ hz_Normal = vec3(0.0, 1.0, 0.0);\n \ hz_tangent = vec4(1.0, 0.0, 0.0, 1.0);\n", scale[0], scale[1], diff --git a/crates/horizon-client/src/gfx/pack_uniforms.rs b/crates/horizon-client/src/gfx/pack_uniforms.rs index c4df4377b..8f5f1a2de 100644 --- a/crates/horizon-client/src/gfx/pack_uniforms.rs +++ b/crates/horizon-client/src/gfx/pack_uniforms.rs @@ -399,7 +399,8 @@ impl FrameUniforms { _ => Value::i(&[0]), } }; - self.values = NAMES.iter().map(|n| value(n)).collect(); + self.values.clear(); + self.values.extend(NAMES.iter().map(|n| value(n))); self.frame = (self.frame + 1) % 720_720; } diff --git a/crates/horizon-client/src/graphics.rs b/crates/horizon-client/src/graphics.rs index b51a586ab..4f6f04bc0 100644 --- a/crates/horizon-client/src/graphics.rs +++ b/crates/horizon-client/src/graphics.rs @@ -255,6 +255,12 @@ pub struct Graphics { pub resolution_scale: u32, /// FXAA over the world. pub fxaa: bool, + /// HDR output (scRGB), where the display path offers it. + pub hdr: bool, + /// HDR paper white (where SDR white sits), in nits. + pub hdr_paper_white: u32, + /// HDR peak brightness the world's highlights reach, in nits. + pub hdr_peak: u32, /// Battery mode: at most 60 frames per second in a world and 30 in menus /// or behind other windows, and half the worker threads. Off by default; /// it changes when frames are drawn, never what they show or the ticks. @@ -286,6 +292,9 @@ impl Default for Graphics { overlay: Overlay::Off, resolution_scale: 100, fxaa: false, + hdr: false, + hdr_paper_white: 200, + hdr_peak: 1000, battery: false, api: GraphicsApi::Auto, shader_pack: String::new(), @@ -337,6 +346,9 @@ impl Graphics { "workers" => g.workers = number(g.workers).min(64), "resolutionScale" => g.resolution_scale = number(g.resolution_scale).clamp(50, 200), "fxaa" => g.fxaa = flag(g.fxaa), + "hdr" => g.hdr = flag(g.hdr), + "hdrPaperWhite" => g.hdr_paper_white = number(g.hdr_paper_white).clamp(80, 480), + "hdrPeak" => g.hdr_peak = number(g.hdr_peak).clamp(200, 2000), "batteryMode" => g.battery = flag(g.battery), "graphicsApi" => g.api = GraphicsApi::from_name(value).unwrap_or_default(), "pickedShaderPack" => g.shader_pack = value.to_owned(), @@ -354,7 +366,7 @@ impl Graphics { } pub fn serialize(&self) -> String { format!( - "preset:{}\nlodDistance:{}\nfarDetail:{}\ncaveCulling:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nbatteryMode:{}\ngraphicsApi:{}\npickedShaderPack:{}\n", + "preset:{}\nlodDistance:{}\nfarDetail:{}\ncaveCulling:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nhdr:{}\nhdrPaperWhite:{}\nhdrPeak:{}\nbatteryMode:{}\ngraphicsApi:{}\npickedShaderPack:{}\n", self.preset.name(), self.lod_distance, self.far_detail.name(), @@ -379,6 +391,9 @@ impl Graphics { }, self.resolution_scale, bool_text(self.fxaa), + bool_text(self.hdr), + self.hdr_paper_white, + self.hdr_peak, bool_text(self.battery), self.api.name(), self.shader_pack, @@ -444,7 +459,7 @@ pub fn apply_preset(preset: Preset, s: &mut crate::settings::Settings) { let g = &mut s.horizon; g.preset = preset; g.cave_culling = true; - g.animated_textures = preset != Preset::Performance; + g.animated_textures = true; g.chunk_updates = 0; g.upload_budget_kib = 0; g.sky = true; @@ -476,6 +491,9 @@ mod tests { overlay: Overlay::Graph, resolution_scale: 75, fxaa: true, + hdr: true, + hdr_paper_white: 240, + hdr_peak: 1400, battery: true, api: GraphicsApi::Dx12, shader_pack: "Golden Hour".into(), diff --git a/crates/horizon-client/src/graphics_style.rs b/crates/horizon-client/src/graphics_style.rs index e02a0e1d9..62979903b 100644 --- a/crates/horizon-client/src/graphics_style.rs +++ b/crates/horizon-client/src/graphics_style.rs @@ -118,8 +118,9 @@ impl Style { (x, y, w): (f32, f32, f32), label: &Text, hover: bool, + active: bool, ) { - ui::button(batch, atlas, x, y, w, 20.0, label, true, hover); + ui::button(batch, atlas, x, y, w, 20.0, label, active, hover); } pub fn slider( &self, diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index ba99f89a8..d55e44d99 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -37,6 +37,9 @@ pub enum H { Overlay, ResolutionScale, Antialiasing, + Hdr, + HdrPaperWhite, + HdrPeak, BatteryMode, GraphicsApi, } @@ -221,6 +224,21 @@ pub fn rows(level: Level) -> Vec { Medium, "FXAA smooths jagged edges of the world; slightly softer image.", ), + h( + H::Hdr, + None, + "HDR output on an HDR display: lava, fire and sunlight shine brighter.", + ), + h( + H::HdrPaperWhite, + None, + "HDR: how bright white paper and menus look. Match your desktop.", + ), + h( + H::HdrPeak, + None, + "HDR: how bright the brightest highlights get. Your display's peak.", + ), h( H::PresentMode, None, @@ -324,6 +342,8 @@ impl H { } H::Workers => Some(g.workers as f32 / max_workers() as f32), H::ResolutionScale => Some((g.resolution_scale as f32 - 50.0) / 150.0), + H::HdrPaperWhite => Some((g.hdr_paper_white as f32 - 80.0) / 400.0), + H::HdrPeak => Some((g.hdr_peak as f32 - 200.0) / 1800.0), _ => None, } } @@ -365,6 +385,9 @@ impl H { }, H::ResolutionScale => labelled("Resolution Scale", format!("{}%", g.resolution_scale)), H::Antialiasing => labelled("Anti-aliasing", if g.fxaa { "FXAA" } else { "Off" }), + H::Hdr => labelled("HDR", on_off(g.hdr)), + H::HdrPaperWhite => labelled("Paper White", format!("{} nits", g.hdr_paper_white)), + H::HdrPeak => labelled("Peak Brightness", format!("{} nits", g.hdr_peak)), H::BatteryMode => labelled("Battery Mode", on_off(g.battery)), H::GraphicsApi => labelled("Graphics API", g.api.label()), H::Overlay => labelled( @@ -387,6 +410,8 @@ impl H { } H::Workers => g.workers = (v * max_workers() as f32).round() as u32, H::ResolutionScale => g.resolution_scale = (50.0 + (v * 30.0).round() * 5.0) as u32, + H::HdrPaperWhite => g.hdr_paper_white = (80.0 + (v * 40.0).round() * 10.0) as u32, + H::HdrPeak => g.hdr_peak = (200.0 + (v * 36.0).round() * 50.0) as u32, _ => {} } } @@ -418,6 +443,7 @@ impl H { H::AnimatedTextures => g.animated_textures = !g.animated_textures, H::PresentMode => g.present_mode = step(&PresentMode::ALL, g.present_mode, back), H::Antialiasing => g.fxaa = !g.fxaa, + H::Hdr => g.hdr = !g.hdr, H::BatteryMode => g.battery = !g.battery, H::GraphicsApi => g.api = step(&GraphicsApi::ALL, g.api, back), H::Pacing => { @@ -442,6 +468,10 @@ fn max_workers() -> u32 { } impl Item { + /// False for a setting whose system is not in Horizon yet (`Opt::available`). + fn available(self) -> bool { + !matches!(self, Item::Vanilla(o) if !o.available()) + } /// On/off settings and their value. pub fn switch(self, s: &Settings) -> Option { let g = &s.horizon; @@ -453,6 +483,7 @@ impl Item { Item::Horizon(H::Weather) => g.weather, Item::Horizon(H::AnimatedTextures) => g.animated_textures, Item::Horizon(H::Antialiasing) => g.fxaa, + Item::Horizon(H::Hdr) => g.hdr, Item::Horizon(H::BatteryMode) => g.battery, Item::Vanilla(Opt::ViewBobbing) => s.view_bobbing, Item::Vanilla(Opt::Vsync) => s.vsync, @@ -483,6 +514,9 @@ impl Item { } } pub fn set_slider(self, s: &mut Settings, v: f32) { + if !self.available() { + return; + } match self { Item::Vanilla(o) => o.set_slider(s, v), Item::Horizon(h) => h.set_slider(s, v), @@ -490,6 +524,9 @@ impl Item { self.touched(s); } pub fn cycle(self, s: &mut Settings, back: bool, framebuffer: [i32; 2]) { + if !self.available() { + return; + } match self { Item::Vanilla(o) => o.cycle(s, back, framebuffer), Item::Horizon(h) => h.cycle(s, back), @@ -662,6 +699,7 @@ impl GraphicsUi { }) .collect(); let mut index = 0; + let mut tooltip = None; for wd in &widgets { let hover = ui::hovered(cursor, wd.x, wd.y, wd.w, 20.0) && (!wd.list || (cursor.1 >= top && cursor.1 < bottom)); @@ -673,6 +711,13 @@ impl GraphicsUi { continue; } let label = item.label(s); + let live = item.available(); + if hover && !live { + tooltip = Some(atlas.font.split( + &Text::literal("This feature is not yet available in Horizon."), + 170.0, + )); + } match item.slider(s) { Some(value) => STYLE.slider( batch, @@ -682,7 +727,14 @@ impl GraphicsUi { value, hover || self.dragging == Some(item), ), - None => STYLE.button(batch, atlas, (wd.x, wd.y, wd.w), &label, hover), + None => STYLE.button( + batch, + atlas, + (wd.x, wd.y, wd.w), + &label, + hover && live, + live, + ), } STYLE.description( batch, @@ -705,6 +757,7 @@ impl GraphicsUi { (wd.x, wd.y, wd.w), &Text::literal(label), hover, + true, ); } } @@ -724,6 +777,9 @@ impl GraphicsUi { Level::Advanced => "Graphics: Advanced", }; STYLE.title(batch, atlas, &Text::literal(title)); + if let Some(lines) = tooltip { + ui::tooltip(batch, atlas, &lines, cursor); + } } /// A press (or a drag with `drag`) at `(x, y)`. pub fn click( @@ -761,6 +817,8 @@ impl GraphicsUi { } return match wd.target { Target::Button(action) => vec![Action::ButtonClick, action], + // A disabled control does nothing: no sound, no preset change. + Target::Item(item) if !item.available() => Vec::new(), Target::Item(item) => { if item.slider(s).is_some() { self.dragging = Some(item); diff --git a/crates/horizon-client/src/hdr.wgsl b/crates/horizon-client/src/hdr.wgsl new file mode 100644 index 000000000..bf6c27cca --- /dev/null +++ b/crates/horizon-client/src/hdr.wgsl @@ -0,0 +1,69 @@ +// Horizon's HDR output pass: the frame, drawn as without HDR in vanilla's gamma +// space, decoded to linear light at the paper white and written to the scRGB +// swapchain (1.0 = 80 nits). Bright pixels of light sources that still show the +// world as it was before the hand and HUD are expanded towards the peak. +@group(0) @binding(0) var frame: texture_2d; +@group(0) @binding(1) var world: texture_2d; + +struct Params { + // Paper white in scRGB units (nits / 80). + paper: f32, + // Peak brightness relative to paper white; 1 expands nothing. + peak: f32, + // 1 when this frame drew a world. + world: f32, + // 1 paints expanded pixels magenta (HORIZON_HDR_DEBUG=1). + debug: f32, +}; +@group(0) @binding(2) var params: Params; + +// Light sources are lifted evenly rather than by a highlight curve: vanilla's +// textures were drawn for SDR, so a curve on their brightest pixels blows out +// near-white spots (glowstone) and leaves the rest (lava, a jack o'lantern's +// face) nearly as it was. Pixels brighter than LIFT_FULL get STRENGTH of the +// headroom, dimmer ones less down to none at LIFT_START (lava's crust, a +// lantern's metal), and no channel goes past the peak. Brightness is the mean +// of luminance and the brightest channel, so saturated light counts as bright. +const LIFT_START: f32 = 0.18; +const LIFT_FULL: f32 = 0.42; +const STRENGTH: f32 = 0.7; + +// Whether `c` still shows the world pixel `w`: the same, or darkened evenly +// across its channels, as the vignette and other screen-wide tints darken it. +// The hand, HUD and text replace pixels instead, so they never pass. +fn shows_world(c: vec3, w: vec3) -> bool { + if all(c == w) { + return true; + } + let k = c / max(w, vec3(1.0 / 255.0)); + let mean = (k.r + k.g + k.b) / 3.0; + return mean <= 1.01 && mean > 0.5 && all(abs(k - vec3(mean)) < vec3(0.03)); +} + +@vertex fn vs_hdr(@builtin(vertex_index) i: u32) -> @builtin(position) vec4 { + let p = vec2(f32((i << 1u) & 2u), f32(i & 2u)); + return vec4(p * 2.0 - 1.0, 0.0, 1.0); +} + +@fragment fn fs_hdr(@builtin(position) pos: vec4) -> @location(0) vec4 { + let at = vec2(pos.xy); + let c = textureLoad(frame, at, 0).rgb; + // Gamma 2.2, as SDR displays and the compositors' SDR paths decode it. + var light = pow(max(c, vec3(0.0)), vec3(2.2)); + let w = textureLoad(world, at, 0); + // The world's alpha is 0 on light-emitting blocks, the sun and the moon + // (terrain.wgsl, the celestial pipeline): only those shine. + if params.world > 0.5 && params.peak > 1.0 && w.a < 0.75 && shows_world(c, w.rgb) { + let y = 0.5 * (dot(light, vec3(0.2126, 0.7152, 0.0722)) + max(light.r, max(light.g, light.b))); + let lift = smoothstep(LIFT_START, LIFT_FULL, y); + if lift > 0.0 { + let top = max(light.r, max(light.g, light.b)); + let gain = min(1.0 + (params.peak - 1.0) * STRENGTH * lift, params.peak / max(top, 1e-4)); + light *= max(gain, 1.0); + if params.debug > 0.5 { + light = mix(light, vec3(gain, 0.0, gain), 0.6); + } + } + } + return vec4(light * params.paper, 1.0); +} diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index 25c719bfb..46821df27 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -111,6 +111,12 @@ pub enum HealthEvent { amount: f32, }, Phase(&'static str), + /// `Player.hurtArmor`: a hit that doesn't bypass armor wears the worn + /// pieces (`LivingEntity.getDamageAfterArmorAbsorb`); the game applies it. + ArmorHurt { + source: DamageTypeId, + amount: f32, + }, /// `ServerLevel.broadcastDamageEvent`: the client's /// `LivingEntity.handleDamageEvent` plays the source's hurt sound. DamageBroadcast { @@ -139,6 +145,7 @@ impl HealthEvent { format!("record-damage {:08x}", amount.to_bits()) } Self::Phase(name) => name.into(), + Self::ArmorHurt { amount, .. } => format!("hurt-armor {:08x}", amount.to_bits()), Self::DamageBroadcast { .. } => "broadcast-damage".into(), Self::Criterion { .. } => "hurt-criterion".into(), } @@ -295,6 +302,20 @@ impl PlayerMotion { source: DamageTypeId, amount: f32, blocking: Option, + ) -> Result { + self.hurt_caused_by(resources, rules, source, amount, blocking, false) + } + /// `hurt_blocking` from a source whose causing entity is a living + /// non-player (`living_cause`), which the `when_caused_by_living_non_player` + /// damage types scale with the difficulty. + pub fn hurt_caused_by( + &mut self, + resources: &HealthResources, + rules: HealthRules, + source: DamageTypeId, + amount: f32, + blocking: Option, + living_cause: bool, ) -> Result { if self.client_side { return Ok(BlockOutcome::default()); @@ -315,6 +336,7 @@ impl PlayerMotion { invulnerable, rules, source, + living_cause, events: &mut self.events, dead: &mut h.dead, sync_velocity: &mut h.sync_velocity, @@ -390,6 +412,8 @@ pub(crate) struct Environment<'a> { pub(crate) invulnerable: bool, pub(crate) rules: HealthRules, pub(crate) source: DamageSource<'a, ()>, + /// The causing entity is a living non-player (a mob, or its projectile's owner). + pub(crate) living_cause: bool, pub(crate) events: &'a mut Vec, pub(crate) dead: &'a mut bool, pub(crate) sync_velocity: &'a mut bool, @@ -517,9 +541,14 @@ impl ServerDamageEnvironment for Environment<'_> { fn bypasses(&mut self, kind: Bypass) -> io::Result { Ok(self.source.bypasses(kind)) } - fn hurt_armor(&mut self, _: &mut Attributes, _: f32) -> io::Result<()> { + fn hurt_armor(&mut self, _: &mut Attributes, damage: f32) -> io::Result<()> { + // The worn armor lives in the game, which wears it from this event. + self.event(HealthEvent::ArmorHurt { + source: self.source.type_id(), + amount: damage, + }); Ok(()) - } // empty equipment + } fn has_resistance(&mut self) -> io::Result { Ok(self.status.resistance.is_some()) } @@ -773,8 +802,13 @@ impl PlayerHurtWorld for Environment<'_> { Ok(()) } fn scales_with_difficulty(&mut self, _: &mut State) -> io::Result { - Ok(self.source.definition().scaling == Scaling::Always) - } // no causing entity + // DamageSource.scalesWithDifficulty. + Ok(match self.source.definition().scaling { + Scaling::Never => false, + Scaling::Always => true, + Scaling::LivingNonPlayer => self.living_cause, + }) + } fn difficulty(&mut self, _: &mut State) -> io::Result { Ok(self.rules.difficulty) } diff --git a/crates/horizon-client/src/hud_overlays.rs b/crates/horizon-client/src/hud_overlays.rs index ecc23a5ee..c6b098f75 100644 --- a/crates/horizon-client/src/hud_overlays.rs +++ b/crates/horizon-client/src/hud_overlays.rs @@ -191,6 +191,53 @@ pub fn effects(w: i32, demo: bool, effects: &[EffectIcon]) -> Vec { out } +/// The saving indicator: `Hud.tickAutosaveIndicator` fades a value towards 1 +/// while the server is saving and `extractSavingIndicator` draws the text. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct SavingIndicator { + last: f32, + value: f32, +} +impl SavingIndicator { + /// `Hud.tickAutosaveIndicator`: `Mth.lerp(0.2F, value, saving ? 1 : 0)`. + pub fn tick(&mut self, saving: bool) { + self.last = self.value; + self.value += (if saving { 1.0 } else { 0.0 } - self.value) * 0.2; + } + /// `Hud.extractSavingIndicator` without the option check: the text in the + /// bottom right corner. + pub fn draw( + &self, + w: i32, + h: i32, + partial: f32, + font: &Font, + label: Text, + background: u32, + ) -> Vec { + let mut out = Vec::new(); + if self.value <= 0.0 && self.last <= 0.0 { + return out; + } + let fade = (self.last + (self.value - self.last) * partial).clamp(0.0, 1.0); + let alpha = (255.0 * fade).floor() as u32; + if alpha > 0 { + let label_width = width(font, &label); + let color = crate::hud_layout::argb(alpha, 255, 255, 255); + text_with_backdrop( + &mut out, + label, + w - label_width - 5, + h - 9 - 5, + label_width, + color, + background, + ); + } + out + } +} + /// Titles and the action bar: `Hud.title`, `subtitle`, `titleTime`, the /// fade times and `overlayMessageString` / `overlayMessageTime`. #[derive(Clone, Debug, PartialEq)] @@ -1111,8 +1158,9 @@ impl SubtitleOverlay { s.purge_old_instances(3000.0 * frame.multiplier, now); } if s.audible_from(position) && !s.played.is_empty() { - width = width.max(width_of(&Text::translate(&s.key, &[]))); - audible.push(i); + let text_width = width_of(&Text::translate(&s.key, &[])); + width = width.max(text_width); + audible.push((i, text_width)); } } if audible.is_empty() { @@ -1121,7 +1169,7 @@ impl SubtitleOverlay { let w = |s: &str| font.width(s) as i32; width += w("<") + w(" ") + w(">") + w(" "); let mut row = 0; - for i in audible { + for (i, text_width) in audible { let s = &self.subtitles[i]; let text_value = Text::translate(&s.key, &[]); let Some(closest) = s.best_candidate(position) else { @@ -1145,7 +1193,6 @@ impl SubtitleOverlay { let half_width = width / 2; let height = 9; let half_height = height / 2; - let text_width = width_of(&text_value); let brightness = s.brightness(closest, frame.multiplier, now); out.push(GuiDraw::Push(vec![ PoseOp::Translate( diff --git a/crates/horizon-client/src/hunger.rs b/crates/horizon-client/src/hunger.rs index 15eac144f..34f414d50 100644 --- a/crates/horizon-client/src/hunger.rs +++ b/crates/horizon-client/src/hunger.rs @@ -151,6 +151,7 @@ impl FoodWorld for TickWorld<'_> { .damage .source::<()>(id, None, None, None) .expect("validated starvation source"), + living_cause: false, events: self.events, dead: self.dead, sync_velocity: self.sync_velocity, diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index c07e2f352..253bc6cc5 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -52,6 +52,8 @@ pub struct StackData { pub pot_decorations: Option; 4]>>, /// `minecraft:bundle_contents`. pub bundle_contents: Vec, + /// `BundleContents.selectedItem`: runtime only, never saved or sent. + pub bundle_selected: BundleSelected, /// `minecraft:suspicious_stew_effects`: (effect id, duration). pub stew_effects: Vec<(Arc, i32)>, /// `minecraft:map_post_processing`: 0 lock, 1 scale. @@ -60,6 +62,20 @@ pub struct StackData { /// max stack size...), kept as their saved values in key order. pub other: Vec<(String, Tag)>, } +/// A bundle's selected item index (-1: none). Like vanilla's +/// `BundleContents.equals` it is left out when stacks are compared. +#[derive(Clone, Copy, Debug)] +pub struct BundleSelected(pub i32); +impl Default for BundleSelected { + fn default() -> Self { + Self(-1) + } +} +impl PartialEq for BundleSelected { + fn eq(&self, _: &Self) -> bool { + true + } +} /// The components `components_tag` writes from modelled fields. const MODELLED: &[&str] = &[ "minecraft:banner_patterns", @@ -204,6 +220,14 @@ impl ItemStack { pub fn custom_name(&self) -> Option<&str> { self.data().and_then(|d| d.custom_name.as_deref()) } + /// `minecraft:item_name` in the current language (`getItemName`'s + /// component). It stays in the patch as loaded, so a translatable name + /// saves and reaches clients unchanged; the ominous banner's is modelled + /// by `ominous_banner` instead. + pub fn item_name(&self) -> Option { + let name = self.data()?.other("minecraft:item_name")?; + Some(crate::entity_nbt::name_text(name).plain()) + } pub fn potion(&self) -> Option<&str> { self.data().and_then(|d| d.potion.as_deref()) } @@ -783,6 +807,7 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option>>, extents: Mutex>>>, + /// GUI items already drawn: the HUD vertices of a static item at a GUI position + /// (`gui::draw`), which are the same every frame it stays there. + pub(crate) gui_drawn: Mutex>>, /// Entity model layers of the special renderers. parts: HashMap, /// `colormap/grass.png` as ARGB. @@ -452,6 +455,7 @@ impl ItemRenderer { }, baked: Mutex::default(), extents: Mutex::default(), + gui_drawn: Mutex::default(), parts, grass, }) @@ -649,6 +653,7 @@ pub fn tag_json(tag: &Tag) -> Value { /// The resolver's view of a client stack: its item, count and component patch. pub fn stack_view(stack: &crate::items::ItemStack) -> StackView { let mut view = StackView::new(&stack.item, stack.count as i32); + view.bundle_selected = stack.data().map_or(-1, |d| d.bundle_selected.0); if let Some(Tag::Compound(c)) = crate::item_data::components_tag(stack.damage, stack.data()) { for (k, v) in &c { let key = k.to_string_lossy(); diff --git a/crates/horizon-client/src/item_render/gui.rs b/crates/horizon-client/src/item_render/gui.rs index e3d7cc876..ff25fff1d 100644 --- a/crates/horizon-client/src/item_render/gui.rs +++ b/crates/horizon-client/src/item_render/gui.rs @@ -8,7 +8,7 @@ use super::{Foil, ItemQuad, ItemRenderState, ItemRenderer, SpecialHost}; use crate::hud::{HudBatch, Rect}; use glam::{EulerRot, Mat4, Vec2, Vec3}; -use std::{collections::HashMap, f32::consts::PI}; +use std::{collections::HashMap, f32::consts::PI, sync::Arc}; mod depth; @@ -148,6 +148,95 @@ pub fn draw( if state.is_empty() { return; } + // A static item drawn where it was drawn before gives the same vertices: + // take them instead of submitting, sorting and clipping its quads again. + let key = DrawnKey::of(state, renderer, sprites, x, y); + if let Some(key) = &key + && let Some(drawn) = renderer + .gui_drawn + .lock() + .ok() + .and_then(|d| d.get(key).cloned()) + { + batch.vertices.extend_from_slice(&drawn); + return; + } + let start = batch.vertices.len(); + draw_now(state, renderer, sprites, host, batch, x, y, time); + if let Some(key) = key + && let Ok(mut drawn) = renderer.gui_drawn.lock() + { + // GUI positions and items are few; a long scroll through every tab stays bounded. + if drawn.len() >= DRAWN_LIMIT { + drawn.clear(); + } + drawn.insert(key, batch.vertices[start..].into()); + } +} + +/// Entries of `ItemRenderer::gui_drawn` before it starts over. +const DRAWN_LIMIT: usize = 8192; + +/// What a GUI item's vertices depend on: its layers' baked models (kept for the +/// renderer's life, so their addresses name them), tints and transforms, the +/// atlas, and the exact position. None for items whose drawing changes with time +/// or the host: a glint, or a special model renderer. +#[derive(Clone, PartialEq, Eq, Hash)] +pub(crate) struct DrawnKey { + renderer: usize, + sprites: (usize, usize), + at: [u32; 2], + oversized: bool, + layers: Vec<(usize, Vec, [u32; 16], bool)>, +} +impl DrawnKey { + fn of( + state: &ItemRenderState, + renderer: &ItemRenderer, + sprites: &HashMap, + x: f32, + y: f32, + ) -> Option { + if state.animated { + return None; + } + let layers = state + .layers + .iter() + .map(|layer| match &layer.geometry { + super::LayerGeometry::Quads(baked) if layer.foil == super::FoilType::None => { + Some(( + Arc::as_ptr(baked) as usize, + layer.tints.clone(), + layer.matrix.to_cols_array().map(f32::to_bits), + layer.uses_block_light, + )) + } + _ => None, + }) + .collect::>>()?; + Some(Self { + renderer: std::ptr::from_ref(renderer) as usize, + sprites: (std::ptr::from_ref(sprites) as usize, sprites.len()), + at: [x.to_bits(), y.to_bits()], + oversized: state.oversized_in_gui, + layers, + }) + } +} + +/// [`draw`] without the cache. +#[allow(clippy::too_many_arguments)] +fn draw_now( + state: &ItemRenderState, + renderer: &ItemRenderer, + sprites: &HashMap, + host: &dyn SpecialHost, + batch: &mut HudBatch, + x: f32, + y: f32, + time: f32, +) { let pose = Mat4::from_translation(Vec3::new(x + 8.0, y + 8.0, 0.0)) * Mat4::from_scale(Vec3::new(16.0, -16.0, 16.0)); let mut quads: Vec = Vec::new(); diff --git a/crates/horizon-client/src/item_sync.rs b/crates/horizon-client/src/item_sync.rs index 930304ec4..fc35e15e7 100644 --- a/crates/horizon-client/src/item_sync.rs +++ b/crates/horizon-client/src/item_sync.rs @@ -238,6 +238,125 @@ mod tests { use super::*; use horizon_protocol::registry::Ids; + #[test] + fn merchant_water_cost_survives_the_offer_packet() { + use horizon_protocol::{ + buf::{Codec, Reader, Writer}, + packets::play::{NetOffer, Offers}, + }; + let mut components = vec![String::new(); component::POTION_CONTENTS as usize + 1]; + components[component::POTION_CONTENTS as usize] = "minecraft:potion_contents".into(); + let builtin = Builtin { + registries: [ + ( + "minecraft:item".into(), + Ids::from_names(vec!["minecraft:potion".into(), "minecraft:emerald".into()]), + ), + ( + "minecraft:potion".into(), + Ids::from_names(vec!["minecraft:water".into()]), + ), + ( + "minecraft:data_component_type".into(), + Ids::from_names(components), + ), + ] + .into(), + }; + let dynamic = Dynamic::default(); + let water = ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"); + let wire = crate::lan::guest::stack_to_network( + |name| builtin.get("minecraft:item").unwrap().id(name).unwrap(), + |registry, name| builtin.get(registry)?.id(name), + &Some(water.clone()), + ) + .unwrap(); + let offers = vec![NetOffer { + cost_a: wire.into(), + result: Stack::new(1, 1), + cost_b: Some(Stack::new(1, 2).into()), + out_of_stock: false, + uses: 0, + max_uses: 2, + xp: 0, + special_price: 0, + price_multiplier: 0.05, + demand: 0, + }]; + let mut w = Writer::new(); + Offers::write(&offers, &mut w); + let mut r = Reader::new(&w.data); + let decoded = Offers::read(&mut r).unwrap(); + assert_eq!(r.remaining(), 0); + let cost = crate::merchant::ItemCost { + stack: from_network(&decoded[0].cost_a.clone().into(), &builtin, &dynamic), + }; + assert_eq!(cost.stack, water); + assert_eq!(cost.stack.potion(), Some("minecraft:water")); + let authoritative = crate::merchant::ItemCost { + stack: water.clone(), + }; + for payment in [ + water, + ItemStack::new("minecraft:potion", 1).with_potion("minecraft:swiftness"), + ItemStack::new("minecraft:potion", 1), + ] { + assert_eq!(cost.test(&payment), authoritative.test(&payment)); + } + assert!(cost.test(&ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"))); + assert!( + !cost.test(&ItemStack::new("minecraft:potion", 1).with_potion("minecraft:swiftness")) + ); + let emerald = crate::merchant::ItemCost { + stack: from_network( + &decoded[0].cost_b.clone().unwrap().into(), + &builtin, + &dynamic, + ), + }; + assert!(emerald.test(&ItemStack::new("minecraft:emerald", 2))); + } + + /// A bundle's contents cross the wire, so a server's client can draw + /// its tooltip (BundleContents' stream codec: a list of templates). + #[test] + fn a_bundle_keeps_its_contents_across_the_wire() { + let mut components = vec![String::new(); 60]; + components[component::BUNDLE_CONTENTS as usize] = "minecraft:bundle_contents".into(); + let items = ["minecraft:air", "minecraft:bundle", "minecraft:stone"]; + let builtin = Builtin { + registries: [ + ( + "minecraft:item".to_owned(), + Ids::from_names(items.iter().map(|s| s.to_string()).collect()), + ), + ( + "minecraft:data_component_type".to_owned(), + Ids::from_names(components), + ), + ] + .into(), + }; + let dynamic = Dynamic { + registries: Default::default(), + }; + let mut bundle = ItemStack::new("minecraft:bundle", 1); + bundle.data_mut().bundle_contents = vec![ItemStack::new("minecraft:stone", 32)]; + let wire = crate::lan::guest::stack_to_network( + |name| items.iter().position(|i| *i == name).unwrap_or(0) as i32, + |_, _| None, + &Some(bundle), + ) + .unwrap(); + let back = from_network(&wire, &builtin, &dynamic); + let contents = &back.data().expect("components").bundle_contents; + assert_eq!(contents.len(), 1); + assert_eq!( + (&*contents[0].item, contents[0].count), + ("minecraft:stone", 32) + ); + } + /// What a creative client sends (`stack_to_network`) comes back whole on /// the server: damage, both enchantment lists, repair cost, name, trim. #[test] @@ -246,6 +365,7 @@ mod tests { for (id, name) in [ (component::DAMAGE, "minecraft:damage"), (component::CUSTOM_NAME, "minecraft:custom_name"), + (component::ITEM_NAME, "minecraft:item_name"), (component::ENCHANTMENTS, "minecraft:enchantments"), (component::POTION_CONTENTS, "minecraft:potion_contents"), (component::REPAIR_COST, "minecraft:repair_cost"), @@ -305,6 +425,10 @@ mod tests { .push((Arc::from("minecraft:sharpness"), 2)); d.repair_cost = 9; d.custom_name = Some("Keeper".to_owned()); + // A translatable item name reaches the client as the same component. + let item_name = Tag::compound([("translate", Tag::String("filled_map.monument".into()))]); + d.other + .push(("minecraft:item_name".into(), item_name.clone())); d.trim = Some((Arc::from("minecraft:gold"), Arc::from("minecraft:sentry"))); let id = |registry: &str, name: &str| { builtin @@ -334,6 +458,7 @@ mod tests { ); assert_eq!(d.repair_cost, 9); assert_eq!(d.custom_name.as_deref(), Some("Keeper")); + assert_eq!(d.other("minecraft:item_name"), Some(&item_name)); assert_eq!( d.trim, Some((Arc::from("minecraft:gold"), Arc::from("minecraft:sentry"))) diff --git a/crates/horizon-client/src/item_tooltip.rs b/crates/horizon-client/src/item_tooltip.rs index 6e51de391..63a19b114 100644 --- a/crates/horizon-client/src/item_tooltip.rs +++ b/crates/horizon-client/src/item_tooltip.rs @@ -56,10 +56,9 @@ impl<'a> TooltipDisplay<'a> { else { return true; }; - let component = horizon_world::nbt::JavaString::from(component); - !hidden - .iter() - .any(|tag| matches!(tag, Tag::String(id) if id == &component)) + !hidden.iter().any(|tag| { + matches!(tag, Tag::String(id) if id.0.iter().copied().eq(component.encode_utf16())) + }) } } @@ -109,6 +108,32 @@ fn modifier_line( ) } +/// `Attribute.getStyle`: the colour of a line for an attribute whose value +/// rises or falls. Gravity, scale and the waypoint ranges are neutral, burning +/// time and fall damage are negative, every other attribute is positive. +fn attribute_color(attribute: &str, rises: bool) -> u32 { + let (blue, red) = (rgba(85, 85, 255, 255), rgba(255, 85, 85, 255)); + match attribute { + "burning_time" | "fall_damage_multiplier" => { + if rises { + red + } else { + blue + } + } + "gravity" | "scale" | "waypoint_transmit_range" | "waypoint_receive_range" => { + rgba(170, 170, 170, 255) + } + _ => { + if rises { + blue + } else { + red + } + } + } +} + /// `ItemStack.addAttributeTooltips`: slot groups, colors and optional player /// attack damage/speed bases. Recipe search has no player context. pub fn attribute_lines( @@ -151,10 +176,8 @@ pub fn attribute_lines( ) { let (line, color) = if base.is_some() { (format!(" {line}"), rgba(0, 170, 0, 255)) - } else if *amount > 0.0 { - (line, rgba(85, 85, 255, 255)) } else { - (line, rgba(255, 85, 85, 255)) + (line, attribute_color(path, *amount > 0.0)) }; lines.push((line, color)); } @@ -189,6 +212,9 @@ pub fn name_line(stack: &ItemStack, translate: &dyn Fn(&str) -> Option) if let Some(name) = stack.custom_name() { return name.to_owned(); } + if let Some(name) = stack.item_name() { + return name; + } if stack.data().is_some_and(|d| d.ominous_banner) { return translate("block.minecraft.ominous_banner") .unwrap_or_else(|| "Ominous Banner".to_owned()); @@ -229,6 +255,235 @@ pub fn rarity<'a>(stack: &ItemStack, default: &'a str) -> &'a str { } } +fn is_beehive(path: &str) -> bool { + matches!(path, "beehive" | "bee_nest") +} + +/// `InstrumentComponent.addToTooltip`: the instrument's description. A goat +/// horn without the component has the item's default, the ponder horn. +pub fn instrument_line( + stack: &ItemStack, + display: &TooltipDisplay, + translate: &dyn Fn(&str) -> Option, +) -> Option { + if !display.shows("minecraft:instrument") { + return None; + } + let id = match stack.data().and_then(|d| d.other("minecraft:instrument")) { + Some(Tag::String(id)) => id.to_string_lossy(), + // An inline instrument carries its own description. + Some(inline) => { + return inline + .get("description") + .map(|d| crate::entity_nbt::name_text(d).plain()); + } + None if &*stack.item == "minecraft:goat_horn" => "minecraft:ponder_goat_horn".to_owned(), + None => return None, + }; + let key = format!("instrument.{}", id.replacen(':', ".", 1)); + Some(translate(&key).unwrap_or(key)) +} + +/// `Bees.addToTooltip`: how many bees a hive item holds (a hive item without +/// the component has the item's default, none). +pub fn bees_line( + stack: &ItemStack, + display: &TooltipDisplay, + translate: &dyn Fn(&str) -> Option, +) -> Option { + if !display.shows("minecraft:bees") { + return None; + } + let bees = match stack.data().and_then(|d| d.other("minecraft:bees")) { + Some(Tag::List(bees)) => bees.len(), + Some(_) => return None, + None if is_beehive(stack.item.trim_start_matches("minecraft:")) => 0, + None => return None, + }; + let text = + translate("container.beehive.bees").unwrap_or_else(|| "container.beehive.bees".into()); + Some( + text.replacen("%s", &bees.to_string(), 1) + .replacen("%s", "3", 1), + ) +} + +/// `BlockItemStateProperties.addToTooltip`: a hive item's honey level (a hive +/// item without the component has the item's default, 0). +pub fn honey_line( + stack: &ItemStack, + display: &TooltipDisplay, + translate: &dyn Fn(&str) -> Option, +) -> Option { + if !display.shows("minecraft:block_state") { + return None; + } + let level = match stack.data().and_then(|d| d.other("minecraft:block_state")) { + Some(Tag::Compound(state)) => { + match state.get(&horizon_world::nbt::JavaString::from("honey_level")) { + Some(Tag::String(level)) => level.to_string_lossy().parse::().ok()?, + _ => return None, + } + } + Some(_) => return None, + None if is_beehive(stack.item.trim_start_matches("minecraft:")) => 0, + None => return None, + }; + let text = + translate("container.beehive.honey").unwrap_or_else(|| "container.beehive.honey".into()); + Some( + text.replacen("%s", &level.to_string(), 1) + .replacen("%s", "5", 1), + ) +} + +/// `WrittenBookContent.addToTooltip`: "by " and the generation. +pub fn written_book_lines( + stack: &ItemStack, + display: &TooltipDisplay, + translate: &dyn Fn(&str) -> Option, +) -> Vec { + let text = |key: &str| translate(key).unwrap_or_else(|| key.to_owned()); + let Some(book) = stack + .data() + .and_then(|d| d.written.as_ref()) + .filter(|_| display.shows("minecraft:written_book_content")) + else { + return Vec::new(); + }; + let mut lines = Vec::new(); + if !book.author.trim().is_empty() { + lines.push( + crate::text::format_translation( + &text("book.byAuthor"), + &[crate::text::Text::literal(&book.author)], + ) + .plain(), + ); + } + lines.push(text(&format!("book.generation.{}", book.generation))); + lines +} + +/// `JukeboxPlayable.addToTooltip`: the song's description. +pub fn jukebox_line( + stack: &ItemStack, + info: Option<&ItemInfo>, + display: &TooltipDisplay, + translate: &dyn Fn(&str) -> Option, +) -> Option { + if !display.shows("minecraft:jukebox_playable") { + return None; + } + let song = match stack + .data() + .and_then(|d| d.other("minecraft:jukebox_playable")) + { + Some(Tag::String(song)) => song.to_string_lossy(), + // An inline song carries its own description. + Some(inline) => { + return inline + .get("description") + .map(|d| crate::entity_nbt::name_text(d).plain()); + } + None => info?.jukebox_song.clone()?, + }; + let key = format!("jukebox_song.{}", song.replacen(':', ".", 1)); + Some(translate(&key).unwrap_or(key)) +} + +/// `DyedItemColor.addToTooltip`: "Dyed" (italic, the flag), or with advanced +/// tooltips the colour's hex code. +pub fn dyed_line( + stack: &ItemStack, + display: &TooltipDisplay, + advanced: bool, + translate: &dyn Fn(&str) -> Option, +) -> Option<(String, bool)> { + let rgb = stack.data()?.dyed_color?; + if !display.shows("minecraft:dyed_color") { + return None; + } + let text = |key: &str| translate(key).unwrap_or_else(|| key.to_owned()); + Some(if advanced { + let hex = format!("#{:06X}", rgb & 0xFF_FFFF); + (text("item.color").replacen("%s", &hex, 1), false) + } else { + (text("item.dyed"), true) + }) +} + +/// `ItemStack.UNBREAKABLE_TOOLTIP`. +pub fn unbreakable_line( + stack: &ItemStack, + display: &TooltipDisplay, + translate: &dyn Fn(&str) -> Option, +) -> Option { + (stack.data()?.other("minecraft:unbreakable").is_some() + && display.shows("minecraft:unbreakable")) + .then(|| translate("item.unbreakable").unwrap_or_else(|| "item.unbreakable".into())) +} + +/// `PotionContents.addPotionTooltip`'s attribute block: an empty line, "When +/// Applied:" and the modifiers of the potion's effects (blue for a gain, red +/// for a loss); nothing for a potion whose effects add none. +pub fn potion_modifier_lines( + stack: &ItemStack, + translate: &dyn Fn(&str) -> Option, +) -> Vec<(String, u32)> { + if !is_potion_item(&stack.item) { + return Vec::new(); + } + let applied: Vec<(String, u32)> = stack + .potion() + .and_then(crate::brewing::potion) + .into_iter() + .flat_map(|p| p.effects.iter()) + .filter_map(|(effect, _, amplifier)| { + let (attribute, amount, operation) = effect_modifier(effect)?; + let amount = amount * (*amplifier + 1) as f64; + let line = modifier_line(translate, attribute, amount, operation, false)?; + let color = if amount > 0.0 { + rgba(85, 85, 255, 255) + } else { + rgba(255, 85, 85, 255) + }; + Some((line, color)) + }) + .collect(); + if applied.is_empty() { + return applied; + } + let mut lines = vec![ + (String::new(), u32::MAX), + ( + translate("potion.whenDrank").unwrap_or_else(|| "potion.whenDrank".into()), + rgba(170, 0, 170, 255), + ), + ]; + lines.extend(applied); + lines +} + +/// `ItemStack.components.size()`: the item's default components with the +/// stack's own changes applied. +pub fn component_count(stack: &ItemStack, info: Option<&ItemInfo>) -> usize { + let mut keys: std::collections::HashSet = info + .map(|i| i.components.iter().cloned().collect()) + .unwrap_or_default(); + if let Some(Tag::Compound(patch)) = crate::item_data::components_tag(stack.damage, stack.data()) + { + for key in patch.keys() { + let key = key.to_string_lossy(); + match key.strip_prefix('!') { + Some(removed) => keys.remove(removed), + None => keys.insert(key), + }; + } + } + keys.len() +} + /// The lines of `stack` below its name that its components give, in /// `ItemStack.addDetailsToTooltip` order. pub fn detail_lines( @@ -263,19 +518,9 @@ pub fn detail_lines( )) )); } - // BeehiveBlock: the block state components of the item. - if path == "beehive" { - lines.push( - text("container.beehive.bees") - .replacen("%s", "0", 1) - .replacen("%s", "3", 1), - ); - lines.push( - text("container.beehive.honey") - .replacen("%s", "0", 1) - .replacen("%s", "5", 1), - ); - } + let display = TooltipDisplay::for_stack(stack); + lines.extend(bees_line(stack, &display, translate)); + lines.extend(honey_line(stack, &display, translate)); let data = stack.data(); // PotDecorations.addToTooltip. if let Some(sherds) = data @@ -301,32 +546,13 @@ pub fn detail_lines( .into_iter() .map(|l| l.0), ); - let applied: Vec = stack - .potion() - .and_then(crate::brewing::potion) - .into_iter() - .flat_map(|p| p.effects.iter()) - .filter_map(|(effect, _, amplifier)| { - let (attribute, amount, operation) = effect_modifier(effect)?; - modifier_line( - translate, - attribute, - amount * (*amplifier + 1) as f64, - operation, - false, - ) - }) - .collect(); - if !applied.is_empty() { - lines.push(String::new()); - lines.push(text("potion.whenDrank")); - lines.extend(applied); - } - } - // JukeboxPlayable.addToTooltip: the song's description. - if path.starts_with("music_disc_") { - lines.push(text(&format!("item.minecraft.{path}.desc"))); + lines.extend( + potion_modifier_lines(stack, translate) + .into_iter() + .map(|l| l.0), + ); } + lines.extend(jukebox_line(stack, info, &display, translate)); // Trim.addToTooltip. if let Some((material, pattern)) = data.and_then(|d| d.trim.as_ref()) { let short = |s: &str| s.trim_start_matches("minecraft:").to_owned(); @@ -340,10 +566,7 @@ pub fn detail_lines( text(&format!("trim_material.minecraft.{}", short(material))) )); } - // DyedItemColor.addToTooltip (without advanced tooltips). - if data.is_some_and(|d| d.dyed_color.is_some()) { - lines.push(text("item.dyed")); - } + lines.extend(dyed_line(stack, &display, false, translate).map(|l| l.0)); if let Some(info) = info { lines.extend( attribute_lines(&info.modifiers, None, translate) @@ -612,6 +835,14 @@ mod tests { assert_eq!(rarity(&banner, "common"), "uncommon"); banner.data_mut().custom_name = Some("Captain's Standard".into()); assert_eq!(name_line(&banner, &translate), "Captain's Standard"); + let mut custom_item = ItemStack::new("minecraft:diamond_sword", 1); + custom_item.data_mut().other.push(( + "minecraft:item_name".into(), + Tag::String("Excalibur".into()), + )); + assert_eq!(name_line(&custom_item, &translate), "Excalibur"); + custom_item.data_mut().custom_name = Some("Custom Blade".into()); + assert_eq!(name_line(&custom_item, &translate), "Custom Blade"); banner.enchant("minecraft:unbreaking", 1); assert_eq!(rarity(&banner, "common"), "rare"); let plain = ItemStack::new("minecraft:white_banner", 1); diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 8ac450bcb..10f1c72ad 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -71,6 +71,8 @@ pub struct ItemInfo { /// 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, + /// `tool.can_destroy_blocks_in_creative` (defaults to true). + pub can_destroy_blocks_in_creative: bool, pub food: Option<(u32, f32)>, pub can_always_eat: bool, /// `consumable`: its timing, sound, particles and `on_consume_effects`. @@ -111,6 +113,9 @@ pub struct ItemInfo { pub swappable: bool, /// `equippable.dispensable` (dispensers may put it on an entity). pub equip_dispensable: bool, + /// `equippable.damage_on_hurt`: the item wears when its wearer is hurt + /// (false for the elytra). + pub equip_damage_on_hurt: bool, /// `equippable.allowed_entities` resolved to entity type ids; None allows all. pub equip_allowed: Option>, pub equip_sound: Option, @@ -120,10 +125,14 @@ pub struct ItemInfo { pub crafting_remainder: Option, /// `dye`: the dye colour name (dyes, and anything else with the component). pub dye: Option, + /// `cushion/color`: the DyeColor name of a cushion item. + pub cushion_color: Option, /// `block_transformer`: the registry entry an axe, hoe or shovel uses on blocks. pub block_transformer: Option, /// Has a default `bundle_contents` (the bundles, `BundleItem`). pub bundle: bool, + /// The ids of the item's default components (its prototype's keys). + pub components: Vec, } /// `Item.Properties.craftRemainder` (not a data component, so not in the /// default-component report): what an item leaves in the grid when crafted with. @@ -251,6 +260,10 @@ pub struct Items { loot: HashMap, /// The `jukebox_song` registry. pub songs: HashMap, + /// The enchantment registry: loot functions enchant the items they roll + /// (`EnchantWithLevelsFunction`, `EnchantRandomlyFunction`), and the + /// station menus share this copy. + pub enchantments: Arc, } /// A `JukeboxSong`. #[derive(Clone, Debug)] @@ -392,6 +405,36 @@ impl Items { self.get(&stack.item).is_some_and(|i| i.fire_resistant) } + /// `ItemStack.canBeHurtBy` for the cactus damage type: a `damage_resistant` + /// component naming `minecraft:cactus`, or a damage type tag that holds it. + /// (`#minecraft:is_fire`, as on netherite gear, does not.) + pub fn resists_cactus(&self, stack: &ItemStack) -> bool { + const CACTUS_TAGS: [&str; 5] = [ + "#minecraft:bypasses_shield", + "#minecraft:no_knockback", + "#minecraft:panic_environmental_causes", + "#minecraft:panic_causes", + "#minecraft:sulfur_cube_with_block_immune_to", + ]; + let Some((_, v)) = stack.data().and_then(|data| { + data.other + .iter() + .find(|(key, _)| key == "minecraft:damage_resistant") + }) else { + return false; + }; + match v.get("types") { + Some(horizon_world::nbt::Tag::String(id)) => id + .to_string() + .is_ok_and(|id| id == "minecraft:cactus" || CACTUS_TAGS.contains(&id.as_str())), + Some(horizon_world::nbt::Tag::List(ids)) => ids.iter().any(|t| { + matches!(t, horizon_world::nbt::Tag::String(id) + if id.to_string().is_ok_and(|id| id == "minecraft:cactus")) + }), + _ => false, + } + } + pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> Result { let mut block_for_item: HashMap<&str, BlockStateId> = HashMap::new(); for (i, s) in facts.states.iter().enumerate() { @@ -552,6 +595,10 @@ impl Items { tool_damage_per_block: c .get("minecraft:tool") .map(|t| t["damage_per_block"].as_u64().unwrap_or(1) as u32), + can_destroy_blocks_in_creative: + c["minecraft:tool"]["can_destroy_blocks_in_creative"] + .as_bool() + .unwrap_or(true), food, can_always_eat, // Consumable.CODEC's defaults. @@ -584,6 +631,9 @@ impl Items { equip_dispensable: c["minecraft:equippable"]["dispensable"] .as_bool() .unwrap_or(true), + equip_damage_on_hurt: c["minecraft:equippable"]["damage_on_hurt"] + .as_bool() + .unwrap_or(true), equip_allowed: match &c["minecraft:equippable"]["allowed_entities"] { Value::String(spec) => Some(entity_spec(&entity_tags, spec)), Value::Array(list) => Some( @@ -599,8 +649,13 @@ impl Items { .map(str::to_owned), jukebox_song: c["minecraft:jukebox_playable"].as_str().map(str::to_owned), dye: c["minecraft:dye"].as_str().map(str::to_owned), + cushion_color: c["minecraft:cushion/color"].as_str().map(str::to_owned), block_transformer: c["minecraft:block_transformer"].as_str().map(str::to_owned), bundle: c.get("minecraft:bundle_contents").is_some(), + components: c + .as_object() + .map(|c| c.keys().cloned().collect()) + .unwrap_or_default(), crafting_remainder: CRAFT_REMAINDERS .iter() .find(|(item, _)| *item == name) @@ -701,12 +756,15 @@ impl Items { item_tag_order: load_tag_lists(root, "item")?, loot, songs: load_songs(root), + enchantments: Arc::new(crate::enchant::Enchantments::load(root)), }) } pub fn get(&self, id: &str) -> Option<&ItemInfo> { self.items.get(id) } - /// Only the block and item tags, for tools that need tag membership. + /// Only the block and item tags (and the enchantment registry, which the + /// station rules and loot functions are built from), for tools that need + /// tag membership. pub fn tags_only(root: &Path) -> Result { Ok(Self { items: HashMap::new(), @@ -717,6 +775,7 @@ impl Items { item_tag_order: load_tag_lists(root, "item")?, loot: HashMap::new(), songs: HashMap::new(), + enchantments: Arc::new(crate::enchant::Enchantments::load(root)), }) } /// An item table with only tags, for unit tests of item rules. @@ -734,6 +793,7 @@ impl Items { item_tags, loot: HashMap::new(), songs: HashMap::new(), + enchantments: Arc::new(crate::enchant::Enchantments::default()), } } /// Whether `block` is in the block tag `tag` (`minecraft:fire`, no `#`). @@ -746,6 +806,26 @@ impl Items { None => spec == block, } } + /// `Item.canDestroyBlock`: a tool may forbid block destruction with instabuild. + pub fn can_destroy_block(&self, held: Option<&ItemStack>, creative: bool) -> bool { + if !creative { + return true; + } + let Some(held) = held.filter(|s| s.count > 0 && &*s.item != "minecraft:air") else { + return true; + }; + if let Some(tool) = held.data().and_then(|d| d.other("minecraft:tool")) { + return tool + .get("can_destroy_blocks_in_creative") + .and_then(|v| match v { + horizon_world::nbt::Tag::Byte(v) => Some(*v), + _ => None, + }) + .is_none_or(|v| v != 0); + } + self.get(&held.item) + .is_none_or(|info| info.can_destroy_blocks_in_creative) + } /// `Tool.getMiningSpeed` for the held item (1.0 without a tool component). pub fn mining_speed(&self, held: Option<&ItemStack>, block: &str) -> f32 { let Some(info) = held.and_then(|s| self.get(&s.item)) else { @@ -796,6 +876,7 @@ impl Items { held: None, killed_by_player: false, explosion_radius: None, + this_entity: false, }; ctx.evaluate(table, random) } @@ -860,10 +941,26 @@ impl Items { random: &mut impl RandomSource, sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>, ) -> Vec { - self.block_drops_exploded(registry, state, held, dynamic, random, sequences, None) + self.block_drops_exploded( + registry, state, held, dynamic, random, sequences, None, false, + ) + } + /// `block_drops_with` for a block a player breaks (`Block.playerDestroy`): + /// the player is the loot context's `this` entity, so snow and chorus + /// flower tables see an entity. + pub fn block_drops_by_player( + &self, + registry: &BlockRegistry, + state: BlockStateId, + held: Option<&ItemStack>, + dynamic: &[ItemStack], + random: &mut impl RandomSource, + ) -> Vec { + self.block_drops_exploded(registry, state, held, dynamic, random, None, None, true) } /// `block_drops_full` for a block an explosion destroys: `explosion` - /// is its radius when the explosion decays drops (`DESTROY_WITH_DECAY`). + /// is its radius when the explosion decays drops (`DESTROY_WITH_DECAY`); + /// `breaker` is whether an entity (the player) broke the block. #[allow(clippy::too_many_arguments)] pub fn block_drops_exploded( &self, @@ -874,8 +971,10 @@ impl Items { random: &mut impl RandomSource, sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>, explosion: Option, + breaker: bool, ) -> Vec { - let drops = self.block_drops_raw(registry, state, held, random, sequences, explosion); + let drops = + self.block_drops_raw(registry, state, held, random, sequences, explosion, breaker); if !drops.iter().any(|d| d.item.starts_with(DYNAMIC)) { return drops; } @@ -890,6 +989,7 @@ impl Items { }) .collect() } + #[allow(clippy::too_many_arguments)] fn block_drops_raw( &self, registry: &BlockRegistry, @@ -898,6 +998,7 @@ impl Items { random: &mut impl RandomSource, sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>, explosion_radius: Option, + breaker: bool, ) -> Vec { let Some(block) = registry.state(state) else { return vec![]; @@ -931,6 +1032,7 @@ impl Items { held, killed_by_player: false, explosion_radius, + this_entity: breaker, }; return ctx.evaluate(table, random); } @@ -941,6 +1043,7 @@ impl Items { held, killed_by_player: false, explosion_radius, + this_entity: breaker, }; ctx.evaluate(table, random) } @@ -964,6 +1067,7 @@ impl Items { held, killed_by_player, explosion_radius: None, + this_entity: false, }; ctx.evaluate(table, random) } @@ -996,6 +1100,7 @@ impl Items { held: None, killed_by_player: false, explosion_radius: None, + this_entity: false, }; match table.get("random_sequence").and_then(Value::as_str) { Some(sequence) => ctx.evaluate(table, sequences.get(sequence, seed)), @@ -1021,6 +1126,7 @@ impl Items { held, killed_by_player, explosion_radius: None, + this_entity: false, }; ctx.evaluate(table, random) } @@ -1043,6 +1149,7 @@ impl Items { held, killed_by_player, explosion_radius: None, + this_entity: false, }; ctx.evaluate(table, random) } @@ -1084,6 +1191,8 @@ struct LootContext<'a> { killed_by_player: bool, /// `LootContextParams.EXPLOSION_RADIUS`: an explosion that decays drops. explosion_radius: Option, + /// `LootContextParams.THIS_ENTITY` is set (a player broke the block). + this_entity: bool, } impl LootContext<'_> { /// Level of an enchantment on the tool / killer's weapon. @@ -1244,6 +1353,15 @@ impl LootContext<'_> { }; random.next_float() < chance } + // `this` with no checks (snow, chorus flower) holds when an entity + // broke the block (LootItemEntityPropertyCondition needs the entity). + "minecraft:entity_properties" + if self.this_entity + && c["entity"].as_str() == Some("this") + && c["predicate"].as_object().is_none_or(|p| p.is_empty()) => + { + true + } // Entity flags, equipment and damage-source predicates: none hold // for an unenchanted player kill without fire or lightning. "minecraft:entity_properties" | "minecraft:damage_source_properties" => false, @@ -1371,6 +1489,16 @@ impl LootContext<'_> { self.modifiers(&modifiers, &mut stack, random); produced.push(stack); } + /// An enchantment function's `options` (`HolderSet`): a tag, a list or + /// one id; every enchantment when absent (`registryAccess().listElements`). + fn enchant_pool(e: &crate::enchant::Enchantments, options: &Value) -> Vec> { + match options { + Value::String(s) if s.starts_with('#') => e.tag(s).to_vec(), + Value::String(s) => vec![Arc::from(s.as_str())], + Value::Array(a) => a.iter().filter_map(|x| x.as_str().map(Arc::from)).collect(), + _ => e.list.iter().map(|x| Arc::clone(&x.id)).collect(), + } + } fn modifiers(&self, m: &Value, stack: &mut ItemStack, random: &mut R) { let list: Vec<&Value> = match m { Value::Array(a) => a.iter().collect(), @@ -1449,6 +1577,54 @@ impl LootContext<'_> { .with_potion(id); } } + // EnchantWithLevelsFunction: EnchantmentHelper.enchantItem on + // the context's random (the End cities' gear). + "minecraft:enchant_with_levels" => { + let cost = Self::int_number(&f["levels"], random); + let e = &self.items.enchantments; + let pool = Self::enchant_pool(e, &f["options"]); + let chosen = e.select(self.items, random, &stack.item, cost, &pool); + // EnchantmentHelper.enchantItem: a book becomes one + // enchanted book (the fresh stack's count). + if &*stack.item == "minecraft:book" { + *stack = ItemStack::new("minecraft:enchanted_book", 1); + } + for (id, level) in chosen { + stack.enchant(&id, level); + } + } + // EnchantRandomlyFunction: one enchantment the item accepts, + // at a level between its min and max. + "minecraft:enchant_randomly" => { + let e = &self.items.enchantments; + let book = &*stack.item == "minecraft:book"; + let only_compatible = f["only_compatible"].as_bool().unwrap_or(true); + let options: Vec> = Self::enchant_pool(e, &f["options"]) + .into_iter() + .filter(|id| { + book || !only_compatible || e.can_enchant(self.items, id, &stack.item) + }) + .collect(); + if options.is_empty() { + continue; + } + let id = options + [random.next_int_bound(options.len() as i32).unwrap_or(0) as usize] + .clone(); + let max = e.get(&id).map_or(1, |d| d.max_level).max(1); + // `Mth.nextInt(random, 1, max)`: a single-level + // enchantment (Mending) returns 1 without drawing, so the + // rolls after this one keep vanilla's sequence. + let level = if max <= 1 { + 1 + } else { + 1 + random.next_int_bound(max as i32).unwrap_or(0) as u32 + }; + if book { + *stack = ItemStack::new("minecraft:enchanted_book", 1); + } + stack.enchant(&id, level); + } "minecraft:limit_count" => { let limit = &f["limit"]; if let Some(min) = limit["min"].as_i64() { @@ -1571,6 +1747,7 @@ mod tests { held, killed_by_player: block.is_empty(), explosion_radius: None, + this_entity: false, } } @@ -1658,6 +1835,102 @@ mod tests { assert_eq!(drops[0].potion(), Some("minecraft:fire_resistance")); } + /// `/loot give` and every other table this dispatcher rolls: the two + /// enchantment functions (`EnchantWithLevelsFunction`, + /// `EnchantRandomlyFunction`) put their enchantments on the stack. + #[test] + fn loot_enchant_functions_enchant_the_rolled_item() { + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client/26.3"); + if !root.join("items.json").exists() { + return; + } + let assets = crate::assets::Assets::load(&root).unwrap(); + let facts = crate::blocks::BlockFacts::load(&root, assets.registry).unwrap(); + let items = Items::load(&root, assets.registry, &facts).unwrap(); + let props = BTreeMap::new(); + let mut random = LegacyRandom::new(11); + // A sword at levels 20..39 comes out enchanted, as in an End city. + let levels = json!({"pools":[{"rolls":1,"entries":[{"type":"minecraft:item", + "name":"minecraft:diamond_sword","modifier":[ + {"type":"minecraft:enchant_with_levels","levels":{"type":"minecraft:uniform","min":20.0,"max":39.0}}]}]}]}); + let mut enchanted = 0; + for _ in 0..40 { + let drops = ctx(&items, None, &props, "").evaluate(&levels, &mut random); + if drops[0].enchantments().is_empty() { + continue; + } + enchanted += 1; + assert_eq!(&*drops[0].item, "minecraft:diamond_sword"); + // Levels stay within the enchantment's range. + for (id, level) in drops[0].enchantments() { + let max = items + .enchantments + .get(id) + .expect("a known enchantment") + .max_level; + assert!((1..=max).contains(level), "{id} at {level}"); + } + } + assert!( + enchanted > 30, + "only {enchanted} of 40 rolls were enchanted" + ); + // `enchant_randomly` on a book makes one enchanted book, its levels + // stored; the pool is the enchantment tag it names. + let book = json!({"pools":[{"rolls":1,"entries":[{"type":"minecraft:item", + "name":"minecraft:book","modifier":[ + {"type":"minecraft:enchant_randomly","options":"#minecraft:on_random_loot"}]}]}]}); + let drops = ctx(&items, None, &props, "").evaluate(&book, &mut random); + assert_eq!(&*drops[0].item, "minecraft:enchanted_book"); + assert_eq!(drops[0].count, 1); + assert!(drops[0].enchantments().is_empty()); + let stored = drops[0].stored_enchantments(); + assert_eq!(stored.len(), 1, "{stored:?}"); + assert!( + items + .enchantments + .in_tag("minecraft:on_random_loot", &stored[0].0) + ); + // An item no enchantment accepts keeps none of them. + let dirt = json!({"pools":[{"rolls":1,"entries":[{"type":"minecraft:item", + "name":"minecraft:dirt","modifier":[ + {"type":"minecraft:enchant_with_levels","levels":{"type":"minecraft:constant","value":30.0}}]}]}]}); + let drops = ctx(&items, None, &props, "").evaluate(&dirt, &mut random); + assert!(drops[0].enchantments().is_empty()); + } + + /// `Mth.nextInt(random, 1, max)` returns `1` without drawing when the + /// enchantment has one level (`EnchantRandomlyFunction.enchantItem`), so + /// the rolls after it must not shift. Vanilla with `LegacyRandom(11)`: a + /// Mending book, then `set_count` uniform 1..64, is 46. + #[test] + fn a_single_level_enchantment_draws_no_level() { + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client/26.3"); + if !root.join("items.json").exists() { + return; + } + let assets = crate::assets::Assets::load(&root).unwrap(); + let facts = crate::blocks::BlockFacts::load(&root, assets.registry).unwrap(); + let items = Items::load(&root, assets.registry, &facts).unwrap(); + let props = BTreeMap::new(); + let table = json!({"pools":[{"rolls":1,"entries":[{"type":"minecraft:item", + "name":"minecraft:book","modifier":[ + {"type":"minecraft:enchant_randomly","options":"minecraft:mending"}, + {"type":"minecraft:set_count","count":{"type":"minecraft:uniform","min":1.0,"max":64.0}}]}]}]}); + let drops = ctx(&items, None, &props, "").evaluate(&table, &mut LegacyRandom::new(11)); + assert_eq!(drops.len(), 1); + assert_eq!(&*drops[0].item, "minecraft:enchanted_book"); + assert_eq!( + drops[0].stored_enchantments(), + [("minecraft:mending".to_owned().into(), 1)], + "the book keeps its single-level enchantment" + ); + // 46 is vanilla's count for this seed; an extra level draw gives 28. + assert_eq!(drops[0].count, 46); + } + #[test] fn always_edible_and_consume_effects_loaded() { let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) diff --git a/crates/horizon-client/src/keybinds.rs b/crates/horizon-client/src/keybinds.rs index a59aa627c..2047b9117 100644 --- a/crates/horizon-client/src/keybinds.rs +++ b/crates/horizon-client/src/keybinds.rs @@ -2,7 +2,6 @@ //! defaults, `key_:key.keyboard.x` persistence, display names, and the //! translation of rebound physical keys back to the default keys the game //! logic listens for. -use crate::text::Text; use std::collections::BTreeMap; use winit::{event::MouseButton, keyboard::KeyCode}; @@ -225,40 +224,7 @@ pub fn mouse_button(name: &str) -> Option { _ => return None, }) } -/// InputConstants.Key.getDisplayName: one-character keys as the upper-case -/// character, others by translation. -pub fn display_name(key: &str) -> Text { - if let Some(rest) = key.strip_prefix("key.keyboard.") - && rest.chars().count() == 1 - { - let c = rest.to_uppercase(); - return Text::literal(c); - } - let symbol = match key { - "key.keyboard.minus" => Some("-"), - "key.keyboard.equal" => Some("="), - "key.keyboard.left.bracket" => Some("["), - "key.keyboard.right.bracket" => Some("]"), - "key.keyboard.backslash" => Some("\\"), - "key.keyboard.semicolon" => Some(";"), - "key.keyboard.apostrophe" => Some("'"), - "key.keyboard.grave.accent" => Some("`"), - "key.keyboard.comma" => Some(","), - "key.keyboard.period" => Some("."), - "key.keyboard.slash" => Some("/"), - _ => None, - }; - if let Some(s) = symbol { - return Text::literal(s); - } - if let Some(n) = key.strip_prefix("key.mouse.") - && n.parse::().is_ok() - && !crate::lang::has(key) - { - return Text::translate("key.mouse", &[Text::literal(n)]); - } - Text::translate(key, &[]) -} +pub use horizon_client_core::key_display::display_name; /// Current bindings by mapping name. #[derive(Clone, Debug, PartialEq, Eq)] @@ -275,6 +241,20 @@ impl Default for KeyBinds { } } } +/// Each default key once, in order: two mappings that share a default key +/// (Advancements and the debug profiler both on L) are one press of it, not +/// two (the second would close the screen the first opened). Vanilla clicks +/// both mappings, but the profiler one only acts with F3 held. +fn distinct(keys: Vec) -> Vec { + let mut out = Vec::with_capacity(keys.len()); + for k in keys { + if !out.contains(&k) { + out.push(k); + } + } + out +} + impl KeyBinds { pub fn get(&self, name: &str) -> &str { self.keys @@ -320,49 +300,80 @@ impl KeyBinds { } /// The mapping a physical input triggers (first in list order). pub fn mapping_for(&self, key: &str) -> Option<&'static str> { - MAPPINGS.iter().map(|m| m.0).find(|n| self.get(n) == key) + self.mappings_for(key).next() + } + /// Every mapping a physical input triggers, in list order: like + /// `KeyMapping.set`/`click`, one key drives all the mappings bound to it. + pub fn mappings_for<'a>(&'a self, key: &'a str) -> impl Iterator + 'a { + MAPPINGS + .iter() + .map(|m| m.0) + .filter(move |n| self.get(n) == key) } /// Translate a physical key into the default key of the mapping it is /// bound to, so game code written against vanilla defaults follows the /// player's bindings. `None` means the key now does nothing; mouse - /// mappings bound to keys come back as `Err(button)`. + /// mappings bound to keys come back as `Err(button)`. The first of + /// [`KeyBinds::translate_all`]. pub fn translate(&self, key: KeyCode) -> Option> { + self.translate_all(key).into_iter().next() + } + /// The default keys of every mapping `key` is bound to (empty when it + /// now does nothing), so a key bound to two mappings (forward and + /// sprint) drives both, as `KeyMapping.set` does. + pub fn translate_all(&self, key: KeyCode) -> Vec> { let Some(name) = key_name(key) else { - return Some(Ok(key)); + return vec![Ok(key)]; }; - if let Some(mapping) = self.mapping_for(name) { - let default = Self::default_of(mapping); - if let Some(code) = key_code(default) { - return Some(Ok(code)); - } - return mouse_button(default).map(Err); + let bound: Vec<_> = self + .mappings_for(name) + .filter_map(|mapping| { + let default = Self::default_of(mapping); + match key_code(default) { + Some(code) => Some(Ok(code)), + None => mouse_button(default).map(Err), + } + }) + .collect(); + if !bound.is_empty() { + return distinct(bound); } // An unbound key whose default meaning was moved elsewhere is inert. if MAPPINGS .iter() .any(|(n, d, _)| *d == name && !self.is_default(n)) { - return None; + return Vec::new(); } - Some(Ok(key)) + vec![Ok(key)] } /// Translate a mouse button the same way (keys bound to mouse buttons). pub fn translate_mouse(&self, button: MouseButton) -> Option> { + self.translate_mouse_all(button).into_iter().next() + } + /// [`KeyBinds::translate_all`] for a mouse button. + pub fn translate_mouse_all(&self, button: MouseButton) -> Vec> { let name = mouse_name(button); - if let Some(mapping) = self.mapping_for(&name) { - let default = Self::default_of(mapping); - if let Some(b) = mouse_button(default) { - return Some(Err(b)); - } - return key_code(default).map(Ok); + let bound: Vec<_> = self + .mappings_for(&name) + .filter_map(|mapping| { + let default = Self::default_of(mapping); + match mouse_button(default) { + Some(b) => Some(Err(b)), + None => key_code(default).map(Ok), + } + }) + .collect(); + if !bound.is_empty() { + return distinct(bound); } if MAPPINGS .iter() .any(|(n, d, _)| *d == name && !self.is_default(n)) { - return None; + return Vec::new(); } - Some(Err(button)) + vec![Err(button)] } /// `AbstractContainerScreen.checkHotbarMouseClicked`: off hand, then hotbar. pub fn container_mouse_key(&self, button: MouseButton, creative: bool) -> Option { diff --git a/crates/horizon-client/src/lan/chunks.rs b/crates/horizon-client/src/lan/chunks.rs index d7dcc6cd8..9ca20b894 100644 --- a/crates/horizon-client/src/lan/chunks.rs +++ b/crates/horizon-client/src/lan/chunks.rs @@ -66,6 +66,7 @@ pub fn block_entity_type(name: &str) -> Option<&'static str> { "sculk_catalyst" => "minecraft:sculk_catalyst", "sculk_shrieker" => "minecraft:sculk_shrieker", "crafter" => "minecraft:crafter", + "potent_sulfur" => "minecraft:potent_sulfur", "chiseled_bookshelf" => "minecraft:chiseled_bookshelf", "trial_spawner" => "minecraft:trial_spawner", "vault" => "minecraft:vault", @@ -952,6 +953,11 @@ pub fn entity_tag(entity: &BlockEntity) -> Option { Some(Tag::compound(entries)) } BlockEntity::Jukebox(_) | BlockEntity::Lectern(_) => None, + // CampfireBlockEntity.getUpdateTag: the items alone. + BlockEntity::Campfire(c) => Some(Tag::compound([( + "Items", + crate::save::encode_items(&c.items), + )])), _ => None, } } diff --git a/crates/horizon-client/src/lan/commands.rs b/crates/horizon-client/src/lan/commands.rs index 71b7fa68d..c3e462348 100644 --- a/crates/horizon-client/src/lan/commands.rs +++ b/crates/horizon-client/src/lan/commands.rs @@ -86,6 +86,18 @@ impl CommandTree { /// The ClientboundCommandsPacket for a player with `level` permissions. pub fn packet(&self, level: u8, dedicated: bool, builtin: &Builtin) -> Commands { + self.packet_with(level, dedicated, builtin, &Value::Null) + } + + /// [`CommandTree::packet`] with more commands after vanilla's: `extra` + /// is a root in the report's format (server mods' commands). + pub fn packet_with( + &self, + level: u8, + dedicated: bool, + builtin: &Builtin, + extra: &Value, + ) -> Commands { let mut nodes = vec![Node { name: String::new(), kind: 0, @@ -99,16 +111,18 @@ impl CommandTree { let suggestions: HashMap<&str, &'static str> = SUGGESTIONS.iter().copied().collect(); let mut paths: HashMap, usize> = HashMap::new(); paths.insert(Vec::new(), 0); - fill( - &self.root, - 0, - &mut Vec::new(), - level, - dedicated, - &suggestions, - &mut nodes, - &mut paths, - ); + for root in [&self.root, extra] { + fill( + root, + 0, + &mut Vec::new(), + level, + dedicated, + &suggestions, + &mut nodes, + &mut paths, + ); + } // enumerateNodes: breadth first from the root, each node's children // (in registration order) then its redirect target. let mut ids = vec![None; nodes.len()]; @@ -365,4 +379,33 @@ mod tests { ); assert!(op.nodes[3].restricted); } + + #[test] + fn server_mods_commands_follow_vanillas() { + let report: Value = serde_json::from_str( + r#"{"type":"root","children":{"me":{"type":"literal","children":{"action":{"type":"argument","parser":"minecraft:message","executable":true}}}}}"#, + ) + .unwrap(); + let mods: Value = serde_json::from_str( + r#"{"type":"root","children":{"beacon":{"type":"literal","executable":true,"children":{ + "height":{"type":"argument","parser":"brigadier:integer","properties":{"min":1,"max":64},"executable":true}}}}}"#, + ) + .unwrap(); + let tree = CommandTree { root: report }; + let packet = tree.packet_with(0, true, &Builtin::default(), &mods); + let names: Vec<_> = packet.nodes.iter().map(|n| n.name.as_str()).collect(); + assert_eq!(names, ["", "me", "beacon", "action", "height"]); + let beacon = &packet.nodes[2]; + assert!(beacon.executable && !beacon.restricted); + assert_eq!(beacon.children, [4]); + let height = packet.nodes[4].parser.as_ref().unwrap(); + assert_eq!(height.1, vec![3, 0, 0, 0, 1, 0, 0, 0, 64]); + // No mods: vanilla's tree as it is. + assert_eq!( + tree.packet_with(0, true, &Builtin::default(), &Value::Null) + .nodes + .len(), + 3 + ); + } } diff --git a/crates/horizon-client/src/lan/conn.rs b/crates/horizon-client/src/lan/conn.rs index fb91f3006..f2dcf701d 100644 --- a/crates/horizon-client/src/lan/conn.rs +++ b/crates/horizon-client/src/lan/conn.rs @@ -823,6 +823,17 @@ fn login_and_configure( _ => {} } }; + // A Horizon client hears that this server runs its mods' quiet commands + // (horizon_protocol::quiet); a vanilla one is told nothing. + if brand == "horizon" { + send( + c, + cfg::Clientbound::CustomPayload(cfg::CustomPayload { + channel: horizon_protocol::quiet::CHANNEL.into(), + data: Vec::new(), + }), + )?; + } for packet in sync.registry_packets(known_pack) { send(c, cfg::Clientbound::RegistryData(packet))?; } diff --git a/crates/horizon-client/src/lan/containers.rs b/crates/horizon-client/src/lan/containers.rs index 7e150e7bd..59f01552e 100644 --- a/crates/horizon-client/src/lan/containers.rs +++ b/crates/horizon-client/src/lan/containers.rs @@ -36,6 +36,30 @@ impl Hub { /// ClientboundSoundPacket for a sound event name (an inline event when /// the registry does not know it). + pub fn sound_packet( + &self, + name: &str, + at: [f64; 3], + volume: f32, + pitch: f32, + source: i32, + seed: i64, + ) -> C { + let sound = match self.sync.id("minecraft:sound_event", name) { + Some(id) => (id, None), + None => (-1, Some((name.to_owned(), None))), + }; + C::Sound(play::Sound { + sound, + source, + x: (at[0] * 8.0) as i32, + y: (at[1] * 8.0) as i32, + z: (at[2] * 8.0) as i32, + volume, + pitch, + seed, + }) + } pub fn sound( &self, name: &str, @@ -45,20 +69,7 @@ impl Hub { source: i32, except: Option, ) { - let sound = match self.sync.id("minecraft:sound_event", name) { - Some(id) => (id, None), - None => (-1, Some((name.to_owned(), None))), - }; - let packet = C::Sound(play::Sound { - sound, - source, - x: (at[0] * 8.0) as i32, - y: (at[1] * 8.0) as i32, - z: (at[2] * 8.0) as i32, - volume, - pitch, - seed: self.ticks as i64, - }); + let packet = self.sound_packet(name, at, volume, pitch, source, self.ticks as i64); self.broadcast_near(at, f64::from(volume.max(1.0)) * 16.0, &packet, except); } @@ -120,6 +131,22 @@ impl Hub { ); } + /// `ServerPlayer.crit` (`magicCrit` when `magic`): send the victim's + /// animation to the players tracking the attacker and the attacker + /// themselves (`sendToTrackingPlayersAndSelf`). + pub fn critical_hit(&self, attacker: i32, target: i32, magic: bool) { + let body = C::Animate(play::Animate { + id: target, + action: if magic { 2 } else { 1 }, + }) + .encode(); + for g in self.guests.iter().filter(|g| { + self.here(g) && (g.entity_id == attacker || g.tracker.is_tracking(attacker)) + }) { + g.sender.send(body.clone()); + } + } + /// `ServerLevel.broadcastDamageEvent`: the clients around show the hurt /// entity's flash and hear its hurt sound. pub fn damage_event( @@ -406,6 +433,42 @@ impl Hub { drops } + /// `AbstractContainerMenu.setSelectedBundleItemIndex` on the guest's open + /// menu: a container's own slots, or the inventory's. A bundle's selection + /// lives on the server's stack until the click that takes from it. + pub fn select_bundle_item(&mut self, conn: u32, slot: usize, index: i32, world: &mut World) { + let Some(g) = self.guests.iter_mut().find(|g| g.conn == conn) else { + return; + }; + let open = g.menu.as_ref().map(|m| (m.size, m.slots)); + let mut items = match open { + Some((size, source)) if slot < size => source.read(world, g), + _ => None, + }; + let stack = match open { + Some((size, _)) if slot < size => items + .as_mut() + .and_then(|items| items.get_mut(slot)) + .and_then(Option::as_mut), + Some((size, _)) => g + .inventory + .get_mut(player_slot(slot - size)) + .and_then(Option::as_mut), + None => match slot { + 9..=35 => g.inventory.get_mut(slot).and_then(Option::as_mut), + 36..=44 => g.inventory.get_mut(slot - 36).and_then(Option::as_mut), + 45 => g.offhand.as_mut(), + _ => None, + }, + }; + if let Some(stack) = stack { + crate::bundle::toggle_selected(stack, index); + } + if let (Some((_, source)), Some(items)) = (open, items) { + source.write(world, g, items); + } + } + /// A click on the inventory menu (window 0) the game applied itself /// (the crafting grid): the client is corrected like after any click. pub fn inventory_clicked( diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index ae3089006..920052b5a 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -611,8 +611,9 @@ pub struct Viewer<'a> { } /// 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). +/// horizontally, its id, its tracking range in blocks (scaled by +/// `entity-broadcast-range-percentage`) and the chunk it is in (an index +/// into the tick's chunks). #[derive(Clone, Copy)] struct Probe { x: f64, @@ -627,7 +628,7 @@ struct Probe { /// 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 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]; @@ -641,6 +642,9 @@ fn sees(v: &Viewer, p: &Probe, chunks: &[(i32, i32)], held: &mut [u8]) -> bool { /// One level's tracked entities (ChunkMap.entityMap). #[derive(Default)] pub struct Entities { + /// `entity-broadcast-range-percentage` (None: 100), which scales every + /// type's tracking range (MinecraftServer.getScaledTrackingDistance). + pub range_percent: Option, states: crate::fast_hash::FxHashMap, /// The level tick, stamped on every entity still in the level. tick: u32, @@ -732,7 +736,9 @@ impl Entities { x: e.position[0], z: e.position[2], id: e.id, - range: s.range, + range: self + .range_percent + .map_or(s.range * 16, |p| p * (s.range * 16) / 100), chunk, }); } diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index aa1994257..7e43cf04e 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -237,6 +237,8 @@ pub struct Guest { pub drag: Option<(u8, Vec)>, /// The compound this player was loaded from, for fields Horizon does not model. pub saved: Option, + /// `ServerPlayer.seenCredits`: the end poem has been shown. + pub seen_credits: bool, /// `ServerPlayer.recipeBook`. pub recipe_book: crate::recipe_book::Settings, /// `PlayerAdvancements`: the criteria obtained, whether they came from @@ -358,6 +360,7 @@ impl Guest { next_window: 0, drag: None, saved: None, + seen_credits: false, recipe_book: Default::default(), advancements: Default::default(), advancements_loaded: false, @@ -601,6 +604,18 @@ fn network_stack( horizon_protocol::item::Component::Stacks(charged), )); } + // What a bundle holds, for its tooltip (ClientBundleTooltip). + if !d.bundle_contents.is_empty() { + let contents = d + .bundle_contents + .iter() + .filter_map(|c| network_stack(item_id, synced_id, &Some(c.clone()))) + .collect(); + stack.added.push(( + horizon_protocol::item::component::BUNDLE_CONTENTS, + horizon_protocol::item::Component::Stacks(contents), + )); + } // The books a lectern shows and a guest reads. if !d.writable_pages.is_empty() { stack.added.push(( @@ -633,6 +648,13 @@ fn network_stack( horizon_protocol::item::Component::Text(horizon_protocol::text::literal(name)), )); } + // The component as loaded, so a translatable name stays one. + if let Some(name) = s.data().and_then(|d| d.other("minecraft:item_name")) { + stack.added.push(( + horizon_protocol::item::component::ITEM_NAME, + horizon_protocol::item::Component::Text(name.clone()), + )); + } Some(stack) } diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 910911d80..f9b6e8ce7 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -21,7 +21,7 @@ use crate::{ use horizon_core::geometry::{Aabb, ShapeOp, Vec3, VoxelShape}; use horizon_protocol::ids::play::clientbound as ids; use horizon_protocol::{ - entity_data::{Value, serializer}, + entity_data::{Particle, ParticleData, Value, serializer}, packets::play::{self, Clientbound as C, Serverbound as S}, text::{literal, translatable}, }; @@ -87,6 +87,29 @@ pub struct HostState { pub living_flags: i8, /// The bed the host sleeps in (`LivingEntity.SLEEPING_POS`). pub bed: Option<[i32; 3]>, + pub body: BodyFlags, +} + +/// What the other players see of a player's body besides sneaking and +/// sprinting: the pose and the rest of `Entity.DATA_SHARED_FLAGS_ID`. +#[derive(Clone, Copy, Debug, Default)] +pub struct BodyFlags { + /// `Entity.isFallFlying`: gliding with elytra. + pub gliding: bool, + /// `Entity.isSwimming` (the swimming flag). + pub swimming: bool, + /// The swimming pose of a player crawling under a block. + pub crawling: bool, + /// The crouching pose, held without sneaking under a low ceiling. + pub crouching: bool, + /// `LivingEntity.isAutoSpinAttack`: Riptide's spin. + pub spin_attack: bool, + /// `Entity.isOnFire`. + pub on_fire: bool, + /// `Entity.isInvisible`: the invisibility effect. + pub invisible: bool, + /// The glowing effect. + pub glowing: bool, } /// Everything the hub needs from the game for one tick. @@ -128,6 +151,11 @@ pub enum HostEvent { line: String, secure: bool, }, + /// A chat message a player sent (after it was broadcast), for server mods. + PlayerChat { + sender: u128, + text: String, + }, /// A server log warning (ServerGamePacketListenerImpl's LOGGER.warn). Warn(String), /// A server log error (LOGGER.error). @@ -163,6 +191,8 @@ pub struct Hub { level_sync: std::collections::HashMap, /// Operators and their permission levels (dedicated servers). pub ops: std::collections::HashMap, + /// `entity-broadcast-range-percentage` (dedicated servers). + pub entity_range_percent: i32, chat_type: i32, dimension_type: i32, clock_ids: Vec, @@ -172,6 +202,9 @@ pub struct Hub { entities: std::collections::HashMap, /// What one tick of entity tracking sends each guest, kept between ticks. entity_out: Vec>>, + /// Server mods' commands, a root in the commands report's format, sent + /// after vanilla's; the key the game last set them for. + mod_commands: (serde_json::Value, Option), } fn string(s: &str) -> Tag { @@ -327,6 +360,7 @@ impl Hub { ticking: (20.0, false), stepping: 0, ops: Default::default(), + entity_range_percent: 100, weather: (false, 0.0, 0.0), level_sync: Default::default(), chat_type, @@ -336,6 +370,7 @@ impl Hub { entity_types: Default::default(), entities: Default::default(), entity_out: Vec::new(), + mod_commands: (serde_json::Value::Null, None), teams: Vec::new(), } } @@ -371,9 +406,21 @@ impl Hub { id } pub fn stack(&mut self, s: &Option) -> Option { - let id = s.as_ref().map(|s| self.item_id(&s.item))?; + let item = s.as_ref()?.item.clone(); + let id = self.item_id(&item); let sync = self.sync.clone(); - stack_to_network(|_| id, |registry, name| sync.id(registry, name), s) + // The stacks inside it (a bundle's contents, a crossbow's projectiles) + // have ids of their own. + let item_id = |name: &str| { + if name == &*item { + return id; + } + sync.builtin + .get("minecraft:item") + .and_then(|i| i.id(name)) + .unwrap_or(0) + }; + stack_to_network(item_id, |registry, name| sync.id(registry, name), s) } pub fn broadcast(&self, packet: &C) { @@ -832,13 +879,36 @@ impl Hub { } } + /// The key [`Hub::set_mod_commands`] last had: the game compares it + /// with its server mods' each tick. + pub fn mod_commands_key(&self) -> Option { + self.mod_commands.1 + } + /// Server mods' commands changed: every player gets their tree again. + pub fn set_mod_commands(&mut self, key: u64, commands: serde_json::Value) { + let resend = self.mod_commands.0 != commands; + self.mod_commands = (commands, Some(key)); + if resend { + for i in 0..self.guests.len() { + if self.guests[i].placed { + self.send_commands(i); + } + } + } + } + /// Commands.sendCommands: the command tree for this player. fn send_commands(&self, i: usize) { let g = &self.guests[i]; let packet = match &self.sync.commands { Some(tree) => { let dedicated = self.config.dedicated && !self.config.integrated; - tree.packet(g.permission, dedicated, &self.sync.builtin) + tree.packet_with( + g.permission, + dedicated, + &self.sync.builtin, + &self.mod_commands.0, + ) } None => play::Commands { nodes: vec![play::CommandNode { @@ -1483,6 +1553,49 @@ impl Hub { // ---- entities ------------------------------------------------------ + /// `LivingEntity.updateSynchronizedMobEffectParticles`: DATA_EFFECT_PARTICLES + /// (10) and DATA_EFFECT_AMBIENCE_ID (11) for the visible `effects`, as + /// (effect, ambient). The entries are left out when there is nothing to + /// show, which is their default. + pub fn effect_meta<'a>( + &self, + effects: impl IntoIterator, + ) -> Vec<(u8, i32, Value)> { + let mut particles = Vec::new(); + let mut all_ambient = true; + for (effect, ambient) in effects { + let effect = effect.trim_start_matches("minecraft:"); + // MobEffect.particleFactory: the omens have their own particles, + // the others an entity effect in their colour (faint if ambient). + let (name, data) = match effect { + "trial_omen" | "raid_omen" => (effect, None), + _ => { + let Some(def) = crate::brewing::effect(effect) else { + continue; + }; + let alpha = if ambient { 38 } else { 255 }; + let argb = (alpha << 24) | def.color as i32; + ("entity_effect", Some(ParticleData::Color(argb))) + } + }; + let Some(id) = + self.registry_id("minecraft:particle_type", &format!("minecraft:{name}")) + else { + continue; + }; + particles.push(Particle { id, data }); + all_ambient &= ambient; + } + if particles.is_empty() { + return Vec::new(); + } + let mut meta = vec![(10, serializer::PARTICLES, Value::Particles(particles))]; + if all_ambient { + meta.push((11, serializer::BOOLEAN, Value::Bool(true))); + } + meta + } + fn player_state( &self, id: i32, @@ -1490,21 +1603,29 @@ impl Hub { position: [f64; 3], rot: (f32, f32, f32), on_ground: bool, - flags: (bool, bool, bool, bool), + flags: (bool, bool, bool), + body: BodyFlags, living_flags: i8, bed: Option<[i32; 3]>, skin: u8, health: f32, equipment: Vec<(u8, Option)>, attributes: Vec, + effects: &[EffectInstance], ) -> EntityState { - let (sneaking, sprinting, gliding, sleeping) = flags; - let shared = shared_flags(sneaking, sprinting, gliding); + let (sneaking, sprinting, sleeping) = flags; + let shared = shared_flags(sneaking, sprinting, &body); + // Player.getDesiredPose (and updatePlayerPose's crawl): sleeping, + // swimming, gliding, Riptide's spin, crouching. let pose = if sleeping { 2 - } else if gliding { + } else if body.swimming || body.crawling { + 3 + } else if body.gliding { 1 - } else if sneaking { + } else if body.spin_attack { + 4 + } else if sneaking || body.crouching { 5 } else { 0 @@ -1530,6 +1651,14 @@ impl Hub { if skin != 0 { meta.push((16, serializer::BYTE, Value::Byte(skin as i8))); } + meta.extend( + self.effect_meta( + effects + .iter() + .filter(|e| e.visible) + .map(|e| (e.id, e.ambient)), + ), + ); EntityState { id, uuid, @@ -1542,7 +1671,11 @@ impl Hub { velocity: [0.0; 3], data: 0, meta, - defaults: Vec::new(), + // The effect swirls go back to none. + defaults: vec![ + (10, serializer::PARTICLES, Value::Particles(Vec::new())), + (11, serializer::BOOLEAN, Value::Bool(false)), + ], equipment, attributes, precise: false, @@ -1590,13 +1723,15 @@ impl Hub { h.position, (h.yaw, h.pitch, h.head_yaw), h.on_ground, - (h.sneaking, h.sprinting, false, h.bed.is_some()), + (h.sneaking, h.sprinting, h.bed.is_some()), + h.body, h.living_flags, h.bed, 0x7F, h.health, equipment, h.attributes.clone(), + &[], )); } let placed: Vec = (0..self.guests.len()) @@ -1622,7 +1757,8 @@ impl Hub { g.position, (g.yaw, g.pitch, g.head_yaw), g.on_ground, - (g.sneaking, g.sprinting, g.fall_flying, g.sleeping), + (g.sneaking, g.sprinting, g.sleeping), + guest_body(g), g.living_flags, g.bed, g.info.model_customisation, @@ -1632,6 +1768,7 @@ impl Hub { .as_ref() .map(|m| super::attributes::syncable(&m.attributes)) .unwrap_or_default(), + &g.effects.list, ) }) .collect(); @@ -1661,6 +1798,7 @@ impl Hub { out, }) .collect(); + level.range_percent = Some(self.entity_range_percent); let (types, sync) = (&mut self.entity_types, &self.sync); level.tick(&entities, &self.riding, &mut viewers, |kind| { entity_type(types, sync, kind) @@ -1781,7 +1919,7 @@ impl Hub { // too, so the sprint a hit stops (Player.causeExtraKnockback) stops // on its client. let g = &mut self.guests[i]; - let shared = shared_flags(g.sneaking, g.sprinting, g.fall_flying); + let shared = shared_flags(g.sneaking, g.sprinting, &guest_body(g)); if shared != g.sent_shared { g.sent_shared = shared; g.send(&C::SetEntityData(play::SetEntityData { @@ -2026,6 +2164,20 @@ impl Hub { 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), + // handlePlayerAction (a dig starting, stopping or finishing) is the + // game's, run after this pass. A move queued behind it is checked + // against the block the player just broke and falls through, so it + // would be sent back; it waits for the next tick, when the block is + // gone, as vanilla handles the two packets in order. + S::PlayerAction(p) if p.action <= 3 => { + events.push(HostEvent::Packet(conn, Box::new(S::PlayerAction(p)))); + if matches!( + self.guests[i].inbox.front(), + Some(S::MovePlayerPos(_) | S::MovePlayerPosRot(_)) + ) { + break; + } + } other => events.push(HostEvent::Packet(conn, Box::new(other))), } } @@ -2561,16 +2713,44 @@ fn ticking_state(rate: f32, frozen: bool) -> C { raw(ids::TICKING_STATE, w.data) } -/// Entity.DATA_SHARED_FLAGS_ID of a player: crouching, sprinting, gliding. -fn shared_flags(sneaking: bool, sprinting: bool, gliding: bool) -> i8 { +/// What the others see of a guest's body, from its server-side state. +fn guest_body(g: &Guest) -> BodyFlags { + let m = g.motion.as_deref(); + BodyFlags { + gliding: g.fall_flying, + swimming: m.is_some_and(|m| m.swimming), + crawling: m.is_some_and(|m| m.pose == crate::pose::Pose::Swimming && !m.swimming), + crouching: m.is_some_and(|m| m.pose == crate::pose::Pose::Crouching), + spin_attack: m.is_some_and(|m| m.auto_spin_attack_ticks > 0), + on_fire: m.is_some_and(|m| m.fire_ticks > 0), + invisible: g.effects.get("invisibility").is_some(), + glowing: g.effects.get("glowing").is_some(), + } +} + +/// Entity.DATA_SHARED_FLAGS_ID of a player: on fire 0x01, crouching 0x02, +/// sprinting 0x08, swimming 0x10, invisible 0x20, glowing 0x40, gliding 0x80. +fn shared_flags(sneaking: bool, sprinting: bool, body: &BodyFlags) -> i8 { let mut shared = 0i8; + if body.on_fire { + shared |= 0x01; + } if sneaking { shared |= 0x02; } if sprinting { shared |= 0x08; } - if gliding { + if body.swimming { + shared |= 0x10; + } + if body.invisible { + shared |= 0x20; + } + if body.glowing { + shared |= 0x40; + } + if body.gliding { shared |= -128; } shared diff --git a/crates/horizon-client/src/lan/hub/chat.rs b/crates/horizon-client/src/lan/hub/chat.rs index bdc7c3fb2..591c0dfc5 100644 --- a/crates/horizon-client/src/lan/hub/chat.rs +++ b/crates/horizon-client/src/lan/hub/chat.rs @@ -219,6 +219,10 @@ impl Hub { }; let line = format!("<{name}> {}", message.content); self.broadcast_chat(&message, &bound, line, events); + events.push(HostEvent::PlayerChat { + sender: uuid, + text: message.content, + }); } /// handleChatSessionUpdate: a new profile key, validated against the diff --git a/crates/horizon-client/src/lan/menu.rs b/crates/horizon-client/src/lan/menu.rs index 4185dadc4..641e45b1b 100644 --- a/crates/horizon-client/src/lan/menu.rs +++ b/crates/horizon-client/src/lan/menu.rs @@ -5,7 +5,7 @@ //! menu are returned for the game to drop. use super::guest::Guest; use crate::{ - bundle::{Contents, can_be_in_bundle}, + bundle::{Contents, can_be_in_bundle, toggle_selected}, items::{ItemStack, Items}, world::World, }; @@ -37,6 +37,10 @@ pub struct Menu { pub sent_data: Vec, } +/// The y of the key a chest minecart's or chest boat's items are kept under +/// while a menu shows them. +pub const VEHICLE_KEY_Y: i32 = -100_000; + /// Where the slots of a container menu live. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Slots { @@ -72,10 +76,12 @@ impl Slots { Slots::Ender => at.into_iter().collect(), _ => self.halves(), }; + // A vehicle's container is kept under a key, not a block: the game + // checks its reach to the vehicle (`isChestVehicleStillValid`). self.valid(world) && blocks .iter() - .all(|k| guest.within_block_range([k.0, k.1, k.2], 4.0)) + .all(|k| k.1 == VEHICLE_KEY_Y || guest.within_block_range([k.0, k.1, k.2], 4.0)) } /// Container slot `n`. pub fn get(self, world: &World, guest: &Guest, mut n: usize) -> Option { @@ -508,7 +514,10 @@ fn bundle_click(view: &mut View, i: usize, right: bool, rules: &dyn Rules) -> bo } } (carried, _) => { + // toggleSelectedItem(-1), then the click goes on. view.guest.carried = carried; + toggle_selected(&mut bundle, -1); + view.set(i, Some(bundle)); return false; } } diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index 90fe0bcfe..f5eb935c9 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -85,6 +85,7 @@ pub fn apply(guest: &mut Guest, level: &Level) { .map(|s| [s[0] + 0.5, s[1], s[2] + 0.5]); guest.respawn_elsewhere = level.respawn_elsewhere.clone(); guest.saved = level.player_extra.clone(); + guest.seen_credits = level.seen_credits; let extra = level.player_extra.as_ref(); let short = |key: &str, default: i64| { extra @@ -166,6 +167,7 @@ pub fn store(guest: &Guest, level: &mut Level) { level.spawn = guest.spawn.map(|s| [s[0] - 0.5, s[1], s[2] - 0.5]); level.respawn_elsewhere = guest.respawn_elsewhere.clone(); level.on_ground = guest.on_ground; + level.seen_credits = guest.seen_credits; level.player_extra = guest.saved.clone(); // The live body's fire, air and fall distance (Entity.saveWithoutId), // or what the file had while the player has no body yet. diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 6bf40d1f0..fa5ef1c4d 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -19,13 +19,11 @@ pub mod biome; pub mod block_entities; pub mod block_entity_anim; pub mod block_entity_item; -pub mod block_entity_nbt; pub mod block_entity_render; pub mod block_transform; pub mod blocks; pub mod border_render; pub mod boss_overlay; -pub mod bossbar; pub mod breaking; pub mod brewing; pub mod bundle; @@ -38,10 +36,8 @@ pub mod clipboard; pub mod clock; pub mod clouds; pub mod collisions; -pub mod command; pub mod command_block; pub mod command_storage; -pub mod component; pub mod confirm_screen; pub mod container_screen; pub mod containers; @@ -50,6 +46,7 @@ pub mod cooldowns; pub mod crafting; pub mod crash; pub mod creative; +pub mod cushion; pub mod data_cmd; pub mod datapack; pub mod debug_chart; @@ -70,7 +67,6 @@ pub mod extras; pub mod extras_hud; pub mod falling_block; pub mod fast_hash; -pub mod fastutil_order; pub mod fire_render; pub mod first_person; pub mod flatgen; @@ -79,7 +75,6 @@ pub mod font; pub mod friends_screen; pub mod game_mode_switcher; pub mod gamepad; -pub mod gamerules; pub mod gfx; pub mod gizmos; pub mod gossip; @@ -108,7 +103,6 @@ pub mod keybinds; pub mod keymapping; pub mod lan; pub mod landing; -pub mod lang; pub mod level_loading; pub mod light; pub mod locator_bar; @@ -130,7 +124,6 @@ pub mod mouse; pub mod moved_extras; pub mod multiplayer; pub mod music; -pub mod nbt_path; pub mod net; pub mod nether_portal; pub mod offline_name; @@ -159,7 +152,6 @@ pub mod recipe_book; pub mod recipe_book_screen; pub mod reconnect; pub mod save; -pub mod scoreboard; pub mod scoreboard_cmd; pub mod screen_draw; pub mod screen_effects; @@ -172,7 +164,6 @@ pub mod shader_pack_list; pub mod shadows; pub mod signs; pub mod skins; -pub mod snbt; pub mod sound_engine; pub mod sound_events; pub mod spans; @@ -185,7 +176,6 @@ pub mod structure_blocks; pub mod tab_list; pub mod telemetry; pub mod testgen; -pub mod text; pub mod text_display; pub mod tick_chunk_membership; pub mod ticket_levels; @@ -205,4 +195,15 @@ pub mod world; pub mod world_spawn; pub mod worldborder; pub mod zip; -pub type Result = std::result::Result>; +pub use horizon_client_core::Result; +pub use horizon_client_core::block_entity_nbt; +pub use horizon_client_core::bossbar; +pub use horizon_client_core::component; +pub use horizon_client_core::fastutil_order; +pub use horizon_client_core::gamerules; +pub use horizon_client_core::lang; +pub use horizon_client_core::nbt_path; +pub use horizon_client_core::scoreboard; +pub use horizon_client_core::snbt; +pub use horizon_client_core::text; +pub use horizon_command as command; diff --git a/crates/horizon-client/src/lod.rs b/crates/horizon-client/src/lod.rs index a429863a7..1ee61cdf4 100644 --- a/crates/horizon-client/src/lod.rs +++ b/crates/horizon-client/src/lod.rs @@ -752,6 +752,25 @@ impl Lod { saved_order: VecDeque::new(), } } + /// The solid ground at block column (x, z): its top face's height and + /// its block, from the finest tile sampled there. For aiming past the + /// resident chunks (`game.raycast`); water is passed, as the view's ray + /// passes it. + pub fn ground(&self, x: i32, z: i32) -> Option<(i32, BlockStateId)> { + (0..=MAX_LEVEL).find_map(|level| { + let size = 16 << level; + let key = TileKey { + x: x.div_euclid(size), + z: z.div_euclid(size), + level, + }; + let columns = self.ready.get(&key).filter(|c| c.len() == CELLS * CELLS)?; + let cell = size / CELLS as i32; + let (cx, cz) = ((x - key.x * size) / cell, (z - key.z * size) / cell); + let surface = columns[cz as usize * CELLS + cx as usize].surface?; + Some((surface.height, surface.state)) + }) + } pub fn stats(&self) -> (usize, usize) { (self.active.len(), self.ready.len()) } diff --git a/crates/horizon-client/src/menu/bundle.rs b/crates/horizon-client/src/menu/bundle.rs index fba4a488e..78a52655a 100644 --- a/crates/horizon-client/src/menu/bundle.rs +++ b/crates/horizon-client/src/menu/bundle.rs @@ -1,7 +1,7 @@ //! `BundleItem`'s click overrides in a PICKUP click //! (`tryItemClickBehaviourOverride`). use super::{Env, Menu, tidy}; -use crate::bundle::{Contents, INSERT, INSERT_FAIL, REMOVE_ONE, can_be_in_bundle}; +use crate::bundle::{Contents, INSERT, INSERT_FAIL, REMOVE_ONE, can_be_in_bundle, toggle_selected}; impl Menu { /// The carried stack's `overrideStackedOnOther`, then the clicked @@ -88,8 +88,11 @@ impl Menu { } } (carried, _) => { - // toggleSelectedItem(-1): Horizon keeps no selected item. + // toggleSelectedItem(-1), then the click goes on. self.carried = carried; + toggle_selected(&mut bundle, -1); + let slot = self.slots[s]; + self.containers[slot.container][slot.index] = Some(bundle); return false; } } diff --git a/crates/horizon-client/src/mesher.rs b/crates/horizon-client/src/mesher.rs index fff3c6aa0..48d2f08bd 100644 --- a/crates/horizon-client/src/mesher.rs +++ b/crates/horizon-client/src/mesher.rs @@ -113,6 +113,14 @@ mod vertex_tests { assert!((a - b).abs() <= 0.5 / 32768.0, "{a} {b}"); } } + #[test] + fn emission_keeps_the_colour_and_the_free_bits() { + let rgb = super::pack_rgb([0x12, 0x34, 0x56]); + assert_eq!(super::emitting(rgb, 0), rgb); + assert_eq!(super::emitting(rgb, 9), 0xF656_3412); + assert_eq!(super::emitting(rgb, 15), 0xF056_3412); + assert_eq!(super::emitting(rgb, 15) | super::EMISSION_BITS, rgb); + } } pub struct SectionMesh { pub solid: Vec, @@ -566,6 +574,14 @@ impl Padded { } /// Set on a terrain vertex's sprite layer when its texture alpha must be ignored. pub const OPAQUE_LAYER: u16 = 1 << 15; +/// The bits of `TerrainVertex::color`'s alpha byte that hold the light its face emits, for +/// HDR output's highlights (`gfx/hdr.rs`): 15 minus the level, so the usual 0xFF means none. +/// The byte's other four bits stay set. +pub const EMISSION_BITS: u32 = 0x0F00_0000; +/// `color` marked as emitting light `level` (0 to 15). +pub fn emitting(color: u32, level: u8) -> u32 { + color & !EMISSION_BITS | u32::from(15 - level.min(15)) << 24 +} const UNSET: u32 = u32::MAX; const NO_BIOME: u16 = u16::MAX; /// The `ColorResolver`s `ClientLevel` caches block tints for. @@ -880,7 +896,7 @@ impl Mesher<'_> { } else { face.layer as u16 }, - pack_rgb(rgb), + emitting(pack_rgb(rgb), state.emission.max(q.light_emission)), pack_coords(lighting::with_emission(coords[i], q.light_emission)), )); } diff --git a/crates/horizon-client/src/mesher/fluid.rs b/crates/horizon-client/src/mesher/fluid.rs index 6e42685ba..d30b914a4 100644 --- a/crates/horizon-client/src/mesher/fluid.rs +++ b/crates/horizon-client/src/mesher/fluid.rs @@ -227,8 +227,11 @@ pub(super) fn tesselate( } else { 0xFF_FFFF }; + // Lava emits light level 15. + let emission = if water { 0 } else { 15 }; let color = |by: f32| { - pack_rgb([16, 8, 0].map(|shift| lighting::scale((tint >> shift & 255) as i32, by) as u32)) + let rgb = [16, 8, 0].map(|shift| lighting::scale((tint >> shift & 255) as i32, by) as u32); + crate::mesher::emitting(pack_rgb(rgb), emission) }; let height = |p: [i32; 3]| -> f32 { let s = at(p); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 1b5dddbe7..2325c3f5b 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -25,6 +25,7 @@ pub mod creaking; pub mod creaking_heart; pub mod cube; pub mod data; +pub mod doors; pub mod drops; pub mod enderman; pub mod equine; @@ -49,6 +50,7 @@ pub mod nether; pub mod path; pub mod phantom; pub mod piglin; +pub mod polar_bear; pub mod rabbit; pub mod raider; pub mod ravager; @@ -68,6 +70,7 @@ pub mod tame; pub mod trader; pub mod transport_items; pub mod trial_spawner; +pub mod turtle; pub mod undead; pub mod vex; pub mod villager; @@ -515,6 +518,8 @@ pub enum DamageKind { InFire, Lava, Drown, + /// `dry_out`: an axolotl out of water for too long. + DryOut, Magic, Sting, Cactus, @@ -573,7 +578,11 @@ impl Damage { pub fn causes_panic(&self) -> bool { !matches!( self.kind, - DamageKind::Fall | DamageKind::Drown | DamageKind::Generic | DamageKind::InWall + DamageKind::Fall + | DamageKind::Drown + | DamageKind::DryOut + | DamageKind::Generic + | DamageKind::InWall ) } /// DamageTypeTags.BYPASSES_ARMOR @@ -606,6 +615,7 @@ impl Damage { | DamageKind::InFire | DamageKind::Lava | DamageKind::Drown + | DamageKind::DryOut | DamageKind::Magic | DamageKind::Cactus | DamageKind::Generic @@ -636,6 +646,8 @@ pub struct Attrs { pub struct Extra { /// Players: crouching and riding (HumanoidModel's poses). pub crouching: bool, + /// Players: sprinting (`Entity.DATA_SHARED_FLAGS_ID`), for the dust they raise. + pub sprinting: bool, pub passenger: bool, /// AgeableMob.age: negative while a baby (a tadpole counts up to 24000). pub age: i32, @@ -665,6 +677,8 @@ pub struct Extra { pub chested: bool, /// The chest contents of a donkey or mule (15 slots). pub items: Vec>, + /// `Piglin.inventory` (`SimpleContainer(8)`): what it picked up and kept. + pub inventory: Vec, pub tame: bool, pub sitting: bool, /// The owner's UUID (tamed animals). @@ -709,9 +723,18 @@ pub struct Extra { /// A copper golem's `openedChestPos`. pub opened_chest: Option<[i32; 3]>, pub point: Option<[f64; 3]>, + /// `NEAREST_REPELLENT`: the nearest repelling block a hoglin or piglin + /// sensed, looked up every 20 ticks. + pub repellent: Option<[i32; 3]>, pub vector: [f64; 3], /// Active status effects: (effect id, ticks left, amplifier). pub effects: Vec<(&'static str, i32, i32)>, + /// The effects above given with `hideParticles`: no swirls for them. + pub hidden_effects: Vec<&'static str>, + /// `LivingEntity.DATA_EFFECT_PARTICLES` and `DATA_EFFECT_AMBIENCE_ID` as a + /// server gave them: the swirls around it, and whether they are all faint. + pub effect_particles: Vec, + pub effect_ambient: bool, /// An invisible illusioner's mirror images. pub illusions: Option, /// A villager's claimed bed head and meeting bell. @@ -723,6 +746,8 @@ pub struct Extra { /// the spin the rope's torque gives it. pub leash: Option, pub leash_pending: Option, + /// The UUID of the player behind `Holder::Player` (host or guest). + pub leash_player: Option<[i32; 4]>, pub leash_spin: f64, /// More species scratch values. pub scratch: [i32; 4], @@ -868,6 +893,11 @@ pub struct Mob { /// Events a mob tick asks the game to act on. #[derive(Clone, Debug)] pub enum MobEvent { + /// Squid.handleEntityEvent(19), resetting the remote tentacle cycle. + SquidCycle { + mob: u32, + at: [f64; 3], + }, /// Rabbit entity event 1, sent only when a ground jump actually happens. RabbitHop { mob: u32, @@ -965,6 +995,14 @@ pub enum MobEvent { owner: u32, }, Shoot([f64; 3], [f64; 3]), + /// The mob the `Explode` right after this comes from + /// (`ServerExplosion.source`), and whether it is a charged creeper: the + /// exploding creeper is already out of the mob list when the game applies + /// the blast, so its victims' loot cannot look it up. + ExplosionSource { + mob: u32, + charged: bool, + }, Explode([f64; 3], f32), /// Melee or ranged damage to another mob. AttackMob { @@ -1001,6 +1039,24 @@ pub enum MobEvent { pos: [i32; 3], open: bool, }, + /// `BreakDoorGoal.tick` at its end: the door is removed (`removeBlock`), + /// then level events 1021 and 2001 with the state that is left there. + BreakDoor { + pos: [i32; 3], + }, + /// `Level.destroyBlockProgress` for a mob's crack on a block (`-1` + /// clears it). + DestroyProgress { + mob: u32, + pos: [i32; 3], + progress: i32, + }, + /// `Level.levelEvent`: the game plays and sends the event. + LevelEvent { + id: i32, + pos: [i32; 3], + data: i32, + }, /// Destroy a block, dropping nothing (sheep eating grass becomes dirt via SetBlock). BreakBlock { pos: [i32; 3], @@ -1098,6 +1154,13 @@ pub enum MobEvent { partner: u32, child: Option<([i32; 3], Option)>, }, + /// `WorkAtComposter.useWorkstation`: a farmer at its composter makes + /// bread and composts seeds (the game applies it to the villager's + /// inventory and the block). + WorkAtComposter { + mob: u32, + pos: [i32; 3], + }, /// A villager asks whether enough neighbours want an iron golem. GolemCheck { mob: u32, @@ -1126,8 +1189,10 @@ pub enum MobEvent { target: Who, aggressive: bool, }, - /// Drop the loot of a gift table (chicken eggs, armadillo scutes). + /// Drop the loot of a gift table (chicken eggs, sniffer seeds) with the + /// mob as `this` (`LivingEntity.dropFromGiftLootTable`). GiftLoot { + mob: u32, table: &'static str, at: [f64; 3], }, @@ -1151,6 +1216,18 @@ pub enum MobEvent { DigParticles { at: [f64; 3], }, + /// `Zombie.hurtServer`: a zombie hurt with a target in sight (its own, + /// else the attacker) may call a reinforcement against it on Hard. + Reinforcements { + mob: u32, + target: Who, + }, + /// `LevelEvent.PARTICLES_DESTROY_BLOCK` (2001) at `pos` for the block at + /// `block`: a turtle's digging. + BlockBreakEffect { + pos: [i32; 3], + block: [i32; 3], + }, /// `Warden.applyDarknessAround`: darkness for survival players nearby. Darkness { at: [f64; 3], @@ -1243,6 +1320,18 @@ pub struct Seen { /// `MAX_HEALTH`, `JUMP_STRENGTH` and `MOVEMENT_SPEED` base values (a /// horse's breeding stock). pub stats: [f64; 3], + /// `Wolf.isInSittingPose`. + pub sitting: bool, + /// `Entity.isVehicle` or `isPassenger`. + pub ridden: bool, + /// The active effects, without namespace (`slowness`, `poison`...). + pub effects: Vec<&'static str>, +} +impl Seen { + /// `LivingEntity.hasEffect`, by id without namespace. + pub fn has_effect(&self, effect: &str) -> bool { + self.effects.contains(&effect) + } } impl Mob { pub fn burning_time(&self) -> f64 { @@ -1315,6 +1404,14 @@ impl Mob { m.extra.vector[0], m.attrs.speed, ], + sitting: m.extra.sitting, + ridden: m.rider.is_some() || m.extra.rider.is_some() || m.extra.mount.is_some(), + effects: m + .extra + .effects + .iter() + .map(|e| e.0.trim_start_matches("minecraft:")) + .collect(), } } /// `EntityType.getCategory`'s name. @@ -1459,6 +1556,8 @@ pub struct PlayerView { pub yaw: f32, /// The Hero of the Village effect. pub hero: bool, + /// The active effects, without namespace (`slowness`, `poison`...). + pub effects: Vec<&'static str>, /// The player's UUID (villagers' gossip is keyed by it). pub uuid: [i32; 4], /// The mobs on the player's team (`isAlliedTo`): combat targeting @@ -1468,6 +1567,12 @@ pub struct PlayerView { /// (`EntitySelector.pushableBy` on the client). pub remote: bool, } +impl PlayerView { + /// `LivingEntity.hasEffect`, by id without namespace. + pub fn has_effect(&self, effect: &str) -> bool { + self.effects.contains(&effect) + } +} #[derive(Clone)] pub struct MobWorld<'a> { pub world: &'a World, @@ -1752,6 +1857,10 @@ impl Mob { self.health -= amount; self.hurt_time = 10; } + // Animal.actuallyHurt: damage taken ends love mode (`resetLove`). + if drops::is_animal(self.species()) { + self.extra.in_love = 0; + } self.last_damage = Some((source, i64::from(self.age))); if let Some(who) = source.attacker { self.ai.last_hurt_by = Some(who); @@ -1789,6 +1898,12 @@ impl Mob { } } } + // Squid.hurtServer: a squid hurt after a living entity hit it squirts ink. + if matches!(self.species(), Species::Squid | Species::GlowSquid) + && self.ai.last_hurt_by.is_some() + { + aquatic::spawn_ink(self); + } true } /// LivingEntity.knockback(power, xd, zd) towards the negative direction. @@ -1839,7 +1954,8 @@ impl Mob { /// Movement speed attribute bonus (baby zombies, sprinting modifiers). /// MOVEMENT_SPEED including effects (speed +20%/level, slowness -15%/level). pub fn movement_speed(&self) -> f64 { - let mut v = strider::movement_speed(self, self.attrs.speed) * self.speed_bonus(); + let mut v = strider::movement_speed(self, witch::speed(self, self.attrs.speed)) + * self.speed_bonus(); for (e, _, amp) in &self.extra.effects { match *e { "minecraft:speed" => v *= 1.0 + 0.2 * f64::from(amp + 1), @@ -1854,8 +1970,15 @@ impl Mob { } pub fn add_effect(&mut self, effect: &'static str, ticks: i32, amplifier: i32) { if let Some(e) = self.extra.effects.iter_mut().find(|e| e.0 == effect) { - e.1 = e.1.max(ticks); - e.2 = e.2.max(amplifier); + // MobEffectInstance.update: a stronger effect replaces the old one + // with its own duration, an equal one keeps the longer duration, + // and a weaker one never changes the active effect. + if amplifier > e.2 { + e.1 = ticks; + e.2 = amplifier; + } else if amplifier == e.2 { + e.1 = e.1.max(ticks); + } } else { self.extra.effects.push((effect, ticks, amplifier)); } diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index c9bc15fda..26b94eeac 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -106,6 +106,7 @@ pub enum Family { Strider, Bat, Bee, + PolarBear, } pub fn family(s: Species) -> Family { use Species as S; @@ -167,6 +168,7 @@ pub fn family(s: Species) -> Family { S::Strider => Family::Strider, S::Bat => Family::Bat, S::Bee => Family::Bee, + S::PolarBear => Family::PolarBear, _ => Family::Generic, } } @@ -183,6 +185,9 @@ pub fn register(m: &mut Mob) { if m.species() == Species::Rabbit { super::rabbit::register(m); } + if m.species() == Species::Turtle { + super::turtle::register(m); + } } Family::Inert => {} Family::Witch => super::witch::register(m), @@ -224,6 +229,7 @@ pub fn register(m: &mut Mob) { Family::Strider => super::strider::register(m), Family::Bat => super::bat::register(m), Family::Bee => super::bee::register(m), + Family::PolarBear => super::polar_bear::register(m), } // FloatGoal's constructor lets the navigation float, as do the // constructors of these brain-driven and flying mobs. A floater rises @@ -413,6 +419,7 @@ pub fn tick( super::axolotl::tick_animation(m); m.anim.end_tick(m.ai.swinging); tick_swing(m); + flower_contact_effects(m, w); if m.species() == Species::CopperGolem { // CopperGolem.tick: updateWeathering after the living tick. super::copper_golem::update_weathering(m, w, level_random, events); @@ -441,6 +448,34 @@ pub fn tick_swing(m: &mut Mob) { } m.anim.attack_anim = m.ai.swing_time as f32 / 6.0; } +/// `LivingEntity.baseTick` refills a breather's air by 4, then +/// `Axolotl.handleAirSupply` (unless the mob has no AI): water or rain fills +/// it, anywhere else it runs down from the pre-tick value, and at -20 the +/// axolotl dries out. +fn axolotl_air_supply(m: &mut Mob, w: &MobWorld) { + let before = m.air; + m.air = (m.air + 4).min(super::axolotl::MAX_AIR); + if m.no_ai { + return; + } + // Entity.isInRain: rain at the block, or at the top of the box. + let (x, y, z) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + let top = (m.position.y + f64::from(m.height())).floor() as i32; + let in_rain = w.raining_at(x, y, z) || w.raining_at(x, top, z); + if m.fluids.in_water || in_rain { + m.air = super::axolotl::MAX_AIR; + } else { + m.air = before - 1; + if m.air <= -20 { + m.air = 0; + m.damage(2.0, Damage::of(DamageKind::DryOut)); + } + } +} /// Entity.baseTick + LivingEntity.baseTick + Mob.baseTick. fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.was_eye_in_water = m.fluids.eye_in_water; @@ -500,7 +535,9 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.damage(1.0, Damage::of(DamageKind::InWall)); } // Air supply and drowning (WaterAnimal.handleAirSupply for aquatic mobs). - if m.kind.flags.needs_water { + if m.species() == Species::Axolotl { + axolotl_air_supply(m, w); + } else if m.kind.flags.needs_water { if !m.fluids.in_water { m.air -= 1; if m.air == -20 { @@ -641,7 +678,7 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & } // AbstractHorse.aiStep: the tail swishes now and then (moveTail). if super::equine::is_equine(m.species()) { - let _ = m.random.next_int_bound(200); + super::equine::tail_tick(m); } // Monster.aiStep: updateNoActionTime (Raider: always +2). if is_monster(m.species()) @@ -668,6 +705,9 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & // serverAiStep has no goals, so it only falls and is pushed. let immobile = (m.species() == Species::Ravager && super::ravager::immobile(m)) || m.species() == Species::Mannequin; + if m.species() == Species::Piglin && m.alive() { + super::piglin::celebrate(m, w); + } if m.alive() && !immobile { server_ai_step(m, w, level_random, events); } else { @@ -712,6 +752,14 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & // setAge at the age boundary: refreshDimensions. if m.extra.age >= 0 { m.fudge_position_after_size_change(w, bw, bh); + // Turtle.ageBoundaryReached: a grown turtle drops a scute. + if m.species() == Species::Turtle { + events.push(MobEvent::GiftLoot { + mob: m.id, + table: "minecraft:gameplay/turtle_grow", + at: [m.position.x, m.position.y, m.position.z], + }); + } } } else if m.extra.age > 0 { m.extra.age -= 1; @@ -746,7 +794,7 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & if m.kind.flags.burns_in_day && m.alive() && sun_burn_tick(m, w) && m.extra.head.is_none() { m.ignite_for_ticks(160); } - species_ai_step(m, w, events); + species_ai_step(m, w, level_random, events); } impl Mob { /// LivingEntity.isPushable (and the push it takes from `Entity.push(Entity)`): @@ -944,6 +992,7 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { | Species::Parched | Species::WitherSkeleton | Species::ZombifiedPiglin => undead::custom_server_ai_step(m, cx), + Species::Vindicator => super::illager::vindicator_server_ai_step(m), Species::Enderman => super::enderman::custom_server_ai_step(m, cx), Species::Blaze => super::nether::blaze_server_ai_step(m, cx), Species::ElderGuardian => super::guardian::elder_server_ai_step(m, cx), @@ -955,7 +1004,12 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { _ => {} } } -fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { +fn species_ai_step( + m: &mut Mob, + w: &MobWorld, + level_random: &mut LegacyRandom, + events: &mut Vec, +) { if family(m.species()) == Family::Aquatic { aquatic::ai_step(m, w, events); } @@ -978,6 +1032,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { Species::Wither => super::wither::ai_step(m, w, events), Species::Allay => super::allay::ai_step(m), Species::Bee => super::bee::ai_step(m, w), + Species::PolarBear => super::polar_bear::ai_step(m, w), Species::Breeze => super::breeze::ai_step(m), Species::Sniffer => super::sniffer::ai_step(m, events), Species::HappyGhast => super::happy_ghast::ai_step(m, w), @@ -988,7 +1043,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } Species::Shulker => { super::shulker::tick(m, w, events); - super::shulker::ai_step(m, w, events); + super::shulker::ai_step(m, w, level_random, events); } Species::SnowGolem => super::golem::snow_ai_step(m, w, events), Species::CopperGolem => super::copper_golem::ai_step(m, w, events), @@ -999,6 +1054,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } Species::Nautilus | Species::ZombieNautilus => super::nautilus::ai_step(m, w, events), Species::Chicken => farm::chicken_ai_step(m, w, events), + Species::Turtle => super::turtle::ai_step(m, w, events), Species::Sheep if m.extra.anim_ticks > 0 => { m.extra.anim_ticks -= 1; } @@ -1024,6 +1080,10 @@ fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool { if m.species() == Species::Mannequin { return true; } + // Mob.checkDespawn discards disallowed types even when persistent or NoAI. + if w.difficulty.effective == 0.0 && !super::spawn_rules::allowed_in_peaceful(m.species()) { + return false; + } let Some(p) = w.nearest_player else { return true; }; @@ -1238,6 +1298,20 @@ pub fn walk_target_value(m: &Mob, w: &MobWorld, p: [i32; 3]) -> f32 { if m.species() == Species::Strider { return super::strider::walk_target_value(m, w, p); } + // Hoglin.getWalkTargetValue: nowhere near a repellent, crimson nylium best. + if m.species() == Species::Hoglin { + let near = m.extra.repellent.is_some_and(|r| { + let d = |i: usize| i64::from(r[i] - p[i]); + d(0) * d(0) + d(1) * d(1) + d(2) * d(2) < 64 + }); + return if near { + -1.0 + } else if w.block_name(p[0], p[1] - 1, p[2]) == "minecraft:crimson_nylium" { + 10.0 + } else { + 0.0 + }; + } // Bee.getWalkTargetValue: any air block. if m.species() == Species::Bee { return if w.facts.is_air(w.world.block(p[0], p[1], p[2])) { @@ -1306,6 +1380,11 @@ pub fn after_hurt(m: &mut Mob, source: &Damage) { Species::Warden => super::warden::hurt(m, source), Species::Wolf => super::tame::after_hurt(m, source), Species::Nautilus | Species::ZombieNautilus => super::nautilus::after_hurt(m, source), + Species::Zombie + | Species::Husk + | Species::Drowned + | Species::ZombieVillager + | Species::ZombifiedPiglin => super::undead::after_hurt(m, source), // NeutralMob: an iron golem hit by the player stays angry a while. // PiglinAi.wasHurtBy: drop what is being admired, no admiring for // a while after a player's hit, and anger. @@ -1446,6 +1525,56 @@ pub fn custom_travel(m: &mut Mob, w: &MobWorld, input: Vec3, events: &mut Vec = Vec::new(); + for at in [m.previous, m.position] { + let cells = |lo: f64, hi: f64| lo.floor() as i32..=hi.floor() as i32; + for x in cells(at.x - half, at.x + half) { + for y in cells(at.y + 1.0e-5, at.y + height) { + for z in cells(at.z - half, at.z + half) { + let p = [x, y, z]; + if visited.contains(&p) { + continue; + } + match w.block_name(x, y, z) { + "minecraft:wither_rose" => { + // isInvulnerableTo(wither): the invulnerable time + // after a hit; WitherBoss and WitherSkeleton + // refuse the effect (`canBeAffected`). + if m.invulnerable <= 0 + && !m.invulnerable_flag + && !matches!(m.species(), Species::Wither | Species::WitherSkeleton) + { + m.add_effect("minecraft:wither", 40, 0); + } + } + "minecraft:open_eyeblossom" + if m.species() == Species::Bee + && super::bee::attracts_bees(w, p) + && !m.has_effect("minecraft:poison") => + { + m.add_effect("minecraft:poison", 25, 0); + } + _ => continue, + } + visited.push(p); + } + } + } + } +} + /// MobEffect ticking for the effects mobs receive (poison, wither, regeneration). fn tick_effects(m: &mut Mob) { let mut effects = std::mem::take(&mut m.extra.effects); @@ -1470,6 +1599,9 @@ fn tick_effects(m: &mut Mob) { *ticks -= 1; } effects.retain(|e| e.1 > 0); + m.extra + .hidden_effects + .retain(|h| effects.iter().any(|e| e.0 == *h)); m.extra.effects = effects; } diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index b2158132b..a4c27960e 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -102,7 +102,7 @@ impl AnimState { pub fn end_tick(&mut self, _swinging: bool) {} } /// Part poses for one draw, keyed by part name. -#[derive(Clone)] +#[derive(Clone, Default)] pub struct Poses { map: HashMap, dummy: [f32; 9], @@ -113,20 +113,24 @@ pub struct Poses { } impl Poses { pub fn new(model: &Part) -> Self { - let mut map = HashMap::new(); + let mut poses = Self::default(); + poses.reset(model); + poses + } + /// Refills this for another model, keeping the map and the sets' capacity: + /// a mob draws its body and every equipment layer each frame. + pub fn reset(&mut self, model: &Part) { fn walk(p: &Part, map: &mut HashMap) { map.insert(p.name.clone(), p.pose); for c in &p.children { walk(c, map); } } - walk(model, &mut map); - Self { - map, - dummy: [0.0; 9], - skipped: Default::default(), - hidden: Default::default(), - } + self.map.clear(); + self.dummy = [0.0; 9]; + self.skipped.clear(); + self.hidden.clear(); + walk(model, &mut self.map); } pub fn get(&mut self, name: &str) -> &mut [f32; 9] { match self.map.get_mut(name) { @@ -189,14 +193,16 @@ pub fn state(m: &Mob, alpha: f32) -> State { swing += 1.0; } let swing = m.anim.attack_anim_o + swing * alpha; - let alive = m.alive(); + // LivingEntityRenderer.extractRenderState: riding motion is not walking. + let walking = m.alive() && !m.extra.passenger; State { - pos: if alive { - m.limb_position - m.limb_speed * (1.0 - alpha) + pos: if walking { + // WalkAnimationState.position(partial): babies' legs move 3 times as far. + (m.limb_position - m.limb_speed * (1.0 - alpha)) * if m.is_baby() { 3.0 } else { 1.0 } } else { 0.0 }, - speed: if alive { + speed: if walking { (m.previous_limb_speed + (m.limb_speed - m.previous_limb_speed) * alpha).min(1.0) } else { 0.0 @@ -243,18 +249,24 @@ pub enum ArmPose { pub fn humanoid_pub(p: &mut Poses, s: &State, _m: &Mob) { humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty)); } -/// `AnimationUtils.swingWeaponDown` with the right arm as the main arm. -pub(super) fn swing_weapon_down(p: &mut Poses, swing: f32, age: f32) { +/// `AnimationUtils.swingWeaponDown`: the main arm swings down, the other +/// one hangs and bobs. +pub(super) fn swing_weapon_down(p: &mut Poses, swing: f32, age: f32, left_main: bool) { let attack2 = (swing * PI).msin(); let attack = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin(); + let (main, off) = if left_main { + ("left_arm", "right_arm") + } else { + ("right_arm", "left_arm") + }; p.zrot("right_arm", 0.0); p.zrot("left_arm", 0.0); p.yrot("right_arm", PI / 20.0); p.yrot("left_arm", -PI / 20.0); - p.xrot("right_arm", -1.884_955_8 + (age * 0.09).mcos() * 0.15); - p.xrot("left_arm", -0.0 + (age * 0.19).mcos() * 0.5); - p.get("right_arm")[3] += attack2 * 2.2 - attack * 0.4; - p.get("left_arm")[3] += attack2 * 1.2 - attack * 0.4; + p.xrot(main, -1.884_955_8 + (age * 0.09).mcos() * 0.15); + p.xrot(off, -0.0 + (age * 0.19).mcos() * 0.5); + p.get(main)[3] += attack2 * 2.2 - attack * 0.4; + p.get(off)[3] += attack2 * 1.2 - attack * 0.4; bob(p, "right_arm", age, 1.0); bob(p, "left_arm", age, -1.0); } @@ -281,6 +293,8 @@ pub struct Hum { pub using_item: bool, /// The arm the current swing moves (`Some(true)` for the right one). pub swing_right_arm: Option, + /// `mainArm` is the left one (`Mob.isLeftHanded`): a mob's swing uses it. + pub left_main: bool, } impl Hum { pub fn new(right: ArmPose, left: ArmPose) -> Self { @@ -298,6 +312,7 @@ impl Hum { swim: 0.0, using_item: false, swing_right_arm: None, + left_main: false, } } } @@ -310,7 +325,7 @@ impl ArmPose { } } /// `AnimationUtils.animateCrossbowHold`. -fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) { +pub(super) fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) { let (hold, shoot) = if in_right { ("right_arm", "left_arm") } else { @@ -322,7 +337,7 @@ fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) { p.xrot(shoot, -1.5 + hx); } /// `AnimationUtils.animateCrossbowCharge`. -fn crossbow_charge(p: &mut Poses, max: f32, ticks: f32, in_right: bool) { +pub(super) fn crossbow_charge(p: &mut Poses, max: f32, ticks: f32, in_right: bool) { let (hold, pull) = if in_right { ("right_arm", "left_arm") } else { @@ -413,13 +428,17 @@ pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) { pose_arm(p, h.right, true, h); } } - // setupAttackAnimation (WHACK swing with the right arm). + // setupAttackAnimation (WHACK swing with the arm of the swinging hand). let hx = p.get("head")[3]; let swing = s.swing; + let swing_left = h.swing_right_arm.map_or(h.left_main, |right| !right); if swing > 0.0 && h.weapon_swing { - swing_weapon_down(p, swing, s.age); + swing_weapon_down(p, swing, s.age, h.left_main); } else if swing > 0.0 { - let body_y = (swing.sqrt() * PI * 2.0).msin() * 0.2; + let mut body_y = (swing.sqrt() * PI * 2.0).msin() * 0.2; + if swing_left { + body_y = -body_y; + } p.yrot("body", body_y); let age_scale = if s.baby { 0.5 } else { 1.0 }; { @@ -439,7 +458,7 @@ pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) { let eased = 1.0 - (1.0 - swing).powi(4); let aa = (eased * PI).msin(); let bb = (swing * PI).msin() * -(hx - 0.7) * 0.75; - let r = p.get("right_arm"); + let r = p.get(if swing_left { "left_arm" } else { "right_arm" }); r[3] -= aa * 1.2 + bb; r[4] += body_y * 2.0; r[5] += (swing * PI).msin() * -0.4; @@ -647,6 +666,7 @@ pub fn setup( } else { Hum::new(main, ArmPose::Empty) }; + h.left_main = m.main_arm_left(); h.zombie = Some(m.ai.aggressive); h.holding = m.extra.main_hand.is_some(); h.crouching = m.extra.crouching; @@ -710,6 +730,7 @@ pub fn setup( h.swim = m.extra.swim.amount(s.partial); h.using_item = m.extra.using_item > 0; h.swing_right_arm = m.extra.swing_right_arm; + h.left_main = m.main_arm_left(); humanoid(p, s, &h); if m.ai.aggressive && !bow { // SkeletonModel melee pose. diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index dc80c6ea4..f63a42239 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -24,6 +24,58 @@ const Z_BODY_ROT: usize = 3; const TENTACLE_SPEED: usize = 4; const ROTATE_SPEED: usize = 5; +/// `Squid.spawnInk`: the squirt sound and 30 ink particles shot from under +/// the squid, turned by its body rotation. +pub fn spawn_ink(m: &mut Mob) { + let sound = if m.species() == Species::GlowSquid { + "entity.glow_squid.squirt" + } else { + "entity.squid.squirt" + }; + let kind = if m.species() == Species::GlowSquid { + "glow_squid_ink" + } else { + "squid_ink" + }; + // makeSound draws the voice pitch even for a silent squid. + let pitch = m.voice_pitch(); + if !m.silent { + let at = [m.position.x, m.position.y, m.position.z]; + m.outbox.push(MobEvent::Sound( + sound, + at, + super::ai::sound_volume(m), + pitch, + )); + } + // rotateVector: xRot(xBodyRotO), then yRot(-yBodyRotO). + let to_radians = (std::f64::consts::PI / 180.0) as f32; + let (x_rot, y_rot) = ( + m.anim.vo[X_BODY_ROT] * to_radians, + -m.previous_body_yaw * to_radians, + ); + let rotate = |v: Vec3| v.rotate_x(x_rot).rotate_y(y_rot); + let pos = rotate(Vec3::new(0.0, -1.0, 0.0)).add_vector(m.position); + let offset_scale: f32 = if m.is_baby() { 0.1 } else { 0.3 }; + for _ in 0..30 { + let x = f64::from(m.random.next_float()) * 0.6 - 0.3; + let z = f64::from(m.random.next_float()) * 0.6 - 0.3; + let dir = rotate(Vec3::new(x, -1.0, z)); + let d = dir.scale(f64::from(offset_scale + m.random.next_float() * 2.0)); + // ServerLevel.sendParticles with a count of 0 and speed 0.1: one + // particle moving at the float offset times the float speed. + let speed = f64::from(0.1f32); + m.outbox.push(MobEvent::ParticleAt { + kind, + at: [pos.x, pos.y + 0.5, pos.z], + velocity: [ + speed * f64::from(d.x as f32), + speed * f64::from(d.y as f32), + speed * f64::from(d.z as f32), + ], + }); + } +} pub fn register(m: &mut Mob) { use Species as S; match m.species() { @@ -36,6 +88,7 @@ pub fn register(m: &mut Mob) { m.anim.v[TENTACLE_SPEED] = speed; } S::Axolotl => { + m.air = super::axolotl::MAX_AIR; // Native controller scaling is essential: the base speed attribute is 1.0. m.ai.mov.kind = MoveKind::SmoothSwimming { max_turn_x: 85.0, @@ -234,12 +287,40 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } /// Squid.aiStep: tentacle cycle, propulsion and body rotation. fn squid_ai_step(m: &mut Mob) { + squid_step(m, false); +} + +/// Squid.aiStep also runs on remote entities: animate from packet velocity, +/// without running goals or replacing that velocity with the server's movement vector. +pub fn squid_client_step(m: &mut Mob) { + if matches!(m.species(), Species::Squid | Species::GlowSquid) { + m.anim.vo = m.anim.v; + squid_step(m, true); + } +} + +/// Squid.handleEntityEvent(19): begin the next server-synchronised tentacle cycle. +pub fn squid_cycle_event(m: &mut Mob) { + if matches!(m.species(), Species::Squid | Species::GlowSquid) { + m.anim.v[TENTACLE_MOVEMENT] = 0.0; + } +} + +fn squid_step(m: &mut Mob, client: bool) { let v = &mut m.anim.v; v[TENTACLE_MOVEMENT] += v[TENTACLE_SPEED]; - if v[TENTACLE_MOVEMENT] > PI * 2.0 { - v[TENTACLE_MOVEMENT] -= PI * 2.0; - if m.random.next_int_bound(10).unwrap_or(1) == 0 { - m.anim.v[TENTACLE_SPEED] = 1.0 / (m.random.next_float() + 1.0) * 0.2; + if f64::from(v[TENTACLE_MOVEMENT]) > std::f64::consts::TAU { + if client { + v[TENTACLE_MOVEMENT] = PI * 2.0; + } else { + v[TENTACLE_MOVEMENT] -= PI * 2.0; + if m.random.next_int_bound(10).unwrap_or(1) == 0 { + m.anim.v[TENTACLE_SPEED] = 1.0 / (m.random.next_float() + 1.0) * 0.2; + } + m.outbox.push(MobEvent::SquidCycle { + mob: m.id, + at: [m.position.x, m.position.y, m.position.z], + }); } } let v = &mut m.anim.v; @@ -248,28 +329,39 @@ fn squid_ai_step(m: &mut Mob) { let scale = v[TENTACLE_MOVEMENT] / PI; v[TENTACLE_ANGLE] = (scale * scale * PI).msin() * PI * 0.25; if scale > 0.75 { - let mv = m.extra.vector; - m.velocity = Vec3::new(mv[0], mv[1], mv[2]); + if !client { + let mv = m.extra.vector; + m.velocity = Vec3::new(mv[0], mv[1], mv[2]); + } m.anim.v[ROTATE_SPEED] = 1.0; } else { m.anim.v[ROTATE_SPEED] *= 0.8; } } else { v[TENTACLE_ANGLE] = 0.0; - m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9); + if !client { + m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9); + } m.anim.v[ROTATE_SPEED] *= 0.99; } let mv = m.velocity; let horizontal = (mv.x * mv.x + mv.z * mv.z).sqrt(); - m.body_yaw += (-(mv.x.atan2(mv.z) as f32).to_degrees() - m.body_yaw) * 0.1; + m.body_yaw += (-(horizon_core::geometry::trig::atan2(mv.x, mv.z) as f32) * 57.295776 + - m.body_yaw) + * 0.1; m.yaw = m.body_yaw; let v = &mut m.anim.v; v[Z_BODY_ROT] += PI * v[ROTATE_SPEED] * 1.5; - v[X_BODY_ROT] += (-(horizontal.atan2(mv.y) as f32).to_degrees() - v[X_BODY_ROT]) * 0.1; + v[X_BODY_ROT] += (-(horizon_core::geometry::trig::atan2(horizontal, mv.y) as f32) + * 57.295776 + - v[X_BODY_ROT]) + * 0.1; } else { v[TENTACLE_ANGLE] = v[TENTACLE_MOVEMENT].msin().abs() * PI * 0.25; - let yd = m.velocity.y - m.kind.gravity; - m.velocity = Vec3::new(0.0, yd * 0.98, 0.0); + if !client { + let yd = m.velocity.y - m.kind.gravity; + m.velocity = Vec3::new(0.0, yd * 0.98, 0.0); + } let v = &mut m.anim.v; v[X_BODY_ROT] += (-90.0 - v[X_BODY_ROT]) * 0.02; } diff --git a/crates/horizon-client/src/mobs/axolotl.rs b/crates/horizon-client/src/mobs/axolotl.rs index 55f15717c..2815418e3 100644 --- a/crates/horizon-client/src/mobs/axolotl.rs +++ b/crates/horizon-client/src/mobs/axolotl.rs @@ -3,6 +3,8 @@ use super::{Mob, MobEvent, MobWorld, Species, Who, animal_brain, keyframes::Anim use horizon_core::random::RandomSource; pub const PLAY_DEAD_TICKS: i32 = 200; pub const HUNTING_COOLDOWN: i64 = 2400; +/// `Axolotl.getMaxAirSupply`. +pub const MAX_AIR: i32 = 6000; /// AxolotlAttackablesSensor: always-hostile targets bypass the hunting cooldown. pub fn prey_eligible( diff --git a/crates/horizon-client/src/mobs/bat.rs b/crates/horizon-client/src/mobs/bat.rs index 9f38e9e60..ca5efa4a2 100644 --- a/crates/horizon-client/src/mobs/bat.rs +++ b/crates/horizon-client/src/mobs/bat.rs @@ -132,6 +132,10 @@ pub fn tick(m: &mut Mob) { } else { m.velocity.y *= 0.6; } + setup_animation_states(m); +} +/// `Bat.setupAnimationStates`: client visuals, without changing server motion. +pub fn setup_animation_states(m: &mut Mob) { let age = m.age as f32; if resting(m) { m.anim.states[0].stop(); diff --git a/crates/horizon-client/src/mobs/body_anim.rs b/crates/horizon-client/src/mobs/body_anim.rs index 4411d347b..0e88fafb2 100644 --- a/crates/horizon-client/src/mobs/body_anim.rs +++ b/crates/horizon-client/src/mobs/body_anim.rs @@ -959,7 +959,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool { let st = &m.anim.states; match m.species() { Species::Goat => goat(p, s, &Goat::from_mob(m)), - Species::PolarBear => polar_bear(p, s, 0.0), + Species::PolarBear => polar_bear(p, s, super::polar_bear::standing_scale(m, s.partial)), Species::Panda => panda(p, s, &Panda::default()), Species::Llama | Species::TraderLlama => { llama(p, s, m.extra.chested && !s.baby); @@ -969,8 +969,8 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool { s, &Turtle { on_land: !m.fluids.in_water && m.on_ground, - laying_egg: false, - has_egg: false, + laying_egg: m.extra.flag2, + has_egg: m.extra.flag, }, ), Species::Strider => strider(p, s, m.rider.is_some()), diff --git a/crates/horizon-client/src/mobs/doors.rs b/crates/horizon-client/src/mobs/doors.rs new file mode 100644 index 000000000..a55ab9863 --- /dev/null +++ b/crates/horizon-client/src/mobs/doors.rs @@ -0,0 +1,252 @@ +//! Doors a mob gets through on its own: `DoorInteractGoal` with its two +//! users, `BreakDoorGoal` (zombies that can break doors, vindicators in a +//! raid) and `OpenDoorGoal` (`AbstractIllager.RaiderOpenDoorGoal`). +use super::{ + Mob, MobEvent, MobWorld, Species, + goals::{Cx, Goal, MOVE, goal_clone, reduced}, + nav::NavKind, + raider, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; + +/// `DefaultDoorBreakTime`: `BreakDoorGoal.getDoorBreakTime` is +/// `max(240, doorBreakTime)`, and the vindicator's 6 is below it. +const DOOR_BREAK_TIME: i32 = 240; + +/// `GoalUtils.hasGroundPathNavigation`: ground, wall-climbing and +/// amphibious navigations walk. +pub fn can_navigate_ground(m: &Mob) -> bool { + matches!( + m.ai.nav.kind, + NavKind::Ground | NavKind::WallClimber | NavKind::Amphibious + ) +} +/// `Zombie.setCanBreakDoors`: only a mob that walks can break doors, and +/// then its navigation opens them. +pub fn set_can_break_doors(m: &mut Mob, can_break: bool) { + let can_break = can_break && can_navigate_ground(m); + m.extra.can_break_doors = can_break; + m.ai.nav.can_open_doors = can_break; +} +/// The species that extend `Zombie` (`CanBreakDoors` is theirs to save). +pub fn is_zombie(s: Species) -> bool { + matches!( + s, + Species::Zombie + | Species::Husk + | Species::Drowned + | Species::ZombieVillager + | Species::ZombifiedPiglin + ) +} +/// `DoorBlock.isWoodenDoor`: a door a hand opens, which is any but iron. +fn wooden_door(w: &MobWorld, p: [i32; 3]) -> bool { + let name = w.block_name(p[0], p[1], p[2]); + name.ends_with("_door") && name != "minecraft:iron_door" +} +/// `DoorInteractGoal`'s door: where it is and whether one is there. +#[derive(Clone, Debug, Default)] +struct Interact { + door: [i32; 3], + has_door: bool, +} +impl Interact { + /// `DoorInteractGoal.canUse`: the mob bumped into something and a + /// wooden door is on its path within 1.5 blocks, or at its own head. + fn can_use(&mut self, m: &Mob, w: &MobWorld) -> bool { + if !can_navigate_ground(m) || !m.horizontal_collision { + return false; + } + let Some(path) = m.ai.nav.path.as_ref().filter(|p| !p.is_done()) else { + return false; + }; + for node in path + .nodes + .iter() + .take((path.next + 2).min(path.nodes.len())) + { + self.door = [node.x, node.y + 1, node.z]; + let dx = m.position.x - f64::from(node.x); + let dz = m.position.z - f64::from(node.z); + if dx * dx + dz * dz <= 2.25 { + self.has_door = wooden_door(w, self.door); + if self.has_door { + return true; + } + } + } + let at = m.position; + self.door = [ + at.x.floor() as i32, + at.y.floor() as i32 + 1, + at.z.floor() as i32, + ]; + self.has_door = wooden_door(w, self.door); + self.has_door + } + /// `DoorInteractGoal.isOpen`: the door is still there and open. + fn is_open(&mut self, w: &MobWorld) -> bool { + if !self.has_door { + return false; + } + let d = self.door; + if !w.block_name(d[0], d[1], d[2]).ends_with("_door") { + self.has_door = false; + return false; + } + w.prop(d[0], d[1], d[2], "open") == Some("true") + } + /// `DoorInteractGoal.setOpen`. + fn set_open(&self, cx: &mut Cx, open: bool) { + let d = self.door; + if self.has_door && cx.w.block_name(d[0], d[1], d[2]).ends_with("_door") { + cx.events.push(MobEvent::SetDoorOpen { pos: d, open }); + } + } +} +/// `BlockPos.closerToCenterThan`. +fn closer_to_center(p: [i32; 3], at: Vec3, distance: f64) -> bool { + Vec3::new( + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, + ) + .distance_squared(at) + < distance * distance +} + +/// `BreakDoorGoal`: crack the door in the way for 240 ticks, then remove it. +/// A zombie does it on hard only; `Vindicator.VindicatorBreakDoorGoal` on +/// normal and hard, in a raid, and holds the mob's movement. +#[derive(Clone, Debug)] +pub struct BreakDoor { + interact: Interact, + vindicator: bool, + break_time: i32, + last_break_progress: i32, +} +impl BreakDoor { + /// `Zombie.breakDoorGoal`, added when the zombie can break doors. + pub fn zombie() -> Self { + Self::new(false) + } + /// `Vindicator.VindicatorBreakDoorGoal`. + pub fn vindicator() -> Self { + Self::new(true) + } + fn new(vindicator: bool) -> Self { + Self { + interact: Interact::default(), + vindicator, + break_time: 0, + last_break_progress: -1, + } + } + /// `DOOR_BREAKING_PREDICATE`. + fn valid_difficulty(&self, w: &MobWorld) -> bool { + if self.vindicator { + w.difficulty.normal || w.difficulty.hard + } else { + w.difficulty.hard + } + } + /// `BreakDoorGoal.canUse` after `DoorInteractGoal.canUse`. + fn can_break(&mut self, m: &Mob, w: &MobWorld) -> bool { + self.interact.can_use(m, w) + && w.mob_griefing + && self.valid_difficulty(w) + && !self.interact.is_open(w) + } +} +impl Goal for BreakDoor { + goal_clone!(); + fn flags(&self) -> u8 { + if self.vindicator { MOVE } else { 0 } + } + fn every_tick(&self) -> bool { + true + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if self.vindicator { + return raider::has_active_raid(m) + && m.random.next_int_bound(reduced(10)).unwrap_or(1) == 0 + && self.can_break(m, cx.w); + } + m.extra.can_break_doors && self.can_break(m, cx.w) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + (!self.vindicator || raider::has_active_raid(m)) + && self.break_time <= DOOR_BREAK_TIME + && !self.interact.is_open(cx.w) + && closer_to_center(self.interact.door, m.position, 2.0) + && self.valid_difficulty(cx.w) + } + fn start(&mut self, m: &mut Mob, _cx: &mut Cx) { + self.break_time = 0; + if self.vindicator { + m.ai.no_action_time = 0; + } + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + cx.events.push(MobEvent::DestroyProgress { + mob: m.id, + pos: self.interact.door, + progress: -1, + }); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let door = self.interact.door; + if m.random.next_int_bound(20).unwrap_or(1) == 0 { + cx.events.push(MobEvent::LevelEvent { + id: 1019, + pos: door, + data: 0, + }); + if !m.ai.swinging { + m.swing(); + } + } + self.break_time += 1; + let progress = (self.break_time as f32 / DOOR_BREAK_TIME as f32 * 10.0) as i32; + if progress != self.last_break_progress { + cx.events.push(MobEvent::DestroyProgress { + mob: m.id, + pos: door, + progress, + }); + self.last_break_progress = progress; + } + if self.break_time == DOOR_BREAK_TIME && self.valid_difficulty(cx.w) { + cx.events.push(MobEvent::BreakDoor { pos: door }); + } + } +} + +/// `AbstractIllager.RaiderOpenDoorGoal` (`OpenDoorGoal` that does not wait +/// to close): open the door in the way during a raid. It never continues, so +/// it closes the door again as soon as it stops. +#[derive(Clone, Debug, Default)] +pub struct RaiderOpenDoor { + interact: Interact, +} +impl Goal for RaiderOpenDoor { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn every_tick(&self) -> bool { + true + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.interact.can_use(m, cx.w) && raider::has_active_raid(m) + } + fn can_continue(&mut self, _m: &mut Mob, _cx: &mut Cx) -> bool { + false + } + fn start(&mut self, _m: &mut Mob, cx: &mut Cx) { + self.interact.set_open(cx, true); + } + fn stop(&mut self, _m: &mut Mob, cx: &mut Cx) { + self.interact.set_open(cx, false); + } +} diff --git a/crates/horizon-client/src/mobs/drops.rs b/crates/horizon-client/src/mobs/drops.rs index e5ccfd283..064cf0583 100644 --- a/crates/horizon-client/src/mobs/drops.rs +++ b/crates/horizon-client/src/mobs/drops.rs @@ -304,6 +304,7 @@ fn loot_stack(item: &str, count: i32) -> LootStack { map: false, exploration: None, ominous_amplifier: None, + stew_effects: Vec::new(), } } /// `Mob.dropChances.byEquipment(slot)`: the recorded chance, or the one the @@ -350,6 +351,9 @@ pub fn loot_entity(m: &Mob, vehicle: Option) -> LootEntity { .to_owned(), ); } + if s == S::Chicken { + e.chicken_variant = super::finalize::variant_component(m).map(|(_, id)| id); + } e.powered = s == S::Creeper && m.extra.charged; e.equipment = SLOTS .iter() @@ -455,6 +459,14 @@ pub fn die(m: &mut Mob, d: &Death, sequences: &mut RandomSequences) -> (Vec= m.extra.counter + 600 { + if cx.w.daylight && !cx.w.end && m.age as i32 >= m.extra.counter + 600 { let br = super::hostile::mob_brightness(m, cx.w); let (x, y, z) = ( m.position.x.floor() as i32, @@ -330,8 +331,11 @@ impl Goal for TakeBlock { fn flags(&self) -> u8 { 0 } - fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { - m.extra.carried.is_none() && m.random.next_int_bound(reduced(20)).unwrap_or(1) == 0 + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + // EndermanTakeBlockGoal.canUse: needs mobGriefing, checked before the draw. + m.extra.carried.is_none() + && cx.w.mob_griefing + && m.random.next_int_bound(reduced(20)).unwrap_or(1) == 0 } fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { let x = (m.position.x - 2.0 + m.random.next_double() * 4.0).floor() as i32; @@ -378,8 +382,11 @@ impl Goal for LeaveBlock { fn flags(&self) -> u8 { 0 } - fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { - m.extra.carried.is_some() && m.random.next_int_bound(reduced(2000)).unwrap_or(1) == 0 + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + // EndermanLeaveBlockGoal.canUse: needs mobGriefing, checked before the draw. + m.extra.carried.is_some() + && cx.w.mob_griefing + && m.random.next_int_bound(reduced(2000)).unwrap_or(1) == 0 } fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { let Some(carried) = m.extra.carried else { diff --git a/crates/horizon-client/src/mobs/equine.rs b/crates/horizon-client/src/mobs/equine.rs index 5bb5faf53..1155388fd 100644 --- a/crates/horizon-client/src/mobs/equine.rs +++ b/crates/horizon-client/src/mobs/equine.rs @@ -28,6 +28,8 @@ pub const MARKINGS: [&str; 5] = ["", "white", "whitefield", "whitedots", "blackd pub const EAT: usize = 0; pub const STAND: usize = 1; pub const MOUTH: usize = 2; +/// `AbstractHorse.tailCounter`: client-side, it only drives the model. +pub const TAIL: usize = 3; /// What a rider asks of its mount this tick. #[derive(Clone, Copy, Debug, Default)] @@ -418,6 +420,20 @@ pub fn ridden_step(m: &mut Mob) { } } } +/// `AbstractHorse.aiStep`'s `moveTail` (one in 200 ticks) and the counter's +/// step in `tick` (it runs to 8, then stops). A client runs it on its own +/// random, as vanilla's client-side `aiStep` does. +pub fn tail_tick(m: &mut Mob) { + if m.random.next_int_bound(200).unwrap_or(1) == 0 { + m.anim.v[TAIL] = 1.0; + } + if m.anim.v[TAIL] > 0.0 { + m.anim.v[TAIL] += 1.0; + if m.anim.v[TAIL] > 8.0 { + m.anim.v[TAIL] = 0.0; + } + } +} /// `AbstractHorse.aiStep` and `tick`: healing, grazing, the rear and the /// eating/standing/mouth animations. pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { @@ -603,7 +619,15 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { t[1] += speed * age; t[2] += speed * 2.0 * age; } - p.yrot("tail", 0.0); + // animateTail: the tail swings while the counter runs. + p.yrot( + "tail", + if m.anim.v[TAIL] > 0.0 { + (s.age * 0.7).mcos() + } else { + 0.0 + }, + ); if baby && donkey { // BabyDonkeyModel overrides the state's pitch with -30 degrees and // sets the head parts again. diff --git a/crates/horizon-client/src/mobs/farm.rs b/crates/horizon-client/src/mobs/farm.rs index 83d5ac1f5..87951b0e2 100644 --- a/crates/horizon-client/src/mobs/farm.rs +++ b/crates/horizon-client/src/mobs/farm.rs @@ -80,6 +80,7 @@ pub fn chicken_ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec) { let at = [m.position.x, m.position.y, m.position.z]; events.push(MobEvent::Sound("entity.chicken.egg", at, 1.0, pitch)); events.push(MobEvent::GiftLoot { + mob: m.id, table: "minecraft:gameplay/chicken_lay", at, }); diff --git a/crates/horizon-client/src/mobs/finalize.rs b/crates/horizon-client/src/mobs/finalize.rs index 4eeed885b..6e5daff1f 100644 --- a/crates/horizon-client/src/mobs/finalize.rs +++ b/crates/horizon-client/src/mobs/finalize.rs @@ -590,6 +590,14 @@ pub fn has_modifier(m: &Mob, a: Attr, id: &str) -> bool { .as_ref() .is_some_and(|s| s.modifiers.iter().any(|x| x.attr == a && x.id == id)) } +/// The amount of a permanent modifier, if the mob has it. +pub fn modifier_amount(m: &Mob, a: Attr, id: &str) -> Option { + m.extra + .attributes + .as_ref() + .and_then(|s| s.modifiers.iter().find(|x| x.attr == a && x.id == id)) + .map(|x| x.amount) +} /// `addOrReplacePermanentModifier`. pub fn add_modifier(m: &mut Mob, a: Attr, id: &'static str, amount: f64, op: Op) { let s = m.extra.attributes.get_or_insert_with(Box::default); @@ -605,6 +613,59 @@ pub fn add_modifier(m: &mut Mob, a: Attr, id: &'static str, amount: f64, op: Op) } refresh(m, a); } +/// `Zombie.handleAttributes`, from the zombie's own random. +pub fn zombie_attributes(m: &mut Mob, special: f32, reason: Reason) { + let r = &mut m.random; + let reinforcements = if m.kind.species == Species::ZombifiedPiglin { + 0.0 + } else { + r.next_double() * f64::from(0.1f32) + }; + let knockback = r.next_double() * f64::from(0.05f32); + let follow = r.next_double() * 1.5 * f64::from(special); + let leader = r.next_float() < special * 0.05; + let leader_rolls = leader.then(|| (r.next_double() * 0.25 + 0.5, r.next_double() * 3.0 + 1.0)); + set_base(m, Attr::SpawnReinforcements, reinforcements); + add_modifier( + m, + Attr::KnockbackResistance, + "minecraft:random_spawn_bonus", + knockback, + Op::AddValue, + ); + if follow > 1.0 { + add_modifier( + m, + Attr::FollowRange, + "minecraft:zombie_random_spawn_bonus", + follow, + Op::AddMultipliedTotal, + ); + } + if let Some((reinforce, health)) = leader_rolls { + add_modifier( + m, + Attr::SpawnReinforcements, + "minecraft:leader_zombie_bonus", + reinforce, + Op::AddValue, + ); + add_modifier( + m, + Attr::MaxHealth, + "minecraft:leader_zombie_bonus", + health, + Op::AddMultipliedTotal, + ); + if !matches!( + reason, + Reason::Conversion | Reason::Load | Reason::DimensionTravel + ) { + m.health = max_health(m); + } + super::doors::set_can_break_doors(m, true); + } +} pub fn max_health(m: &Mob) -> f32 { value(m, Attr::MaxHealth) as f32 } @@ -829,6 +890,14 @@ pub fn set_item(m: &mut Mob, slot: usize, id: &str) { } gear::set(m, gear_slot(slot), Vec::new()); } +/// The enchantments on what `m` has in `slot`. +pub fn slot_enchantments(m: &Mob, slot: usize) -> gear::Levels { + gear::gear(m).map_or_else(Vec::new, |g| g.slots[gear_slot(slot)].clone()) +} +/// Replace the enchantments of what `m` has in `slot` (after `set_item`). +pub fn set_slot_enchantments(m: &mut Mob, slot: usize, levels: gear::Levels) { + gear::set(m, gear_slot(slot), levels); +} /// `Mob.setDropChance`. pub fn set_drop_chance(m: &mut Mob, slot: usize, chance: f32) { let c = m @@ -1144,70 +1213,17 @@ impl Ctx<'_, L, R> { } } } - m.extra.can_break_doors = self.float() < special * 0.1; + let can_break_doors = self.float() < special * 0.1; + super::doors::set_can_break_doors(m, can_break_doors); if reason != Reason::Conversion { self.populate(m); self.enchant(m); } } self.halloween(m); - self.zombie_attributes(m, special, reason); + zombie_attributes(m, special, reason); g } - /// `Zombie.handleAttributes`, from the zombie's own random. - fn zombie_attributes(&mut self, m: &mut Mob, special: f32, reason: Reason) { - let r = &mut m.random; - let reinforcements = if m.kind.species == Species::ZombifiedPiglin { - 0.0 - } else { - r.next_double() * f64::from(0.1f32) - }; - let knockback = r.next_double() * f64::from(0.05f32); - let follow = r.next_double() * 1.5 * f64::from(special); - let leader = r.next_float() < special * 0.05; - let leader_rolls = - leader.then(|| (r.next_double() * 0.25 + 0.5, r.next_double() * 3.0 + 1.0)); - set_base(m, Attr::SpawnReinforcements, reinforcements); - add_modifier( - m, - Attr::KnockbackResistance, - "minecraft:random_spawn_bonus", - knockback, - Op::AddValue, - ); - if follow > 1.0 { - add_modifier( - m, - Attr::FollowRange, - "minecraft:zombie_random_spawn_bonus", - follow, - Op::AddMultipliedTotal, - ); - } - if let Some((reinforce, health)) = leader_rolls { - add_modifier( - m, - Attr::SpawnReinforcements, - "minecraft:leader_zombie_bonus", - reinforce, - Op::AddValue, - ); - add_modifier( - m, - Attr::MaxHealth, - "minecraft:leader_zombie_bonus", - health, - Op::AddMultipliedTotal, - ); - if !matches!( - reason, - Reason::Conversion | Reason::Load | Reason::DimensionTravel - ) { - m.health = max_health(m); - } - m.extra.can_break_doors = true; - } - } fn husk(&mut self, m: &mut Mob, g: Option, reason: Reason) -> Option { let mut g = self.zombie(m, g, reason); if reason != Reason::Conversion { diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 7f73e32c4..d0b784166 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -1017,6 +1017,8 @@ pub struct MeleeAttack { pub speed: f64, pub follow_unseen: bool, pub zombie: bool, + /// `PolarBear.PolarBearMeleeAttackGoal`: rears up before each strike. + pub polar_bear: bool, path_target: [f64; 3], recalc: i32, pub until_attack: i32, @@ -1031,6 +1033,7 @@ impl MeleeAttack { speed, follow_unseen, zombie: false, + polar_bear: false, path_target: [0.0; 3], recalc: 0, until_attack: 0, @@ -1043,6 +1046,10 @@ impl MeleeAttack { self.zombie = true; self } + pub fn polar_bear(mut self) -> Self { + self.polar_bear = true; + self + } pub fn interval(mut self, ticks: i32) -> Self { self.interval = ticks; self @@ -1098,6 +1105,9 @@ impl Goal for MeleeAttack { } m.ai.aggressive = false; m.nav_stop(); + if self.polar_bear { + super::polar_bear::set_standing(m, false); + } } fn every_tick(&self) -> bool { true @@ -1131,7 +1141,17 @@ impl Goal for MeleeAttack { self.recalc = adjusted(true, self.recalc); } self.until_attack = (self.until_attack - 1).max(0); - if self.until_attack <= 0 && m.within_melee_range(&t) && m.sees(cx.w, who) { + if self.polar_bear { + let cooldown = adjusted(true, self.interval); + super::polar_bear::check_and_perform_attack( + &mut self.until_attack, + cooldown, + m, + who, + &t, + cx, + ); + } else if self.until_attack <= 0 && m.within_melee_range(&t) && m.sees(cx.w, who) { self.until_attack = adjusted(true, self.interval); m.swing(); super::ai::do_hurt_target(m, who, cx); @@ -1210,6 +1230,9 @@ pub struct NearestTarget { pub interval: i32, /// Extra condition on the attacker, checked after the random interval. pub when: Option bool>, + /// Mobs closer than this squared distance are not picked + /// (`GuardianAttackSelector`: `distanceToSqr > 9`). + pub beyond_sqr: Option, /// A condition checked before anything else, by subclasses overriding /// `canUse` (SpiderTargetGoal: only in the dark). pub gate: Option bool>, @@ -1242,6 +1265,7 @@ impl NearestTarget { must_reach: false, interval: reduced(10), when: None, + beyond_sqr: None, gate: None, label: None, found: None, @@ -1274,6 +1298,10 @@ impl NearestTarget { self.when = Some(f); self } + pub fn beyond(mut self, distance_sqr: f64) -> Self { + self.beyond_sqr = Some(distance_sqr); + self + } pub fn gate(mut self, f: fn(&Mob, &MobWorld) -> bool) -> Self { self.gate = Some(f); self @@ -1284,9 +1312,25 @@ impl NearestTarget { self } } +/// `AbstractIllager.canAttack`: a baby `AbstractVillager` is never attacked. +fn illager_spares(attacker: Species, target: &Seen) -> bool { + matches!( + attacker, + Species::Pillager | Species::Vindicator | Species::Evoker | Species::Illusioner + ) && target.baby + && matches!(target.species, Species::Villager | Species::WanderingTrader) +} /// TargetGoal.canContinueToUse pub fn target_continue(st: &mut TargetState, must_see: bool, m: &mut Mob, cx: &mut Cx) -> bool { let Some(who) = m.ai.target else { return false }; + if let Who::Mob(id) = who + && cx + .w + .seen(id) + .is_some_and(|s| illager_spares(m.species(), s)) + { + return false; + } let Some(t) = cx.w.target_info(who) else { return false; }; @@ -1345,10 +1389,12 @@ impl Goal for NearestTarget { prey => { let pos = Vec3::new(m.position.x, m.eye_y(), m.position.z); let id = m.id; + let attacker = m.species(); let candidates: Vec<(u32, Vec3)> = cx.w.nearby(pos, range, move |s| { s.id != id && !s.playing_dead + && !illager_spares(attacker, s) && match prey { Prey::Species(list) => list.contains(&s.species), Prey::Filter(f) => f(s), @@ -1361,6 +1407,9 @@ impl Goal for NearestTarget { if m.distance_sqr(cpos) > range * range { continue; } + if self.beyond_sqr.is_some_and(|d| m.distance_sqr(cpos) <= d) { + continue; + } if !m.sees(cx.w, Who::Mob(cid)) { continue; } @@ -1393,6 +1442,9 @@ pub struct HurtByTarget { /// `Bee.BeeHurtByOtherGoal`: kept only while angry, and alerting others /// only when the attacker is in sight. pub bee: bool, + /// `PolarBear.PolarBearHurtByTargetGoal`: a hurt cub only calls the + /// adult bears and drops the target itself. + pub polar_bear: bool, timestamp: i32, st: TargetState, } @@ -1403,6 +1455,7 @@ impl HurtByTarget { alert_except: vec![], ignore: vec![], bee: false, + polar_bear: false, timestamp: 0, st: TargetState { unseen_memory: 300, @@ -1422,6 +1475,10 @@ impl HurtByTarget { self.bee = true; self } + pub fn polar_bear(mut self) -> Self { + self.polar_bear = true; + self + } } impl Default for HurtByTarget { fn default() -> Self { @@ -1433,6 +1490,8 @@ impl Goal for HurtByTarget { fn name(&self) -> &'static str { if self.bee { "BeeHurtByOtherGoal" + } else if self.polar_bear { + "PolarBearHurtByTargetGoal" } else { "HurtByTarget" } @@ -1471,7 +1530,9 @@ impl Goal for HurtByTarget { self.timestamp = m.ai.last_hurt_by_time; self.st.unseen_memory = 300; self.st.unseen = 0; - if self.alert + // PolarBearHurtByTargetGoal.start: a cub alerts the adults itself. + let cub = self.polar_bear && m.is_baby(); + if (self.alert || cub) && let Some(by) = m.ai.target { let range = m.attrs.follow_range; @@ -1491,6 +1552,8 @@ impl Goal for HurtByTarget { && (s.position.z - pos.z).abs() <= range + 1.0 }) .filter(|s| !self.alert_except.contains(&s.species)) + // PolarBearHurtByTargetGoal.alertOther: adults only. + .filter(|s| !(self.polar_bear && s.baby)) .filter(|s| Who::Mob(s.id) != by) .map(|s| s.id) .collect(); @@ -1505,6 +1568,9 @@ impl Goal for HurtByTarget { }); } } + if cub { + m.ai.target = None; + } } fn stop(&mut self, m: &mut Mob, _: &mut Cx) { m.ai.target = None; @@ -1762,6 +1828,10 @@ impl Goal for Breed { if tamable && (!m.extra.tame || m.extra.sitting) { return false; } + // TurtleBreedGoal.canUse: not while carrying an egg. + if species == Species::Turtle && super::turtle::has_egg(m) { + return false; + } let id = m.id; // Horses and donkeys breed together (AbstractHorse.canParent: tame). // Sniffer.canMate: calm states only. @@ -1771,11 +1841,16 @@ impl Goal for Breed { } let llama = super::llama::is_llama(species); let equine = matches!(species, Species::Horse | Species::Donkey) || llama; - if equine && !m.extra.tame { - return false; - } - // Llama.canParent: not ridden, and at full health. - if llama && (m.rider.is_some() || m.health < m.attrs.max_health) { + // AbstractHorse.canParent: tame, an adult, not a vehicle or passenger + // and at full health. + if equine + && (!m.extra.tame + || m.is_baby() + || m.rider.is_some() + || m.extra.rider.is_some() + || m.extra.mount.is_some() + || m.health < m.attrs.max_health) + { return false; } self.partner = @@ -1788,7 +1863,10 @@ impl Goal for Breed { && s.in_love && !s.baby && (!tamable || s.tame) - && (!equine || s.tame) + // Wolf.canMate: a sitting wolf is no partner. + && !(species == Species::Wolf && s.sitting) + // AbstractHorse.canParent of the partner. + && (!equine || s.tame && !s.ridden && s.health >= s.stats[0] as f32) && (!sniffer || super::sniffer::can_mate_state(s.variant)) }) .map(|s| s.id) @@ -1832,6 +1910,10 @@ impl Goal for Breed { }); m.extra.in_love = 0; m.extra.age = 6000; + // TurtleBreedGoal.breed: the mother carries an egg, not a baby. + if m.species() == Species::Turtle { + m.extra.flag = true; + } cx.events.push(MobEvent::Breed { parent: m.id, partner: p.id, diff --git a/crates/horizon-client/src/mobs/guardian.rs b/crates/horizon-client/src/mobs/guardian.rs index d6219794d..880655361 100644 --- a/crates/horizon-client/src/mobs/guardian.rs +++ b/crates/horizon-client/src/mobs/guardian.rs @@ -61,7 +61,8 @@ pub fn register(m: &mut Mob) { NearestTarget::species( &[Species::Squid, Species::GlowSquid, Species::Axolotl], true, - ), + ) + .beyond(9.0), ); } /// `GuardianAttackGoal`. @@ -120,9 +121,11 @@ impl Goal for GuardianAttack { 1.0, )); } else if self.attack_time >= attack_duration(m) { - // Indirect magic (1, +2 for the elder; NORMAL difficulty), then + // Indirect magic (1, +2 on Hard, +2 for the elder), then // doHurtTarget. - let magic = if is_elder(m) { 3.0 } else { 1.0 }; + let magic = 1.0 + + if cx.w.difficulty.hard { 2.0 } else { 0.0 } + + if is_elder(m) { 2.0 } else { 0.0 }; let from = [m.position.x, m.position.y, m.position.z]; match who { Who::Player => cx.events.push(MobEvent::DamagePlayer { @@ -241,9 +244,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } else { a.v[SPIKES] += (1.0 - a.v[SPIKES]) * 0.06; } - if m.extra.flag && m.extra.counter2 < attack_duration(m) { - m.extra.counter2 += 1; - } + client_tick(m); if in_water { m.air = 300; } else if m.on_ground { @@ -332,6 +333,13 @@ pub fn elder_server_ai_step(m: &mut Mob, cx: &mut Cx) { ]); } } +/// Guardian.aiStep's visual attack clock, also used by server clients. +/// Does not run attack goals, movement, damage or random draws. +pub fn client_tick(m: &mut Mob) { + if m.extra.flag && m.extra.counter2 < attack_duration(m) { + m.extra.counter2 += 1; + } +} /// The beam's clock for rendering: (attack time with the partial tick, /// attack scale), while a target is locked. pub fn beam(m: &Mob, partial: f32) -> Option<(f32, f32)> { diff --git a/crates/horizon-client/src/mobs/hostile.rs b/crates/horizon-client/src/mobs/hostile.rs index 0d3feaa6c..f1c990c48 100644 --- a/crates/horizon-client/src/mobs/hostile.rs +++ b/crates/horizon-client/src/mobs/hostile.rs @@ -177,6 +177,10 @@ pub fn creeper_tick(m: &mut Mob, events: &mut Vec) { if m.swell >= 30 { m.swell = 30; let radius = if m.extra.charged { 6.0 } else { 3.0 }; + events.push(MobEvent::ExplosionSource { + mob: m.id, + charged: m.extra.charged, + }); events.push(MobEvent::Explode( [m.position.x, m.position.y, m.position.z], radius, diff --git a/crates/horizon-client/src/mobs/illager.rs b/crates/horizon-client/src/mobs/illager.rs index 45ef076d3..00581d6d3 100644 --- a/crates/horizon-client/src/mobs/illager.rs +++ b/crates/horizon-client/src/mobs/illager.rs @@ -72,6 +72,8 @@ pub fn register_vindicator(m: &mut Mob) { let g = &mut m.ai.goals; g.add(0, Float); g.add(1, avoid_creaking(1.0, 1.2)); + g.add(2, super::doors::BreakDoor::vindicator()); + g.add(3, super::doors::RaiderOpenDoor::default()); g.add(4, super::raider::HoldGroundAttack::new(10.0)); g.add(5, MeleeAttack::new(1.0, false)); g.add(8, Stroll::new(0.6)); @@ -86,6 +88,13 @@ pub fn register_vindicator(m: &mut Mob) { .when(|m, _| m.custom_name.as_deref() == Some("Johnny")), ); } +/// `Vindicator.customServerAiStep`: its navigation opens doors while a raid +/// is at its position. +pub fn vindicator_server_ai_step(m: &mut Mob) { + if super::doors::can_navigate_ground(m) { + m.ai.nav.can_open_doors = super::raider::state(m).is_some_and(|s| s.raided); + } +} // Evoker state: `counter` spellCastingTickCount, `variant2` the spell // being cast (0 none, 1 vexes, 2 fangs, 3 wololo), `counter2` the wololo // sheep's id. @@ -179,8 +188,8 @@ impl Goal for UseSpell { fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { let age = i64::from(m.age); if self.spell == Spell::Wololo { - // EvokerWololoSpellGoal.canUse: a blue sheep within 16 (4 up or - // down), no target, griefing on. + // EvokerWololoSpellGoal.canUse: a blue sheep within the box + // (16 sideways, 4 up or down) and `range(16)`, no target, griefing on. if m.ai.target.is_some() || m.extra.counter > 0 || age < self.next || !cx.w.mob_griefing { return false; @@ -196,6 +205,7 @@ impl Goal for UseSpell { && (s.position.x - p.x).abs() <= 16.0 && (s.position.y - p.y).abs() <= 4.0 && (s.position.z - p.z).abs() <= 16.0 + && s.position.distance_squared(p) <= 16.0 * 16.0 }) .map(|s| s.id) .collect(); @@ -210,7 +220,8 @@ impl Goal for UseSpell { return false; } if self.spell == Spell::Vexes { - // EvokerSummonSpellGoal: fewer vexes nearby than a roll of 1..8. + // EvokerSummonSpellGoal: fewer vexes within `range(16)` than a + // roll of 1..8. let p = m.position; let vexes = cx.w.others @@ -218,7 +229,7 @@ impl Goal for UseSpell { .filter(|s| { s.species == Species::Vex && s.alive - && s.position.distance_squared(p) <= 16.0 * 16.0 * 3.0 + && s.position.distance_squared(p) <= 16.0 * 16.0 }) .count() as i32; return m.random.next_int_bound(8).unwrap_or(0) + 1 > vexes; @@ -670,7 +681,12 @@ pub fn anim_pose(m: &Mob, s: &State, p: &mut Poses, pose: ArmPose) { p.xrot("right_arm", x + a * 1.2 - b * 0.4); p.xrot("left_arm", x + a * 1.2 - b * 0.4); } else { - // swingWeaponDown (right-handed). + // swingWeaponDown: the main arm swings down. + let (main, off) = if m.main_arm_left() { + ("left_arm", "right_arm") + } else { + ("right_arm", "left_arm") + }; let swing = s.swing; let a2 = (swing * PI).msin(); let a = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin(); @@ -679,11 +695,11 @@ pub fn anim_pose(m: &Mob, s: &State, p: &mut Poses, pose: ArmPose) { p.yrot("right_arm", PI / 20.0); p.yrot("left_arm", -PI / 20.0); p.xrot( - "right_arm", + main, -1.884_955_8 + (s.age * 0.09).mcos() * 0.15 + (a2 * 2.2 - a * 0.4), ); p.xrot( - "left_arm", + off, -0.0 + (s.age * 0.19).mcos() * 0.5 + (a2 * 1.2 - a * 0.4), ); } diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 394821ace..e9cd42798 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -908,7 +908,7 @@ impl Mob { (distance * 4.0).min(1.0) }; self.limb_speed += (target - self.limb_speed) * 0.4; - self.limb_position += self.limb_speed * if self.is_baby() { 3.0 } else { 1.0 }; + self.limb_position += self.limb_speed; } else { self.limb_speed = 0.0; } diff --git a/crates/horizon-client/src/mobs/piglin.rs b/crates/horizon-client/src/mobs/piglin.rs index 410364097..b62262bb0 100644 --- a/crates/horizon-client/src/mobs/piglin.rs +++ b/crates/horizon-client/src/mobs/piglin.rs @@ -9,14 +9,20 @@ use super::{ NearestTarget, Prey, RandomLookAround, Stroll, goal_clone, }, }; -use horizon_core::geometry::trig::Mth; -use horizon_core::random::RandomSource; +use horizon_core::geometry::{Vec3, trig::Mth}; +use horizon_core::random::{LegacyRandom, RandomSource}; use std::f32::consts::PI; /// `PiglinAi.ADMIRE_DURATION`. pub const ADMIRE: i32 = 119; +/// `PiglinAi.eat`: the `ATE_RECENTLY` memory lasts 200 ticks (kept in +/// `extra.ints[0]` of a piglin). +pub const ATE_RECENTLY: i32 = 200; /// `AbstractPiglin.CONVERSION_TIME` (and the hoglin's). const CONVERSION: i32 = 300; +/// `PiglinAi.CELEBRATION_TIME`: how long the `CELEBRATE_LOCATION` and +/// `DANCING` memories last. +const CELEBRATION: i32 = 300; fn hostile_to_player(m: &Mob, w: &MobWorld) -> bool { if m.is_baby() { @@ -45,7 +51,9 @@ pub fn register_piglin(m: &mut Mob) { g.add(3, super::illager::crossbow_goal(1.0, 8.0)); } g.add(3, MeleeAttack::new(1.0, true)); + g.add(4, PiglinAvoidRepellent); g.add(4, GoToWantedItem); + g.add(4, Celebrate); g.add(5, Stroll::avoiding_water(0.6)); g.add(6, LookAtPlayer::new(8.0)); g.add(7, RandomLookAround::default()); @@ -83,12 +91,16 @@ pub fn register_hoglin(m: &mut Mob) { g.add(1, BabyPanic(super::goals::Panic::new(1.25))); g.add(2, MeleeAttack::new(1.0, true)); g.add(3, super::goals::Breed::new(1.0)); + g.add(3, HoglinAvoidRepellent); g.add(4, super::goals::FollowParent::new(1.1)); g.add(5, Stroll::avoiding_water(0.4)); g.add(6, LookAtPlayer::new(8.0)); m.ai.targets.add(1, HurtByTarget::new().alert()); - m.ai.targets - .add(2, NearestTarget::player(true).when(|m, _| !m.is_baby())); + // `HoglinAi.findNearestValidAttackTarget`: nothing while pacified. + m.ai.targets.add( + 2, + NearestTarget::player(true).when(|m, _| !m.is_baby() && m.extra.ints[0] <= 0), + ); } pub fn register_zoglin(m: &mut Mob) { let g = &mut m.ai.goals; @@ -108,6 +120,49 @@ pub fn register_zoglin(m: &mut Mob) { .interval(10), ); } +/// `SetWalkTargetAwayFrom.pos(NEAREST_REPELLENT, 1.0, 8, true)` of the hoglin's +/// idle activity: closer than 8 blocks to a repellent, walk away from it. +#[derive(Clone, Debug)] +struct HoglinAvoidRepellent; +impl Goal for HoglinAvoidRepellent { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some(r) = m.extra.repellent else { + return false; + }; + // Vec3.atBottomCenterOf. + let avoid = [ + f64::from(r[0]) + 0.5, + f64::from(r[1]), + f64::from(r[2]) + 0.5, + ]; + if m.distance_sqr(Vec3::new(avoid[0], avoid[1], avoid[2])) >= 64.0 { + return false; + } + for _ in 0..10 { + if let Some(p) = m.land_random_pos_away(cx.w, 16, 7, avoid) { + let at = [ + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ]; + m.ai.pending_path = m.create_path_to(cx.w, at, 0); + return m.ai.pending_path.is_some(); + } + } + false + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + !m.ai.nav.is_done() + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + let path = m.ai.pending_path.take(); + m.nav_move_to_path(path, 1.0); + } +} /// Baby hoglins flee what hurts them; adults stand their ground. #[derive(Clone, Debug)] struct BabyPanic(super::goals::Panic); @@ -129,6 +184,54 @@ impl Goal for BabyPanic { self.0.stop(m, cx) } } +/// `PiglinAi.avoidRepellent`: `SetWalkTargetAwayFrom.pos(NEAREST_REPELLENT, 1.0, 8, false)` +/// of the idle activity. Closer than 8 blocks to a repellent and not walking +/// anywhere, walk away from it. +#[derive(Clone, Debug)] +struct PiglinAvoidRepellent; +impl Goal for PiglinAvoidRepellent { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some(r) = m.extra.repellent else { + return false; + }; + // The idle activity: not fighting or admiring, and no walk target yet. + if m.ai.target.is_some() || m.extra.using_item > 0 || !m.ai.nav.is_done() { + return false; + } + // Vec3.atBottomCenterOf. + let avoid = [ + f64::from(r[0]) + 0.5, + f64::from(r[1]), + f64::from(r[2]) + 0.5, + ]; + if m.distance_sqr(Vec3::new(avoid[0], avoid[1], avoid[2])) >= 64.0 { + return false; + } + for _ in 0..10 { + if let Some(p) = m.land_random_pos_away(cx.w, 16, 7, avoid) { + let at = [ + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ]; + m.ai.pending_path = m.create_path_to(cx.w, at, 0); + return m.ai.pending_path.is_some(); + } + } + false + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + !m.ai.nav.is_done() + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + let path = m.ai.pending_path.take(); + m.nav_move_to_path(path, 1.0); + } +} /// Admiring a gold item held in the off hand: stand and look at it. #[derive(Clone, Debug)] struct Admire; @@ -144,6 +247,45 @@ impl Goal for Admire { m.nav_stop(); } } +/// The celebrate activity: `GoToTargetLocation` on the spot a killed target +/// fell (within 2 blocks, or 4 and slower while dancing). +#[derive(Clone, Debug)] +struct Celebrate; +impl Celebrate { + fn walk(m: &mut Mob, cx: &mut Cx) { + let Some(at) = m.extra.home else { return }; + let (close, speed) = if m.extra.scratch[0] > 0 { + (4.0, 0.6) + } else { + (2.0, 1.0) + }; + let center = Vec3::new( + f64::from(at[0]) + 0.5, + f64::from(at[1]), + f64::from(at[2]) + 0.5, + ); + if m.distance_sqr(center) >= close * close { + m.nav_move_to(cx.w, [center.x, center.y, center.z], speed); + } + } +} +impl Goal for Celebrate { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + m.extra.scratch[1] > 0 && m.extra.home.is_some() && m.extra.using_item == 0 + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + Self::walk(m, cx); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if m.ai.nav.is_done() { + Self::walk(m, cx); + } + } +} /// `GoToWantedItem`: walk to the gold the game spotted. #[derive(Clone, Debug)] struct GoToWantedItem; @@ -165,18 +307,102 @@ impl Goal for GoToWantedItem { m.extra.point = None; } } +/// `HoglinSpecificSensor.findNearestRepellent`: the nearest `#hoglin_repellents` +/// block within 8 blocks sideways and 4 up or down. +fn find_hoglin_repellent(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> { + let tag = w.block_tags.get("minecraft:hoglin_repellents")?; + let at = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + w.nearest_block(at, 8, 4, |_, name| tag.contains(name)) +} +/// The hoglin's repellent memories: the sensor (every 20 ticks), the end of +/// `PACIFIED` (`ints[0]`), a hit ending it (`HoglinAi.wasHurtBy`, `ints[1]` +/// remembers the hit seen) and `BecomePassiveIfMemoryPresent(NEAREST_REPELLENT, 200)`. +fn hoglin_repellent(m: &mut Mob, w: &MobWorld) { + if m.extra.ints[0] > 0 { + m.extra.ints[0] -= 1; + } + if m.ai.last_hurt_by.is_some() && m.ai.last_hurt_by_time != m.extra.ints[1] { + m.extra.ints[1] = m.ai.last_hurt_by_time; + m.extra.ints[0] = 0; + } + if m.age.wrapping_add(m.id).is_multiple_of(20) { + m.extra.repellent = find_hoglin_repellent(m, w); + } + if m.extra.ints[0] <= 0 && m.extra.repellent.is_some() { + m.extra.ints[0] = 200; + m.ai.target = None; + } +} +/// `StartCelebratingIfTargetDead` for a piglin (`scratch[0]` dancing, +/// `scratch[1]` ticks of celebration left, `scratch[2]` the hit seen, `home` +/// the `CELEBRATE_LOCATION`): a killed target starts a celebration at its +/// spot, and a hoglin's death makes the piglin dance one time in ten. +/// `PiglinAi.wasHurtBy` ends both. Runs before the target goals drop the +/// dead target. +pub fn celebrate(m: &mut Mob, w: &MobWorld) { + if m.extra.scratch[1] > 0 { + m.extra.scratch[1] -= 1; + if m.extra.scratch[1] == 0 { + m.extra.scratch[0] = 0; + m.extra.home = None; + } + } + if let Some(by) = m.ai.last_hurt_by + && m.ai.last_hurt_by_time != m.extra.scratch[2] + { + m.extra.scratch[2] = m.ai.last_hurt_by_time; + // PiglinAi.wasHurtBy: another piglin's hit ends nothing. + let piglin = + matches!(by, Who::Mob(id) if w.seen(id).is_some_and(|s| s.species == Species::Piglin)); + if !piglin { + m.extra.scratch[0] = 0; + m.extra.scratch[1] = 0; + m.extra.home = None; + } + } + if m.extra.scratch[1] > 0 { + return; + } + let Some(target) = m.ai.target else { return }; + let Some(t) = w.target_info(target).filter(|t| !t.alive) else { + return; + }; + let hoglin = + matches!(target, Who::Mob(id) if w.seen(id).is_some_and(|s| s.species == Species::Hoglin)); + // PiglinAi.wantsToDance: a fresh random seeded with the game time, not + // the piglin's own. + if hoglin && LegacyRandom::new(w.game_time).next_float() < 0.1 { + m.extra.scratch[0] = 1; + } + m.extra.scratch[1] = CELEBRATION; + m.extra.home = Some([ + t.position.x.floor() as i32, + t.position.y.floor() as i32, + t.position.z.floor() as i32, + ]); +} /// Per-tick piglin and hoglin state: admiring, anger, zombification and the /// hoglin attack animation. Returns a conversion when it happens. pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { if m.extra.anim_ticks > 0 { m.extra.anim_ticks -= 1; } + if m.species() == Species::Hoglin && m.alive() { + hoglin_repellent(m, w); + } if m.extra.anger > 0 { m.extra.anger -= 1; if m.extra.anger == 0 && m.ai.target == Some(Who::Player) && !hostile_to_player(m, w) { m.ai.target = None; } } + if m.species() == Species::Piglin && m.extra.ints[0] > 0 { + m.extra.ints[0] -= 1; + } // Admiring disabled after being hit by a player. if m.extra.egg_time > 0 { m.extra.egg_time -= 1; @@ -219,6 +445,26 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } else { m.extra.counter2 = 0; } + // PiglinSpecificSensor (every 20 ticks): the nearest repelling block. + if m.species() == Species::Piglin && m.alive() && m.age.wrapping_add(m.id).is_multiple_of(20) { + m.extra.repellent = find_piglin_repellent(m, w); + } +} +/// `PiglinSpecificSensor.findNearestRepellent`: the nearest `#piglin_repellents` +/// block within 8 blocks sideways and 4 up or down; a soul campfire only +/// counts while lit. +fn find_piglin_repellent(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> { + let tag = w.block_tags.get("minecraft:piglin_repellents")?; + let at = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + w.nearest_block(at, 8, 4, |p, name| { + tag.contains(name) + && (name != "minecraft:soul_campfire" + || w.prop(p[0], p[1], p[2], "lit") == Some("true")) + }) } /// `HoglinBase.hurtAndThrowTarget`. pub fn hoglin_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { @@ -265,7 +511,10 @@ pub fn ears(p: &mut Poses, s: &State) { /// Piglins' and brutes' ears flap (`AbstractPiglinModel`), arms follow the /// arm pose (`PiglinModel`). pub fn piglin_anim(m: &Mob, s: &State, p: &mut Poses) { - let pose = if m.extra.using_item > 0 { + // Piglin.getArmPose: dancing comes first. + let pose = if m.extra.scratch[0] > 0 { + PiglinPose::Dancing + } else if m.extra.using_item > 0 { PiglinPose::AdmiringItem } else if m.extra.flag { PiglinPose::CrossbowCharge @@ -276,7 +525,14 @@ pub fn piglin_anim(m: &Mob, s: &State, p: &mut Poses) { } else { PiglinPose::Default }; - piglin_pose(p, s, pose, 25.0, m.extra.using_item as f32); + piglin_pose( + p, + s, + pose, + 25.0, + m.extra.using_item as f32, + m.main_arm_left(), + ); } /// `PiglinArmPose`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -288,11 +544,19 @@ pub enum PiglinPose { CrossbowCharge, AdmiringItem, } -/// `PiglinModel.setupAnim` for a piglin facing right-handed. -pub fn piglin_pose(p: &mut Poses, s: &State, pose: PiglinPose, max_charge: f32, ticks: f32) { - use super::anim::{ArmPose, Hum, humanoid}; +/// `PiglinModel.setupAnim`; `left` when the piglin's main arm is the left one. +pub fn piglin_pose( + p: &mut Poses, + s: &State, + pose: PiglinPose, + max_charge: f32, + ticks: f32, + left: bool, +) { + use super::anim::{ArmPose, Hum, crossbow_charge, crossbow_hold, humanoid}; let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty); h.weapon_swing = pose == PiglinPose::MeleeWeapon; + h.left_main = left; h.charge = (max_charge, ticks); humanoid(p, s, &h); ears(p, s); @@ -319,27 +583,22 @@ pub fn piglin_pose(p: &mut Poses, s: &State, pose: PiglinPose, max_charge: f32, p.get("left_arm")[1] += (dance * 40.0).msin() * 0.5 + 0.5; p.get("body")[1] += (dance * 40.0).msin() * 0.35; } - PiglinPose::MeleeWeapon if s.swing == 0.0 => p.xrot("right_arm", -1.8), - PiglinPose::CrossbowHold => { - p.yrot("right_arm", -0.3 + hy); - p.yrot("left_arm", 0.6 + hy); - p.xrot("right_arm", -PI / 2.0 + hx + 0.1); - p.xrot("left_arm", -1.5 + hx); - } - PiglinPose::CrossbowCharge => { - p.yrot("right_arm", -0.8); - p.xrot("right_arm", -0.970_796_35); - p.xrot("left_arm", -0.970_796_35); - let alpha = ticks.clamp(0.0, max_charge) / max_charge; - p.yrot("left_arm", 0.4 + alpha * (0.85 - 0.4)); - let x = -0.970_796_35 + alpha * (-PI / 2.0 - -0.970_796_35); - p.xrot("left_arm", x); + // holdWeaponHigh + PiglinPose::MeleeWeapon if s.swing == 0.0 => { + p.xrot(if left { "left_arm" } else { "right_arm" }, -1.8) } + PiglinPose::CrossbowHold => crossbow_hold(p, hx, hy, !left), + PiglinPose::CrossbowCharge => crossbow_charge(p, max_charge, ticks, !left), PiglinPose::AdmiringItem => { p.xrot("head", 0.5); p.yrot("head", 0.0); - p.yrot("left_arm", 0.5); - p.xrot("left_arm", -0.9); + if left { + p.yrot("right_arm", -0.5); + p.xrot("right_arm", -0.9); + } else { + p.yrot("left_arm", 0.5); + p.xrot("left_arm", -0.9); + } } _ => {} } diff --git a/crates/horizon-client/src/mobs/polar_bear.rs b/crates/horizon-client/src/mobs/polar_bear.rs new file mode 100644 index 000000000..bfd464a93 --- /dev/null +++ b/crates/horizon-client/src/mobs/polar_bear.rs @@ -0,0 +1,191 @@ +//! Polar bears (`PolarBear`): a neutral animal that defends its cubs, +//! fights back when hurt, and rears up before each swing. A cub flees what +//! hurts it and calls the adults. +//! +//! `extra.flag` is `DATA_STANDING_ID`, `extra.counter` the warning sound's +//! delay, `extra.anger` the `NeutralMob` anger left and `extra.flag2` whether +//! the player is who it is angry at. `anim.v[STAND]` is +//! `clientSideStandAnimation`. +use horizon_core::{geometry::Vec3, random::RandomSource}; + +use super::{ + DamageKind, Mob, MobWorld, Species, Who, + goals::{ + Cx, Float, FollowParent, Goal, HurtByTarget, LookAtPlayer, MOVE, MeleeAttack, + NearestTarget, Panic, RandomLookAround, Stroll, goal_clone, + }, + world::TargetInfo, +}; + +/// `anim.v` slot of `clientSideStandAnimation`. +pub const STAND: usize = 0; +/// `STAND_ANIMATION_TICKS`. +const STAND_TICKS: f32 = 6.0; + +pub fn register(m: &mut Mob) { + let g = &mut m.ai.goals; + g.add(0, Float); + g.add(1, MeleeAttack::new(1.25, true).polar_bear()); + g.add(1, PolarBearPanic(Panic::new(2.0))); + g.add(4, FollowParent::new(1.25)); + g.add(5, Stroll::new(1.0)); + g.add(6, LookAtPlayer::new(6.0)); + g.add(7, RandomLookAround::default()); + let t = &mut m.ai.targets; + t.add(1, HurtByTarget::new().polar_bear()); + // PolarBearAttackPlayersGoal: players near a cub, within half the + // follow range, never for a cub itself. + t.add( + 2, + NearestTarget::player(true) + .interval(20) + .follow_scale(0.5) + .reach() + .gate(|m, _| !m.is_baby()) + .when(cub_nearby) + .named("PolarBearAttackPlayersGoal"), + ); + t.add( + 3, + NearestTarget::player(true).when(|m, _| m.extra.anger > 0 && m.extra.flag2), + ); + t.add( + 4, + NearestTarget::species(&[Species::Fox], true) + .interval(10) + .reach() + .when(|m, _| !m.is_baby()), + ); +} + +/// `PolarBearAttackPlayersGoal.canUse`: a polar bear cub within 8 blocks +/// (4 up and down). +fn cub_nearby(m: &Mob, w: &MobWorld) -> bool { + let area = m.bounds().inflate(Vec3::new(8.0, 4.0, 8.0)); + w.others_near(area) + .any(|s| s.species == Species::PolarBear && s.baby && s.bounds.intersects(area)) +} + +/// `PanicGoal` with a function of the bear's age for the damage tag: a cub +/// panics at `PANIC_CAUSES`, an adult only at `PANIC_ENVIRONMENTAL_CAUSES`. +#[derive(Clone, Debug)] +struct PolarBearPanic(Panic); +impl Goal for PolarBearPanic { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + (m.is_baby() || environmental_panic(m)) && self.0.can_use(m, cx) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_continue(m, cx) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.start(m, cx) + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.stop(m, cx) + } +} +/// `DamageTypeTags.PANIC_ENVIRONMENTAL_CAUSES` (fire, lava, cactus), or +/// burning. +fn environmental_panic(m: &Mob) -> bool { + m.fire_ticks > 0 && !m.kind.flags.fire_immune + || m.last_damage.is_some_and(|(d, t)| { + matches!( + d.kind, + DamageKind::OnFire | DamageKind::InFire | DamageKind::Lava | DamageKind::Cactus + ) && i64::from(m.age) - t <= 40 + }) +} + +/// `PolarBear.setStanding`. +pub fn set_standing(m: &mut Mob, standing: bool) { + m.extra.flag = standing; +} + +/// `PolarBear.playWarningSound`. +fn play_warning_sound(m: &mut Mob, cx: &mut Cx) { + if m.extra.counter <= 0 { + m.voice("entity.polar_bear.warning", cx.events); + m.extra.counter = 40; + } +} + +/// `PolarBearMeleeAttackGoal.checkAndPerformAttack`: strike when ready and +/// in reach, rear up and growl in the last 10 ticks while close. +pub fn check_and_perform_attack( + until_attack: &mut i32, + cooldown: i32, + m: &mut Mob, + who: Who, + t: &TargetInfo, + cx: &mut Cx, +) { + if *until_attack <= 0 && m.within_melee_range(t) && m.sees(cx.w, who) { + *until_attack = cooldown; + super::ai::do_hurt_target(m, who, cx); + set_standing(m, false); + return; + } + let reach = t.bounds.size().x as f32 + 3.0; + if m.distance_sqr(t.position) < f64::from(reach * reach) { + if *until_attack <= 0 { + set_standing(m, false); + *until_attack = cooldown; + } + if *until_attack <= 10 { + set_standing(m, true); + play_warning_sound(m, cx); + } + } else { + *until_attack = cooldown; + set_standing(m, false); + } +} + +/// `PolarBear.tick`'s client half: `clientSideStandAnimation` follows the +/// synched standing flag by one tick a tick. A client of a server runs it +/// too. +pub fn client_tick(m: &mut Mob) { + let v = m.anim.v[STAND]; + m.anim.vo[STAND] = v; + let step = if m.extra.flag { 1.0 } else { -1.0 }; + m.anim.v[STAND] = (v + step).clamp(0.0, STAND_TICKS); +} +/// `PolarBear.getStandingAnimationScale`. +pub fn standing_scale(m: &Mob, partial: f32) -> f32 { + m.anim.lerp(STAND, partial) / STAND_TICKS +} + +/// `PolarBear.tick`: the stand animation, the warning sound's delay and +/// `NeutralMob.updatePersistentAnger`. +pub fn ai_step(m: &mut Mob, w: &MobWorld) { + client_tick(m); + if m.extra.counter > 0 { + m.extra.counter -= 1; + } + if m.ai.target.is_some() { + // Anger follows the target and starts over every tick it is held: + // 20 to 39 seconds (`PERSISTENT_ANGER_TIME`). + m.extra.flag2 = m.ai.target == Some(Who::Player); + m.extra.anger = 400 + m.random.next_int_bound(381).unwrap_or(0); + } else if m.extra.anger > 0 { + m.extra.anger -= 1; + if m.extra.anger == 0 { + stop_being_angry(m); + } + } + // A player in creative or spectator mode is forgiven at once. + if m.extra.flag2 && w.player.as_ref().is_some_and(|p| p.creative || p.spectator) { + stop_being_angry(m); + } +} +/// `NeutralMob.stopBeingAngry`. +fn stop_being_angry(m: &mut Mob) { + m.ai.last_hurt_by = None; + m.ai.target = None; + m.extra.anger = 0; + m.extra.flag2 = false; +} diff --git a/crates/horizon-client/src/mobs/rabbit.rs b/crates/horizon-client/src/mobs/rabbit.rs index a2ab6e95c..ac4c3850f 100644 --- a/crates/horizon-client/src/mobs/rabbit.rs +++ b/crates/horizon-client/src/mobs/rabbit.rs @@ -1,5 +1,9 @@ //! Rabbit hopping controls and the clocks consumed by `RabbitModel`. -use super::{Mob, MobEvent, MobWorld, control::Operation}; +use super::{ + Mob, MobEvent, MobWorld, + control::Operation, + goals::{Breed, Tempt}, +}; use horizon_core::{ geometry::{Vec3, trig}, random::RandomSource, @@ -14,7 +18,12 @@ const IDLE_TIMEOUT: usize = 3; const CLIENT_JUMP_TICKS: usize = 4; const CLIENT_JUMP_DURATION: usize = 5; +/// Rabbit.registerGoals after the generic panic and stroll: BreedGoal and +/// TemptGoal with rabbit food. pub fn register(m: &mut Mob) { + let food = m.kind.food.clone(); + m.ai.goals.add(2, Breed::new(0.8)); + m.ai.goals.add(3, Tempt::new(1.0, food, false)); m.ai.mov.kind = super::control::MoveKind::Custom; m.ai.nav.can_float = true; m.extra.ints[IDLE_TIMEOUT] = m.random.next_int_bound(40).unwrap_or(0) + 180; diff --git a/crates/horizon-client/src/mobs/raider.rs b/crates/horizon-client/src/mobs/raider.rs index 6c3ab9b64..d2ed62374 100644 --- a/crates/horizon-client/src/mobs/raider.rs +++ b/crates/horizon-client/src/mobs/raider.rs @@ -30,6 +30,9 @@ pub struct State { pub celebrating: bool, /// The raid is active (`hasActiveRaid`); set by the game every tick. pub active_raid: bool, + /// A raid is active within 96 blocks (`ServerLevel.isRaided`); set by + /// the game every tick for vindicators. + pub raided: bool, /// The raid is won or lost (`Raid.isOver`), lost (`isLoss`). pub raid_over: bool, pub raid_loss: bool, diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index bbbf26738..077fd38a6 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -951,21 +951,25 @@ fn draw_normals( return; } let normals = normals.part(p); - for poly in part.polygons.iter().filter(|_| !poses.skips(part)) { - let normal = poly.vertex_normal(normals); - for v in poly.vertices { - let pos = m.transform_point3(glam::Vec3::new(v[0], v[1], v[2]) / 16.0); - out.push(Vertex { - normal, - pos: pos.to_array(), - uv: [ - uv[0] + (uv[2] - uv[0]) * v[3], - uv[1] + (uv[3] - uv[1]) * v[4], - ], - layer: overlay, - color, - light, - }); + // `skips` is a name lookup: ask once per part, not once per polygon. A part + // hidden this way still draws its children, so only the polygons are gated. + if !poses.skips(part) { + for poly in &part.polygons { + let normal = poly.vertex_normal(normals); + for v in poly.vertices { + let pos = m.transform_point3(glam::Vec3::new(v[0], v[1], v[2]) / 16.0); + out.push(Vertex { + normal, + pos: pos.to_array(), + uv: [ + uv[0] + (uv[2] - uv[0]) * v[3], + uv[1] + (uv[3] - uv[1]) * v[4], + ], + layer: overlay, + color, + light, + }); + } } } for c in &part.children { @@ -1094,6 +1098,9 @@ fn render_visible( } } } + // One Poses refilled for every layer (armour draws up to seven): it keeps + // its maps' capacity. + let mut layer_poses = Poses::default(); for layer in all_layers { let Some(part) = m.kind.layer(&layer.model).cloned() else { continue; @@ -1101,8 +1108,8 @@ fn render_visible( let Some(uv) = atlas(&layer.texture) else { continue; }; - let mut poses = Poses::new(&part); - anim::setup(m, &s, &mut poses, &data.animations); + layer_poses.reset(&part); + anim::setup(m, &s, &mut layer_poses, &data.animations); if matches!(m.species(), Species::Villager | Species::ZombieVillager) && let Some((folder, variant)) = layer .texture @@ -1113,7 +1120,7 @@ fn render_visible( data.villager_hats .read() .unwrap_or_else(std::sync::PoisonError::into_inner) - .apply(folder, variant, profession, &mut poses); + .apply(folder, variant, profession, &mut layer_poses); } let light = if layer.full_bright { 240 | 240 << 8 @@ -1128,7 +1135,16 @@ fn render_visible( None => overlay, }; let start = out.len(); - draw(&part, base, &poses, uv, layer.color, light, overlay, out); + draw( + &part, + base, + &layer_poses, + uv, + layer.color, + light, + overlay, + out, + ); if layer.full_bright && m.species() != Species::Warden { for vertex in &mut out[start..] { vertex.normal = [0; 4]; diff --git a/crates/horizon-client/src/mobs/shulker.rs b/crates/horizon-client/src/mobs/shulker.rs index 11ebdadb4..6f0edc2d7 100644 --- a/crates/horizon-client/src/mobs/shulker.rs +++ b/crates/horizon-client/src/mobs/shulker.rs @@ -3,7 +3,7 @@ //! their face is lost or when badly hurt, and shrugging off arrows while //! closed. use super::{ - Damage, DamageKind, Mob, MobEvent, MobWorld, Who, + Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who, anim::{Poses, State}, goals::{ Cx, Goal, HurtByTarget, LOOK, LookAtPlayer, MOVE, NearestTarget, RandomLookAround, @@ -14,7 +14,7 @@ use crate::projectiles::{Projectile, ProjectileWorld, STEPS}; use horizon_core::geometry::trig::Mth; use horizon_core::{ geometry::{Aabb, Vec3}, - random::RandomSource, + random::{LegacyRandom, RandomSource}, }; use std::f32::consts::PI; @@ -164,12 +164,62 @@ pub fn after_hurt(m: &mut Mob) { m.extra.flag = true; } } -/// The deferred teleport of `after_hurt`. -pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { +/// `Shulker.hurtServer` after a shulker bullet's damage: unless the +/// low-health teleport was drawn instead (`else if`), `hitByShulkerBullet` +/// runs on the next tick. Whether the shell is open is read here, at hurt +/// time, so a goal opening it before that tick cannot change the outcome. +pub fn hit_by_bullet(m: &mut Mob) { + if m.species() == Species::Shulker && !m.extra.flag && m.extra.counter != 0 { + m.extra.flag2 = true; + } +} +/// The deferred teleport of `after_hurt` and `hitByShulkerBullet`. +pub fn ai_step( + m: &mut Mob, + w: &MobWorld, + level_random: &mut LegacyRandom, + events: &mut Vec, +) { if m.extra.flag { m.extra.flag = false; teleport(m, w, events); } + if m.extra.flag2 { + m.extra.flag2 = false; + hit_by_shulker_bullet(m, w, level_random, events); + } +} +/// `Shulker.hitByShulkerBullet` (only queued by an open shulker): it +/// teleports, and leaves a new one of its colour behind unless shulkers +/// crowd the place (one in five fewer chances for every other shulker +/// within 8 blocks). +fn hit_by_shulker_bullet( + m: &mut Mob, + w: &MobWorld, + level_random: &mut LegacyRandom, + events: &mut Vec, +) { + let old_position = m.position; + let old_box = m.bounds(); + if !teleport(m, w, events) { + return; + } + let area = old_box.inflate(Vec3::new(8.0, 8.0, 8.0)); + // The shulker itself stands within reach of its old box, so it counts. + let others = w + .others_near(area) + .filter(|s| { + s.alive && s.species == Species::Shulker && s.id != m.id && s.bounds.intersects(area) + }) + .count(); + let failure_chance = others as f32 / 5.0; + // The level's random, not the shulker's. + if level_random.next_float() < failure_chance { + return; + } + let mut baby = Mob::new(0, m.kind.clone(), old_position, 0.0); + baby.extra.color = m.extra.color; + events.push(MobEvent::Spawn(Box::new(baby))); } /// A ProjectileWorld over the mob world, for aiming a new bullet. struct Probe<'a, 'w> { diff --git a/crates/horizon-client/src/mobs/sniffer.rs b/crates/horizon-client/src/mobs/sniffer.rs index 6979171b8..c0c8d8155 100644 --- a/crates/horizon-client/src/mobs/sniffer.rs +++ b/crates/horizon-client/src/mobs/sniffer.rs @@ -94,6 +94,7 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec) { if current == DIGGING && now(m) == m.extra.ints[3] { let h = head_block(m); events.push(MobEvent::GiftLoot { + mob: m.id, table: "minecraft:gameplay/sniffer_digging", at: [f64::from(h[0]), f64::from(h[1]), f64::from(h[2])], }); diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index 93e3fe119..58118d2c2 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -35,6 +35,8 @@ pub fn placement_ok(species: Species, w: &MobWorld, x: i32, y: i32, z: i32) -> b #[derive(Clone, Copy, Debug)] pub struct LocalDifficulty { pub effective: f32, + /// The world difficulty is normal. + pub normal: bool, /// The world difficulty is hard. pub hard: bool, } @@ -45,9 +47,11 @@ impl LocalDifficulty { /// the overworld clock, the chunk's inhabited time and the moon. pub fn new(base: u8, total: i64, inhabited: i64, moon: f32) -> Self { let hard = base == 3; + let normal = base == 2; if base == 0 { return Self { effective: 0.0, + normal, hard, }; } @@ -60,6 +64,7 @@ impl LocalDifficulty { } Self { effective: f32::from(base) * (0.75 + global + local), + normal, hard, } } @@ -148,6 +153,14 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { S::Pig | S::Cow | S::Chicken => m.extra.variant = climate_index, S::Sheep => m.extra.color = super::farm::sheep_color(biome.climate, &mut m.random), S::Mooshroom => m.extra.variant = 0, + // Turtle.finalizeSpawn: home is where it spawned. + S::Turtle => { + m.extra.home = Some([ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]) + } S::Frog => m.extra.variant = biome.frog, S::Wolf => m.extra.variant = biome.wolf, S::Cat => m.extra.variant = super::tame::cat_variant(m, biome.full_moon), @@ -158,6 +171,9 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { if m.random.next_float() < 0.05 { m.extra.age = i32::MIN / 2; } + // setCanBreakDoors(nextFloat() < special * 0.1), before the gear. + let can_break_doors = m.random.next_float() < difficulty.special() * 0.1; + super::doors::set_can_break_doors(m, can_break_doors); if m.species() != S::Drowned { populate_armor(m, difficulty); } @@ -191,6 +207,9 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { // ZombifiedPiglin.populateDefaultEquipmentSlots: a golden sword, or // one time in 20 a golden spear. S::ZombifiedPiglin => { + // Zombie.finalizeSpawn's setCanBreakDoors. + let can_break_doors = m.random.next_float() < difficulty.special() * 0.1; + super::doors::set_can_break_doors(m, can_break_doors); let spear = m.random.next_int_bound(20).unwrap_or(1) == 0; m.extra.main_hand = Some( if spear { @@ -264,6 +283,18 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { S::Slime | S::MagmaCube => super::cube::finalize(m), _ => {} } + // Zombie.finalizeSpawn ends with handleAttributes: the reinforcement + // chance (and a leader's bonus) that `Zombie.hurtServer` reads. + if matches!( + m.species(), + S::Zombie | S::Husk | S::Drowned | S::ZombieVillager | S::ZombifiedPiglin + ) { + super::finalize::zombie_attributes( + m, + difficulty.special(), + super::finalize::Reason::Natural, + ); + } } /// VillagerType.byBiome pub fn villager_type(b: &BiomeFacts) -> u8 { diff --git a/crates/horizon-client/src/mobs/turtle.rs b/crates/horizon-client/src/mobs/turtle.rs new file mode 100644 index 000000000..98dd5b558 --- /dev/null +++ b/crates/horizon-client/src/mobs/turtle.rs @@ -0,0 +1,209 @@ +//! Turtles (`Turtle`): the egg a bred mother carries (`TurtleBreedGoal`), her +//! walk home (`TurtleGoHomeGoal`) and the egg she digs into the sand +//! (`TurtleLayEggGoal`). `extra.flag` is `hasEgg`, `extra.flag2` `isLayingEgg`, +//! `extra.counter` `layEggCounter` and `extra.home` `homePos`. +use super::{ + Mob, MobEvent, MobWorld, + goals::{Breed, Cx, Goal, JUMP, MOVE, MoveToBlock, goal_clone, reduced}, +}; +use horizon_core::random::RandomSource; + +pub fn register(m: &mut Mob) { + let g = &mut m.ai.goals; + g.add(1, Breed::new(1.0)); + g.add(1, LayEgg(MoveToBlock::new(1.0, 16, 1))); + g.add(4, GoHome::default()); +} +/// `Turtle.hasEgg`. +pub fn has_egg(m: &Mob) -> bool { + m.extra.flag +} +/// `Turtle.setLayingEgg`. +fn set_laying_egg(m: &mut Mob, on: bool) { + m.extra.counter = i32::from(on); + m.extra.flag2 = on; +} +/// `homePos.closerToCenterThan(position, distance)`. Spawning, hatching and +/// loading all set a home; one made any other way is at home where it stands. +fn close_to_home(m: &Mob, distance: f64) -> bool { + let home = m.extra.home.unwrap_or([ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]); + let d = [ + f64::from(home[0]) + 0.5 - m.position.x, + f64::from(home[1]) + 0.5 - m.position.y, + f64::from(home[2]) + 0.5 - m.position.z, + ]; + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < distance * distance +} +fn block_of(m: &Mob) -> [i32; 3] { + [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ] +} +/// `TurtleEggBlock.isSand`. +fn is_sand(w: &MobWorld, p: [i32; 3]) -> bool { + w.has_tag("minecraft:sand", w.block_name(p[0], p[1], p[2])) +} +/// `Turtle.aiStep`: while digging, sand crumbs fly every fifth tick. +pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + if m.alive() && m.extra.flag2 && m.extra.counter >= 1 && m.extra.counter % 5 == 0 { + let at = block_of(m); + let below = [at[0], at[1] - 1, at[2]]; + if is_sand(w, below) { + events.push(MobEvent::BlockBreakEffect { + pos: at, + block: below, + }); + } + } +} + +/// `Turtle.TurtleLayEggGoal`: a mother with an egg within 9 blocks of home +/// walks to sand with air above, digs for 200 ticks and lays it. +#[derive(Clone, Debug)] +struct LayEgg(MoveToBlock); +impl LayEgg { + /// `isValidTarget`: sand with air above it. + fn valid(w: &MobWorld, p: [i32; 3]) -> bool { + w.facts.is_air(w.world.block(p[0], p[1] + 1, p[2])) && is_sand(w, p) + } +} +impl Goal for LayEgg { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | JUMP + } + fn name(&self) -> &'static str { + "TurtleLayEggGoal" + } + fn every_tick(&self) -> bool { + true + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !(has_egg(m) && close_to_home(m, 9.0)) { + return false; + } + // MoveToBlockGoal.canUse. + if self.0.next_start > 0 { + self.0.next_start -= 1; + return false; + } + self.0.next_start = reduced(200 + m.random.next_int_bound(200).unwrap_or(0)); + self.0.find_nearest(m, cx.w, Self::valid) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_continue(cx.w, Self::valid) && has_egg(m) && close_to_home(m, 9.0) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.start(m, cx.w); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.tick(m, cx.w); + if m.fluids.in_water || !self.0.reached { + return; + } + if m.extra.counter < 1 { + set_laying_egg(m, true); + } else if m.extra.counter > 200 { + let at = [m.position.x, m.position.y, m.position.z]; + let pitch = 0.9 + m.random.next_float() * 0.2; + cx.events + .push(MobEvent::Sound("entity.turtle.lay_egg", at, 0.3, pitch)); + // Blocks.TURTLE_EGG with EGGS = nextInt(4) + 1 above the sand. + let eggs = m.random.next_int_bound(4).unwrap_or(0) + 1; + let registry = cx.w.registry; + let state = registry + .default_state("minecraft:turtle_egg") + .and_then(|d| registry.state(d).cloned()) + .and_then(|mut s| { + s.properties.insert("eggs".into(), eggs.to_string()); + registry.resolve(&s).ok() + }); + let b = self.0.block; + if let Some(state) = state { + cx.events.push(MobEvent::SetBlock { + pos: [b[0], b[1] + 1, b[2]], + state, + }); + } + m.extra.flag = false; + set_laying_egg(m, false); + m.extra.in_love = 600; + } + if m.extra.flag2 { + m.extra.counter += 1; + } + } +} + +/// `Turtle.TurtleGoHomeGoal`: a mother with an egg heads home; any adult +/// that strayed 64 blocks away does now and then. +#[derive(Clone, Debug, Default)] +struct GoHome { + stuck: bool, + close_to_home_try_ticks: i32, +} +impl Goal for GoHome { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn name(&self) -> &'static str { + "TurtleGoHomeGoal" + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + if m.is_baby() { + false + } else if has_egg(m) { + true + } else { + m.random.next_int_bound(reduced(700)).unwrap_or(1) == 0 && !close_to_home(m, 64.0) + } + } + fn start(&mut self, _m: &mut Mob, _cx: &mut Cx) { + self.stuck = false; + self.close_to_home_try_ticks = 0; + } + fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + !close_to_home(m, 7.0) && !self.stuck && self.close_to_home_try_ticks <= reduced(600) + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let home = m.extra.home.unwrap_or(block_of(m)); + let close = close_to_home(m, 16.0); + if close { + self.close_to_home_try_ticks += 1; + } + if !m.ai.nav.is_done() { + return; + } + let to = [ + f64::from(home[0]) + 0.5, + f64::from(home[1]), + f64::from(home[2]) + 0.5, + ]; + let mut next = m + .default_random_pos_towards(cx.w, 16, 3, to, std::f64::consts::PI / 10.0) + .or_else(|| m.default_random_pos_towards(cx.w, 8, 7, to, std::f64::consts::FRAC_PI_2)); + if let Some(at) = next + && !close + && cx.w.block_name( + at[0].floor() as i32, + at[1].floor() as i32, + at[2].floor() as i32, + ) != "minecraft:water" + { + next = m.default_random_pos_towards(cx.w, 16, 5, to, std::f64::consts::FRAC_PI_2); + } + match next { + Some(at) => { + m.nav_move_to(cx.w, at, 1.0); + } + None => self.stuck = true, + } + } +} diff --git a/crates/horizon-client/src/mobs/undead.rs b/crates/horizon-client/src/mobs/undead.rs index e77a37641..3707f4bbe 100644 --- a/crates/horizon-client/src/mobs/undead.rs +++ b/crates/horizon-client/src/mobs/undead.rs @@ -1,7 +1,8 @@ //! Zombies (zombie, husk, drowned, zombie villager) and skeletons (skeleton, //! stray, bogged, wither skeleton): goals, bow attacks, water conversion. use super::{ - Mob, MobEvent, Species, Who, + Damage, Mob, MobEvent, Species, Who, + doors::BreakDoor, goals::{ Avoid, AvoidEntity, Cx, FleeSun, Goal, HurtByTarget, LOOK, LookAtPlayer, MOVE, MeleeAttack, NearestTarget, RandomLookAround, RestrictSun, Stroll, goal_clone, @@ -10,11 +11,22 @@ use super::{ use crate::projectiles::{Projectile, ProjectileKind}; use horizon_core::{geometry::Vec3, random::RandomSource}; +/// `Zombie.hurtServer`, once the hit landed: a zombie with a target (its own, +/// else a living attacker) asks the game to try calling a reinforcement; the +/// difficulty, chance and spawn tests are the game's (`call_reinforcements`). +pub fn after_hurt(m: &mut Mob, source: &Damage) { + if let Some(target) = m.ai.target.or(source.attacker) { + m.outbox + .push(MobEvent::Reinforcements { mob: m.id, target }); + } +} + pub fn register(m: &mut Mob) { use Species as S; match m.species() { S::Zombie | S::Husk | S::ZombieVillager => { let g = &mut m.ai.goals; + g.add(1, BreakDoor::zombie()); g.add(4, AttackTurtleEgg::default()); g.add(8, LookAtPlayer::new(8.0)); g.add(8, RandomLookAround::default()); @@ -42,6 +54,7 @@ pub fn register(m: &mut Mob) { S::ZombifiedPiglin => { // ZombifiedPiglin.addBehaviourGoals: neutral until provoked. let g = &mut m.ai.goals; + g.add(1, BreakDoor::zombie()); g.add(8, LookAtPlayer::new(8.0)); g.add(8, RandomLookAround::default()); g.add(2, MeleeAttack::new(1.0, false).zombie()); @@ -58,6 +71,7 @@ pub fn register(m: &mut Mob) { S::Drowned => { // Zombie.registerGoals, then Drowned.addBehaviourGoals. let g = &mut m.ai.goals; + g.add(1, BreakDoor::zombie()); g.add(4, AttackTurtleEgg::default()); g.add(8, LookAtPlayer::new(8.0)); g.add(8, RandomLookAround::default()); @@ -136,12 +150,13 @@ pub fn register(m: &mut Mob) { } // The AbstractSkeleton constructor's reassessWeaponGoal, after // registerGoals; the weapon itself comes with finalizeSpawn. - let interval = if matches!(species, S::Bogged | S::Parched) { - 70 + // getHardAttackInterval / getAttackInterval. + let (hard, normal) = if matches!(species, S::Bogged | S::Parched) { + (50, 70) } else { - 40 + (20, 40) }; - m.ai.goals.add(4, SkeletonWeapon::new(interval)); + m.ai.goals.add(4, SkeletonWeapon::new(hard, normal)); } _ => {} } @@ -217,8 +232,10 @@ pub fn drowned_travel( m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9); true } -/// The trident throw of `Drowned.performRangedAttack`, until thrown tridents -/// exist: an arrow-like shot with the trident's damage. +/// The trident throw of `Drowned.performRangedAttack`: a `ThrownTrident` of +/// the held trident (a plain one when it holds none), owned by the drowned, +/// which cannot be picked up and does not return (`AbstractArrow` constructor: +/// only a player's projectile is `Pickup.ALLOWED`). fn drowned_throw(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { let Some(t) = cx.w.target_info(who) else { return; @@ -228,15 +245,18 @@ fn drowned_throw(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { let yd = t.position.y + (t.bounds.max_position().y - t.bounds.min_position().y) / 3.0 - start.y; let zd = t.position.z - m.position.z; let dist = (xd * xd + zd * zd).sqrt(); - let mut p = Projectile::new( - ProjectileKind::Arrow { - base_damage: 8.0, - critical: false, - effect: None, - }, - start, - Some(Who::Mob(m.id)), - ); + let mut trident = crate::items::ItemStack::new("minecraft:trident", 1); + if m.extra.main_hand.as_deref() == Some("minecraft:trident") + && let Some(g) = super::gear::gear(m) + { + for (e, l) in &g.slots[super::gear::MAIN] { + trident.enchant(e, *l); + } + } + let mut p = Projectile::new(ProjectileKind::Trident, start, Some(Who::Mob(m.id))); + if let Some(a) = p.arrow.as_mut() { + a.set_item(&trident); + } p.shoot( &mut crate::projectiles::own_random(m), [xd, yd + dist * f64::from(0.2_f32), zd], @@ -524,13 +544,20 @@ pub struct SkeletonWeapon { bow: BowAttack, melee: MeleeAttack, use_bow: bool, + /// The weapon the goal was last reassessed for. + assessed: Option, + hard_interval: i32, + normal_interval: i32, } impl SkeletonWeapon { - pub fn new(bow_interval: i32) -> Self { + pub fn new(hard_interval: i32, normal_interval: i32) -> Self { Self { - bow: BowAttack::new(1.0, bow_interval, 15.0), + bow: BowAttack::new(1.0, normal_interval, 15.0), melee: MeleeAttack::new(1.2, false), use_bow: false, + assessed: None, + hard_interval, + normal_interval, } } } @@ -556,6 +583,18 @@ impl Goal for SkeletonWeapon { fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { // The goal registered for the weapon in hand. self.use_bow = holding_bow(m); + // reassessWeaponGoal: a bow gets the hard interval only on Hard; it + // is picked again when the weapon changes (the first check after + // spawning or loading stands for finalizeSpawn and + // readAdditionalSaveData). + if self.assessed != Some(self.use_bow) { + self.assessed = Some(self.use_bow); + self.bow.interval_min = if cx.w.difficulty.hard { + self.hard_interval + } else { + self.normal_interval + }; + } if self.use_bow { self.bow.can_use(m, cx) } else { diff --git a/crates/horizon-client/src/mobs/vex.rs b/crates/horizon-client/src/mobs/vex.rs index de38f6da8..1301d1922 100644 --- a/crates/horizon-client/src/mobs/vex.rs +++ b/crates/horizon-client/src/mobs/vex.rs @@ -29,6 +29,7 @@ pub fn register(m: &mut Mob) { g.add(8, RandomMove); g.add(9, LookAtPlayer::new(3.0).probability(1.0)); g.add(10, LookAtPlayer::mobs(8.0)); + // `HurtByTargetGoal(this, Raider.class)`: raiders are ignored, vexes are not. let mut hurt = HurtByTarget::new().alert(); hurt.ignore = vec![ Species::Pillager, @@ -36,7 +37,7 @@ pub fn register(m: &mut Mob) { Species::Evoker, Species::Illusioner, Species::Witch, - Species::Vex, + Species::Ravager, ]; m.ai.targets.add(1, hurt); m.ai.targets.add(2, CopyOwnerTarget); diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index 575fafaed..aad0ec911 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -284,12 +284,14 @@ pub fn xp(m: &Mob) -> i32 { m.extra.trade.as_ref().map_or(0, |t| t.xp) } /// `Villager.setVillagerData(withProfession)`: a new profession forgets the -/// offers. +/// offers (`offers = null`), so the next `getOffers` rolls the new +/// profession's trades. pub fn set_profession(m: &mut Mob, profession: u8) { if m.extra.variant2 != profession { m.extra.variant2 = profession; if let Some(t) = m.extra.trade.as_mut() { t.offers.clear(); + t.unset = true; } } } @@ -446,6 +448,24 @@ impl Ext { } (stack.count > 0).then_some(stack) } + /// `SimpleContainer.removeItemType`: take up to `count` of the item from + /// the first stacks that hold it. + pub fn remove_item(&mut self, item: &str, mut count: u32) { + let mut slot = 0; + while slot < self.inventory.len() && count > 0 { + let s = &mut self.inventory[slot]; + if &*s.item == item { + let n = s.count.min(count); + s.count -= n; + count -= n; + if s.count == 0 { + self.inventory.remove(slot); + continue; + } + } + slot += 1; + } + } pub fn count_item(&self, item: &str) -> u32 { self.inventory .iter() @@ -752,30 +772,6 @@ pub fn finalize_summoned_golem(m: &mut Mob, random: &mut impl RandomSource) { } m.extra.left_handed = random.next_float() < 0.05; } -/// `PoiManager.take(HOME, ..., 48)`: the nearest bed head not `claimed` -/// (`free_head`: a bed head that is not occupied). -pub fn take_vacant_bed( - claimed: &[[i32; 3]], - from: [i32; 3], - mut free_head: impl FnMut(i32, i32, i32) -> bool, -) -> Option<[i32; 3]> { - let mut best: Option<(i32, [i32; 3])> = None; - for y in from[1] - 8..=from[1] + 8 { - for z in from[2] - 48..=from[2] + 48 { - for x in from[0] - 48..=from[0] + 48 { - let d = (x - from[0]).pow(2) + (y - from[1]).pow(2) + (z - from[2]).pow(2); - if d <= 48 * 48 - && best.is_none_or(|(b, _)| d < b) - && free_head(x, y, z) - && !claimed.contains(&[x, y, z]) - { - best = Some((d, [x, y, z])); - } - } - } - } - best.map(|(_, p)| p) -} /// `Villager.canBreed`: enough food, awake and an adult. pub fn can_breed(m: &Mob) -> bool { m.species() == Species::Villager @@ -846,6 +842,70 @@ pub fn read_nbt(m: &mut Mob, tag: &horizon_world::nbt::Tag) { mod tests { use super::*; + fn villager() -> Mob { + use crate::mobs::{Anim, Brain, Flags, MobType, Part, Species}; + use std::{collections::HashMap, sync::Arc}; + let kind = Arc::new(MobType { + id: "minecraft:villager".into(), + species: Species::Villager, + width: 0.6, + height: 1.95, + eye_height: 1.62, + category: "misc".into(), + max_health: 20.0, + speed: 0.5, + flying_speed: 0.02, + attack_damage: 0.0, + attack_knockback: 0.0, + follow_range: 48.0, + step_height: 0.6, + armor: 0.0, + armor_toughness: 0.0, + knockback_resistance: 0.0, + jump_strength: 0.42, + attributes: Arc::default(), + gravity: 0.08, + safe_fall_distance: 3.0, + fall_damage_multiplier: 1.0, + water_efficiency: 0.0, + water_slowdown: 0.8, + air_speed: 0.02, + baby_scale: 0.5, + head_rot_speed: 10.0, + max_head_x_rot: 40.0, + max_head_y_rot: 75.0, + ambient_interval: 80, + flags: Flags::default(), + model: Arc::new(Part::parse("root", &serde_json::json!({}))), + layers: HashMap::new(), + texture: String::new(), + brain: Brain::Passive, + anim: Anim::Villager, + sounds: [""; 3], + step_sound: None, + food: Arc::default(), + tempt: Arc::default(), + }); + Mob::new(1, kind, horizon_core::geometry::Vec3::ZERO, 0.0) + } + #[test] + fn a_new_profession_rolls_new_offers() { + let mut m = villager(); + set_profession(&mut m, 1); + // Offers made for the first profession. + m.extra.trade.get_or_insert_default().unset = false; + // The same profession keeps them. + set_profession(&mut m, 1); + assert!(!m.extra.trade.as_ref().unwrap().unset); + // A new one forgets them (offers = null), so the next getOffers + // (ensure_offers) rolls the new profession's trades. + set_profession(&mut m, 2); + let t = m.extra.trade.as_ref().unwrap(); + assert!(t.offers.is_empty()); + assert!(t.unset); + assert_eq!(m.extra.variant2, 2); + } + fn stack(item: &str, count: u32) -> ItemStack { ItemStack::new(item, count) } diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index 7b311a9e0..2052eef4c 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -1242,6 +1242,8 @@ enum B { WorkAtPoi { t: Timed, last_check: i64, + /// `WorkAtComposter` (a farmer's package) rather than `WorkAtPoi`. + composter: bool, }, StrollAroundPoi { running: bool, @@ -1635,7 +1637,11 @@ impl B { *birth = now + 275 + i64::from(m.random.next_int_bound(50).unwrap_or(0)); true } - B::WorkAtPoi { t, last_check } => { + B::WorkAtPoi { + t, + last_check, + composter, + } => { let mm = mem(m); let Some(site) = mm.job_site.value() else { return false; @@ -1656,6 +1662,13 @@ impl B { mm.last_worked_at_poi.set(now); mm.look_target.set(Tracker::Block(site)); play_work_sound(m, cx); + // WorkAtComposter.useWorkstation, before the restock. + if *composter { + cx.events.push(MobEvent::WorkAtComposter { + mob: m.id, + pos: site, + }); + } restock_if_due(m, cx.w); true } @@ -3396,8 +3409,10 @@ fn breeding_possible(m: &mut Mob, w: &MobWorld) -> bool { && super::villager::can_breed(m) && w.seen(id).is_some_and(|s| s.in_love) } -/// `VillagerMakeLove.takeVacantBed`: a bed head no villager has claimed. -fn take_bed_for_child(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> { +/// `VillagerMakeLove.takeVacantBed`: `PoiManager.take(HOME, ..., 48)` over a +/// sphere of 48 blocks, the nearest bed head no villager has claimed that the +/// villager can walk to (`canReach`: a path that gets there). +fn take_bed_for_child(m: &mut Mob, w: &MobWorld) -> Option<[i32; 3]> { let claimed: Vec<[i32; 3]> = w .others .iter() @@ -3405,10 +3420,20 @@ fn take_bed_for_child(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> { .filter_map(|s| s.bed) .chain(m.extra.bed) .collect(); - let p = m.position; - let from = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; - super::villager::take_vacant_bed(&claimed, from, |x, y, z| { - w.prop(x, y, z, "part") == Some("head") && w.prop(x, y, z, "occupied") != Some("true") + let from = block_of(m.position); + let mut beds: Vec<[i32; 3]> = homes_in_range(m, w, 48) + .into_iter() + .filter(|p| { + w.prop(p[0], p[1], p[2], "part") == Some("head") + && w.prop(p[0], p[1], p[2], "occupied") != Some("true") + && !claimed.contains(p) + }) + .collect(); + // Nearest first; equally near beds stay in scan order. + beds.sort_by_key(|p| dist_sqr(*p, from)); + beds.into_iter().find(|&p| { + m.create_path_to(w, p, Poi::Home.valid_range()) + .is_some_and(|path| path.reached) }) } /// `BehaviorUtils.lockGazeAndWalkToEachOther`: this villager's half, and @@ -3775,6 +3800,7 @@ fn packages(baby: bool, seed: i64, farmer: bool) -> Vec { B::WorkAtPoi { t: timed(60, 60), last_check: 0, + composter: farmer, }, 7, ), diff --git a/crates/horizon-client/src/mobs/witch.rs b/crates/horizon-client/src/mobs/witch.rs index 0990ae01d..b0ec7866a 100644 --- a/crates/horizon-client/src/mobs/witch.rs +++ b/crates/horizon-client/src/mobs/witch.rs @@ -193,6 +193,11 @@ fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { } Who::Player => false, }; + // `target.hasEffect`: a target that already has the effect gets the next one. + let has = |effect: &str| match who { + Who::Player => cx.w.player.as_ref().is_some_and(|p| p.has_effect(effect)), + Who::Mob(id) => cx.w.seen(id).is_some_and(|s| s.has_effect(effect)), + }; let (effect, ticks, amplifier) = if heals { m.ai.target = None; if health <= 4.0 { @@ -200,11 +205,11 @@ fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { } else { ("minecraft:regeneration", 900, 0) } - } else if dist >= 8.0 { + } else if dist >= 8.0 && !has("slowness") { ("minecraft:slowness", 1800, 0) - } else if health >= 8.0 { + } else if health >= 8.0 && !has("poison") { ("minecraft:poison", 900, 0) - } else if dist <= 3.0 && m.random.next_float() < 0.25 { + } else if dist <= 3.0 && !has("weakness") && m.random.next_float() < 0.25 { ("minecraft:weakness", 1800, 0) } else { ("minecraft:instant_damage", 1, 0) @@ -236,6 +241,15 @@ fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { pitch, )); } +/// The movement speed of a witch with `SPEED_MODIFIER_DRINKING` (-0.25, +/// `ADD_VALUE`) while it drinks: it stands still for the 32 ticks. +pub fn speed(m: &Mob, base: f64) -> f64 { + if m.species() == Species::Witch && m.extra.flag { + (base - 0.25).max(0.0) + } else { + base + } +} /// Witch.aiStep before `super.aiStep()`: the healing cooldown, then drink /// water breathing, fire resistance, healing or swiftness. pub fn ai_step(m: &mut Mob, cx_events: &mut Vec, target_far: bool) { diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index 7836a49ef..bce324228 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -65,6 +65,35 @@ impl MobWorld<'_> { pub fn has_tag(&self, tag: &str, block: &str) -> bool { self.block_tags.get(tag).is_some_and(|s| s.contains(block)) } + /// `findBlocksInBoxByManhattanDistance(at, range_xz, range_y).filterState(..).findFirst()`: + /// the first block `matches` accepts (given its position and name), going + /// out from `at` by Manhattan distance as `BlockPos.withinBoxByManhattanDistance` does. + pub fn nearest_block( + &self, + at: [i32; 3], + range_xz: i32, + range_y: i32, + matches: impl Fn([i32; 3], &str) -> bool, + ) -> Option<[i32; 3]> { + // Visiting order: distance, then x, then y, then +z before -z. + let mut best: Option<((i32, i32, i32, bool), [i32; 3])> = None; + for dx in -range_xz..=range_xz { + for dy in -range_y..=range_y { + for dz in -range_xz..=range_xz { + let key = (dx.abs() + dy.abs() + dz.abs(), dx, dy, dz < 0); + if best.is_some_and(|(k, _)| k <= key) { + continue; + } + let p = [at[0] + dx, at[1] + dy, at[2] + dz]; + let state = self.world.block(p[0], p[1], p[2]); + if !self.facts.is_air(state) && matches(p, &self.facts.get(state).name) { + best = Some((key, p)); + } + } + } + } + best.map(|(_, p)| p) + } /// Level.clip with COLLIDER shapes (optionally stopping at any fluid): true on a miss. pub fn clear_between(&self, from: Vec3, to: Vec3, fluids_block: bool) -> bool { let mut scene = SceneCollisions { @@ -177,6 +206,19 @@ impl MobWorld<'_> { } self.world.light(x, y, z) >> 4 == 15 } + /// Level.isRainingAt: raining, open to the sky, nothing motion blocking + /// above, and the biome's precipitation at the position is rain, not snow + /// or none. + pub fn raining_at(&self, x: i32, y: i32, z: i32) -> bool { + if !self.raining || !self.can_see_sky(x, y, z) || self.motion_blocking_height(x, z) > y { + return false; + } + let Some(chunk) = self.world.chunks.get(&(x >> 4, z >> 4)) else { + return false; + }; + let biome = self.biomes.get(chunk.biome(x, y, z)); + biome.precipitation && biome.temperature_at(BlockPos::new(x, y, z), self.sea_level) >= 0.15 + } /// Level.getLightLevelDependentMagicValue: the dimension's brightness curve /// at the raw (sky darkened) light level. pub fn brightness(&self, x: i32, y: i32, z: i32) -> f32 { diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 0bce8927c..be8dc5837 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -50,6 +50,10 @@ pub struct MotionResources { pub attributes: Arc, pub blocks: BoundMovementProperties, pub climbable: BTreeSet, + /// `BlockTags.CAN_GLIDE_THROUGH`: climbable blocks a gliding player passes. + pub glide_through: BTreeSet, + /// `BlockTags.SOUL_SPEED_BLOCKS`: what Soul Speed's effects look for. + pub soul_speed_blocks: BTreeSet, pub fall_reset: BTreeSet, pub landing: BlockLandingRegistry, pub health: crate::health::HealthResources, @@ -108,11 +112,30 @@ impl MotionResources { suppresses_bounce: tag("minecraft:suppresses_bounce")?, })?, climbable: tag("minecraft:climbable")?, + glide_through: tag("minecraft:can_glide_through")?, + soul_speed_blocks: tag("minecraft:soul_speed_blocks")?, fall_reset: tag("minecraft:fall_damage_resetting")?, }) } } +/// What the `location_changed` enchantment effects (Soul Speed) need to know +/// between ticks. +#[derive(Clone, Debug, Default)] +pub struct LocationEffects { + /// `MovementAffectedByPredicate`: the block under the player + /// (`getBlockPosBelowThatAffectsMyMovement`) is in `#minecraft:soul_speed_blocks`. + pub on_soul_speed_block: bool, + /// `LivingEntity.lastPos`: the block the player was in last tick. + pub block: Option, + /// A landing ran `onChangedBlock` (`LivingEntity.checkFallDamage`). + pub landed: bool, + /// The Soul Speed level of the boots seen last tick (0: none). + pub boots_level: u32, + /// The Soul Speed level whose attribute modifiers are on the player (0: none). + pub applied_level: u32, +} + /// Ordered requests and phase records for world/audio/network consumers. Landing /// hurt dispatch updates stored health synchronously before these are drained. #[derive(Clone, Copy, Debug)] @@ -203,6 +226,14 @@ pub enum MotionEvent { bubble: bool, position: Vec3, }, + /// `HoneyBlock.maybeDoSlideEffects` for a player sliding down the side of + /// the honey block at `pos`: its slide sound, and the server's entity + /// event 53 (the five block particles at the player). + HoneySlide { + pos: BlockPos, + sound: bool, + particles: bool, + }, /// Entity event 67 (`LivingEntity.makeDrownParticles`): eight bubbles /// around a drowning player. Drown, @@ -255,6 +286,8 @@ pub struct PlayerMotion { pub glide_ending: bool, /// Glider durability to take this tick (updateFallFlying). pub glider_wear: u32, + /// Soul Speed's `location_changed` bookkeeping. + pub location_effects: LocationEffects, /// `LivingEntity.autoSpinAttackTicks` and `autoSpinAttackDmg`: Riptide's /// spin. The damage stays until the game has dealt the hit. pub auto_spin_attack_ticks: i32, @@ -308,6 +341,9 @@ pub struct PlayerMotion { /// it travels on the server: `isLocalInstanceAuthoritative` is false, so /// its moves check no fall damage. pub server_copy: bool, + /// The span of `events` a wall hit on the server's copy pushed (sound and + /// damage): `server_travel` keeps them while it drops the simulated moves. + pub wall_hit_events: Option>, /// A client's copy of its own player (`Level.isClientSide`): only the /// server hurts it (`Entity.hurt` does nothing on a client) and ticks its /// food (`ServerPlayer.tick`). Its hurt animation comes from the server. @@ -443,6 +479,7 @@ impl PlayerMotion { fall_fly_ticks: 0, glide_ending: false, glider_wear: 0, + location_effects: LocationEffects::default(), auto_spin_attack_ticks: 0, auto_spin_attack_dmg: 0.0, spin_targets: Vec::new(), @@ -477,6 +514,7 @@ impl PlayerMotion { freeze_immune: false, old_position: position, server_copy: false, + wall_hit_events: None, client_side: false, block_effects: true, powder_snow_entered: Vec::new(), @@ -765,6 +803,10 @@ impl MotionWorld<'_, '_, '_> { .state(self.block(p)) .ok_or("missing scene state")? .name; + // A gliding player passes through vines (`CAN_GLIDE_THROUGH`). + if self.player.fall_flying && self.resources.glide_through.contains(name) { + return Ok(false); + } let climbable = self.resources.climbable.contains(name); if climbable { self.player.last_climbable = Some(p); @@ -834,9 +876,17 @@ impl MotionWorld<'_, '_, '_> { let can_glide = self.player.glider && !self.player.ground.on_ground && !self.player.flying + && self.player.status.levitation.is_none() && !self.player.fluids.was_touching_water && !self.player.is_in_lava(); - if jumping && !toggled && !was_jumping && !self.player.fall_flying && can_glide { + // LocalPlayer.aiStep: `!onClimbable()` before tryToStartFallFlying. + if jumping + && !toggled + && !was_jumping + && !self.climbable()? + && !self.player.fall_flying + && can_glide + { self.player.fall_flying = true; } // LivingEntity.tick fallFlyTicks, then updateFallFlying. @@ -848,8 +898,11 @@ impl MotionWorld<'_, '_, '_> { self.player.fall_distance = 1.0; } self.player.fall_fly_ticks += 1; - // canGlide alone: water and lava don't end a glide. - let still = self.player.glider && !self.player.ground.on_ground && !self.player.flying; + // canGlide alone: water and lava don't end a glide, levitation does. + let still = self.player.glider + && !self.player.ground.on_ground + && !self.player.flying + && self.player.status.levitation.is_none(); if !still { self.player.glide_ending = true; } else if (self.player.fall_fly_ticks + 1) % 10 == 0 @@ -984,6 +1037,7 @@ impl MotionWorld<'_, '_, '_> { ) }); self.player.try_add_frost(on_air)?; + self.update_soul_speed_block()?; if self.player.health.tick_count % 40 == 0 && self.player.is_fully_frozen() && self.player.can_freeze() @@ -996,6 +1050,22 @@ impl MotionWorld<'_, '_, '_> { } Ok(()) } + /// Refresh whether the player stands on a soul speed block, for the + /// `location_changed` enchantment effects (a server's player too, whose + /// client does the walking). + pub fn update_soul_speed_block(&mut self) -> Result<()> { + self.player.location_effects.on_soul_speed_block = self.on_soul_speed_block()?; + Ok(()) + } + /// `MovementAffectedByPredicate` for `#minecraft:soul_speed_blocks`. + fn on_soul_speed_block(&mut self) -> Result { + let on = self.support(movement_support::MOVEMENT_SUPPORT_OFFSET)?; + Ok(self + .assets + .registry + .state(self.block(on)) + .is_some_and(|s| self.resources.soul_speed_blocks.contains(&s.name))) + } /// Player.travel: swim steering, then LivingEntity.travel (fluids first, /// then gliding, then air), keeping 0.6 of the vertical speed while flying. fn player_travel(&mut self, input: Vec3) -> Result<()> { @@ -1021,7 +1091,14 @@ impl MotionWorld<'_, '_, '_> { { horizon_world::living_fluid::travel_in_fluid(self, input)?; } else if self.player.fall_flying { - self.travel_fall_flying()?; + // LivingEntity.travelFallFlying: on a climbable the glide ends and + // the player moves like in the air. + if self.climbable()? { + self.travel_in_air(input)?; + self.player.fall_flying = false; + } else { + self.travel_fall_flying()?; + } } else { self.travel_in_air(input)?; } @@ -1048,7 +1125,14 @@ impl MotionWorld<'_, '_, '_> { p.server_copy = false; (p.position, p.ground, p.collision) = (position, ground, collision); (p.history, p.fall_distance, p.steps) = (history, fall_distance, steps); + // The wall hit is the server's own: its sound and damage events stay. + let kept: Vec<_> = p + .wall_hit_events + .take() + .map(|span| p.events.drain(span).collect()) + .unwrap_or_default(); p.events.truncate(events); + p.events.extend(kept); travelled } /// `LivingEntity.checkAutoSpinAttack`: the first living entity in the @@ -1083,7 +1167,7 @@ impl MotionWorld<'_, '_, '_> { /// `Entity.applyEffectsFromBlocks` for the blocks Horizon's player reacts /// to inside its movement path: powder snow (`PowderSnowBlock.entityInside` /// and the FREEZE / EXTINGUISH effects), cobwebs, sweet berry bushes, - /// cactus and lit campfires, and the magma block it stands on + /// cactus and lit campfires, and the magma and slime blocks it stands on /// (`stepOn`). Pressure plates, tripwires and rails are the world tick's /// scan. pub fn apply_effects_from_blocks(&mut self) -> Result<()> { @@ -1141,14 +1225,22 @@ impl MotionWorld<'_, '_, '_> { // MagmaBlock's hot floor hurts unless it steps carefully (sneaks). if self.player.ground.on_ground { let on = self.legacy_on_position()?; - let magma = self - .assets - .registry - .state(self.block(on)) - .is_some_and(|s| s.name == "minecraft:magma_block"); + let under = self.assets.registry.state(self.block(on)); + let magma = under.is_some_and(|s| s.name == "minecraft:magma_block"); + let slime = under.is_some_and(|s| s.name == "minecraft:slime_block"); if magma && !self.player.shift_key_down { self.environment_hurt("minecraft:hot_floor", 1.0)?; } + // SlimeBlock.stepOn: a slow walk on slime drags the horizontal + // speed (the client moves its own player, so not the server's copy). + if slime && !damage_only && !self.player.shift_key_down { + let abs_delta_y = self.player.velocity.y.abs(); + if abs_delta_y < 0.1 { + let scale = 0.4 + abs_delta_y * 0.2; + self.player.velocity.x *= scale; + self.player.velocity.z *= scale; + } + } } let mut visited = std::collections::HashSet::new(); let mut entered = Vec::new(); @@ -1365,6 +1457,9 @@ impl MotionWorld<'_, '_, '_> { "minecraft:sweet_berry_bush" if damage_only => { self.sweet_berry_bush_damage(state)?; } + // HoneyBlock.entityInside: a server's player slides too, so + // its fall distance resets (its client moves it). + "minecraft:honey_block" => self.honey_block_inside(p)?, // PowderSnowBlock.entityInside's FREEZE. "minecraft:powder_snow" if damage_only => entered.push((step, p)), _ => {} @@ -1395,6 +1490,50 @@ impl MotionWorld<'_, '_, '_> { } Ok(iterations + 1) } + /// `HoneyBlock.entityInside`: a falling player touching a side of the block + /// slides down it (`isSlidingDown`, `doSlideMovement`, `maybeDoSlideEffects`). + fn honey_block_inside(&mut self, pos: BlockPos) -> Result<()> { + let old_delta_y = |dy: f64| dy / f64::from(0.98_f32) + 0.08; + let new_delta_y = |dy: f64| (dy - 0.08) * f64::from(0.98_f32); + let position = self.player.position; + let velocity = self.player.velocity; + if self.player.ground.on_ground + || position.y > f64::from(pos.y) + 0.9375 - 1.0e-7 + || old_delta_y(velocity.y) >= -0.08 + { + return Ok(()); + } + let dx = (f64::from(pos.x) + 0.5 - position.x).abs(); + let dz = (f64::from(pos.z) + 0.5 - position.z).abs(); + let overlap = 0.4375 + f64::from(self.player.dimensions.width / 2.0); + if !(dx + 1.0e-7 > overlap || dz + 1.0e-7 > overlap) { + return Ok(()); + } + // doSlideMovement + let old = old_delta_y(velocity.y); + if old < -0.13 { + let factor = -0.05 / old; + self.player.velocity = + Vec3::new(velocity.x * factor, new_delta_y(-0.05), velocity.z * factor); + } else { + self.player.velocity = Vec3::new(velocity.x, new_delta_y(-0.05), velocity.z); + } + self.player.fall_distance = 0.0; + // maybeDoSlideEffects: the sound, then the server's event 53. + let random = &mut self.scene.random; + let sound = random.next_int_bound(5).map_err(|e| format!("{e:?}"))? == 0; + // Only the server broadcasts event 53 (`!level.isClientSide()`). + let particles = !self.player.client_side + && random.next_int_bound(5).map_err(|e| format!("{e:?}"))? == 0; + if sound || particles { + self.player.events.push(MotionEvent::HoneySlide { + pos, + sound, + particles, + }); + } + Ok(()) + } /// `Player.makeStuckInBlock`: the next move is scaled by `multiplier` /// (and the fall forgotten) unless flying; the impulse context resets /// either way. @@ -1528,7 +1667,7 @@ impl MotionWorld<'_, '_, '_> { let lean = pitch; let look_h = (look.x * look.x + look.z * look.z).sqrt(); let move_h = (v.x * v.x + v.z * v.z).sqrt(); - let gravity = 0.08; + let gravity = living_motion::effective_gravity(self)?; let lift = f64::from(lean.cos()).powi(2); let mut m = Vec3::new(v.x, v.y + gravity * (-1.0 + lift * 0.75), v.z); if m.y < 0.0 && look_h > 0.0 { @@ -1556,7 +1695,44 @@ impl MotionWorld<'_, '_, '_> { } self.player.velocity = Vec3::new(m.x * 0.99, m.y * 0.98, m.z * 0.99); let movement = self.player.velocity; - self.move_self(movement) + self.move_self(movement)?; + // LivingEntity.handleFallFlyingCollisions: only the server hurts. + if !self.player.client_side && self.player.collision.horizontal { + let new_h = { + let v = self.player.velocity; + (v.x * v.x + v.z * v.z).sqrt() + }; + let dmg = ((move_h - new_h) * 10.0 - 3.0) as f32; + if dmg > 0.0 { + let first = self.player.events.len(); + // getFallDamageSound((int) dmg) + let sound = if dmg as i32 > 4 { + crate::landing::SceneSound::BigFall + } else { + crate::landing::SceneSound::SmallFall + }; + self.player + .events + .push(MotionEvent::Fall(crate::landing::FallEvent::Sound { + sound, + position: None, + volume: 1.0, + pitch: 1.0, + })); + let id = self + .resources + .health + .damage + .id("minecraft:fly_into_wall") + .ok_or("missing fly_into_wall damage type")?; + let rules = self.scene.health_rules; + self.player.hurt(&self.resources.health, rules, id, dmg)?; + if self.player.server_copy { + self.player.wall_hit_events = Some(first..self.player.events.len()); + } + } + } + Ok(()) } /// `LocalPlayer.move`: the move, then `updateAutoJump` with the float /// horizontal displacement. @@ -1834,6 +2010,10 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> { if self.player.status.slow_falling || self.player.status.levitation.is_some() { self.player.fall_distance = 0.0; } + // LivingEntity.checkFallDamage: a landing runs onChangedBlock. + if grounded && self.player.fall_distance > 0.0 { + self.player.location_effects.landed = true; + } if self.player.spawn_extra_particles_on_fall && grounded && self.player.fall_distance > 0.0 { self.player.events.push(MotionEvent::SmashLanding { diff --git a/crates/horizon-client/src/motion/environment.rs b/crates/horizon-client/src/motion/environment.rs index fc3c63c77..5e9bdfec8 100644 --- a/crates/horizon-client/src/motion/environment.rs +++ b/crates/horizon-client/src/motion/environment.rs @@ -161,6 +161,29 @@ pub(crate) fn fire_contact( } damage } +/// `CactusBlock.entityInside`: the box (deflated by `1.0E-5`, as in +/// `Entity.checkInsideBlocks`) touches a cactus; its inside shape is the +/// whole block. +pub(crate) fn cactus_contact( + world: &World, + registry: &horizon_world::registry::BlockRegistry, + bounds: Aabb, +) -> bool { + let b = bounds.deflate(Vec3::new(1e-5, 1e-5, 1e-5)); + for x in b.min_position().x.floor() as i32..=b.max_position().x.floor() as i32 { + for y in b.min_position().y.floor() as i32..=b.max_position().y.floor() as i32 { + for z in b.min_position().z.floor() as i32..=b.max_position().z.floor() as i32 { + if registry + .state(world.block(x, y, z)) + .is_some_and(|s| s.name == "minecraft:cactus") + { + return true; + } + } + } + } + false +} impl LivingFluidWorld for MotionWorld<'_, '_, '_> { fn in_water(&mut self) -> Result { Ok(self.player.fluids.was_touching_water) diff --git a/crates/horizon-client/src/multiplayer.rs b/crates/horizon-client/src/multiplayer.rs index 07d8552ff..39ea26502 100644 --- a/crates/horizon-client/src/multiplayer.rs +++ b/crates/horizon-client/src/multiplayer.rs @@ -11,9 +11,15 @@ use std::{ collections::HashMap, path::{Path, PathBuf}, sync::{Arc, Mutex}, - time::Duration, + time::{Duration, Instant}, }; +const SERVER_NAME: crate::clipboard::FieldId = ("server.name", 0); +const SERVER_ADDRESS: crate::clipboard::FieldId = ("server.address", 0); +const SERVER_DIRECT: crate::clipboard::FieldId = ("server.direct", 0); +const FRIEND_CODE: crate::clipboard::FieldId = ("friend.code", 0); +const FRIEND_RELAY: crate::clipboard::FieldId = ("friend.relay", 0); + /// The result of pinging one address. #[derive(Clone, Debug)] pub enum Ping { @@ -491,7 +497,7 @@ impl Screen { w / 2.0 - 100.0, h / 4.0 + 96.0 + 18.0, 200.0, - "Done", + &crate::lang::get_or("gui.done", "Done"), servers::parse_address(address).is_some(), 50, ), @@ -499,7 +505,7 @@ impl Screen { w / 2.0 - 100.0, h / 4.0 + 120.0 + 18.0, 200.0, - "Cancel", + &crate::lang::get_or("gui.cancel", "Cancel"), true, 51, ), @@ -532,7 +538,7 @@ impl Screen { w / 2.0 - 100.0, h / 4.0 + 96.0 + 12.0, 200.0, - "Join Server", + &crate::lang::get_or("selectServer.select", "Join Server"), servers::parse_address(address).is_some(), 52, ), @@ -540,7 +546,7 @@ impl Screen { w / 2.0 - 100.0, h / 4.0 + 120.0 + 12.0, 200.0, - "Cancel", + &crate::lang::get_or("gui.cancel", "Cancel"), true, 53, ), @@ -558,7 +564,7 @@ impl Screen { w / 2.0 - 100.0, h / 4.0 + 120.0 + 18.0, 200.0, - "Cancel", + &crate::lang::get_or("gui.cancel", "Cancel"), true, 57, ), @@ -568,7 +574,7 @@ impl Screen { w / 2.0 - 100.0, h / 2.0 + 30.0, 200.0, - "Back to Server List", + &crate::lang::get_or("gui.toMenu", "Back to Server List"), true, 54, )]; @@ -587,18 +593,21 @@ impl Screen { } } /// An EditBox and its label: the label at `label_y` (one pixel in, in - /// 0xA0A0A0), the 200x20 box at `box_y`. + /// 0xA0A0A0), the 200x20 box at `box_y`. The box is the same `EditBox` + /// the world screens edit (`Caret`): cursor, selection and scrolling. fn field( atlas: &HudAtlas, batch: &mut HudBatch, + caret: &mut crate::ui::Caret, + focused_at: Instant, label: &str, value: &str, + id: crate::clipboard::FieldId, + max: usize, (label_y, box_y): (f32, f32), focused: bool, - blink: bool, ) { let x = (batch.width.ceil() / 2.0).floor() - 100.0; - crate::widgets::target_as([x, box_y, 200.0, 20.0], crate::widgets::Kind::Field); batch.text( atlas, label, @@ -607,35 +616,25 @@ impl Screen { rgba(160, 160, 160, 255), true, ); - batch.fill( + caret.draw( + batch, atlas, - x, - box_y, - 200.0, - 20.0, - if focused { - u32::MAX - } else { - rgba(160, 160, 160, 255) - }, - ); - batch.fill(atlas, x + 1.0, box_y + 1.0, 198.0, 18.0, rgba(0, 0, 0, 255)); - let shown = if focused && blink { - format!("{value}_") - } else { - value.to_owned() - }; - batch.text( - atlas, - &shown, - x + 4.0, - box_y + 6.0, - rgba(224, 224, 224, 255), - true, + (id, value, max), + [x, box_y, 200.0, 20.0], + focused, + focused_at, ); } - pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, blink: bool, cursor: (f32, f32)) { + pub fn draw( + &self, + atlas: &HudAtlas, + batch: &mut HudBatch, + caret: &mut crate::ui::Caret, + focused_at: Instant, + cursor: (f32, f32), + ) { let (w, h) = (batch.width, batch.height); + let max = self.max_length(); crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false); let centered = |batch: &mut HudBatch, text: &str, y: f32, color: u32| { let tw = HudBatch::text_width(atlas, text); @@ -876,10 +875,10 @@ impl Screen { } => { centered( batch, - if index.is_some() { - "Edit Server Info" + &if index.is_some() { + crate::lang::get_or("manageServer.edit.title", "Edit Server Info") } else { - "Add Server" + crate::lang::get_or("manageServer.add.title", "Add Server") }, 17.0, u32::MAX, @@ -888,20 +887,26 @@ impl Screen { Self::field( atlas, batch, - "Server Name", + caret, + focused_at, + &crate::lang::get_or("manageServer.enterName", "Server Name"), name, + SERVER_NAME, + max, (53.0, 66.0), *focus == 0, - blink, ); Self::field( atlas, batch, - "Server Address", + caret, + focused_at, + &crate::lang::get_or("manageServer.enterIp", "Server Address"), address, + SERVER_ADDRESS, + max, (94.0, 106.0), *focus == 1, - blink, ); } Self::Direct { address } => { @@ -916,11 +921,14 @@ impl Screen { Self::field( atlas, batch, - &crate::lang::get_or("addServer.enterIp", "Server Address"), + caret, + focused_at, + &crate::lang::get_or("manageServer.enterIp", "Server Address"), address, + SERVER_DIRECT, + max, (100.0, 116.0), true, - blink, ); } Self::ConfirmDelete { name, lines, .. } => { @@ -954,26 +962,32 @@ impl Screen { Self::field( atlas, batch, + caret, + focused_at, "Invite Code", code, + FRIEND_CODE, + max, (53.0, 64.0), *focus == 0, - blink, ); Self::field( atlas, batch, + caret, + focused_at, "Relay (optional)", relay, + FRIEND_RELAY, + max, (94.0, 105.0), *focus == 1, - blink, ); } Self::Disconnected { reason, retry } => { centered( batch, - "Connection Lost", + &crate::lang::get_or("disconnect.lost", "Connection Lost"), h / 2.0 - 40.0, rgba(170, 170, 170, 255), ); @@ -1019,7 +1033,7 @@ impl Screen { (Self::List { .. }, Some(42)) => { *self = Self::Edit { index: None, - name: "Minecraft Server".into(), + name: crate::lang::get_or("selectServer.defaultName", "Minecraft Server"), address: String::new(), focus: 1, packs: None, @@ -1261,6 +1275,19 @@ impl Screen { scroll.release(); } } + /// The focused box, in GUI pixels: name at 66, address at 106 + /// (`ManageServerScreen`), direct address at 116, friend fields at 64 and 105. + pub fn focused_box(&self, (w, _h): (f32, f32)) -> Option<[f32; 4]> { + let y = match self { + Self::Edit { focus: 0, .. } => 66.0, + Self::Edit { .. } => 106.0, + Self::Direct { .. } => 116.0, + Self::Friend { focus: 0, .. } => 64.0, + Self::Friend { .. } => 105.0, + _ => return None, + }; + Some([(w / 2.0).floor() - 100.0, y, 200.0, 20.0]) + } fn focused_field(&mut self) -> Option<&mut String> { match self { Self::Edit { @@ -1297,11 +1324,11 @@ impl Screen { /// The focused text field, its id and maximum length (copy and paste). pub fn focused_text(&mut self) -> Option<(crate::clipboard::FieldId, &mut String, usize)> { let id = match self { - Self::Edit { focus: 0, .. } => ("server.name", 0), - Self::Edit { .. } => ("server.address", 0), - Self::Direct { .. } => ("server.direct", 0), - Self::Friend { focus: 0, .. } => ("friend.code", 0), - Self::Friend { .. } => ("friend.relay", 0), + Self::Edit { focus: 0, .. } => SERVER_NAME, + Self::Edit { .. } => SERVER_ADDRESS, + Self::Direct { .. } => SERVER_DIRECT, + Self::Friend { focus: 0, .. } => FRIEND_CODE, + Self::Friend { .. } => FRIEND_RELAY, _ => return None, }; let max = self.max_length(); @@ -1315,21 +1342,6 @@ impl Screen { 128 } } - pub fn type_text(&mut self, text: &str) { - let max = self.max_length(); - if let Some(field) = self.focused_field() { - for c in text.chars().filter(|c| !c.is_control()) { - if field.chars().count() < max { - field.push(c); - } - } - } - } - pub fn backspace(&mut self) { - if let Some(field) = self.focused_field() { - field.pop(); - } - } pub fn tab(&mut self) { if let Self::Edit { focus, .. } | Self::Friend { focus, .. } = self { *focus = (*focus + 1) % 2; diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index 0eb260477..34daaf85c 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -40,6 +40,8 @@ pub enum Event { Status(String), /// The server's `minecraft:brand` custom payload. Brand(String), + /// The server runs mods' quiet commands (`horizon_protocol::quiet`). + QuietCommands, /// Configuration finished: the play state begins with these registries. Joined { registries: Arc, @@ -668,6 +670,8 @@ fn receive_brand(payload: &cfg::CustomPayload, send: &Sender) { && let Ok(brand) = horizon_protocol::buf::Reader::new(&payload.data).string(32767) { let _ = send.send(Event::Brand(brand)); + } else if payload.channel == horizon_protocol::quiet::CHANNEL { + let _ = send.send(Event::QuietCommands); } } diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 61fda9878..a40d11258 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -67,6 +67,7 @@ pub enum Opt { ReducedDebugInfo, HighContrast, ShowSubtitles, + MusicFrequency, NotificationDisplayTime, Narrator, TextBackground, @@ -172,6 +173,10 @@ impl Opt { | Opt::MonochromeLogo | Opt::RotateWithMinecarts | Opt::HighContrastBlockOutlines + // Saved, but nothing in rendering reads them yet. + | Opt::ChunkFade + | Opt::ImprovedTransparency + | Opt::ChunkBuilder ) } fn file_key(self) -> Option<&'static str> { @@ -192,6 +197,7 @@ impl Opt { Opt::NarratorHotkey => "narratorHotkey", Opt::RotateWithMinecarts => "rotateWithMinecart", Opt::HighContrastBlockOutlines => "highContrastBlockOutline", + Opt::MusicFrequency => "musicFrequency", _ => return None, }) } @@ -248,6 +254,7 @@ impl Opt { Opt::ReducedDebugInfo => "options.reducedDebugInfo", Opt::HighContrast => "options.accessibility.high_contrast", Opt::ShowSubtitles => "options.showSubtitles", + Opt::MusicFrequency => "options.music_frequency", Opt::NotificationDisplayTime => "options.notifications.display_time", Opt::Narrator => "options.narrator", Opt::TextBackground => "options.accessibility.text_background", @@ -578,6 +585,11 @@ impl Opt { Opt::ReducedDebugInfo => on_off(s.reduced_debug_info), Opt::HighContrast => on_off(s.high_contrast), Opt::ShowSubtitles => on_off(s.show_subtitles), + Opt::MusicFrequency => tr([ + "options.music_frequency.default", + "options.music_frequency.frequent", + "options.music_frequency.constant", + ][s.file.int("musicFrequency").clamp(0, 2) as usize]), Opt::ForceUnicode => on_off(s.force_unicode), Opt::JapaneseGlyphs => on_off(s.japanese_glyphs), Opt::PadEnabled => on_off(s.controller.enabled), @@ -747,6 +759,11 @@ impl Opt { Opt::ReducedDebugInfo => s.reduced_debug_info = !s.reduced_debug_info, Opt::HighContrast => s.high_contrast = !s.high_contrast, Opt::ShowSubtitles => s.show_subtitles = !s.show_subtitles, + Opt::MusicFrequency => { + let n = next(s.file.int("musicFrequency").clamp(0, 2) as u8, 3); + s.file + .set("musicFrequency", crate::options_file::V::Int(i32::from(n))); + } Opt::ForceUnicode => s.force_unicode = !s.force_unicode, Opt::JapaneseGlyphs => s.japanese_glyphs = !s.japanese_glyphs, Opt::PadEnabled => s.controller.enabled = !s.controller.enabled, @@ -1412,6 +1429,9 @@ impl OptionsUi { let others: Vec = (1..SOUND_SOURCES.len()).map(Opt::Volume).collect(); rows.extend(pairs(&others)); rows.extend(pairs(&[Opt::ShowSubtitles])); + // SoundOptionsScreen: Music Frequency starts the next row (with + // Music Toast, not in Horizon yet). + rows.extend(pairs(&[Opt::MusicFrequency])); rows } Page::Controls => { @@ -2533,6 +2553,21 @@ impl OptionsUi { if opt == Opt::Preset { apply_preset(s); } + if opt == Opt::HighContrast { + // Options.highContrast: the built-in pack follows the option. + let on = s.resource_packs.iter().any(|id| id == "high_contrast"); + if on != s.high_contrast { + s.resource_packs.retain(|id| id != "high_contrast"); + if s.high_contrast { + s.resource_packs.push("high_contrast".into()); + } + // PackSelectionScreen reads the repository each time it + // opens: the next one starts from this selection. + self.pack_selection = s.resource_packs.clone(); + self.pack_screen = None; + events.push(Event::Packs(s.resource_packs.clone())); + } + } events.push(Event::Changed); } Act::Extra(item) => { @@ -2701,6 +2736,7 @@ impl OptionsUi { { let ids = p.commit(); s.resource_packs = ids.clone(); + self.pack_selection = ids.clone(); events.push(Event::Packs(ids)); } } diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index 3099069ba..2e7930b4e 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -23,212 +23,7 @@ use std::{ path::Path, }; -macro_rules! particle_types { - ($($variant:ident = $name:literal),* $(,)?) => { - /// Vanilla particle types with a client implementation here. - #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] - pub enum ParticleType { $($variant),* } - impl ParticleType { - pub const ALL: &'static [ParticleType] = &[$(ParticleType::$variant),*]; - /// Registry path (`minecraft:`), also the sprite-set file name. - pub fn name(self) -> &'static str { - match self { $(ParticleType::$variant => $name),* } - } - pub fn from_name(name: &str) -> Option { - let name = name.strip_prefix("minecraft:").unwrap_or(name); - match name { $($name => Some(ParticleType::$variant),)* _ => None } - } - } - }; -} -particle_types! { - Block = "block", - BlockCrumble = "block_crumble", - Trail = "trail", - DustPillar = "dust_pillar", - FallingDust = "falling_dust", - Smoke = "smoke", - LargeSmoke = "large_smoke", - WhiteSmoke = "white_smoke", - Flame = "flame", - SoulFireFlame = "soul_fire_flame", - CopperFireFlame = "copper_fire_flame", - SmallFlame = "small_flame", - Lava = "lava", - DrippingWater = "dripping_water", - FallingWater = "falling_water", - DrippingLava = "dripping_lava", - FallingLava = "falling_lava", - LandingLava = "landing_lava", - DrippingHoney = "dripping_honey", - FallingHoney = "falling_honey", - LandingHoney = "landing_honey", - FallingNectar = "falling_nectar", - FallingSporeBlossom = "falling_spore_blossom", - SporeBlossomAir = "spore_blossom_air", - DrippingObsidianTear = "dripping_obsidian_tear", - FallingObsidianTear = "falling_obsidian_tear", - LandingObsidianTear = "landing_obsidian_tear", - DrippingDripstoneWater = "dripping_dripstone_water", - FallingDripstoneWater = "falling_dripstone_water", - DrippingDripstoneLava = "dripping_dripstone_lava", - FallingDripstoneLava = "falling_dripstone_lava", - Splash = "splash", - Rain = "rain", - Bubble = "bubble", - SulfurBubbles = "sulfur_bubbles", - BubblePop = "bubble_pop", - BubbleColumnUp = "bubble_column_up", - CurrentDown = "current_down", - Underwater = "underwater", - Portal = "portal", - ReversePortal = "reverse_portal", - Enchant = "enchant", - Nautilus = "nautilus", - VaultConnection = "vault_connection", - Crit = "crit", - EnchantedHit = "enchanted_hit", - DamageIndicator = "damage_indicator", - Heart = "heart", - AngryVillager = "angry_villager", - HappyVillager = "happy_villager", - Composter = "composter", - Mycelium = "mycelium", - Dolphin = "dolphin", - EggCrack = "egg_crack", - Poof = "poof", - Explosion = "explosion", - ExplosionEmitter = "explosion_emitter", - CampfireCosySmoke = "campfire_cosy_smoke", - CampfireSignalSmoke = "campfire_signal_smoke", - Note = "note", - Dust = "dust", - TotemOfUndying = "totem_of_undying", - Firework = "firework", - EndRod = "end_rod", - Ash = "ash", - WhiteAsh = "white_ash", - CrimsonSpore = "crimson_spore", - WarpedSpore = "warped_spore", - CherryLeaves = "cherry_leaves", - PaleOakLeaves = "pale_oak_leaves", - TintedLeaves = "tinted_leaves", - Effect = "effect", - InstantEffect = "instant_effect", - EntityEffect = "entity_effect", - Witch = "witch", - Infested = "infested", - Cloud = "cloud", - Sneeze = "sneeze", - Snowflake = "snowflake", - Soul = "soul", - SculkSoul = "sculk_soul", - DragonBreath = "dragon_breath", - Gust = "gust", - SmallGust = "small_gust", - GustEmitterLarge = "gust_emitter_large", - GustEmitterSmall = "gust_emitter_small", - DustColorTransition = "dust_color_transition", - SculkCharge = "sculk_charge", - SculkChargePop = "sculk_charge_pop", - Shriek = "shriek", - SonicBoom = "sonic_boom", - Vibration = "vibration", - SweepAttack = "sweep_attack", - Glow = "glow", - WaxOn = "wax_on", - WaxOff = "wax_off", - ElectricSpark = "electric_spark", - Scrape = "scrape", - SquidInk = "squid_ink", - GlowSquidInk = "glow_squid_ink", - Item = "item", - ItemSlime = "item_slime", - ItemSnowball = "item_snowball", - ItemCobweb = "item_cobweb", - SulfurCubeGoo = "sulfur_cube_goo", - Flash = "flash", - Firefly = "firefly", - TrialSpawnerDetection = "trial_spawner_detection", - TrialSpawnerDetectionOminous = "trial_spawner_detection_ominous", - TrialOmen = "trial_omen", - RaidOmen = "raid_omen", - OminousSpawning = "ominous_spawning", - Spit = "spit", - Fishing = "fishing", - DustPlume = "dust_plume", - RedPoplarLeaves = "red_poplar_leaves", - OrangePoplarLeaves = "orange_poplar_leaves", - YellowPoplarLeaves = "yellow_poplar_leaves", - PauseMobGrowth = "pause_mob_growth", - ResetMobGrowth = "reset_mob_growth", - BlockMarker = "block_marker", -} -impl ParticleType { - /// `ParticleType.getOverrideLimiter` (`ParticleTypes.register(name, true)`): - /// spawned regardless of distance. - pub fn override_limiter(self) -> bool { - matches!( - self, - Self::BlockMarker - | Self::DamageIndicator - | Self::ExplosionEmitter - | Self::Explosion - | Self::Gust - | Self::GustEmitterLarge - | Self::GustEmitterSmall - | Self::SonicBoom - | Self::SculkCharge - | Self::SculkChargePop - | Self::Vibration - | Self::Poof - | Self::Spit - | Self::SquidInk - | Self::SweepAttack - | Self::CampfireCosySmoke - | Self::CampfireSignalSmoke - | Self::GlowSquidInk - | Self::Glow - | Self::WaxOn - | Self::WaxOff - | Self::ElectricSpark - | Self::Scrape - | Self::TrialSpawnerDetection - | Self::TrialSpawnerDetectionOminous - | Self::VaultConnection - | Self::OminousSpawning - ) - } - /// `SingleQuadParticle.Layer.translucent`: types whose vanilla particle class - /// hardcodes the translucent layer, drawn after translucent terrain. - /// `TerrainParticle`, `BreakingItemParticle` and `BlockMarker` resolve their - /// layer from the sprite instead (`Layer.bySprite`); see the `translucent` - /// sprite set on the engine. - pub fn translucent_layer(self) -> bool { - match self { - // CampfireSmokeParticle. - Self::CampfireCosySmoke | Self::CampfireSignalSmoke - // PlayerCloudParticle. - | Self::Cloud | Self::Sneeze - // SpellParticle. - | Self::Effect | Self::InstantEffect | Self::EntityEffect - | Self::Witch | Self::Infested | Self::TrialOmen | Self::RaidOmen - // EmissiveRisingParticle. - | Self::Soul | Self::SculkSoul - // SculkChargeParticle, SculkChargePopParticle, ShriekParticle, - // VibrationSignalParticle, FireflyParticle, OverlayParticle. - | Self::SculkCharge | Self::SculkChargePop | Self::Shriek - | Self::Vibration | Self::Firefly | Self::Flash - // SimpleAnimatedParticle and its subclasses: EndRodParticle, - // SparkParticle (firework), SquidInkParticle, TotemParticle. - | Self::EndRod | Self::Firework | Self::SquidInk | Self::GlowSquidInk - | Self::TotemOfUndying - // FlyTowardsPositionParticle: its LifetimeAlpha(0, 0.6, 0.25, 1) is not opaque. - | Self::VaultConnection => true, - _ => false, - } - } -} +pub use horizon_client_core::particle_type::ParticleType; /// `ParticleOptions` with the parameters of the option classes used here. #[derive(Clone, Debug)] @@ -1392,16 +1187,17 @@ impl ParticleEngine { } } /// `ClientPacketListener.handleExplosion` + `ClientExplosionTracker`: the - /// explosion particle (emitter for radius >= 2) and up to 512 poof/smoke - /// particles thrown from air inside the radius. + /// explosion particle (the emitter unless `ServerExplosion.isSmall`) and up + /// to 512 poof/smoke particles thrown from air inside the radius. pub fn explosion( &mut self, center: [f64; 3], - radius: f32, + small: bool, block_count: usize, + radius: f32, is_air: &dyn Fn([i32; 3]) -> bool, ) { - let ty = if radius < 2.0 { + let ty = if small { ParticleType::Explosion } else { ParticleType::ExplosionEmitter @@ -1409,6 +1205,18 @@ impl ParticleEngine { self.add(&ParticleOptions::simple(ty), center, [1.0, 0.0, 0.0]); self.explosion_blocks(center, radius, block_count, is_air); } + /// `LlamaSpit.recreateFromPacket`: seven spit particles thrown ahead of a + /// new spit, each faster than the last along x and z. + pub fn llama_spit_burst(&mut self, at: [f64; 3], movement: [f64; 3]) { + for i in 0..7 { + let k = 0.4 + 0.1 * f64::from(i); + self.add( + &ParticleOptions::simple(ParticleType::Spit), + at, + [movement[0] * k, movement[1], movement[2] * k], + ); + } + } /// `ClientExplosionTracker` with `Level.DEFAULT_EXPLOSION_BLOCK_PARTICLES`. pub fn explosion_blocks( &mut self, diff --git a/crates/horizon-client/src/projectiles.rs b/crates/horizon-client/src/projectiles.rs index 219d59b6b..aae9b296b 100644 --- a/crates/horizon-client/src/projectiles.rs +++ b/crates/horizon-client/src/projectiles.rs @@ -28,6 +28,10 @@ pub enum ProjectileKind { critical: bool, effect: Option<(&'static str, i32)>, }, + /// `ThrownTrident` of a mob (a drowned's): flies and sticks with + /// `AbstractArrow`'s tick; the trident itself is the arrow state's + /// `pickup_item`. + Trident, Snowball, Egg, EnderPearl, @@ -66,6 +70,7 @@ impl ProjectileKind { pub fn id(&self) -> &'static str { match self { Self::Arrow { .. } => "minecraft:arrow", + Self::Trident => "minecraft:trident", Self::Snowball => "minecraft:snowball", Self::Egg => "minecraft:egg", Self::EnderPearl => "minecraft:ender_pearl", @@ -152,7 +157,7 @@ fn axis_of(d: u8) -> u8 { } impl Projectile { pub fn new(kind: ProjectileKind, position: Vec3, owner: Option) -> Self { - let kind_is_arrow = matches!(kind, ProjectileKind::Arrow { .. }); + let kind_is_arrow = matches!(kind, ProjectileKind::Arrow { .. } | ProjectileKind::Trident); Self { id: 0, kind, @@ -186,12 +191,13 @@ impl Projectile { self } /// The shooter's bow enchantments; Flame spawns the arrow burning for 100 - /// seconds (`projectile_spawned` ignite). + /// seconds (`projectile_spawned` ignite), Piercing sets its pierce level. pub fn set_bonus(&mut self, bonus: crate::mobs::gear::ArrowBonus) { - if bonus.flame - && let Some(a) = self.arrow.as_mut() - { - a.ignite_for_seconds(100.0); + if let Some(a) = self.arrow.as_mut() { + if bonus.flame { + a.ignite_for_seconds(100.0); + } + a.pierce = bonus.pierce.min(127) as u8; } self.bonus = bonus; } @@ -252,7 +258,7 @@ impl Projectile { } fn gravity(&self) -> f64 { match self.kind { - ProjectileKind::Arrow { .. } => 0.05, + ProjectileKind::Arrow { .. } | ProjectileKind::Trident => 0.05, ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } | ProjectileKind::WitherSkull { .. } => 0.0, @@ -603,8 +609,8 @@ impl Projectile { | ProjectileKind::WitherSkull { .. } => { self.apply_hurting_inertia(water); } - // Arrows tick with `arrows::tick`. - ProjectileKind::Arrow { .. } => {} + // Arrows and tridents tick with `arrows::tick`. + ProjectileKind::Arrow { .. } | ProjectileKind::Trident => {} ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge => {} // LlamaSpit.tick: gone in water; drag and gravity follow the move. ProjectileKind::LlamaSpit => { @@ -745,7 +751,8 @@ impl Projectile { ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge => return None, ProjectileKind::WitherSkull { dangerous: false } => "entity/wither/wither", ProjectileKind::WitherSkull { dangerous: true } => "entity/wither/wither_invulnerable", - ProjectileKind::Arrow { .. } => return None, + // Drawn as their models by the game. + ProjectileKind::Arrow { .. } | ProjectileKind::Trident => return None, }) } /// Render scale of the item billboard (fireball renderers). diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 0c353bb38..dc08d90b0 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -36,7 +36,7 @@ use horizon_world::{ worldgen::terrain::TerrainBlockStates, }; use std::{ - collections::{BTreeMap, HashMap}, + collections::{BTreeMap, HashMap, HashSet}, fs, path::{Path, PathBuf}, sync::{ @@ -247,6 +247,44 @@ pub struct SaveTables { block_entity: Vec, heightmaps: crate::assets::Properties, air: u32, + /// The POI type and its max tickets of each state (`PoiTypes`). + poi: Vec>, +} +/// `PoiTypes.register`: the POI type of a block state and its max tickets. +pub fn poi_type(state: &horizon_world::chunk::BlockState) -> Option<(&'static str, i32)> { + let name = state.name.strip_prefix("minecraft:")?; + Some(match name { + "blast_furnace" => ("minecraft:armorer", 1), + "smoker" => ("minecraft:butcher", 1), + "cartography_table" => ("minecraft:cartographer", 1), + "brewing_stand" => ("minecraft:cleric", 1), + "composter" => ("minecraft:farmer", 1), + "barrel" => ("minecraft:fisherman", 1), + "fletching_table" => ("minecraft:fletcher", 1), + "cauldron" | "lava_cauldron" | "water_cauldron" | "powder_snow_cauldron" => { + ("minecraft:leatherworker", 1) + } + "lectern" => ("minecraft:librarian", 1), + "stonecutter" => ("minecraft:mason", 1), + "loom" => ("minecraft:shepherd", 1), + "smithing_table" => ("minecraft:toolsmith", 1), + "grindstone" => ("minecraft:weaponsmith", 1), + "bell" => ("minecraft:meeting", 32), + "beehive" => ("minecraft:beehive", 0), + "bee_nest" => ("minecraft:bee_nest", 0), + "nether_portal" => ("minecraft:nether_portal", 0), + "lodestone" => ("minecraft:lodestone", 0), + "test_instance_block" => ("minecraft:test_instance", 0), + // PoiTypes.BEDS is the sixteen colours: no straw bed. + bed if bed.ends_with("_bed") && bed != "straw_bed" => { + if state.properties.get("part").map(String::as_str) != Some("head") { + return None; + } + ("minecraft:home", 1) + } + rod if rod.ends_with("lightning_rod") => ("minecraft:lightning_rod", 0), + _ => return None, + }) } impl SaveTables { pub fn new(assets: &crate::assets::Assets) -> Self { @@ -275,6 +313,9 @@ impl SaveTables { block_entity: Vec::new(), heightmaps: assets.properties.clone(), air: registry.default_state("minecraft:air").map_or(0, |s| s.0), + poi: (0..registry.len()) + .map(|id| registry.state(BlockStateId(id as u32)).and_then(poi_type)) + .collect(), } } /// Tables with only the heightmaps' state facts, for tests. @@ -287,6 +328,7 @@ impl SaveTables { block_entity: Vec::new(), heightmaps, air: 0, + poi: Vec::new(), } } /// Which states carry a block entity (`BlockFacts`), to drop entries for @@ -297,6 +339,35 @@ impl SaveTables { } } +/// A container's loot table and what Horizon rolled from it. Vanilla keeps +/// `LootTable` and `LootTableSeed` until the container is first opened; +/// Horizon rolls when it generates or loads the chunk, and saves the table +/// again while the container still holds exactly the rolled items. +#[derive(Clone, Debug, PartialEq)] +pub struct RolledLoot { + pub pos: (i32, i32, i32), + pub table: String, + /// The saved `LootTableSeed`, written back unless 0 (trySaveLootTable). + pub seed: Option, + /// The rolled `Items`. + pub items: Tag, +} +impl RolledLoot { + /// Puts the loot table back in place of `Items` while they are still the + /// roll; false once the container holds anything else. + pub fn restore(&self, map: &mut Compound) -> bool { + if map.get(&"Items".into()) != Some(&self.items) { + return false; + } + map.remove(&"Items".into()); + map.insert("LootTable".into(), string(&self.table)); + if let Some(seed) = self.seed.filter(|s| *s != 0) { + map.insert("LootTableSeed".into(), Tag::Long(seed)); + } + true + } +} + /// Save data loaded with a chunk that Horizon keeps but does not simulate. #[derive(Clone, Debug, Default)] pub struct ChunkExtras { @@ -318,6 +389,8 @@ pub struct ChunkExtras { pub fluid_ticks: Vec, /// Game time written as `LastUpdate`. pub last_update: i64, + /// Containers still holding their loot table's roll. + pub rolled_loot: Vec, } fn tick_list(ticks: &[SavedTick], name: impl Fn(u32) -> Option) -> Tag { @@ -526,6 +599,12 @@ pub fn encode_block_entity( } } BlockEntity::Sculk(s) => entries.extend(s.to_nbt()), + // CampfireBlockEntity.saveAdditional. + BlockEntity::Campfire(c) => { + entries.push(("Items", encode_items(&c.items))); + entries.push(("CookingTimes", Tag::IntArray(c.progress.to_vec()))); + entries.push(("CookingTotalTimes", Tag::IntArray(c.total.to_vec()))); + } BlockEntity::Crafter(c) => { entries.push(("Items", encode_items(&c.items))); entries.push(( @@ -569,6 +648,7 @@ pub fn encode_block_entity( BlockEntity::Vault(v) => entries.extend(v.save()), BlockEntity::Beehive(h) => entries.extend(h.to_nbt()), BlockEntity::CommandBlock(c) => entries.extend(c.save()), + BlockEntity::DaylightDetector => {} } Tag::compound(entries) } @@ -594,6 +674,34 @@ pub fn decode_banner(tag: &Tag) -> crate::containers::Banner { }, } } +/// A loaded container with a loot table and no items yet, rolled as +/// generation rolls it (Horizon does not unpack on first open). +fn roll_loaded_loot( + chunk: &Chunk, + biomes: &Biomes, + tag: &Tag, + be: &mut ((i32, i32, i32), crate::containers::BlockEntity), +) -> Option { + let crate::containers::BlockEntity::Chest(slots) = &mut be.1 else { + return None; + }; + let table = text(tag.get("LootTable"))?; + if slots.iter().any(Option::is_some) { + return None; + } + let loot = crate::structure_blocks::loaded_loot_data()?; + let (x, y, z) = be.0; + let biome = &biomes.get(chunk.biome(x & 15, y, z & 15)).name; + let seed = crate::structure_blocks::loot_seed(tag); + Some(crate::structure_blocks::roll_container( + slots, + Some(&loot), + table, + seed, + be.0, + biome, + )) +} pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers::BlockEntity)> { use crate::containers::BlockEntity; let int = |k: &str| number(tag.get(k)).map(|v| v as i32); @@ -676,8 +784,10 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain Tag::Int(n) => *n, _ => continue, }; - f.recipes_used - .insert(id.to_string_lossy(), count.max(0) as u32); + // Saves from before the key was namespaced hold both forms of an id. + *f.recipes_used + .entry(crate::containers::recipe_used_key(&id.to_string_lossy())) + .or_insert(0) += count.max(0) as u32; } } } @@ -704,6 +814,18 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain } BlockEntity::Sign(sign) => sign.decode(tag), BlockEntity::Sculk(s) => s.load(tag), + // CampfireBlockEntity.loadAdditional: missing time arrays stay zeros. + BlockEntity::Campfire(c) => { + for (slot, item) in decode_items(tag.get("Items"), 4).into_iter().enumerate() { + c.items[slot] = item; + } + let ints = |key: &str| match tag.get(key) { + Some(Tag::IntArray(v)) => std::array::from_fn(|i| v.get(i).copied().unwrap_or(0)), + _ => [0; 4], + }; + c.progress = ints("CookingTimes"); + c.total = ints("CookingTotalTimes"); + } BlockEntity::Crafter(c) => { for (slot, item) in decode_items(tag.get("Items"), 9).into_iter().enumerate() { c.items[slot] = item; @@ -724,7 +846,8 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain | BlockEntity::Lectern(_) | BlockEntity::Banner(_) | BlockEntity::CreakingHeart(_) - | BlockEntity::Skull(_) => {} + | BlockEntity::Skull(_) + | BlockEntity::DaylightDetector => {} BlockEntity::Spawner(s) => **s = crate::mobs::spawner::Spawner::load(tag), BlockEntity::TrialSpawner(s) => **s = crate::mobs::trial_spawner::TrialSpawner::load(tag), BlockEntity::Vault(v) => **v = crate::vault::Vault::load(tag), @@ -734,18 +857,164 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain Some((pos, entity)) } +/// The chunk's points of interest as `PoiManager` saves them: each section +/// with POI blocks, valid, with a record per block at its max tickets (a +/// freshly made world). None when the chunk has none. +pub fn encode_poi(chunk: &Chunk, tables: &SaveTables) -> Option { + let kind = |v: u32| tables.poi.get(v as usize).copied().flatten(); + let mut sections = Compound::new(); + let mut states = [0u32; 4096]; + for (si, section) in chunk.sections.iter().enumerate() { + if !section.blocks.maybe_has(|v| kind(v).is_some()) { + continue; + } + section.unpack(&mut states); + let y = (MIN_Y >> 4) + si as i32; + let records: Vec = states + .iter() + .enumerate() + .filter_map(|(i, &v)| { + let (id, tickets) = kind(v)?; + let i = i as i32; + let pos = [ + chunk.x * 16 + (i & 15), + y * 16 + (i >> 8), + chunk.z * 16 + ((i >> 4) & 15), + ]; + let mut record = vec![("pos", Tag::IntArray(pos.to_vec())), ("type", string(id))]; + // PoiRecord.CODEC: free_tickets defaults to 0 and is then left out. + if tickets != 0 { + record.push(("free_tickets", Tag::Int(tickets))); + } + Some(Tag::compound(record)) + }) + .collect(); + if !records.is_empty() { + sections.insert( + y.to_string().as_str().into(), + Tag::compound([("Valid", Tag::Byte(1)), ("Records", Tag::List(records))]), + ); + } + } + (!sections.is_empty()).then(|| poi_root(sections)) +} +/// A record's `free_tickets` from the POI file the chunk had, while the same +/// POI is still there: a bed or job site a villager claimed stays claimed. +fn keep_claims(saved: &mut NamedTag, old: &NamedTag) { + let key = |r: &Tag| match (r.get("pos"), text(r.get("type"))) { + (Some(Tag::IntArray(pos)), Some(kind)) => Some((pos.clone(), kind)), + _ => None, + }; + let mut claims = HashMap::new(); + if let Some(Tag::Compound(sections)) = old.tag.get("Sections") { + for section in sections.values() { + if let Some(Tag::List(records)) = section.get("Records") { + for r in records { + if let Some(k) = key(r) { + claims.insert(k, number(r.get("free_tickets")).unwrap_or(0) as i32); + } + } + } + } + } + let Tag::Compound(root) = &mut saved.tag else { + return; + }; + let Some(Tag::Compound(sections)) = root.get_mut(&"Sections".into()) else { + return; + }; + for section in sections.values_mut() { + let Tag::Compound(section) = section else { + continue; + }; + let Some(Tag::List(records)) = section.get_mut(&"Records".into()) else { + continue; + }; + for r in records { + let Some(&tickets) = key(r).and_then(|k| claims.get(&k)) else { + continue; + }; + if let Tag::Compound(r) = r { + if tickets == 0 { + r.remove(&"free_tickets".into()); + } else { + r.insert("free_tickets".into(), Tag::Int(tickets)); + } + } + } + } +} +fn poi_root(sections: Compound) -> NamedTag { + NamedTag { + name: "".into(), + tag: Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("Sections", Tag::Compound(sections)), + ]), + } +} + +/// What a dimension's saved chunks depend on: skylight and the build height +/// (`DimensionType.minY` and `height`). `Chunk` always holds the Overworld's +/// sections; a level saves only the ones inside its own height. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct LevelShape { + pub sky_light: bool, + pub min_y: i32, + pub height: i32, +} +impl LevelShape { + pub const OVERWORLD: Self = Self { + sky_light: true, + min_y: MIN_Y, + height: SECTIONS as i32 * 16, + }; + pub const NETHER: Self = Self { + sky_light: false, + min_y: 0, + height: 256, + }; + pub const END: Self = Self { + sky_light: true, + min_y: 0, + height: 256, + }; + /// The shape of a dimension folder (`dimensions/minecraft/`, or the + /// old `DIM-1` and `DIM1`). + pub fn for_dir(root: &Path) -> Self { + if root.ends_with("the_nether") || root.ends_with("DIM-1") { + Self::NETHER + } else if root.ends_with("the_end") || root.ends_with("DIM1") { + Self::END + } else { + Self::OVERWORLD + } + } + fn min_section(self) -> i32 { + self.min_y >> 4 + } + fn section_count(self) -> usize { + (self.height >> 4) as usize + } + fn has_section(self, y: i32) -> bool { + (self.min_section()..self.min_section() + self.section_count() as i32).contains(&y) + } +} + /// A column's sections as `Heightmap.primeHeightmaps` reads them. struct HeightmapView<'a> { sections: &'a [Arc
], tables: &'a SaveTables, + min_y: i32, + height: i32, } impl HeightmapChunk for HeightmapView<'_> { type State = crate::assets::StateFacts; fn min_y(&self) -> i32 { - MIN_Y + self.min_y } fn height(&self) -> i32 { - SECTIONS as i32 * 16 + self.height } fn highest_section_y(&self) -> i32 { let top = self @@ -765,7 +1034,7 @@ impl HeightmapChunk for HeightmapView<'_> { } } /// Heightmaps kept after world generation (`ChunkStatus.FULL.heightmapsAfter`). -fn heightmaps(chunk: &Chunk, tables: &SaveTables) -> Tag { +fn heightmaps(chunk: &Chunk, tables: &SaveTables, shape: LevelShape) -> Tag { let kinds = [ HeightmapType::WorldSurface, HeightmapType::OceanFloor, @@ -774,11 +1043,13 @@ fn heightmaps(chunk: &Chunk, tables: &SaveTables) -> Tag { ]; let mut maps: Vec = kinds .iter() - .filter_map(|k| Heightmap::new(*k, MIN_Y, SECTIONS as i32 * 16).ok()) + .filter_map(|k| Heightmap::new(*k, shape.min_y, shape.height).ok()) .collect(); let view = HeightmapView { sections: &chunk.sections, tables, + min_y: shape.min_y, + height: shape.height, }; let mut refs: Vec<&mut Heightmap> = maps.iter_mut().collect(); if Heightmap::prime(&view, &mut refs).is_err() { @@ -808,7 +1079,12 @@ pub fn client_heightmaps_in( .iter() .filter_map(|(id, k)| Heightmap::new(*k, min_y, height).ok().map(|m| (*id, m))) .collect(); - let view = HeightmapView { sections, tables }; + let view = HeightmapView { + sections, + tables, + min_y, + height, + }; let mut refs: Vec<&mut Heightmap> = maps.iter_mut().map(|(_, m)| m).collect(); if Heightmap::prime(&view, &mut refs).is_err() { return Vec::new(); @@ -834,17 +1110,18 @@ fn nibbles(light: &Light, sky: bool) -> Vec { } pub fn encode(chunk: &Chunk, registry: &BlockRegistry, biomes: &Biomes) -> NamedTag { - encode_with(chunk, registry, biomes, None, true) + encode_with(chunk, registry, biomes, None, LevelShape::OVERWORLD) } /// The chunk NBT vanilla's `SerializableChunkData.write` produces for a full -/// chunk. `sky_light` is false in dimensions without skylight. +/// chunk in a level of `shape`. pub fn encode_with( chunk: &Chunk, registry: &BlockRegistry, biomes: &Biomes, tables: Option<&SaveTables>, - sky_light: bool, + shape: LevelShape, ) -> NamedTag { + let sky_light = shape.sky_light; let mut sections = Vec::new(); let air = tables.map_or(0, |t| t.air); // Sky layers below the highest section with light other than 15 are @@ -856,6 +1133,9 @@ pub fn encode_with( }); for (si, section) in chunk.sections.iter().enumerate() { let y = (MIN_Y >> 4) + si as i32; + if !shape.has_section(y) { + continue; + } // PalettedContainer.pack: distinct states in index order, indices at // the saved width. let packed = section.blocks.pack(); @@ -959,7 +1239,16 @@ pub fn encode_with( } None => current, }; - crate::block_entity_nbt::canonical(&merged).unwrap_or(merged) + let mut saved = crate::block_entity_nbt::canonical(&merged).unwrap_or(merged); + if let Some(r) = extras.and_then(|x| x.rolled_loot.iter().find(|r| r.pos == *p)) + && let Tag::Compound(map) = &mut saved + && !r.restore(map) + { + // A loaded source still carries the table; kept, it rolls again on load. + map.remove(&"LootTable".into()); + map.remove(&"LootTableSeed".into()); + } + saved }) .collect(); if let Some(extras) = extras { @@ -985,7 +1274,7 @@ pub fn encode_with( ("DataVersion", Tag::Int(DATA_VERSION)), ("xPos", Tag::Int(chunk.x)), ("zPos", Tag::Int(chunk.z)), - ("yPos", Tag::Int(MIN_Y >> 4)), + ("yPos", Tag::Int(shape.min_section())), ("Status", string("minecraft:full")), ("LastUpdate", Tag::Long(extras.map_or(0, |e| e.last_update))), ("isLightOn", Tag::Byte(i8::from(chunk.lit))), @@ -1017,11 +1306,30 @@ pub fn encode_with( .collect(); s.insert("References".into(), Tag::Compound(refs)); } + let starts: Compound = chunk + .structure_starts + .iter() + .filter_map(|start| match start.save() { + Some(tag) => Some((start.name.as_str().into(), tag)), + None => { + log::warn!( + "Horizon: structure start {} not saved: one of its pieces cannot be", + start.name + ); + None + } + }) + .collect(); + if !starts.is_empty() + && let Some(Tag::Compound(s)) = map.get_mut(&"structures".into()) + { + s.insert("starts".into(), Tag::Compound(starts)); + } map.entry("PostProcessing".into()) - .or_insert_with(|| Tag::List(vec![Tag::List(Vec::new()); SECTIONS])); + .or_insert_with(|| Tag::List(vec![Tag::List(Vec::new()); shape.section_count()])); } if let Some(t) = tables { - put(&mut root, "Heightmaps", heightmaps(chunk, t)); + put(&mut root, "Heightmaps", heightmaps(chunk, t, shape)); let names = |k: u32| t.block_names.get(k as usize).cloned(); let (blocks, fluids) = extras.map_or((&[][..], &[][..]), |e| { (&e.block_ticks[..], &e.fluid_ticks[..]) @@ -1189,10 +1497,13 @@ fn decode_column( extras.block_entity_order.push((x, y, z)); } match decode_block_entity(e) { - Some(be) => { + Some(mut be) => { if let Some(name) = text(e.get("CustomName")) { chunk.block_names.push((be.0, name)); } + if let Some(rolled) = roll_loaded_loot(&chunk, biomes, e, &mut be) { + extras.rolled_loot.push(rolled); + } extras.block_entity_sources.push((be.0, e.clone())); chunk.block_entities.push(be); } @@ -1237,18 +1548,19 @@ pub fn encode_proto( registry: &BlockRegistry, biomes: &Biomes, tables: Option<&SaveTables>, - sky_light: bool, + shape: LevelShape, ) -> NamedTag { - let mut root = encode_with(&proto.column, registry, biomes, tables, sky_light); + let mut root = encode_with(&proto.column, registry, biomes, tables, shape); let status = if proto.decorated { ChunkStatus::Features } else { ChunkStatus::Terrain }; // ProtoChunk.postProcessing: one list per section, packed section offsets. - let mut marks = vec![Vec::new(); SECTIONS]; + let mut marks = vec![Vec::new(); shape.section_count()]; for &[x, y, z] in &proto.column.postprocess { - if let Some(list) = marks.get_mut(((y - MIN_Y) >> 4) as usize) { + let section = usize::try_from((y - shape.min_y) >> 4).ok(); + if let Some(list) = section.and_then(|s| marks.get_mut(s)) { list.push(Tag::Short( ((x & 15) | (y & 15) << 4 | (z & 15) << 8) as i16, )); @@ -1555,6 +1867,9 @@ enum Record { Tag(Arc), /// A chunk to encode on the writer thread. Chunk(Arc, Arc), + /// A chunk's points of interest, made on the writer thread against the + /// saved ones (`resolve_poi`). + Poi(Arc, Arc), Delete, } /// What encoding a chunk needs, captured when it is queued. @@ -1562,7 +1877,7 @@ struct Encoding { registry: &'static BlockRegistry, biomes: Arc, tables: Option>, - sky_light: bool, + shape: LevelShape, } impl Record { fn tag(&self) -> Option> { @@ -1573,16 +1888,88 @@ impl Record { e.registry, &e.biomes, e.tables.as_deref(), - e.sky_light, + e.shape, ))), + Record::Poi(c, t) => encode_poi(c, t).map(Arc::new), Record::Delete => None, } } } +/// A queued POI record as it is written: claims kept from the saved one, and +/// a chunk that lost its last POI gets an empty one, as vanilla trusts a +/// saved section. None when the chunk never had any. +fn resolve_poi( + root: &Path, + cache: &RegionCache, + (x, z): (i32, i32), + record: &Record, +) -> Option { + let Record::Poi(chunk, tables) = record else { + return Some(record.clone()); + }; + let old = read_region_record(root, cache, "poi", x, z).unwrap_or_else(|e| { + log::warn!("Horizon: could not read the poi record of chunk {x} {z}: {e}"); + None + }); + let tag = match (encode_poi(chunk, tables), old) { + (Some(mut tag), Some(old)) => { + keep_claims(&mut tag, &old); + tag + } + (Some(tag), None) => tag, + (None, Some(_)) => poi_root(Compound::new()), + (None, None) => return None, + }; + Some(Record::Tag(Arc::new(tag))) +} +fn read_region_record( + root: &Path, + cache: &RegionCache, + folder: &str, + x: i32, + z: i32, +) -> Result> { + let key = (x >> 5, z >> 5); + let path = region_path(root, folder, key.0, key.1); + let Some(region) = cached_region(cache, key, &path, false)? else { + return Ok(None); + }; + let record = region + .lock() + .map_err(|_| "region file poisoned")? + .read(ChunkPos::new(x, z))?; + Ok(match record { + Some(r) => Some(r.nbt(Limits::default())?), + None => None, + }) +} /// Chunk and entity records waiting for the writer thread, by (entities?, /// x, z): reads see them before the region files do. -type PendingWrites = Mutex>; -type WriteBatch = (bool, Vec<((i32, i32), Record, u64)>); +type PendingWrites = Mutex>; +type WriteBatch = (Folder, Vec<((i32, i32), Record, u64)>); +/// The region folders of a dimension. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum Folder { + Region, + Entities, + Poi, +} +impl Folder { + fn of(name: &str) -> Self { + match name { + "entities" => Self::Entities, + "poi" => Self::Poi, + _ => Self::Region, + } + } + fn name(self) -> &'static str { + match self { + Self::Region => "region", + Self::Entities => "entities", + Self::Poi => "poi", + } + } +} /// The background thread that encodes chunks and writes them into the region files, in /// submission order. @@ -1604,30 +1991,79 @@ pub struct SaveDir { pub root: PathBuf, regions: Arc, entity_regions: Arc, + poi_regions: Arc, pending: Arc, sequence: AtomicU64, writer: Mutex>, outstanding: Arc, /// Set by `Persistent` before the first load. pub tables: OnceLock>, - /// False in dimensions without skylight (no SkyLight layers are written). - pub sky_light: bool, + /// The dimension's skylight and height, from its folder name. + pub shape: LevelShape, +} +fn is_forced_ticket(ticket: &Tag) -> bool { + matches!(ticket.get("type"), Some(Tag::String(t)) if *t == JavaString::from("minecraft:forced")) } impl SaveDir { pub fn new(root: PathBuf) -> Self { - let sky_light = !root.ends_with("the_nether") && !root.ends_with("DIM-1"); + let shape = LevelShape::for_dir(&root); Self { root, regions: Default::default(), entity_regions: Default::default(), + poi_regions: Default::default(), pending: Default::default(), sequence: AtomicU64::new(0), writer: Mutex::new(None), outstanding: Default::default(), tables: OnceLock::new(), - sky_light, + shape, } } + /// 26.3's TicketStorage: persistent tickets live in each dimension's + /// data/minecraft/chunk_tickets.dat, with ChunkPos.CODEC's [x, z] int array. + pub fn load_forced_chunks(&self) -> HashSet<(i32, i32)> { + let Some(data) = read_saved_data(&self.root, "chunk_tickets") else { + return HashSet::new(); + }; + let Some(Tag::List(tickets)) = data.get("tickets") else { + return HashSet::new(); + }; + tickets + .iter() + .filter(|t| is_forced_ticket(t)) + .filter_map(|t| match t.get("chunk_pos")? { + Tag::IntArray(pos) if pos.len() == 2 => Some((pos[0], pos[1])), + _ => None, + }) + .collect() + } + pub fn save_forced_chunks(&self, forced: &HashSet<(i32, i32)>) -> Result<()> { + if forced.is_empty() && !saved_data_path(&self.root, "chunk_tickets").exists() { + return Ok(()); + } + let mut data = compound_or_empty(read_saved_data(&self.root, "chunk_tickets")); + // Preserve persistent tickets Horizon does not simulate. + let mut tickets = match data.get("tickets") { + Some(Tag::List(tickets)) => tickets + .iter() + .filter(|t| !is_forced_ticket(t)) + .cloned() + .collect::>(), + _ => Vec::new(), + }; + let mut chunks: Vec<_> = forced.iter().copied().collect(); + chunks.sort_unstable(); + tickets.extend(chunks.into_iter().map(|(x, z)| { + Tag::compound([ + ("type", Tag::String("minecraft:forced".into())), + ("level", Tag::Int(31)), // ChunkMap.FORCED_TICKET_LEVEL: ENTITY_TICKING. + ("chunk_pos", Tag::IntArray(vec![x, z])), + ]) + })); + put(&mut data, "tickets", Tag::List(tickets)); + write_saved_data(&self.root, "chunk_tickets", data) + } fn region_path(&self, folder: &str, rx: i32, rz: i32) -> PathBuf { region_path(&self.root, folder, rx, rz) } @@ -1636,27 +2072,23 @@ impl SaveDir { .pending .lock() .ok()? - .get(&(folder != "region", x, z)) + .get(&(Folder::of(folder), x, z)) .map(|(_, r)| r.clone()); if let Some(record) = pending { return record.tag().map(|t| (*t).clone()); } - let key = (x >> 5, z >> 5); - let cache = if folder == "region" { - &self.regions - } else { - &self.entity_regions + let cache = match Folder::of(folder) { + Folder::Region => &self.regions, + Folder::Entities => &self.entity_regions, + Folder::Poi => &self.poi_regions, }; - 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() + read_region_record(&self.root, cache, folder, x, z).ok()? } pub fn load(&self, x: i32, z: i32, registry: &BlockRegistry, biomes: &Biomes) -> Option { let root = self.read_record("region", x, z)?; let tables = self.tables.get().map(|t| &**t); let mut chunk = decode_with(&root, registry, biomes, tables)?; - load_light(&root.tag, &mut chunk, self.sky_light); + load_light(&root.tag, &mut chunk, self.shape.sky_light); Some(chunk) } /// A proto chunk saved before it became final (`decode_proto`). @@ -1681,7 +2113,7 @@ impl SaveDir { let records = protos .iter() .map(|p| { - let tag = encode_proto(p, registry, biomes, tables, self.sky_light); + let tag = encode_proto(p, registry, biomes, tables, self.shape); ((p.column.x, p.column.z), Some(tag)) }) .collect(); @@ -1710,16 +2142,16 @@ impl SaveDir { .into_iter() .map(|(k, t)| (k, t.map_or(Record::Delete, |t| Record::Tag(Arc::new(t))))) .collect(); - self.queue(folder != "region", records, wait) + self.queue(Folder::of(folder), records, wait) } - fn queue(&self, entities: bool, records: Vec<((i32, i32), Record)>, wait: bool) -> Result<()> { + fn queue(&self, folder: Folder, records: Vec<((i32, i32), Record)>, wait: bool) -> Result<()> { if !records.is_empty() { let mut batch = Vec::with_capacity(records.len()); { let mut pending = self.pending.lock().map_err(|_| "pending writes poisoned")?; for (key, record) in records { let seq = self.sequence.fetch_add(1, Ordering::Relaxed); - pending.insert((entities, key.0, key.1), (seq, record.clone())); + pending.insert((folder, key.0, key.1), (seq, record.clone())); batch.push((key, record, seq)); } } @@ -1730,7 +2162,7 @@ impl SaveDir { .map_err(|_| "writer poisoned")? += 1; let mut writer = self.writer.lock().map_err(|_| "writer poisoned")?; let writer = writer.get_or_insert_with(|| self.start_writer()); - if writer.send.send((entities, batch)).is_err() { + if writer.send.send((folder, batch)).is_err() { *self .outstanding .error @@ -1753,30 +2185,36 @@ impl SaveDir { fn start_writer(&self) -> Writer { let (send, receive) = mpsc::channel::(); let root = self.root.clone(); - let (regions, entity_regions) = (self.regions.clone(), self.entity_regions.clone()); + let (regions, entity_regions, poi_regions) = ( + self.regions.clone(), + self.entity_regions.clone(), + self.poi_regions.clone(), + ); let pending = self.pending.clone(); let outstanding = self.outstanding.clone(); let thread = std::thread::Builder::new() .name("horizon-region-writer".into()) .spawn(move || { - for (entities, batch) in receive { - let (folder, cache) = if entities { - ("entities", &entity_regions) - } else { - ("region", ®ions) + for (kind, batch) in receive { + let cache = match kind { + Folder::Region => ®ions, + Folder::Entities => &entity_regions, + Folder::Poi => &poi_regions, }; + let folder = kind.name(); // 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) + p.get(&(kind, k.0, k.1)).is_none_or(|p| p.0 <= seq) }) }; - let records: Vec<_> = batch + let resolved: Vec<_> = batch .iter() .filter(|(k, _, seq)| newest(k, *seq)) - .map(|(k, r, _)| (*k, r)) + .filter_map(|(k, r, _)| Some((*k, resolve_poi(&root, cache, *k, r)?))) .collect(); + let records: Vec<_> = resolved.iter().map(|(k, r)| (*k, r)).collect(); let result = write_region_records(&root, cache, folder, &records); if let Err(e) = &result { let message = format!("failed to write {folder} files: {e}"); @@ -1788,11 +2226,8 @@ impl SaveDir { && let Ok(mut pending) = pending.lock() { for (k, _, seq) in &batch { - if pending - .get(&(entities, k.0, k.1)) - .is_some_and(|p| p.0 == *seq) - { - pending.remove(&(entities, k.0, k.1)); + if pending.get(&(kind, k.0, k.1)).is_some_and(|p| p.0 == *seq) { + pending.remove(&(kind, k.0, k.1)); } } } @@ -1856,13 +2291,24 @@ impl SaveDir { .map(|c| { ( (c.x, c.z), - Some(encode_with(c, registry, biomes, tables, self.sky_light)), + Some(encode_with(c, registry, biomes, tables, self.shape)), ) }) .collect(); self.write_records("region", records, true)?; + self.save_poi(chunks, true)?; Ok(chunks.len()) } + fn save_poi(&self, chunks: &[Arc], wait: bool) -> Result<()> { + let Some(tables) = self.tables.get() else { + return Ok(()); + }; + let records = chunks + .iter() + .map(|c| ((c.x, c.z), Record::Poi(c.clone(), tables.clone()))) + .collect(); + self.queue(Folder::Poi, records, wait) + } /// `save` on the writer thread: returns before the files are written; /// loads see the chunks meanwhile. pub fn save_later( @@ -1875,13 +2321,14 @@ impl SaveDir { registry, biomes: biomes.clone(), tables: self.tables.get().cloned(), - sky_light: self.sky_light, + shape: self.shape, }); let records = chunks .iter() .map(|c| ((c.x, c.z), Record::Chunk(c.clone(), encoding.clone()))) .collect(); - self.queue(false, records, false)?; + self.queue(Folder::Region, records, false)?; + self.save_poi(chunks, false)?; Ok(chunks.len()) } /// Write the entity chunks (`EntityStorage`): an empty list deletes it. @@ -1988,28 +2435,7 @@ fn write_saved_data(world: &Path, name: &str, data: Tag) -> Result<()> { Tag::compound([("data", data), ("DataVersion", Tag::Int(DATA_VERSION))]), ) } -pub fn uuid_text(u: [i32; 4]) -> String { - let hex: String = u.iter().map(|v| format!("{:08x}", *v as u32)).collect(); - format!( - "{}-{}-{}-{}-{}", - &hex[0..8], - &hex[8..12], - &hex[12..16], - &hex[16..20], - &hex[20..32] - ) -} -pub fn uuid_from_text(s: &str) -> Option<[i32; 4]> { - let hex: String = s.chars().filter(|c| *c != '-').collect(); - if hex.len() != 32 { - return None; - } - let mut out = [0i32; 4]; - for (i, v) in out.iter_mut().enumerate() { - *v = u32::from_str_radix(&hex[i * 8..i * 8 + 8], 16).ok()? as i32; - } - Some(out) -} +pub use horizon_client_core::uuid::{uuid_from_text, uuid_text}; /// A random (version 4) UUID as vanilla's four-int form. pub fn random_uuid() -> [i32; 4] { let t = std::time::SystemTime::now() @@ -3326,7 +3752,7 @@ impl SaveDir { .pending .lock() .ok()? - .get(&(false, x, z)) + .get(&(Folder::Region, x, z)) .map(|(_, record)| record.clone()); let root = if let Some(record) = pending { record.tag().map(|tag| (*tag).clone())? @@ -3345,7 +3771,7 @@ impl SaveDir { { return None; } - decode_lod_surfaces(&root, assets, biomes, self.sky_light) + decode_lod_surfaces(&root, assets, biomes, self.shape.sky_light) } } @@ -3436,6 +3862,277 @@ impl ChunkGenerator for Persistent { #[cfg(test)] mod tests { + #[test] + fn points_of_interest_save_as_poi_sections() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES") else { + return; + }; + let assets = crate::assets::Assets::load(&PathBuf::from(root)).expect("assets"); + let tables = SaveTables::new(&assets); + let state = |name: &str, props: &[(&str, &str)]| { + let mut s = assets + .registry + .state(assets.registry.default_state(name).unwrap()) + .unwrap() + .clone(); + for (k, v) in props { + s.properties.insert((*k).into(), (*v).into()); + } + assets.registry.id(&s).unwrap().0 + }; + let mut chunk = Chunk::empty(2, -1); + chunk.set(1, 70, 1, state("minecraft:red_bed", &[("part", "head")])); + chunk.set(1, 70, 2, state("minecraft:red_bed", &[("part", "foot")])); + chunk.set(5, 71, 5, state("minecraft:bell", &[])); + chunk.set(6, 71, 5, state("minecraft:stone", &[])); + chunk.set(9, 70, 9, state("minecraft:straw_bed", &[("part", "head")])); + assert!(encode_poi(&Chunk::empty(0, 0), &tables).is_none()); + let saved = encode_poi(&chunk, &tables).expect("records"); + let Some(Tag::Compound(sections)) = saved.tag.get("Sections") else { + panic!("no sections"); + }; + assert_eq!(sections.len(), 1); + let section = §ions[&"4".into()]; + assert_eq!(section.get("Valid"), Some(&Tag::Byte(1))); + let Some(Tag::List(records)) = section.get("Records") else { + panic!("no records"); + }; + let records: Vec<_> = records + .iter() + .map(|r| { + ( + text(r.get("type")).unwrap(), + r.get("pos").cloned(), + number(r.get("free_tickets")), + ) + }) + .collect(); + assert_eq!( + records, + [ + ( + "minecraft:home".into(), + Some(Tag::IntArray(vec![33, 70, -15])), + Some(1) + ), + ( + "minecraft:meeting".into(), + Some(Tag::IntArray(vec![37, 71, -11])), + Some(32) + ), + ] + ); + } + + #[test] + fn a_chunk_that_loses_its_last_poi_saves_empty_sections() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES") else { + return; + }; + let root = PathBuf::from(root); + let assets = crate::assets::Assets::load(&root).expect("assets"); + let biomes = Arc::new(Biomes::load(&root).expect("biomes")); + let bell = assets.registry.default_state("minecraft:bell").unwrap().0; + let dir = std::env::temp_dir().join(format!("horizon-poi-save-{}", std::process::id())); + fs::create_dir_all(&dir).unwrap(); + let save = SaveDir::new(dir.clone()); + let _ = save.tables.set(Arc::new(SaveTables::new(&assets))); + let mut chunk = Chunk::empty(0, 0); + chunk.set(5, 71, 5, bell); + let sections = |save: &SaveDir| match save.read_record("poi", 0, 0)?.tag.get("Sections") { + Some(Tag::Compound(s)) => Some(s.len()), + _ => None, + }; + save.save_later(&[Arc::new(chunk.clone())], assets.registry, &biomes) + .unwrap(); + save.flush().unwrap(); + assert_eq!(sections(&save), Some(1)); + chunk.set(5, 71, 5, 0); + save.save_later(&[Arc::new(chunk)], assets.registry, &biomes) + .unwrap(); + save.flush().unwrap(); + assert_eq!(sections(&SaveDir::new(dir.clone())), Some(0)); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn saved_poi_records_keep_their_claims() { + let record = |pos: [i32; 3], kind: &str, tickets: Option| { + let mut r = vec![("pos", Tag::IntArray(pos.to_vec())), ("type", string(kind))]; + if let Some(t) = tickets { + r.push(("free_tickets", Tag::Int(t))); + } + Tag::compound(r) + }; + let poi = |records: Vec| { + let mut sections = Compound::new(); + sections.insert( + "4".into(), + Tag::compound([("Valid", Tag::Byte(1)), ("Records", Tag::List(records))]), + ); + poi_root(sections) + }; + let old = poi(vec![ + record([1, 70, 1], "minecraft:home", None), + record([5, 71, 5], "minecraft:meeting", Some(30)), + ]); + let mut saved = poi(vec![ + record([1, 70, 1], "minecraft:home", Some(1)), + record([5, 71, 5], "minecraft:meeting", Some(32)), + record([9, 71, 9], "minecraft:home", Some(1)), + ]); + keep_claims(&mut saved, &old); + let expected = poi(vec![ + record([1, 70, 1], "minecraft:home", None), + record([5, 71, 5], "minecraft:meeting", Some(30)), + record([9, 71, 9], "minecraft:home", Some(1)), + ]); + assert_eq!(saved.tag, expected.tag); + } + + #[test] + fn unopened_rolled_containers_save_their_loot_table() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES") else { + return; + }; + let root = PathBuf::from(root); + let assets = crate::assets::Assets::load(&root).expect("assets"); + let biomes = Biomes::load(&root).expect("biomes"); + let tables = SaveTables::new(&assets); + let chest = assets.registry.default_state("minecraft:chest").unwrap(); + let mut slots = vec![None; 27]; + slots[3] = Some(crate::items::ItemStack::new("minecraft:bone", 2)); + let mut chunk = Chunk::empty(0, 0); + chunk.set(1, 64, 2, chest.0); + chunk.block_entities.push(( + (1, 64, 2), + crate::containers::BlockEntity::Chest(slots.clone()), + )); + let rolled = RolledLoot { + pos: (1, 64, 2), + table: "minecraft:chests/simple_dungeon".into(), + seed: Some(42), + items: encode_items(&slots), + }; + chunk.saved = Some(Arc::new(ChunkExtras { + rolled_loot: vec![rolled], + ..ChunkExtras::default() + })); + let saved_chest = |chunk: &Chunk| -> Tag { + let saved = encode_with( + chunk, + assets.registry, + &biomes, + Some(&tables), + LevelShape::OVERWORLD, + ); + let Some(Tag::List(list)) = saved.tag.get("block_entities") else { + panic!("no block entities"); + }; + list[0].clone() + }; + let unopened = saved_chest(&chunk); + assert_eq!( + text(unopened.get("LootTable")).as_deref(), + Some("minecraft:chests/simple_dungeon") + ); + assert_eq!(number(unopened.get("LootTableSeed")), Some(42)); + assert!(unopened.get("Items").is_none()); + // Taking an item makes the items the container's own. + if let crate::containers::BlockEntity::Chest(s) = &mut chunk.block_entities[0].1 { + s[3] = None; + s[4] = Some(crate::items::ItemStack::new("minecraft:bone", 1)); + } + let opened = saved_chest(&chunk); + assert!(opened.get("LootTable").is_none()); + assert!(opened.get("Items").is_some()); + // Loaded with its table, rolled, then emptied: no table, or it refills on load. + let mut extras = ChunkExtras::clone(chunk.saved.as_ref().unwrap()); + extras.block_entity_sources = vec![( + (1, 64, 2), + Tag::compound([ + ("id", string("minecraft:chest")), + ("x", Tag::Int(1)), + ("y", Tag::Int(64)), + ("z", Tag::Int(2)), + ("LootTable", string("minecraft:chests/simple_dungeon")), + ("LootTableSeed", Tag::Long(42)), + ]), + )]; + chunk.saved = Some(Arc::new(extras)); + if let crate::containers::BlockEntity::Chest(s) = &mut chunk.block_entities[0].1 { + s.fill(None); + } + let emptied = saved_chest(&chunk); + assert!(emptied.get("LootTable").is_none()); + assert!(emptied.get("LootTableSeed").is_none()); + } + + #[test] + fn nether_and_end_chunks_save_with_their_own_height() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES") else { + return; + }; + let root = PathBuf::from(root); + let assets = crate::assets::Assets::load(&root).expect("assets"); + let biomes = Biomes::load(&root).expect("biomes"); + let tables = SaveTables::new(&assets); + let rack = assets + .registry + .default_state("minecraft:netherrack") + .unwrap(); + let mut chunk = Chunk::empty(0, 0); + for y in 0..128 { + chunk.set(0, y, 0, rack.0); + } + let saved = encode_with( + &chunk, + assets.registry, + &biomes, + Some(&tables), + LevelShape::NETHER, + ); + assert_eq!(number(saved.tag.get("yPos")), Some(0)); + let Some(Tag::List(sections)) = saved.tag.get("sections") else { + panic!("no sections"); + }; + let ys: Vec = sections + .iter() + .filter_map(|s| number(s.get("Y")).map(|y| y as i32)) + .collect(); + assert_eq!(ys, (0..16).collect::>()); + let Some(Tag::List(post)) = saved.tag.get("PostProcessing") else { + panic!("no PostProcessing"); + }; + assert_eq!(post.len(), 16); + // Heightmap values count from the level's minimum: the column's top + // block at y=127 reads 128 (vanilla), not 192 (from the Overworld's -64). + let Some(Tag::LongArray(surface)) = saved + .tag + .get("Heightmaps") + .and_then(|h| h.get("WORLD_SURFACE")) + else { + panic!("no WORLD_SURFACE"); + }; + assert_eq!(surface[0] & 0x1ff, 128); + let overworld = encode_with( + &chunk, + assets.registry, + &biomes, + Some(&tables), + LevelShape::OVERWORLD, + ); + assert_eq!(number(overworld.tag.get("yPos")), Some(-4)); + assert_eq!( + LevelShape::for_dir(Path::new("w/dimensions/minecraft/the_end")), + LevelShape::END + ); + assert_eq!( + LevelShape::for_dir(Path::new("w/DIM-1")), + LevelShape::NETHER + ); + } + #[test] fn saved_far_surface_reads_builds_and_water_without_gameplay_chunks() { let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES") else { @@ -3554,7 +4251,7 @@ mod tests { "unfinished proto saves must not suppress complete decoration" ); let mut nether = SaveDir::new(dir.clone()); - nether.sky_light = false; + nether.shape = LevelShape::NETHER; let dark = nether.lod_surfaces(-2, 3, &assets, &biomes).unwrap(); assert!( dark.iter() @@ -3873,6 +4570,31 @@ mod tests { assert_eq!(back.redstone_signal(), 2); } #[test] + fn campfire_block_entity_round_trips() { + let mut c = crate::containers::Campfire::default(); + c.items[1] = Some(crate::items::ItemStack::new("minecraft:beef", 1)); + c.progress[1] = 120; + c.total[1] = 600; + let tag = encode_block_entity( + (3, 64, -2), + &crate::containers::BlockEntity::Campfire(Box::new(c.clone())), + "minecraft:soul_campfire", + ); + // One block entity type for both campfires. + assert_eq!(text(tag.get("id")).as_deref(), Some("minecraft:campfire")); + let (pos, back) = decode_block_entity(&tag).expect("campfire"); + assert_eq!(pos, (3, 64, -2)); + let crate::containers::BlockEntity::Campfire(back) = back else { + panic!("not a campfire"); + }; + assert_eq!(*back, c); + // The update tag a server's clients get: the items alone. + let update = + crate::lan::chunks::entity_tag(&crate::containers::BlockEntity::Campfire(Box::new(c))) + .expect("update tag"); + assert!(update.get("Items").is_some() && update.get("CookingTimes").is_none()); + } + #[test] fn spawner_block_entity_round_trips() { // A dungeon spawner as vanilla saves it (`id` is mob_spawner, not the block). let saved = horizon_world::nbt::parse_snbt( @@ -4382,4 +5104,108 @@ mod tests { }; assert_eq!(back.recipes_used.get("minecraft:cooked_porkchop"), Some(&3)); } + /// The world's save (Level.write) writes the rules as they are now, and a + /// world opened again reads them back (#74). + #[test] + fn level_save_keeps_changed_rules() { + use crate::gamerules::{GameRules, Value}; + let dir = + std::env::temp_dir().join(format!("horizon-gamerules-level-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut level = super::Level::default(); + level.write(&dir).unwrap(); + // Rules changed while playing, then saved and loaded again. + let mut rules = GameRules::load(&dir); + assert_eq!(rules, GameRules::default()); + assert!(rules.set("advance_time", Value::Bool(false))); + assert!(rules.set("advance_weather", Value::Bool(false))); + assert!(rules.set("random_tick_speed", Value::Int(0))); + level.game_rules = rules.by_name(); + level.write(&dir).unwrap(); + assert_eq!(GameRules::load(&dir), rules); + let read = super::Level::read(&dir).unwrap(); + assert_eq!(read.game_rules, rules.by_name()); + assert_eq!(read.game_rule("advance_time"), 0); + let _ = std::fs::remove_dir_all(dir); + } + + /// A save written before the key was namespaced holds an id twice, once bare: vanilla + /// refuses such a furnace, so a load merges them under the full id. + #[test] + fn a_furnaces_recipes_used_merges_bare_and_full_ids() { + use crate::containers::BlockEntity; + let Some(BlockEntity::Furnace(mut f)) = BlockEntity::for_block("minecraft:furnace") else { + panic!("a furnace"); + }; + f.recipes_used + .insert("iron_ingot_from_smelting_iron_ore".to_owned(), 2); + f.recipes_used + .insert("minecraft:iron_ingot_from_smelting_iron_ore".to_owned(), 3); + let tag = encode_block_entity((1, 64, 2), &BlockEntity::Furnace(f), "minecraft:furnace"); + let Some((_, BlockEntity::Furnace(back))) = decode_block_entity(&tag) else { + panic!("a furnace back"); + }; + assert_eq!(back.recipes_used.len(), 1); + assert_eq!( + back.recipes_used + .get("minecraft:iron_ingot_from_smelting_iron_ore"), + Some(&5) + ); + } + + #[test] + fn forced_chunks_survive_dimension_restarts_and_removals() { + let root = std::env::temp_dir().join(format!("horizon-forced-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + let dimensions = [ + "minecraft:overworld", + "minecraft:the_nether", + "minecraft:the_end", + ]; + for (i, dim) in dimensions.iter().enumerate() { + let save = SaveDir::new(dimension_dir(&root, dim)); + assert!(save.load_forced_chunks().is_empty()); + let forced = HashSet::from([(i as i32, -17), (-23, i as i32), (-1, -1)]); + save.save_forced_chunks(&forced).unwrap(); + } + for (i, dim) in dimensions.iter().enumerate() { + let path = dimension_dir(&root, dim); + let save = SaveDir::new(path.clone()); + let mut forced = save.load_forced_chunks(); + assert_eq!( + forced, + HashSet::from([(i as i32, -17), (-23, i as i32), (-1, -1)]) + ); + let mut data = read_saved_data(&path, "chunk_tickets").unwrap(); + let other = Tag::compound([ + ("type", Tag::String("minecraft:portal".into())), + ("level", Tag::Int(30)), + ("chunk_pos", Tag::IntArray(vec![7, -8])), + ("ticks_left", Tag::Long(42)), + ]); + if let Some(Tag::List(tickets)) = data.get_mut("tickets") { + assert!( + tickets + .iter() + .all(|t| t.get("level") == Some(&Tag::Int(31))) + ); + tickets.push(other.clone()); + } + write_saved_data(&path, "chunk_tickets", data).unwrap(); + forced.remove(&(-1, -1)); + save.save_forced_chunks(&forced).unwrap(); + drop(save); + let reopened = SaveDir::new(path.clone()); + assert_eq!(reopened.load_forced_chunks(), forced); + reopened.save_forced_chunks(&HashSet::new()).unwrap(); + assert!(SaveDir::new(path.clone()).load_forced_chunks().is_empty()); + assert_eq!( + read_saved_data(&path, "chunk_tickets") + .unwrap() + .get("tickets"), + Some(&Tag::List(vec![other])) + ); + } + fs::remove_dir_all(root).unwrap(); + } } diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 74c428923..2308794d3 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -5,11 +5,7 @@ use crate::keybinds::KeyBinds; use crate::options_file::{OptionsFile, V}; use std::{fs, path::Path}; -/// SoundSource names in vanilla order. -pub const SOUND_SOURCES: [&str; 11] = [ - "master", "music", "record", "weather", "block", "hostile", "neutral", "player", "ambient", - "voice", "ui", -]; +pub use horizon_client_core::sound_source::SOUND_SOURCES; /// Per-source volumes for the mixer (soundCategory_* except master). static SOURCE_VOLUMES: std::sync::RwLock<[f32; 11]> = std::sync::RwLock::new([1.0; 11]); diff --git a/crates/horizon-client/src/sprint.rs b/crates/horizon-client/src/sprint.rs index c2099306c..872667b55 100644 --- a/crates/horizon-client/src/sprint.rs +++ b/crates/horizon-client/src/sprint.rs @@ -134,3 +134,76 @@ impl SprintState { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + + fn standing() -> Conditions { + Conditions { + enough_food: true, + on_ground: true, + ..Conditions::default() + } + } + + fn step(state: &mut SprintState, keys: Keys, sprinting: &mut bool) { + let current = *sprinting; + let mut next = current; + state + .tick( + keys, + Conditions { + sprinting: current, + ..standing() + }, + 7, + |value| { + next = value; + Ok::<(), ()>(()) + }, + ) + .unwrap(); + *sprinting = next; + } + + /// Vanilla sprint is a state. Releasing the sprint key, including on the + /// jump tick, keeps it while forward is held; releasing forward stops it. + #[test] + fn sprint_survives_releasing_the_key_through_a_jump() { + let mut state = SprintState::default(); + let mut sprinting = false; + step( + &mut state, + Keys { + forward: true, + sprint: true, + ..Keys::default() + }, + &mut sprinting, + ); + assert!(sprinting); + step( + &mut state, + Keys { + forward: true, + jump: true, + ..Keys::default() + }, + &mut sprinting, + ); + assert!( + sprinting, + "a jump after the sprint key comes up must stay a sprint" + ); + step( + &mut state, + Keys { + jump: true, + ..Keys::default() + }, + &mut sprinting, + ); + assert!(!sprinting); + } +} diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index 715c2663e..c5ed5d881 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -14,7 +14,8 @@ use std::{fs, path::Path, sync::Arc}; /// Everything the workstation menus read, loaded once with the resources. pub struct StationData { - pub enchantments: Enchantments, + /// The same registry `Items` carries (`Items::enchantments`). + pub enchantments: std::sync::Arc, pub recipes: StationRecipes, pub brewing: crate::brewing::Brewing, pub trades: crate::merchant::Trades, @@ -25,7 +26,7 @@ pub struct StationData { impl StationData { pub fn load(root: &Path, items: &Items) -> Self { Self { - enchantments: Enchantments::load(root), + enchantments: std::sync::Arc::clone(&items.enchantments), recipes: StationRecipes::load(root, items), brewing: crate::brewing::Brewing::load(root, items), trades: crate::merchant::Trades::load(root), @@ -174,7 +175,9 @@ pub fn increased_repair_cost(cost: u32) -> u32 { pub fn hover_name(names: &dyn Fn(&str) -> String, stack: &ItemStack) -> String { stack .custom_name() - .map_or_else(|| names(&stack.item), str::to_owned) + .map(str::to_owned) + .or_else(|| stack.item_name()) + .unwrap_or_else(|| names(&stack.item)) } /// `AnvilMenu.createResult`. `name` is the rename box text (None = untouched). pub fn anvil_result( @@ -445,6 +448,7 @@ pub fn grindstone_experience( #[derive(Clone, Debug)] pub enum Smithing { Transform { + id: String, template: Ingredient, base: Ingredient, addition: Ingredient, @@ -524,6 +528,7 @@ impl StationRecipes { ); match v["type"].as_str().unwrap_or("") { "minecraft:smithing_transform" => smithing.push(Smithing::Transform { + id, template: ingredient(&v["template"], items), base: ingredient(&v["base"], items), addition: ingredient(&v["addition"], items), @@ -627,6 +632,7 @@ impl StationRecipes { base: b, addition: a, result, + .. } => { if t.test(template) && b.test(base) && a.test(addition) { // SmithingTransformRecipe: transmute the base keeping its components. diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 643a604bc..c0a96f504 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -175,6 +175,11 @@ pub enum Done { } struct Queued { priority: i64, + /// The column the job is for and what it adds to the column's distance + /// (`Streaming::submit`): the priority is computed again from them when + /// the centre moves (`Streaming::requeue`). None for saves, which go first. + at: Option<(i32, i32)>, + bias: i64, order: u64, job: Job, } @@ -222,6 +227,9 @@ pub struct Streaming { /// radius it was last ranked for. decoration_order: DecorationOrder, order_area: Option<((i32, i32), i32)>, + /// What the queued jobs' priorities were computed from (`requeue`): the + /// centre, the loading screen, the band, and the extra areas. + queue_basis: (((i32, i32), bool, Option), Vec<((i32, i32), i32)>), finishing: FxHashSet<(i32, i32)>, decorates: bool, lighting: FxHashMap<(i32, i32), u64>, @@ -544,6 +552,7 @@ impl Streaming { saving: 0, decoration_order: DecorationOrder::default(), order_area: None, + queue_basis: Default::default(), finishing: Default::default(), decorates: generator.decorates(), lighting: Default::default(), @@ -648,15 +657,39 @@ impl Streaming { world.dirty_sections.take_column(x, z); world.chunks.remove(&(x, z)) } - fn submit(&mut self, priority: i64, job: Job) { + /// Queue a job for the column `at`, nearest first: its distance (`distance`) + /// times four plus `bias`, which orders a column's jobs. A job without a + /// column (a save) goes ahead of every other. + fn submit(&mut self, at: Option<(i32, i32)>, bias: i64, job: Job) { self.order += 1; + let priority = at.map_or(i64::MIN, |(x, z)| self.distance(x, z) * 4 + bias); self.shared.queue.lock().unwrap().push(Queued { priority, + at, + bias, order: self.order, job, }); self.shared.ready.notify_one(); } + /// Rank the queued jobs again when what their priorities were computed + /// from changed: the centre, the extra areas, the band, or the loading + /// screen (ring order, `Ranges::rings`, whose values are far above the + /// distances used after it). Vanilla's chunk task queue follows the + /// current ticket levels in the same way. Without it, generation queued + /// while the loading screen was up waited behind every job queued after + /// it, and with it the decoration of the chunks around the player: at + /// render distance 32 nothing was decorated until every proto chunk had + /// been generated. + fn requeue(&mut self) { + let basis = (self.center, self.loading, self.band); + if self.queue_basis.0 == basis && self.queue_basis.1 == self.extra { + return; + } + self.queue_basis = (basis, self.extra.clone()); + let mut queue = self.shared.queue.lock().unwrap(); + rank_again(&mut queue, |x, z| self.distance(x, z)); + } fn receive_decorated(&mut self, x: i32, z: i32, region: [Proto; 9]) { self.generation_scan.exhausted = false; self.decorating -= 1; @@ -686,7 +719,7 @@ impl Streaming { self.saving += 1; // Ahead of every other job: a column generated again meanwhile // would not find them saved. - self.submit(i64::MIN, Job::Save(protos)); + self.submit(None, 0, Job::Save(protos)); } } fn receive_generated(&mut self, mut chunk: Chunk, world: &mut World) { @@ -829,6 +862,7 @@ impl Streaming { return (uploads, Vec::new()); } ExtraCover::refresh(&mut self.cover, &self.extra); + self.requeue(); self.relight_edits(world); let deferred = std::mem::take(&mut self.deferred); let received = std::iter::from_fn(|| self.results.try_recv().ok()); @@ -984,7 +1018,7 @@ impl Streaming { .expect("present proto"); self.finishing.insert((x, z)); self.written.remove(&(x, z)); - self.submit(self.distance(x, z) * 4, Job::Finish(proto)); + self.submit(Some((x, z)), 0, Job::Finish(proto)); } } // Decorate chunks whose 3x3 proto neighbourhood is available, in @@ -1052,7 +1086,7 @@ impl Streaming { w.0 = self.decoration_order.rank_or_append(w.2, w.3); } wanted.sort_unstable(); - for (_, d, x, z) in wanted { + for (_, _, x, z) in wanted { if self.decorating >= workers * 2 { break; } @@ -1091,7 +1125,7 @@ impl Streaming { Err(_) => continue, }; self.decorating += 1; - self.submit(d * 4 + 1, Job::Decorate(x, z, region)); + self.submit(Some((x, z)), 1, Job::Decorate(x, z, region)); } } self.schedule_generation(world, workers); @@ -1111,7 +1145,8 @@ impl Streaming { self.light_snapshots .insert((x, z), self.light_edit_sequence); self.submit( - self.distance(x, z) * 4 + 1, + Some((x, z)), + 1, Job::Light(x, z, region, self.sequence, self.sky_light), ); } @@ -1183,7 +1218,8 @@ impl Streaming { self.sequence += 1; self.meshing.insert((x, sy, z), self.sequence); self.submit( - self.distance(x, z) * 4 + if first { 2 } else { 0 }, + Some((x, z)), + if first { 2 } else { 0 }, Job::Mesh( x, sy, @@ -1222,9 +1258,9 @@ impl Streaming { loading: self.loading, }; if let Some(wanted) = self.generation_scan.candidates(input, workers * 3) { - for (d, x, z) in wanted { + for (_, x, z) in wanted { self.generating.insert((x, z)); - self.submit(d * 4, Job::Generate(x, z)); + self.submit(Some((x, z)), 0, Job::Generate(x, z)); } } } @@ -1381,6 +1417,14 @@ impl Streaming { pub fn band(&self) -> Option { self.band } + /// Rank the chunks `/forceload add` over chunks `(x0, z0)..=(x1, z1)` + /// decorates in vanilla's order (`forced_order`), after every chunk + /// ranked before. + pub fn rank_forced(&mut self, x0: i32, z0: i32, x1: i32, z1: i32) { + for (x, z) in horizon_world::worldgen::decoration_order::forced_order(x0, z0, x1, z1) { + self.decoration_order.rank_or_append(x, z); + } + } /// Generate, light and keep the chunks of `band` (none: stop), and let /// go of what earlier bands held as it falls out of range. The chunks a /// band reaches are ranked for decoration row by row, as they first come @@ -1738,10 +1782,78 @@ fn section_indexes(mut bits: u32) -> impl Iterator { }) }) } +/// The queued jobs' priorities computed again from each one's column +/// `distance` (`Streaming::submit`). +fn rank_again(queue: &mut BinaryHeap, distance: impl Fn(i32, i32) -> i64) { + if queue.is_empty() { + return; + } + let mut jobs = std::mem::take(queue).into_vec(); + for job in &mut jobs { + if let Some((x, z)) = job.at { + job.priority = distance(x, z) * 4 + job.bias; + } + } + *queue = BinaryHeap::from(jobs); +} #[cfg(test)] mod tests { use super::*; + #[test] + fn queued_jobs_follow_the_centre_and_the_loading_screen() { + let forced = HashSet::new(); + let ranges = |center| Ranges { + center, + radius: 32, + extra: &[], + forced: &forced, + cover: None, + band: None, + }; + let generate = |x, z, priority, order| Queued { + priority, + at: Some((x, z)), + bias: 0, + order, + job: Job::Generate(x, z), + }; + let loading = ranges((0, 0)); + let queued = || { + BinaryHeap::from(vec![ + // Queued while the loading screen was up: ring order. + generate(3, 1, loading.priority(3, 1, true) * 4, 1), + // Queued after it closed: plain distances, far below any ring past the first. + generate(20, 0, loading.priority(20, 0, false) * 4, 2), + Queued { + priority: i64::MIN, + at: None, + bias: 0, + order: 3, + job: Job::Save(Vec::new()), + }, + ]) + }; + let pops = |mut queue: BinaryHeap| { + std::iter::from_fn(move || queue.pop()) + .map(|q| q.at) + .collect::>() + }; + assert_eq!( + pops(queued()), + [None, Some((20, 0)), Some((3, 1))], + "the stale order" + ); + let mut queue = queued(); + rank_again(&mut queue, |x, z| loading.priority(x, z, false)); + assert_eq!(pops(queue), [None, Some((3, 1)), Some((20, 0))]); + // The player moved: the job near the new centre goes first. + let mut queue = BinaryHeap::from(vec![generate(3, 1, 0, 1), generate(20, 0, 1, 2)]); + let moved = ranges((19, 0)); + rank_again(&mut queue, |x, z| moved.priority(x, z, false)); + assert_eq!(queue.pop().and_then(|q| q.at), Some((20, 0))); + } + #[test] fn view_distance_is_vanillas_shape() { // ChunkTrackingView.isInViewDistance at render distance 12: a column diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index 9503294e0..0a4c9a88e 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -9,7 +9,7 @@ use horizon_world::{ }; use std::{ path::Path, - sync::{Arc, OnceLock}, + sync::{Arc, Mutex}, }; /// The `custom_data` key holding an exploration map's search until the game @@ -63,6 +63,12 @@ pub fn loot_item_with_components(s: &horizon_world::loot::LootStack) -> ItemStac if let Some(level) = s.ominous_amplifier.filter(|l| *l > 0) { item.data_mut().ominous_amplifier = Some(level.clamp(0, 4) as u8); } + // set_stew_effect's `suspicious_stew_effects`. + for (effect, duration) in &s.stew_effects { + item.data_mut() + .stew_effects + .push((Arc::from(effect.as_str()), *duration)); + } item } @@ -108,10 +114,13 @@ pub fn has_pending_map(item: &ItemStack) -> bool { }) } +/// None until `loot_data` runs; `Some(None)` when the tables failed to load. +static LOOT: Mutex>>> = Mutex::new(None); + /// Loot data of the resource root, loaded once per process. pub fn loot_data(root: &Path) -> Option> { - static LOOT: OnceLock>> = OnceLock::new(); - LOOT.get_or_init(|| match LootData::load(root) { + let mut loot = LOOT.lock().unwrap_or_else(|e| e.into_inner()); + loot.get_or_insert_with(|| match LootData::load(root) { Ok(data) => Some(Arc::new(data)), Err(e) => { log::warn!("Horizon: loot tables unavailable, structure containers stay empty: {e}"); @@ -121,6 +130,63 @@ pub fn loot_data(root: &Path) -> Option> { .clone() } +/// The loot data `loot_data` loaded, if it ran. +pub fn loaded_loot_data() -> Option> { + LOOT.lock() + .unwrap_or_else(|e| e.into_inner()) + .clone() + .flatten() +} + +/// Let go of the loot data: for a preload no world used +/// (game/world_loading.rs). The next `loot_data` loads it again. +pub fn forget_loot_data() { + *LOOT.lock().unwrap_or_else(|e| e.into_inner()) = None; +} + +/// `RandomizableContainer.unpackLootTable` of a container at `pos`: `table` +/// rolled into `slots`. A missing or zero seed is the level's random in +/// vanilla; Horizon derives one from the position. Without loot data the +/// container stays empty and still saves its table. +pub fn roll_container( + slots: &mut [Option], + loot: Option<&LootData>, + table: String, + saved_seed: Option, + pos: (i32, i32, i32), + biome: &str, +) -> crate::save::RolledLoot { + let seed = saved_seed.filter(|s| *s != 0).unwrap_or_else(|| { + horizon_core::random::position_seed(horizon_core::position::BlockPos::new( + pos.0, pos.1, pos.2, + )) + }); + if let Some(loot) = loot { + // LootTable.fill spreads the items over the container's own size. + let rolled = loot.fill(&table, seed, slots.len(), Some(biome)); + for (slot, stack) in slots.iter_mut().zip(rolled) { + // With what the rolls put on them: enchantments + // (enchant_with_levels in End city chests), potions and an + // ominous bottle's level. + *slot = stack.map(|s| loot_item_with_components(&s)); + } + } + crate::save::RolledLoot { + pos, + table, + seed: saved_seed, + items: crate::save::encode_items(slots), + } +} + +/// A saved `LootTableSeed`, if any. +pub fn loot_seed(nbt: &Tag) -> Option { + match nbt.get("LootTableSeed") { + Some(Tag::Long(seed)) => Some(*seed), + _ => None, + } +} + fn text(nbt: &Compound, key: &str) -> Option { match nbt.get(&JavaString::from(key)) { Some(Tag::String(s)) => Some(s.to_string_lossy()), @@ -130,100 +196,60 @@ fn text(nbt: &Compound, key: &str) -> Option { /// The client block entity for one of a chunk's generated block entities, /// before a container's loot is unpacked: `StructureTemplate.placeInWorld` -/// hands the template's block entity NBT to the level's block entity. +/// hands the template's block entity NBT to `loadWithComponents`, which is +/// what a chunk load does with a saved one. fn generated_block_entity(block: &str, nbt: &Compound) -> Option { - let mut entity = BlockEntity::for_block(block)?; - match &mut entity { - // MonsterRoomFeature and the structures' setEntityId. - BlockEntity::Spawner(s) => { - **s = crate::mobs::spawner::Spawner::load(&Tag::Compound(nbt.clone())); - } - BlockEntity::TrialSpawner(s) => { - **s = crate::mobs::trial_spawner::TrialSpawner::load(&Tag::Compound(nbt.clone())); - } - BlockEntity::Vault(v) => **v = crate::vault::Vault::load(&Tag::Compound(nbt.clone())), - // BannerBlockEntity.loadAdditional: the End cities' black triangles. - BlockEntity::Banner(b) => *b = crate::save::decode_banner(&Tag::Compound(nbt.clone())), - _ => {} + let fallback = BlockEntity::for_block(block)?; + let mut tag = nbt.clone(); + // RandomizableContainer.tryLoadLootTable: with a table the items are not read. + if text(&tag, "LootTable").is_some() { + tag.remove(&JavaString::from("Items")); } - Some(entity) + // Programmatic block entities (and a template that saved none) carry no id. + if !tag.contains_key(&JavaString::from("id")) { + tag.insert("id".into(), Tag::String(fallback.id().into())); + } + for axis in ["x", "y", "z"] { + tag.insert(axis.into(), Tag::Int(0)); + } + // A saved kind the client cannot decode keeps the block's own entity. + Some( + crate::save::decode_block_entity(&Tag::Compound(tag)) + .map_or(fallback, |(_, entity)| entity), + ) } -/// Client block entities for the generated block entities of a chunk. +/// Client block entities for the generated block entities of a chunk, and the +/// loot rolled into its containers. pub fn block_entities( chunk: &ProtoChunk, loot: Option<&LootData>, -) -> Vec<((i32, i32, i32), BlockEntity)> { +) -> ( + Vec<((i32, i32, i32), BlockEntity)>, + Vec, +) { let mut out = Vec::new(); + let mut rolled = Vec::new(); for (pos, nbt) in &chunk.block_entities { let [x, y, z] = *pos; let block = chunk.block_name(x, y, z); let Some(mut entity) = generated_block_entity(block, nbt) else { continue; }; - if let (BlockEntity::Chest(slots), Some(table), Some(loot)) = - (&mut entity, text(nbt, "LootTable"), loot) - { - let seed = match nbt.get(&JavaString::from("LootTableSeed")) { - Some(Tag::Long(seed)) => *seed, - // Seed 0 means "the level's random": derive one from the position. - _ => horizon_core::random::position_seed(horizon_core::position::BlockPos::new( - x, y, z, - )), - }; - let biome = chunk.biome_at(x, y, z); - for (slot, stack) in slots - .iter_mut() - .zip(loot.fill(&table, seed, 27, Some(biome))) - { - // With what the rolls put on them: enchantments - // (enchant_with_levels in End city chests), potions and an - // ominous bottle's level. - *slot = stack.map(|s| loot_item_with_components(&s)); - } + if let (BlockEntity::Chest(slots), Some(table)) = (&mut entity, text(nbt, "LootTable")) { + let seed = loot_seed(&Tag::Compound(nbt.clone())); + rolled.push(roll_container( + slots, + loot, + table, + seed, + (x, y, z), + chunk.biome_at(x, y, z), + )); } out.push(((x, y, z), entity)); } - out -} - -/// Chest minecarts placed with a loot table (mineshafts): the table rolled -/// into `Items` as `unpackLootTable` would on first open. -pub fn unpack_entity_loot( - chunk: &ProtoChunk, - mut nbt: horizon_world::nbt::Compound, - loot: Option<&LootData>, -) -> horizon_world::nbt::Compound { - let (Some(table), Some(loot)) = ( - match nbt.get(&JavaString::from("LootTable")) { - Some(Tag::String(s)) => Some(s.to_string_lossy()), - _ => None, - }, - loot, - ) else { - return nbt; - }; - let seed = match nbt.get(&JavaString::from("LootTableSeed")) { - Some(Tag::Long(seed)) => *seed, - _ => 0, - }; - let pos = match nbt.get(&JavaString::from("Pos")) { - Some(Tag::List(p)) => std::array::from_fn(|i| match p.get(i) { - Some(Tag::Double(b)) => f64::from_bits(*b).floor() as i32, - _ => 0, - }), - _ => [0; 3], - }; - let biome = chunk.biome_at(pos[0], pos[1], pos[2]); - let slots: Vec> = loot - .fill(&table, seed, 27, Some(biome)) - .into_iter() - .map(|s| s.map(|s| loot_item_with_components(&s))) - .collect(); - nbt.remove(&JavaString::from("LootTable")); - nbt.remove(&JavaString::from("LootTableSeed")); - nbt.insert("Items".into(), crate::save::encode_items(&slots)); - nbt + (out, rolled) } #[cfg(test)] @@ -243,6 +269,7 @@ mod tests { map: false, exploration: None, ominous_amplifier: None, + stew_effects: Vec::new(), }; // An End city chest's enchant_with_levels roll. let boots = loot_item_with_components(&stack( @@ -270,6 +297,24 @@ mod tests { assert_eq!(arrow.potion(), Some("minecraft:slowness")); } + #[test] + fn a_container_rolled_without_loot_data_saves_its_table() { + let mut slots = vec![None; 27]; + let rolled = roll_container( + &mut slots, + None, + "minecraft:chests/simple_dungeon".into(), + Some(7), + (1, 2, 3), + "minecraft:plains", + ); + let mut saved = horizon_world::nbt::Compound::new(); + saved.insert("Items".into(), crate::save::encode_items(&slots)); + assert!(rolled.restore(&mut saved)); + assert!(!saved.contains_key(&"Items".into())); + assert_eq!(saved.get(&"LootTableSeed".into()), Some(&Tag::Long(7))); + } + #[test] fn exploration_maps_wait_in_custom_data_until_searched() { let mut stack = LootStack { @@ -286,6 +331,7 @@ mod tests { "zoom": 1 })))), ominous_amplifier: None, + stew_effects: Vec::new(), }; let mut item = loot_item(&stack); assert!(has_pending_map(&item)); diff --git a/crates/horizon-client/src/terrain.wgsl b/crates/horizon-client/src/terrain.wgsl index 711a2fce7..c0cf44bb5 100644 --- a/crates/horizon-client/src/terrain.wgsl +++ b/crates/horizon-client/src/terrain.wgsl @@ -69,6 +69,8 @@ struct TerrainOut { @location(2) color: vec4, @location(3) spherical: f32, @location(4) cylindrical: f32, + // The light the face emits, 0 to 15 (mesher.rs's `EMISSION_BITS`). + @location(5) @interpolate(flat) emission: u32, } // Horizon Extras' dynamic lights (dynamic_light.rs): the block light, in the vertex's units // (16 per level), a vertex at camera-relative `pos` gets from the frame's light sources, one @@ -121,7 +123,8 @@ fn terrain_vertex(position: vec3, uv: vec2, layer: u32, color: vec4, spherical: f32, cylindrical: f32) -> vec4 { // Bit 15 of the layer marks opaque leaves (forceOpaque): no alpha cutout. let color = sprite(in.uv, in.layer & 0x7fffu) * in.color; if color.a < 0.5 && (in.layer & 0x8000u) == 0u { discard; } - return apply_fog(vec4(color.rgb, 1.0), in.spherical, in.cylindrical); + // Alpha 0 tells HDR output (hdr.wgsl) a light-emitting block's bright pixels + // may shine. Nothing else reads the frame's alpha. + let emissive = select(1.0, 0.0, in.emission > 0u); + return apply_fog(vec4(color.rgb, emissive), in.spherical, in.cylindrical); } @fragment fn fs_translucent(in: TerrainOut) -> @location(0) vec4 { let color = sprite(in.uv, in.layer & 0x7fffu) * in.color; diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index a6967816a..87bd05fd0 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -192,7 +192,7 @@ pub fn list_worlds(saves: &Path) -> Vec { commands: matches!(data.get("allowCommands"), Some(horizon_world::nbt::Tag::Byte(v)) if *v != 0), version: data.get("Version").and_then(|v| v.get("Name")) .and_then(|v| match v { horizon_world::nbt::Tag::String(s) => Some(s.to_string_lossy()), _ => None }) - .unwrap_or_else(|| "Unknown".into()), + .unwrap_or_else(|| lang::get_or("selectWorld.versionUnknown", "Unknown")), }) }) .collect(); @@ -272,7 +272,7 @@ impl Title { } pub(crate) fn new_world() -> Mode { Mode::Create { - name: "New World".into(), + name: lang::get_or("selectWorld.newWorld", "New World"), seed: String::new(), creative: false, focus: 0, @@ -867,7 +867,13 @@ impl Title { } Mode::Select { worlds, selected } => { crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false); - centered(atlas, batch, "Select World", 8.0, u32::MAX); + centered( + atlas, + batch, + &lang::get_or("selectWorld.title", "Select World"), + 8.0, + u32::MAX, + ); self.caret.borrow_mut().draw( batch, atlas, @@ -1113,7 +1119,8 @@ impl Title { Mode::Multiplayer(screen) => screen.draw( atlas, batch, - (self.started.elapsed().as_millis() / 300).is_multiple_of(2), + &mut self.caret.borrow_mut(), + self.started, cursor, ), } @@ -1408,8 +1415,7 @@ impl Title { mode => caret_field(mode, self.search_focused, &mut self.search), } } - /// Whether the focused field edits at its cursor (every field but the - /// server screens', which still append). + /// Whether the focused field edits at its cursor. pub fn has_caret_field(&mut self) -> bool { caret_field(&mut self.mode, self.search_focused, &mut self.search).is_some() } @@ -1429,15 +1435,9 @@ impl Title { } /// EditBox.charTyped / insertText at the cursor. pub fn type_text(&mut self, text: &str) { - if let Mode::Multiplayer(screen) = &mut self.mode { - return screen.type_text(text); - } self.edit_field(|edit| edit.insert_text(text)); } pub fn backspace(&mut self) { - if let Mode::Multiplayer(screen) = &mut self.mode { - return screen.backspace(); - } self.field_key(winit::keyboard::KeyCode::Backspace, false, false); } /// EditBox.keyPressed: moving and deleting in the focused field. @@ -1465,6 +1465,7 @@ impl Title { Mode::Create { focus, options, .. } => create_world::field_rect(w, h, options.tab) .filter(|(id, _)| id == focus) .map(|(_, rect)| rect), + Mode::Multiplayer(screen) => screen.focused_box((w, h)), _ => None, } } @@ -1617,8 +1618,9 @@ const SEARCH: crate::clipboard::FieldId = ("world.search", 0); const EDIT_NAME: crate::clipboard::FieldId = ("world.edit-name", 0); const WORLD_NAME: crate::clipboard::FieldId = ("world.name", 0); const WORLD_SEED: crate::clipboard::FieldId = ("world.seed", 0); -/// The focused field of the world screens: the list's search, the world -/// name being edited, or Create New World's name or seed. +/// The focused field of the world screens and the server screens: the list's +/// search, a world name or seed, or Add Server, Direct Connection and Join a +/// Friend. fn caret_field<'a>( mode: &'a mut Mode, search_focused: bool, @@ -1638,6 +1640,7 @@ fn caret_field<'a>( 1 => Some((WORLD_SEED, seed, 32)), _ => None, }, + Mode::Multiplayer(screen) => screen.focused_text(), _ => None, } } diff --git a/crates/horizon-client/src/title/tests.rs b/crates/horizon-client/src/title/tests.rs index 572be2ef2..fcaf68225 100644 --- a/crates/horizon-client/src/title/tests.rs +++ b/crates/horizon-client/src/title/tests.rs @@ -824,3 +824,50 @@ fn world_fields_edit_at_their_cursor() { f.title.field_key(KeyCode::Backspace, false, false); assert_eq!(f.title.search, "world"); } + +#[test] +fn server_fields_edit_at_their_cursor() { + use winit::keyboard::KeyCode; + let mut f = Fixture::new(); + f.title.mode = Mode::Multiplayer(crate::multiplayer::Screen::Edit { + index: None, + name: "Minecraft Server".into(), + address: String::new(), + focus: 1, + packs: None, + }); + f.title.type_text("localhost"); + for _ in 0..4 { + assert!(f.title.field_key(KeyCode::ArrowLeft, false, false)); + } + f.title.type_text("X"); + let Mode::Multiplayer(crate::multiplayer::Screen::Edit { address, .. }) = &f.title.mode else { + panic!("add server"); + }; + assert_eq!(address, "localXhost"); + // Shift+Home selects back to the start; typing replaces the selection. + f.title.field_key(KeyCode::Home, false, true); + f.title.type_text("Y"); + let Mode::Multiplayer(crate::multiplayer::Screen::Edit { address, .. }) = &f.title.mode else { + panic!("add server"); + }; + assert_eq!(address, "Yhost"); + // Tab moves to the name, which edits at its own cursor. + f.title.tab(); + f.title.field_key(KeyCode::ArrowLeft, false, false); + f.title.type_text("X"); + let Mode::Multiplayer(crate::multiplayer::Screen::Edit { name, .. }) = &f.title.mode else { + panic!("add server"); + }; + assert_eq!(name, "Minecraft ServeXr"); + f.title.mode = Mode::Multiplayer(crate::multiplayer::Screen::Direct { + address: String::new(), + }); + f.title.type_text("one two"); + // Ctrl+Backspace deletes the word before the caret. + f.title.field_key(KeyCode::Backspace, true, false); + let Mode::Multiplayer(crate::multiplayer::Screen::Direct { address }) = &f.title.mode else { + panic!("direct"); + }; + assert_eq!(address, "one "); +} diff --git a/crates/horizon-client/src/ui.rs b/crates/horizon-client/src/ui.rs index 1954a29dc..e034f2b39 100644 --- a/crates/horizon-client/src/ui.rs +++ b/crates/horizon-client/src/ui.rs @@ -658,6 +658,8 @@ pub struct EditBox { display: usize, pub max_length: usize, pub bordered: bool, + /// `MultiLineEditBox`: a book page keeps line breaks. A single-line box strips them. + pub multiline: bool, pub x: f32, pub y: f32, pub width: f32, @@ -669,7 +671,7 @@ pub struct EditBox { pub text_color: u32, } /// The focused text field of a screen that keeps its values as `String`s -/// (the world list's search, world names, seeds): the `EditBox` state that +/// (the world list's search, world names, seeds, and the server screens): the `EditBox` state that /// outlives a frame, its cursor, selection and scroll. #[derive(Clone, Debug)] pub struct Caret { @@ -853,6 +855,38 @@ pub fn word_position(value: &str, dir: isize, from: usize) -> usize { } pos } +/// `MultilineTextField.getPreviousWord` / `getNextWord`'s `beginIndex` (a book page): any +/// whitespace, line breaks included, separates words, and the search starts from the cursor +/// clamped to the last character, as vanilla's does. +pub fn multiline_word_position(value: &str, dir: isize, from: usize) -> usize { + let chars: Vec = value.chars().collect(); + if chars.is_empty() { + return 0; + } + let mut pos = from.min(chars.len() - 1); + if dir < 0 { + while pos > 0 && java_whitespace(chars[pos - 1]) { + pos -= 1; + } + while pos > 0 && !java_whitespace(chars[pos - 1]) { + pos -= 1; + } + } else { + while pos < chars.len() && !java_whitespace(chars[pos]) { + pos += 1; + } + while pos < chars.len() && java_whitespace(chars[pos]) { + pos += 1; + } + } + pos +} +/// `Character.isWhitespace`: Unicode spaces and line breaks but not the no-break spaces, plus +/// the ASCII separators U+001C to U+001F. +fn java_whitespace(c: char) -> bool { + (c.is_whitespace() && !matches!(c, '\u{85}' | '\u{a0}' | '\u{2007}' | '\u{202f}')) + || ('\u{1c}'..='\u{1f}').contains(&c) +} /// `EditBox.deleteWords(dir)` for an append-only field, whose caret is at the /// end: removes the word in that direction. True when the value changed. pub fn delete_words(value: &mut String, dir: isize) -> bool { @@ -887,6 +921,7 @@ impl EditBox { display: 0, max_length: 32, bordered: true, + multiline: false, x, y, width, @@ -917,6 +952,10 @@ impl EditBox { pub fn reset_blink(&mut self) { self.focused_at = Instant::now(); } + /// The caret is showing (`EditBox`'s blink, on for 300 ms of every 600). + pub fn cursor_visible(&self) -> bool { + self.focused && (self.focused_at.elapsed().as_millis() / 300).is_multiple_of(2) + } pub fn set_value(&mut self, value: &str) { self.value = value.chars().take(self.max_length).collect(); self.move_cursor_to_end(false); @@ -934,7 +973,7 @@ impl EditBox { /// EditBox.insertText: replace the selection, respecting the maximum length. pub fn insert_text(&mut self, text: &str) { let (a, b) = self.selected(); - let filtered = crate::clipboard::filter_text(text, false); + let filtered = crate::clipboard::filter_text(text, self.multiline); let room = self .max_length .saturating_sub(char_len(&self.value) - (b - a)); @@ -960,9 +999,13 @@ impl EditBox { pub fn word_position(&self, dir: isize) -> usize { self.word_position_from(dir, self.cursor) } - /// EditBox.getWordPosition(dir, from). + /// EditBox.getWordPosition(dir, from), or MultilineTextField's word for a book page. fn word_position_from(&self, dir: isize, from: usize) -> usize { - word_position(&self.value, dir, from) + if self.multiline { + multiline_word_position(&self.value, dir, from) + } else { + word_position(&self.value, dir, from) + } } pub fn set_cursor(&mut self, pos: usize, select: bool) { self.cursor = pos.min(char_len(&self.value)); @@ -1492,6 +1535,17 @@ mod tests { assert_eq!(word_position("hi", 1, 99), 2); } #[test] + fn multiline_words_split_at_any_whitespace() { + // Ctrl+Backspace at the end of `one\ntwo` deletes `two` only. + assert_eq!(multiline_word_position("one\ntwo", -1, 7), 4); + // From the end the search starts at the last character, as vanilla's does. + assert_eq!(multiline_word_position("one\n", -1, 4), 0); + assert_eq!(multiline_word_position("a b", -1, 3), 0); + assert_eq!(multiline_word_position("one\n\ntwo", 1, 0), 5); + assert_eq!(multiline_word_position("one\u{a0}two", 1, 0), 7); + assert_eq!(multiline_word_position("", -1, 0), 0); + } + #[test] fn delete_words_removes_the_word_before_the_end() { let mut v = "stone bricks".to_string(); assert!(delete_words(&mut v, -1)); diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index c890213c5..dc729bd8c 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -24,7 +24,9 @@ use horizon_world::{ }; use std::{path::Path, sync::Arc}; mod lod; +mod structure_mobs; use lod::VanillaLodSampler; +use structure_mobs::StructureMobFinalizer; pub struct VanillaTerrain { generator: OverworldGenerator, @@ -32,6 +34,7 @@ pub struct VanillaTerrain { biome_map: Vec, /// Loot tables for generated containers. loot: Option>, + structure_mobs: Arc, /// A worker for structure queries from the game thread. query: std::sync::Mutex>, /// Block state id -> block index, the game's block tick type: worldgen @@ -39,6 +42,8 @@ pub struct VanillaTerrain { tick_blocks: Vec, /// Block index -> default state id: `tick_blocks` the other way. tick_states: Vec, + /// Block state id -> the block entity type of its block, if it has one. + block_entity_types: Vec>, seed: i64, dimension: String, /// When the last proto chunk was generated, in milliseconds since @@ -51,6 +56,51 @@ enum VanillaProto { Ready(Box), Failed(i32, i32), } +/// WorldGenRegion.setBlock gives every block with a block entity a new +/// one: the blocks nothing placed data for (a sculk patch's sensors) get +/// vanilla's defaults. +fn add_default_block_entities(kinds: &[Option<&str>], out: &mut Chunk, raw: &mut Vec) { + let kind = |v: u32| kinds.get(v as usize).copied().flatten(); + let mut states = [0u32; 4096]; + for (si, section) in out.sections.iter().enumerate() { + if !section.blocks.maybe_has(|v| kind(v).is_some()) { + continue; + } + section.unpack(&mut states); + for (i, &v) in states.iter().enumerate() { + let Some(id) = kind(v) else { + continue; + }; + let i = i as i32; + let pos = [ + out.x * 16 + (i & 15), + MIN_Y + si as i32 * 16 + (i >> 8), + out.z * 16 + ((i >> 4) & 15), + ]; + let at = |t: &Tag| { + ["x", "y", "z"] + .iter() + .zip(pos) + .all(|(k, p)| t.get(k) == Some(&Tag::Int(p))) + }; + if raw.iter().any(at) || out.block_entities.iter().any(|(p, _)| *p == pos.into()) { + continue; + } + let tag = Tag::compound([ + ("id", Tag::String(id.into())), + ("x", Tag::Int(pos[0])), + ("y", Tag::Int(pos[1])), + ("z", Tag::Int(pos[2])), + ]); + let tag = crate::block_entity_nbt::canonical(&tag).unwrap_or(tag); + match crate::save::decode_block_entity(&tag) { + Some(modelled) => out.block_entities.push(modelled), + None => raw.push(tag), + } + } + } +} + impl VanillaTerrain { fn client_surface(&self, surface: SurfaceSample) -> crate::lod::Surface { crate::lod::Surface { @@ -119,6 +169,7 @@ impl VanillaTerrain { } let mut tick_blocks = Vec::with_capacity(registry.len()); let mut tick_states = Vec::new(); + let mut block_entity_types = Vec::with_capacity(registry.len()); let mut last: Option<&str> = None; let mut index = 0u32; for id in 0..registry.len() { @@ -133,20 +184,31 @@ impl VanillaTerrain { } last = Some(name); tick_blocks.push(index); + block_entity_types.push(crate::lan::chunks::block_entity_type(name)); } Ok(Self { generator, biome_map, loot, + structure_mobs: Arc::new(StructureMobFinalizer::new( + dir.parent().unwrap_or(dir).to_owned(), + dimension, + )), query: std::sync::Mutex::new(None), tick_blocks, tick_states, + block_entity_types, seed, dimension: dimension.to_owned(), last_proto: std::sync::atomic::AtomicU64::new(0), created: std::time::Instant::now(), }) } + /// The difficulty (0 peaceful to 3 hard) and overworld clock structure + /// mobs are finalized with. + pub fn set_spawn_conditions(&self, difficulty: u8, day_time: i64) { + self.structure_mobs.set_conditions(difficulty, day_time); + } /// A proto chunk's blocks, biomes, scheduled ticks and post-processing /// marks as a column. fn column(&self, chunk: &ProtoChunk) -> Chunk { @@ -158,6 +220,12 @@ impl VanillaTerrain { chunk.terrain.min_y().max(MIN_Y), (chunk.terrain.min_y() + chunk.terrain.height()).min(MIN_Y + HEIGHT), ); + out.structure_refs = chunk + .structures() + .into_iter() + .map(|(id, start, _, _)| (Arc::from(id), (start.x, start.z))) + .collect(); + out.structure_starts = chunk.own_starts(); let mut values = Box::new([0u32; 4096]); for si in 0..SECTIONS as i32 { let base = MIN_Y + si * 16; @@ -327,26 +395,38 @@ impl VanillaTerrain { u64::try_from(self.created.elapsed().as_millis()).unwrap_or(u64::MAX) } } +static SHARED_DATA: std::sync::Mutex)>> = + std::sync::Mutex::new(Vec::new()); +/// Let go of the bundles `shared_data` loaded: for a preload no world used +/// (game/world_loading.rs). A generator that holds one keeps it. +pub fn forget_shared_data() { + SHARED_DATA + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clear(); +} /// The worldgen bundle at `dir`, loaded once and shared by every generator /// and by live feature placement (sapling growth, bone meal). pub fn shared_data( dir: &Path, registry: &'static BlockRegistry, ) -> crate::Result> { - static CACHE: std::sync::Mutex)>> = - std::sync::Mutex::new(Vec::new()); - let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner()); + let mut cache = SHARED_DATA.lock().unwrap_or_else(|e| e.into_inner()); if let Some((_, data)) = cache.iter().find(|(path, _)| path == dir) { return Ok(data.clone()); } + let started = std::time::Instant::now(); let data = GeneratorData::load(dir, registry)?; + log::info!("Horizon: worldgen data loaded in {:?}", started.elapsed()); cache.push((dir.to_owned(), data.clone())); Ok(data) } impl ChunkGenerator for VanillaTerrain { type Worker = GeneratorWorker; fn worker(&self) -> GeneratorWorker { - self.generator.worker() + let mut worker = self.generator.worker(); + worker.set_structure_mobs(self.structure_mobs.clone()); + worker } fn lod_sampler(self: Arc) -> Box { Box::new(VanillaLodSampler::new(self)) @@ -434,6 +514,14 @@ impl ChunkGenerator for VanillaTerrain { .iter() .map(|(pos, nbt)| { let mut nbt = nbt.clone(); + // Placed data can lack its type (a brushable block's loot table + // alone); vanilla saves every pending block entity with its id, + // and skips one without when the chunk finishes. + if let Some(id) = + crate::lan::chunks::block_entity_type(chunk.block_name(pos[0], pos[1], pos[2])) + { + nbt.insert("id".into(), Tag::String(id.into())); + } for (key, v) in ["x", "y", "z"].into_iter().zip(pos) { nbt.insert(key.into(), Tag::Int(*v)); } @@ -531,11 +619,13 @@ impl ChunkGenerator for VanillaTerrain { VanillaProto::Failed(x, z) => return Chunk::empty(x, z), }; let mut out = self.column(&chunk); - out.block_entities = crate::structure_blocks::block_entities(&chunk, self.loot.as_deref()); + let (block_entities, rolled_loot) = + crate::structure_blocks::block_entities(&chunk, self.loot.as_deref()); + out.block_entities = block_entities; // The block entities Horizon does not model (decorated pots with their // sherds and loot table, brushable blocks) stay as placed, like a // loaded chunk's. - let unmodelled: Vec = chunk + let mut unmodelled: Vec = chunk .block_entities .iter() .filter(|(pos, _)| { @@ -555,26 +645,21 @@ impl ChunkGenerator for VanillaTerrain { Some(Tag::Compound(nbt)) }) .collect(); - if !unmodelled.is_empty() { + add_default_block_entities(&self.block_entity_types, &mut out, &mut unmodelled); + if !unmodelled.is_empty() || !rolled_loot.is_empty() { let mut extras = out .saved .take() .map(Arc::unwrap_or_clone) .unwrap_or_default(); extras.block_entities = unmodelled; + extras.rolled_loot = rolled_loot; out.saved = Some(Arc::new(extras)); } - out.structure_refs = chunk - .structures() - .into_iter() - .map(|(id, start, _, _)| (Arc::from(id), (start.x, start.z))) - .collect(); let entities = std::mem::take(&mut chunk.entities); + // Chest minecarts keep their loot table; the game rolls it on load. out.entities = entities .into_iter() - .map(|nbt| { - crate::structure_blocks::unpack_entity_loot(&chunk, nbt, self.loot.as_deref()) - }) .map(horizon_world::nbt::Tag::Compound) .collect(); for s in &mut out.sections { @@ -584,3 +669,35 @@ impl ChunkGenerator for VanillaTerrain { out } } + +#[cfg(test)] +mod default_block_entity_tests { + use super::*; + + #[test] + fn generated_blocks_get_their_block_entities() { + let mut out = Chunk::empty(-2, 3); + out.set(4, -40, 9, 7); + out.set(5, -40, 9, 6); + let mut kinds = vec![None; 8]; + kinds[6] = Some("minecraft:potent_sulfur"); + kinds[7] = Some("minecraft:sculk_sensor"); + let mut raw = vec![]; + add_default_block_entities(&kinds, &mut out, &mut raw); + assert!(matches!( + out.block_entities[..], + [((-28, -40, 57), crate::containers::BlockEntity::Sculk(_))] + )); + assert_eq!(raw.len(), 1); + assert_eq!( + raw[0].get("id"), + Some(&Tag::String("minecraft:potent_sulfur".into())) + ); + add_default_block_entities(&kinds, &mut out, &mut raw); + assert_eq!( + (out.block_entities.len(), raw.len()), + (1, 1), + "a placed block entity is kept, not doubled" + ); + } +} diff --git a/crates/horizon-client/src/vanillagen/structure_mobs.rs b/crates/horizon-client/src/vanillagen/structure_mobs.rs new file mode 100644 index 000000000..dec5aa92b --- /dev/null +++ b/crates/horizon-client/src/vanillagen/structure_mobs.rs @@ -0,0 +1,446 @@ +//! `Mob.finalizeSpawn(level, level.getCurrentDifficultyAt(pos), STRUCTURE, null)` +//! of the mobs structures place (StructureTemplate.placeEntities with +//! finalizeEntities, ocean ruin drowned, mansion illagers, witch huts, +//! monuments), run as decoration places them, with the WorldGenRegion's random. +use crate::{ + enchant::Enchantments, + entity_nbt, + items::Items, + mobs::{ + Mob, MobType, MobTypes, + finalize::{self, Ctx, FinalizeLevel, Reason, SpawnData, SpawnRegistries}, + spawning::{LocalDifficulty, MOON_BRIGHTNESS}, + }, +}; +use chrono::Datelike; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::{LegacyRandom, RandomSource, XoroshiroRandom}, +}; +use horizon_world::{ + nbt::{Compound, Tag}, + worldgen::{generator::StructureMobs, structure::legacy::PieceRandom}, +}; +use std::{ + collections::{HashMap, HashSet}, + path::PathBuf, + sync::{ + Arc, OnceLock, + atomic::{AtomicI64, AtomicU8, Ordering}, + }, +}; + +struct Data { + types: HashMap>, + biome_tags: HashMap>, + registries: SpawnRegistries, + enchantments: Enchantments, + items: Items, + camel_husk: (f32, f32), +} +fn load(root: &std::path::Path) -> Option { + let types = MobTypes::load(root).ok()?.types; + let camel = types.get("minecraft:camel_husk")?; + let camel_husk = (camel.width as f32, camel.height as f32); + Some(Data { + types: types.into_iter().map(|(k, t)| (k, Arc::new(t))).collect(), + biome_tags: crate::items::load_tags(root, "worldgen/biome").unwrap_or_default(), + registries: SpawnRegistries::load(root), + enchantments: Enchantments::load(root), + items: Items::tags_only(root).ok()?, + camel_husk, + }) +} + +pub struct StructureMobFinalizer { + root: PathBuf, + dimension: String, + data: OnceLock>, + /// The level's difficulty (0 peaceful to 3 hard) and overworld clock. + difficulty: AtomicU8, + day_time: AtomicI64, +} +impl StructureMobFinalizer { + pub fn new(root: PathBuf, dimension: &str) -> Self { + Self { + root, + dimension: dimension.to_owned(), + data: OnceLock::new(), + difficulty: AtomicU8::new(2), + day_time: AtomicI64::new(0), + } + } + pub fn set_conditions(&self, difficulty: u8, day_time: i64) { + self.difficulty.store(difficulty, Ordering::Relaxed); + self.day_time.store(day_time, Ordering::Relaxed); + } +} + +struct Level<'a> { + data: &'a Data, + biome: &'a str, + structures: &'a [String], + difficulty: u8, + day_time: i64, + next_id: u32, +} +impl FinalizeLevel for Level<'_> { + fn biome(&self, _: [i32; 3]) -> String { + self.biome.to_owned() + } + fn biome_tag(&self, tag: &str, _: [i32; 3]) -> bool { + self.data + .biome_tags + .get(tag) + .is_some_and(|b| b.contains(self.biome)) + } + fn structures_with_piece_at(&self, _: [i32; 3]) -> Vec { + self.structures.to_vec() + } + fn moon_phase(&self, _: [i32; 3]) -> usize { + self.day_time.div_euclid(24000).rem_euclid(8) as usize + } + fn spawning_monsters(&self) -> bool { + self.difficulty != 0 + } + // No block collision: only a husk's camel asks, and no structure places husks. + fn no_collision(&self, _: Aabb) -> bool { + true + } + // WorldGenRegion holds no entities. + fn free_chicken(&self, _: Aabb) -> Option { + None + } + fn ride_chicken(&mut self, _: u32, _: u32) {} + fn game_time(&self) -> i64 { + self.day_time + } + fn halloween(&self) -> bool { + let today = chrono::Local::now(); + (today.month(), today.day()) == (10, 31) + } + fn create(&mut self, kind: &str, _: Reason) -> Option { + if self.difficulty == 0 && !finalize::allowed_in_peaceful(kind) { + return None; + } + let t = self.data.types.get(kind)?.clone(); + self.next_id += 1; + Some(Mob::new(self.next_id, t, Vec3::ZERO, 0.0)) + } +} + +fn run( + level: &mut Level<'_>, + random: &mut R, + difficulty: LocalDifficulty, + data: &SpawnData<'_>, + m: &mut Mob, +) -> Vec { + let mut cx = Ctx { + level, + random, + difficulty, + data, + created: Vec::new(), + }; + cx.finalize(m, Reason::Structure, None); + cx.created +} + +/// The saved compound of mob `i` with the mobs riding it under `Passengers`. +fn tree(mobs: &[(Mob, Option)], i: usize, dimension: &str) -> Compound { + let (m, raw) = &mobs[i]; + let Tag::Compound(mut c) = entity_nbt::mob_to_nbt(m, [0; 4], raw.as_ref()) else { + return Compound::new(); + }; + c.remove(&"UUID".into()); + entity_nbt::put_brain(&mut c, m, dimension); + let riders: Vec = (0..mobs.len()) + .filter(|&j| mobs[j].0.extra.mount == Some(m.id)) + .map(|j| Tag::Compound(tree(mobs, j, dimension))) + .collect(); + if !riders.is_empty() { + c.insert("Passengers".into(), Tag::List(riders)); + } + c +} + +impl StructureMobs for StructureMobFinalizer { + fn finalize( + &self, + nbt: &mut Compound, + biome: &str, + structures: &[String], + random: &mut dyn PieceRandom, + ) -> bool { + let Some(data) = self.data.get_or_init(|| { + let data = load(&self.root); + if data.is_none() { + log::error!("Horizon: no mob data, structure mobs are finalized when loaded"); + } + data + }) else { + return false; + }; + let mut raw = Tag::Compound(nbt.clone()); + if let Tag::Compound(c) = &mut raw { + c.remove(&"horizon:finalize".into()); + } + let Some(mut m) = entity_nbt::mob_from_nbt(&raw, &data.types, 1) else { + // Not a mob: vanilla finalizes only Mob instances. + return true; + }; + let base = self.difficulty.load(Ordering::Relaxed); + let day_time = self.day_time.load(Ordering::Relaxed); + let mut level = Level { + data, + biome, + structures, + difficulty: base, + day_time, + next_id: 1, + }; + let moon = MOON_BRIGHTNESS[level.moon_phase([0; 3])]; + // WorldGenRegion.getCurrentDifficultyAt: no inhabited time. + let difficulty = LocalDifficulty::new(base, day_time, 0, moon); + let spawn = SpawnData { + registries: &data.registries, + enchantments: &data.enchantments, + items: &data.items, + camel_husk_size: data.camel_husk, + }; + let any = random.as_any(); + let created = if let Some(r) = any.downcast_mut::() { + run(&mut level, r, difficulty, &spawn, &mut m) + } else if let Some(r) = any.downcast_mut::() { + run(&mut level, r, difficulty, &spawn, &mut m) + } else { + log::error!("Horizon: unknown region random, structure mobs are finalized when loaded"); + return false; + }; + let mut mobs = vec![(m, Some(raw))]; + mobs.extend(created.into_iter().map(|c| (c, None))); + let root = mobs + .iter() + .position(|(m, _)| m.extra.mount.is_none()) + .unwrap_or(0); + *nbt = tree(&mobs, root, &self.dimension); + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The bastion's crossbow piglin keeps its crossbow (STRUCTURE skips + /// createSpawnWeapon) and saves what Piglin.addAdditionalSaveData writes. + #[test] + fn bastion_crossbow_piglin_finalizes_as_structure() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES").map(PathBuf::from) else { + return; + }; + let file = root.join("worldgen/structure/minecraft/bastion/mobs/crossbow_piglin.nbt"); + let mut bytes = Vec::new(); + std::io::Read::read_to_end( + &mut flate2::read::GzDecoder::new(std::fs::File::open(file).unwrap()), + &mut bytes, + ) + .unwrap(); + let limits = horizon_world::nbt::Limits::templates(); + let template = horizon_world::nbt::read_named(&bytes, limits) + .unwrap() + .0 + .tag; + let Some(Tag::List(entities)) = template.get("entities") else { + panic!("no entities"); + }; + let Some(Tag::Compound(mut nbt)) = entities[0].get("nbt").cloned() else { + panic!("no nbt"); + }; + nbt.remove(&"UUID".into()); + let hook = StructureMobFinalizer::new(root, "minecraft:the_nether"); + let mut random = LegacyRandom::new(12345); + hook.finalize(&mut nbt, "minecraft:nether_wastes", &[], &mut random); + let keys: Vec = { + let mut k: Vec = nbt.keys().map(|k| k.to_string_lossy()).collect(); + k.sort(); + k + }; + assert_eq!( + keys, + [ + "AbsorptionAmount", + "Air", + "Brain", + "CanPickUpLoot", + "CannotHunt", + "DeathTime", + "FallFlying", + "Fire", + "Health", + "HurtTime", + "Inventory", + "Invulnerable", + "IsBaby", + "IsImmuneToZombification", + "LeftHanded", + "Motion", + "OnGround", + "PersistenceRequired", + "PortalCooldown", + "Pos", + "Rotation", + "TimeInOverworld", + "attributes", + "current_impulse_context_reset_grace_time", + "equipment", + "fall_distance", + "id", + ] + ); + let tag = Tag::Compound(nbt); + let held = tag.get("equipment").and_then(|e| e.get("mainhand")); + assert!( + matches!(held.and_then(|h| h.get("id")), Some(Tag::String(s)) if s.to_string_lossy() == "minecraft:crossbow") + ); + let hunted = tag + .get("Brain") + .and_then(|b| b.get("memories")) + .and_then(|m| m.get("minecraft:hunted_recently")); + assert!(matches!( + hunted.and_then(|h| h.get("ttl")), + Some(Tag::Long(600..=2400)) + )); + let Some(Tag::List(attributes)) = tag.get("attributes") else { + panic!("no attributes"); + }; + assert!(attributes.iter().any(|a| { + matches!(a.get("id"), Some(Tag::String(s)) if s.to_string_lossy() == "minecraft:follow_range") + && matches!(a.get("modifiers"), Some(Tag::List(m)) if m.len() == 1) + })); + } + + fn id(t: Option<&Tag>) -> String { + match t.and_then(|t| t.get("id")) { + Some(Tag::String(s)) => s.to_string_lossy().trim_start_matches("minecraft:").into(), + _ => "-".into(), + } + } + /// What a vanilla world saves of a structure mob that finalizeSpawn decides. + fn describe(mob: &Tag) -> String { + let eq = mob.get("equipment"); + let gear: Vec = ["mainhand", "head", "chest", "legs", "feet"] + .iter() + .map(|slot| id(eq.and_then(|e| e.get(slot)))) + .collect(); + let ttl = match mob + .get("Brain") + .and_then(|b| b.get("memories")) + .and_then(|m| m.get("minecraft:hunted_recently")) + .and_then(|h| h.get("ttl")) + { + Some(Tag::Long(t)) => t.to_string(), + _ => "-".into(), + }; + let bonus = crate::entity_nbt::spawn_bonus(mob).unwrap_or(f64::NAN); + let flag = |k: &str| matches!(mob.get(k), Some(Tag::Byte(1))); + let riders = match mob.get("Passengers") { + Some(Tag::List(p)) => format!( + " [{}]", + p.iter().map(describe).collect::>().join("; ") + ), + _ => String::new(), + }; + format!( + "{} {} ttl={ttl} bonus={bonus:.6} left={} baby={}{riders}", + id(Some(mob)), + gear.join(","), + flag("LeftHanded"), + flag("IsBaby") || matches!(mob.get("Age"), Some(Tag::Int(a)) if *a < 0), + ) + } + /// The described entities of chunk (x, z) after decorating the 3x3 around it. + fn chunk_mobs( + root: &std::path::Path, + seed: i64, + dimension: &str, + x: i32, + z: i32, + ) -> Vec { + use crate::streaming::{ChunkGenerator, Proto}; + let assets = crate::assets::Assets::load(root).unwrap(); + let biomes = crate::biome::Biomes::load(root).unwrap(); + let terrain = super::super::VanillaTerrain::for_dimension( + &root.join("worldgen"), + assets.registry, + &biomes, + seed, + dimension, + ) + .unwrap(); + let mut worker = terrain.worker(); + let mut region: [Proto; 9] = std::array::from_fn(|i| { + terrain.proto(&mut worker, x + i as i32 % 3 - 1, z + i as i32 / 3 - 1) + }); + terrain.decorate(&mut worker, &mut region); + let center = std::mem::replace(&mut region[4], Box::new(())); + let mut got: Vec = terrain + .finish(center) + .entities + .iter() + .map(describe) + .collect(); + got.sort(); + got + } + /// Seed 12345's bastion at chunk (-21, 8): the mobs of chunk (-23, 8) as two + /// vanilla 26.3 runs saved them (weapons and armour, hunting memory, follow + /// range bonus, handedness), from the region random of that chunk. The + /// memories are as placed: vanilla saved them 13 brain ticks later. + #[test] + fn bastion_chunk_mobs_match_vanilla() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES").map(PathBuf::from) else { + return; + }; + let got = chunk_mobs(&root, 12345, "minecraft:the_nether", -23, 8); + let mut expected = [ + "piglin golden_sword,-,golden_chestplate,-,- ttl=1760 bonus=0.013784", + "piglin crossbow,-,-,-,- ttl=806 bonus=-0.011458", + "piglin golden_sword,-,-,-,- ttl=1315 bonus=-0.084585", + "piglin golden_sword,-,-,-,- ttl=1489 bonus=-0.038292", + "piglin_brute golden_axe,-,-,-,- ttl=- bonus=-0.020574", + "piglin crossbow,-,-,-,- ttl=1620 bonus=-0.079135", + "hoglin -,-,-,-,- ttl=- bonus=-0.012052", + "piglin golden_sword,-,-,-,- ttl=783 bonus=-0.077071", + "piglin crossbow,-,-,golden_leggings,- ttl=1431 bonus=0.007058", + ] + .map(|e| format!("{e} left=false baby=false")); + expected.sort(); + assert_eq!(got, expected); + } + + /// Seed 12345's ocean ruin at (53, 39, 424): Drowned.finalizeSpawn mounts the + /// trident drowned on a zombie nautilus, as vanilla saved chunk (3, 26). + #[test] + fn ocean_ruin_drowned_match_vanilla() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES").map(PathBuf::from) else { + return; + }; + let got = chunk_mobs(&root, 12345, "minecraft:overworld", 3, 26); + let d = |gear: &str, bonus: &str| { + format!("drowned {gear},-,-,-,- ttl=- bonus={bonus} left=false baby=false") + }; + let mut expected = vec![ + d("-", "0.001996"), + format!( + "zombie_nautilus -,-,-,-,- ttl=- bonus=-0.044983 left=false baby=false [{}]", + d("trident", "-0.045604") + ), + d("fishing_rod", "-0.059079"), + d("-", "0.021658"), + ]; + expected.sort(); + assert_eq!(got, expected); + } +} diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index d73956d85..83083eba2 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -109,7 +109,9 @@ pub struct Weather { pub thunder_level: (f32, f32), } impl Weather { - pub fn tick(&mut self, random: &mut horizon_core::random::LegacyRandom) { + /// The timers of `advanceWeatherCycle`, which run only while + /// `advance_weather` is on. + pub fn tick_timers(&mut self, random: &mut horizon_core::random::LegacyRandom) { use horizon_core::random::RandomSource; let mut uniform = |min: i32, max: i32| min + random.next_int_bound(max - min + 1).unwrap_or(0); @@ -141,6 +143,10 @@ impl Weather { self.rain_time = uniform(12000, 180000); } } + } + /// The rain and thunder level fade at the end of `advanceWeatherCycle`, + /// which runs whatever `advance_weather` says, so `/weather` still shows. + pub fn tick_levels(&mut self) { self.thunder_level.0 = self.thunder_level.1; self.thunder_level.1 = (self.thunder_level.1 + if self.thundering { 0.01 } else { -0.01 }).clamp(0.0, 1.0); diff --git a/crates/horizon-client/src/world_post.wgsl b/crates/horizon-client/src/world_post.wgsl index 7332213c5..ed1a7a094 100644 --- a/crates/horizon-client/src/world_post.wgsl +++ b/crates/horizon-client/src/world_post.wgsl @@ -18,7 +18,8 @@ struct PostOut { } @fragment fn fs_copy(in: PostOut) -> @location(0) vec4 { - return vec4(textureSampleLevel(world, world_sampler, in.uv, 0.0).rgb, 1.0); + // The alpha carries the emissive mark through to HDR output (hdr.wgsl). + return textureSampleLevel(world, world_sampler, in.uv, 0.0); } fn luma(c: vec3) -> f32 { @@ -28,7 +29,8 @@ fn luma(c: vec3) -> f32 { // FXAA 3.11 (console quality): blend along the local edge direction. @fragment fn fs_fxaa(in: PostOut) -> @location(0) vec4 { let texel = 1.0 / vec2(textureDimensions(world)); - let rgb_m = textureSampleLevel(world, world_sampler, in.uv, 0.0).rgb; + let centre = textureSampleLevel(world, world_sampler, in.uv, 0.0); + let rgb_m = centre.rgb; let nw = luma(textureSampleLevel(world, world_sampler, in.uv + vec2(-0.5, -0.5) * texel, 0.0).rgb); let ne = luma(textureSampleLevel(world, world_sampler, in.uv + vec2(0.5, -0.5) * texel, 0.0).rgb); let sw = luma(textureSampleLevel(world, world_sampler, in.uv + vec2(-0.5, 0.5) * texel, 0.0).rgb); @@ -37,7 +39,7 @@ fn luma(c: vec3) -> f32 { let lo = min(m, min(min(nw, ne), min(sw, se))); let hi = max(m, max(max(nw, ne), max(sw, se))); if hi - lo < max(0.0312, hi * 0.125) { - return vec4(rgb_m, 1.0); + return centre; } var dir = vec2(-((nw + ne) - (sw + se)), (nw + sw) - (ne + se)); let reduce = max((nw + ne + sw + se) * 0.25 * 0.125, 1.0 / 128.0); @@ -49,7 +51,7 @@ fn luma(c: vec3) -> f32 { + textureSampleLevel(world, world_sampler, in.uv + dir * 0.5, 0.0).rgb); let lb = luma(b); if lb < lo || lb > hi { - return vec4(a, 1.0); + return vec4(a, centre.a); } - return vec4(b, 1.0); + return vec4(b, centre.a); } diff --git a/crates/horizon-client/tests/generation_saves.rs b/crates/horizon-client/tests/generation_saves.rs index 30b971e05..2f8c2ab6b 100644 --- a/crates/horizon-client/tests/generation_saves.rs +++ b/crates/horizon-client/tests/generation_saves.rs @@ -315,3 +315,70 @@ fn saved_proto_chunks_restore_exactly() { drop(save); let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn saved_proto_block_entities_keep_their_id() { + use horizon_client::{ + save::{Persistent, SaveDir}, + vanillagen::VanillaTerrain, + }; + use horizon_world::{ + nbt::{Limits, Tag}, + region::RegionFile, + }; + let Some(root) = resources() else { + return; + }; + let assets = Arc::new(Assets::load(&root).unwrap()); + let biomes = Arc::new(Biomes::load(&root).unwrap()); + let terrain = VanillaTerrain::for_dimension( + &root.join("worldgen"), + assets.registry, + &biomes, + 12345, + "minecraft:overworld", + ) + .unwrap(); + let dir = std::env::temp_dir().join(format!("horizon-proto-ids-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let save = Arc::new(SaveDir::new(dir.clone())); + let generator = Persistent { + inner: Arc::new(terrain), + save: save.clone(), + registry: assets.clone(), + biomes, + }; + let mut worker = generator.worker(); + // A cold ocean ruin of seed 12345: its suspicious gravel is placed with a + // loot table and no type. + let keys: Vec<(i32, i32)> = (0..9).map(|i| (43 + i % 3 - 1, 21 + i / 3 - 1)).collect(); + let mut region: [Proto; 9] = + std::array::from_fn(|i| generator.proto(&mut worker, keys[i].0, keys[i].1)); + generator.decorate(&mut worker, &mut region); + generator.save_protos(®ion.iter().collect::>()); + save.flush().unwrap(); + let mut file = RegionFile::open(dir.join("region/r.1.0.mca")).unwrap(); + let mut suspicious = 0; + for &(x, z) in &keys { + let Some(record) = file + .read(horizon_core::position::ChunkPos::new(x, z)) + .unwrap() + else { + continue; + }; + let root = record.nbt(Limits::default()).unwrap(); + let Some(Tag::List(entities)) = root.tag.get("block_entities") else { + continue; + }; + for e in entities { + assert!(e.get("id").is_some(), "chunk {x} {z}: {e:?}"); + if let Some(Tag::String(table)) = e.get("LootTable") { + suspicious += usize::from(table.to_string_lossy().contains("archaeology/")); + } + } + } + assert!(suspicious > 0, "the ruin placed no suspicious blocks"); + drop(generator); + drop(save); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index 34e8265a1..c4ed2884b 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -186,6 +186,7 @@ impl Server { attributes: Vec::new(), bed: None, living_flags: 0, + body: Default::default(), }; let mut ctx = TickCtx { world: &mut self.world, diff --git a/crates/horizon-command/Cargo.toml b/crates/horizon-command/Cargo.toml new file mode 100644 index 000000000..10191ed6f --- /dev/null +++ b/crates/horizon-command/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "horizon-command" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version = "1.90" +description = "Commands (Brigadier): the vanilla command tree, argument types, selectors, parsing, suggestions and the network form of the tree" + +[dependencies] +horizon-client-core = { path = "../horizon-client-core" } +horizon-protocol = { path = "../horizon-protocol" } +horizon-world = { path = "../horizon-world" } + +[lints] +workspace = true diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-command/src/args.rs similarity index 87% rename from crates/horizon-client/src/command/args.rs rename to crates/horizon-command/src/args.rs index ccced67a7..9d24d672f 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-command/src/args.rs @@ -1,192 +1,8 @@ //! Argument types (Brigadier's and Minecraft's `ArgumentType`s): parsing with //! the vanilla error messages and completion suggestions. use super::{CmdResult, CommandError, Context, Reader, SuggestionsBuilder}; -use std::collections::BTreeMap; -/// Registry contents and source state used to validate and complete arguments. -#[derive(Clone, Debug, Default)] -pub struct Registries { - /// Permission level of the command source. - pub permission: u8, - pub items: Vec, - pub item_tags: Vec, - /// Block id -> (property, allowed values). - pub blocks: BTreeMap)>>, - pub block_tags: Vec, - /// Entity types that `summon` can create. - pub summonable: Vec, - /// Every entity type (selector `type=`). - pub entity_types: Vec, - pub effects: Vec, - pub enchantments: Vec, - pub structures: Vec, - pub biomes: Vec, - pub dimensions: Vec, - pub clocks: Vec, - pub timelines: Vec, - pub time_markers: Vec, - pub advancements: Vec, - /// Game rule name -> integer-valued. - pub game_rules: Vec<(String, bool)>, - pub players: Vec, - /// Scoreboard objective names, team names and tracked score holders. - pub objectives: Vec, - pub teams: Vec, - pub tracked: Vec, - /// Loaded datapack functions (`ns:path`) and function tags (`ns:path`). - pub functions: Vec, - /// `/data ... storage` ids. - pub storages: Vec, - /// Boss bar ids and datapack predicate ids. - pub bossbars: Vec, - pub predicates: Vec, - pub item_modifiers: Vec, - pub schedules: Vec, - pub stopwatches: Vec, - pub recipes: Vec, - pub sounds: Vec, - pub damage_types: Vec, - pub attributes: Vec, - pub loot_tables: Vec, - pub templates: Vec, - pub random_sequences: Vec, - pub datapacks_enabled: Vec, - pub datapacks_disabled: Vec, - pub function_tags: Vec, - /// The block the source is looking at (relevant coordinates). - pub target_block: Option<[i32; 3]>, - /// Every registry's element and tag ids (`minecraft:item` -> ...), as - /// the server's registry access and reloadable registries hold them. - pub by_registry: BTreeMap, - /// Blocks whose default state has a block entity. - pub block_entities: std::collections::BTreeSet, - /// Block tag -> member blocks. - pub block_tag_members: BTreeMap>, - /// Data component types with a codec (not transient). - pub persistent_components: Vec, - /// Recipes `/recipe` can give (not special). - pub learnable_recipes: Vec, - /// Advancement id -> criterion names. - pub advancement_criteria: BTreeMap>, - /// World clock -> time markers shown in commands. - pub clock_time_markers: BTreeMap>, - /// Trigger objectives the source may use (`/trigger` suggestions). - pub trigger_objectives: Vec, - /// Objectives with the `trigger` criterion -> holder -> whether its score is locked. - pub trigger_scores: BTreeMap>, -} -/// The ids and tag ids of one registry. -#[derive(Clone, Debug, Default)] -pub struct RegistryIds { - pub ids: Vec, - pub tags: Vec, -} -const EMPTY: &[String] = &[]; -impl Registries { - /// Fill what the game did not build itself from vanilla's exported - /// registries (`command-registries.json`, written by - /// `VanillaCommandParseOracle registries`): built-in registries such as - /// mob effects, data component types and dialogs, block entities and tag - /// members. Registries that data packs reload stay with the game. - pub fn fill_from_export(&mut self, r: &serde_json::Value) { - fn strings(v: &serde_json::Value) -> Vec { - v.as_array() - .map(|a| { - a.iter() - .filter_map(|x| x.as_str().map(str::to_owned)) - .collect() - }) - .unwrap_or_default() - } - let fill = |field: &mut Vec, key: &str| { - if field.is_empty() { - *field = strings(&r[key]); - } - }; - fill(&mut self.effects, "effects"); - fill(&mut self.enchantments, "enchantments"); - fill(&mut self.attributes, "attributes"); - fill(&mut self.damage_types, "damage_types"); - fill(&mut self.templates, "templates"); - fill(&mut self.persistent_components, "persistent_components"); - fill(&mut self.learnable_recipes, "learnable_recipes"); - const RELOADED: [&str; 5] = [ - "minecraft:advancement", - "minecraft:recipe", - "minecraft:loot_table", - "minecraft:predicate", - "minecraft:item_modifier", - ]; - for (name, entry) in r["by_registry"].as_object().into_iter().flatten() { - if RELOADED.contains(&name.as_str()) || self.by_registry.contains_key(name) { - continue; - } - self.by_registry.insert( - name.clone(), - RegistryIds { - ids: strings(&entry["ids"]), - tags: strings(&entry["tags"]), - }, - ); - } - if self.block_entities.is_empty() { - self.block_entities = strings(&r["block_entities"]).into_iter().collect(); - } - if self.block_tag_members.is_empty() { - for (tag, members) in r["block_tag_members"].as_object().into_iter().flatten() { - self.block_tag_members.insert(tag.clone(), strings(members)); - } - } - if self.clock_time_markers.is_empty() { - for (clock, markers) in r["clock_time_markers"].as_object().into_iter().flatten() { - self.clock_time_markers - .insert(clock.clone(), strings(markers)); - } - } - if self.advancement_criteria.is_empty() { - for (id, criteria) in r["advancement_criteria"].as_object().into_iter().flatten() { - self.advancement_criteria - .insert(id.clone(), strings(criteria)); - } - } - } - /// The element ids of a registry (sorted). - pub fn ids(&self, registry: &str) -> &[String] { - if let Some(r) = self.by_registry.get(registry) { - return &r.ids; - } - match registry { - "minecraft:item" => &self.items, - "minecraft:entity_type" => &self.entity_types, - "minecraft:mob_effect" => &self.effects, - "minecraft:enchantment" => &self.enchantments, - "minecraft:worldgen/structure" => &self.structures, - "minecraft:worldgen/biome" => &self.biomes, - "minecraft:world_clock" => &self.clocks, - "minecraft:timeline" => &self.timelines, - "minecraft:attribute" => &self.attributes, - "minecraft:damage_type" => &self.damage_types, - "minecraft:sound_event" => &self.sounds, - "minecraft:predicate" => &self.predicates, - "minecraft:item_modifier" => &self.item_modifiers, - "minecraft:loot_table" => &self.loot_tables, - "minecraft:recipe" => &self.recipes, - "minecraft:advancement" => &self.advancements, - _ => EMPTY, - } - } - /// The tag ids of a registry (sorted). - pub fn tags(&self, registry: &str) -> &[String] { - if let Some(r) = self.by_registry.get(registry) { - return &r.tags; - } - match registry { - "minecraft:item" => &self.item_tags, - "minecraft:block" => &self.block_tags, - _ => EMPTY, - } - } -} +pub use horizon_client_core::registries::{Registries, RegistryIds}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Resource { @@ -637,22 +453,7 @@ pub fn read_identifier(reader: &mut Reader) -> CmdResult { } } } -/// Identifier.parse: `ns:path` or `path`, validated. -pub fn parse_identifier(raw: &str) -> Option { - let (ns, path) = match raw.split_once(':') { - Some(("", path)) => ("minecraft", path), - Some((ns, path)) => (ns, path), - None => ("minecraft", raw), - }; - let ns_ok = ns != ".." - && ns - .chars() - .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-')); - let path_ok = path.chars().all(|c| { - c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/') - }); - (ns_ok && path_ok).then(|| format!("{ns}:{path}")) -} +pub use horizon_client_core::identifier::parse_identifier; pub fn normalize(id: &str) -> String { match id.split_once(':') { Some(("", path)) => format!("minecraft:{path}"), @@ -1220,7 +1021,10 @@ impl ArgType { reader.cursor = start; return Err(CommandError::tr_at( "argument.float.low", - &[&crate::snbt::java_float(*min), &crate::snbt::java_float(v)], + &[ + &horizon_client_core::snbt::java_float(*min), + &horizon_client_core::snbt::java_float(v), + ], reader, )); } @@ -1228,7 +1032,10 @@ impl ArgType { reader.cursor = start; return Err(CommandError::tr_at( "argument.float.big", - &[&crate::snbt::java_float(*max), &crate::snbt::java_float(v)], + &[ + &horizon_client_core::snbt::java_float(*max), + &horizon_client_core::snbt::java_float(v), + ], reader, )); } @@ -1241,8 +1048,8 @@ impl ArgType { return Err(CommandError::tr_at( "argument.double.low", &[ - &crate::snbt::java_double(*min), - &crate::snbt::java_double(v), + &horizon_client_core::snbt::java_double(*min), + &horizon_client_core::snbt::java_double(v), ], reader, )); @@ -1252,8 +1059,8 @@ impl ArgType { return Err(CommandError::tr_at( "argument.double.big", &[ - &crate::snbt::java_double(*max), - &crate::snbt::java_double(v), + &horizon_client_core::snbt::java_double(*max), + &horizon_client_core::snbt::java_double(v), ], reader, )); @@ -1597,7 +1404,7 @@ impl ArgType { return Err(CommandError::tr_at(key, &[&m], reader)); } let text = &reader.string[start..reader.cursor]; - match crate::component::parse_snbt(text) { + match horizon_client_core::component::parse_snbt(text) { Ok((v, _)) => Arg::Str(v.to_string()), Err(_) => Arg::Str(text.to_owned()), } @@ -1645,7 +1452,7 @@ impl ArgType { } let id = &reader.string[start..reader.cursor]; // ObjectiveCriteria.byName: statistics resolve to their canonical name. - match crate::scoreboard::criteria_by_name(id, reg) { + match horizon_client_core::scoreboard::criteria_by_name(id, reg) { Ok(Some(canonical)) => Arg::Str(canonical), Ok(None) => { reader.cursor = start; @@ -1667,7 +1474,7 @@ impl ArgType { } ArgType::ScoreboardSlot => { let name = reader.read_unquoted_string(); - if !crate::scoreboard::display_slot_valid(name) { + if !horizon_client_core::scoreboard::display_slot_valid(name) { return Err(CommandError::tr_at( "argument.scoreboardDisplaySlot.invalid", &[&name], @@ -1695,7 +1502,7 @@ impl ArgType { } ArgType::TeamColor => { let name = reader.read_unquoted_string(); - if crate::scoreboard::team_color_rgb(name).is_none() { + if horizon_client_core::scoreboard::team_color_rgb(name).is_none() { return Err(CommandError::tr_at( "argument.color.invalid", &[&name], @@ -1743,7 +1550,7 @@ impl ArgType { let id = read_identifier(reader)?; let known = reg.ids("minecraft:particle_type"); let exists = if known.is_empty() { - crate::particles::ParticleType::from_name(&id).is_some() + horizon_client_core::particle_type::ParticleType::from_name(&id).is_some() } else { known.contains(&id) }; @@ -1931,15 +1738,16 @@ impl ArgType { } ArgType::Team => builder.suggest_matching(reg.teams.iter().map(String::as_str)), ArgType::Criteria => { - let mut ids: Vec = crate::scoreboard::CUSTOM_CRITERIA + let mut ids: Vec = horizon_client_core::scoreboard::CUSTOM_CRITERIA .iter() .map(|s| (*s).to_owned()) .collect(); - for c in crate::scoreboard::team_colors() { + for c in horizon_client_core::scoreboard::team_colors() { ids.push(format!("teamkill.{c}")); ids.push(format!("killedByTeam.{c}")); } - let stat = |ty: &str, key: &str| crate::scoreboard::stat_criteria(ty, key); + let stat = + |ty: &str, key: &str| horizon_client_core::scoreboard::stat_criteria(ty, key); ids.extend(reg.blocks.keys().map(|b| stat("mined", b))); for ty in ["crafted", "used", "broken", "picked_up", "dropped"] { ids.extend(reg.items.iter().map(|i| stat(ty, i))); @@ -1948,14 +1756,14 @@ impl ArgType { ids.extend(reg.entity_types.iter().map(|e| stat(ty, e))); } ids.extend( - crate::scoreboard::CUSTOM_STATS + horizon_client_core::scoreboard::CUSTOM_STATS .iter() .map(|c| stat("custom", &format!("minecraft:{c}"))), ); builder.suggest_matching(ids.iter().map(String::as_str)); } ArgType::ScoreboardSlot => { - let slots = crate::scoreboard::display_slots(); + let slots = horizon_client_core::scoreboard::display_slots(); builder.suggest_matching(slots.iter().map(String::as_str)); } ArgType::Operation => builder.suggest_matching(OPERATIONS), @@ -1963,7 +1771,7 @@ impl ArgType { ArgType::Particle => { let known = reg.ids("minecraft:particle_type"); if known.is_empty() { - let names: Vec = crate::particles::ParticleType::ALL + let names: Vec = horizon_client_core::particle_type::ParticleType::ALL .iter() .map(|t| format!("minecraft:{}", t.name())) .collect(); @@ -1999,7 +1807,9 @@ impl ArgType { suggest_resources(builder, reg.ids("minecraft:slot_source"), ""); } ArgType::ResourceOrId(registry) => suggest_resources(builder, reg.ids(registry), ""), - ArgType::TeamColor => builder.suggest_matching(crate::scoreboard::team_colors()), + ArgType::TeamColor => { + builder.suggest_matching(horizon_client_core::scoreboard::team_colors()) + } ArgType::Anchor => builder.suggest_matching(["eyes", "feet"]), ArgType::Component | ArgType::Style | ArgType::NbtTag => super::snbt::suggest(builder), ArgType::Swizzle | ArgType::Message | ArgType::Nbt => {} diff --git a/crates/horizon-client/src/command/block.rs b/crates/horizon-command/src/block.rs similarity index 100% rename from crates/horizon-client/src/command/block.rs rename to crates/horizon-command/src/block.rs diff --git a/crates/horizon-client/src/command/codec.rs b/crates/horizon-command/src/codec.rs similarity index 99% rename from crates/horizon-client/src/command/codec.rs rename to crates/horizon-command/src/codec.rs index 7c4d26682..40f5c1ce0 100644 --- a/crates/horizon-client/src/command/codec.rs +++ b/crates/horizon-command/src/codec.rs @@ -6,7 +6,7 @@ use super::{CmdResult, CommandError, Reader}; use horizon_world::nbt::{Compound, JavaString, Tag}; pub fn snbt(t: &Tag) -> String { - crate::snbt::to_snbt(t) + horizon_client_core::snbt::to_snbt(t) } pub fn not_map(t: &Tag) -> String { format!("Not a map: {}", snbt(t)) diff --git a/crates/horizon-client/src/command/component.rs b/crates/horizon-command/src/component.rs similarity index 98% rename from crates/horizon-client/src/command/component.rs rename to crates/horizon-command/src/component.rs index 15a8fa6a0..2933afeca 100644 --- a/crates/horizon-client/src/command/component.rs +++ b/crates/horizon-command/src/component.rs @@ -164,7 +164,7 @@ fn color(t: &Tag) -> R { _ => partial(format!("Invalid color value: {s}")), }; } - if crate::text::named_color(&s).is_some() { + if horizon_client_core::text::named_color(&s).is_some() { Ok(()) } else { partial(format!("Invalid color name: {s}")) @@ -278,7 +278,7 @@ fn content(kind: &str, map: &Compound) -> bool { "nbt" => { let path_ok = get(map, "nbt") .and_then(string_of) - .is_some_and(|p| crate::nbt_path::NbtPath::parse(&p).is_ok()); + .is_some_and(|p| horizon_client_core::nbt_path::NbtPath::parse(&p).is_ok()); let source = if let Some(e) = get(map, "entity") { selector_string(e) } else if let Some(b) = get(map, "block") { diff --git a/crates/horizon-client/src/command/item.rs b/crates/horizon-command/src/item.rs similarity index 99% rename from crates/horizon-client/src/command/item.rs rename to crates/horizon-command/src/item.rs index f2abc91ef..da9c4b8b0 100644 --- a/crates/horizon-client/src/command/item.rs +++ b/crates/horizon-command/src/item.rs @@ -72,9 +72,9 @@ pub fn decode_component(id: &str, t: &Tag) -> Result<(), String> { } else { format!("minecraft:{id}") }; - let known = crate::block_entity_nbt::TYPES + let known = horizon_client_core::block_entity_nbt::TYPES .iter() - .chain(&crate::block_entity_nbt::NEWEST) + .chain(&horizon_client_core::block_entity_nbt::NEWEST) .any(|k| *k == id); if known { Ok(()) diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-command/src/lib.rs similarity index 99% rename from crates/horizon-client/src/command/mod.rs rename to crates/horizon-command/src/lib.rs index a61c8c08d..838c8de87 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-command/src/lib.rs @@ -3,6 +3,7 @@ //! relevant child and keeps the best result, completion suggestions, smart //! usage text and the vanilla error messages. Argument types live in //! [`args`]; the vanilla command tree in [`vanilla`]. +#![forbid(unsafe_code)] pub mod args; pub mod block; pub mod codec; @@ -21,8 +22,8 @@ pub mod tree_world; pub mod vanilla; mod vanilla_order; -use crate::text::Text; pub use args::{Arg, ArgType, Registries}; +use horizon_client_core::text::Text; /// The command id of a mod's command (`Dispatcher::with_mod_commands`). pub const MOD_COMMAND: &str = "mod"; @@ -623,8 +624,10 @@ impl Suggests { for id in ®.summonable { if args::resource_matches(&contents, id) { let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id)); - let name = - crate::lang::get(&format!("entity.{ns}.{}", path.replace('/', "."))); + let name = horizon_client_core::lang::get(&format!( + "entity.{ns}.{}", + path.replace('/', ".") + )); builder.suggest_tooltip(id.clone(), name); } } diff --git a/crates/horizon-client/src/command/network.rs b/crates/horizon-command/src/network.rs similarity index 100% rename from crates/horizon-client/src/command/network.rs rename to crates/horizon-command/src/network.rs diff --git a/crates/horizon-client/src/command/packrat.rs b/crates/horizon-command/src/packrat.rs similarity index 99% rename from crates/horizon-client/src/command/packrat.rs rename to crates/horizon-command/src/packrat.rs index 42f42d9f4..ebe9df09d 100644 --- a/crates/horizon-client/src/command/packrat.rs +++ b/crates/horizon-command/src/packrat.rs @@ -402,7 +402,7 @@ impl<'g, V: Value> State<'g, V> { Reason::Error(e) => e.clone(), }; } - CommandError::new(crate::text::Text::literal("Failed to parse")) + CommandError::new(horizon_client_core::text::Text::literal("Failed to parse")) } /// CachedParseState.parse: a named rule, memoised per position. pub fn parse(&mut self, rule: RuleId) -> Option { diff --git a/crates/horizon-client/src/command/selector.rs b/crates/horizon-command/src/selector.rs similarity index 99% rename from crates/horizon-client/src/command/selector.rs rename to crates/horizon-command/src/selector.rs index eb4e637a4..777124f60 100644 --- a/crates/horizon-client/src/command/selector.rs +++ b/crates/horizon-command/src/selector.rs @@ -687,7 +687,7 @@ impl<'r, 'a> SelectorParser<'r, 'a> { fn fill_selectors(builder: &mut SuggestionsBuilder) { for (s, tip) in SELECTOR_KINDS { - builder.suggest_tooltip(s, crate::lang::get(tip)); + builder.suggest_tooltip(s, horizon_client_core::lang::get(tip)); } } @@ -785,7 +785,9 @@ impl<'r, 'a> SelectorParser<'r, 'a> { if self.can_use(o) && o.starts_with(&lower) { b.suggest_tooltip( format!("{o}="), - crate::lang::get(&format!("argument.entity.options.{o}.description")), + horizon_client_core::lang::get(&format!( + "argument.entity.options.{o}.description" + )), ); } } diff --git a/crates/horizon-client/src/command/snbt.rs b/crates/horizon-command/src/snbt.rs similarity index 100% rename from crates/horizon-client/src/command/snbt.rs rename to crates/horizon-command/src/snbt.rs diff --git a/crates/horizon-client/src/command/tests.rs b/crates/horizon-command/src/tests.rs similarity index 100% rename from crates/horizon-client/src/command/tests.rs rename to crates/horizon-command/src/tests.rs diff --git a/crates/horizon-client/src/command/tree_data.rs b/crates/horizon-command/src/tree_data.rs similarity index 100% rename from crates/horizon-client/src/command/tree_data.rs rename to crates/horizon-command/src/tree_data.rs diff --git a/crates/horizon-client/src/command/tree_execute.rs b/crates/horizon-command/src/tree_execute.rs similarity index 100% rename from crates/horizon-client/src/command/tree_execute.rs rename to crates/horizon-command/src/tree_execute.rs diff --git a/crates/horizon-client/src/command/tree_extra.rs b/crates/horizon-command/src/tree_extra.rs similarity index 100% rename from crates/horizon-client/src/command/tree_extra.rs rename to crates/horizon-command/src/tree_extra.rs diff --git a/crates/horizon-client/src/command/tree_misc.rs b/crates/horizon-command/src/tree_misc.rs similarity index 99% rename from crates/horizon-client/src/command/tree_misc.rs rename to crates/horizon-command/src/tree_misc.rs index a66fd5f37..1bcd880bb 100644 --- a/crates/horizon-client/src/command/tree_misc.rs +++ b/crates/horizon-command/src/tree_misc.rs @@ -230,12 +230,12 @@ fn bossbar(d: &mut Dispatcher, root: usize) { let name = d.argument(name_l, "name", ArgType::Component); d.executes(name, "bossbar.set.name"); let color = d.literal(id, "color"); - for c in crate::bossbar::COLORS { + for c in horizon_client_core::bossbar::COLORS { let l = d.literal(color, c); d.executes(l, "bossbar.set.color"); } let style = d.literal(id, "style"); - for s in crate::bossbar::STYLES { + for s in horizon_client_core::bossbar::STYLES { let l = d.literal(style, s); d.executes(l, "bossbar.set.style"); } diff --git a/crates/horizon-client/src/command/tree_scoreboard.rs b/crates/horizon-command/src/tree_scoreboard.rs similarity index 100% rename from crates/horizon-client/src/command/tree_scoreboard.rs rename to crates/horizon-command/src/tree_scoreboard.rs diff --git a/crates/horizon-client/src/command/tree_world.rs b/crates/horizon-command/src/tree_world.rs similarity index 99% rename from crates/horizon-client/src/command/tree_world.rs rename to crates/horizon-command/src/tree_world.rs index 0bd2edd3b..86ebba0ca 100644 --- a/crates/horizon-client/src/command/tree_world.rs +++ b/crates/horizon-command/src/tree_world.rs @@ -7,7 +7,7 @@ use super::{ args::{ArgType, integer}, vanilla::{ENTITIES, ENTITY, GAMEMASTERS, PLAYERS}, }; -use crate::settings::SOUND_SOURCES; +use horizon_client_core::sound_source::SOUND_SOURCES; fn float(min: f32) -> ArgType { ArgType::Float { min, max: f32::MAX } diff --git a/crates/horizon-client/src/command/vanilla.rs b/crates/horizon-command/src/vanilla.rs similarity index 99% rename from crates/horizon-client/src/command/vanilla.rs rename to crates/horizon-command/src/vanilla.rs index 2ce892077..37ec1c3de 100644 --- a/crates/horizon-client/src/command/vanilla.rs +++ b/crates/horizon-command/src/vanilla.rs @@ -5,7 +5,7 @@ use super::{ Dispatcher, args::{ArgType, Resource, integer}, }; -use crate::gamerules::{RULES, Value}; +use horizon_client_core::gamerules::{RULES, Value}; /// Permission levels (Commands.LEVEL_*). pub const ALL: u8 = 0; diff --git a/crates/horizon-client/src/command/vanilla_order.rs b/crates/horizon-command/src/vanilla_order.rs similarity index 100% rename from crates/horizon-client/src/command/vanilla_order.rs rename to crates/horizon-command/src/vanilla_order.rs diff --git a/crates/horizon-hdr/Cargo.toml b/crates/horizon-hdr/Cargo.toml new file mode 100644 index 000000000..e83e590e8 --- /dev/null +++ b/crates/horizon-hdr/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "horizon-hdr" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version = "1.85" +description = "HDR metadata for the swapchain: the Vulkan calls the crates that forbid unsafe code can't make" + +[dependencies] +wgpu = { version = "30.0.1", default-features = false, features = ["vulkan"] } + +[target.'cfg(not(target_os = "macos"))'.dependencies] +# The version wgpu-hal already uses. +ash = { version = "0.38", default-features = false } + +[lints] +workspace = true diff --git a/crates/horizon-hdr/src/lib.rs b/crates/horizon-hdr/src/lib.rs new file mode 100644 index 000000000..cda61868e --- /dev/null +++ b/crates/horizon-hdr/src/lib.rs @@ -0,0 +1,95 @@ +//! HDR metadata for the swapchain: the Vulkan calls the game crate, which +//! forbids unsafe code, can't make itself. wgpu sets no HDR metadata, and +//! without it a compositor may clip or tone-map everything above 1.0 (80 nits) +//! of an scRGB swapchain. + +/// Opens a Vulkan device with `VK_EXT_hdr_metadata` too, when the GPU offers +/// it, so [`set_metadata`] can tell the compositor the real peak brightness. +/// `None` leaves opening to wgpu. +#[cfg(not(target_os = "macos"))] +pub fn open_vulkan_device( + adapter: &wgpu::Adapter, + desc: &wgpu::DeviceDescriptor<'_>, +) -> Option> { + use wgpu::hal::api::Vulkan; + let open = { + // Safety: only read and opened from here; dropped before wgpu takes it back. + let hal = unsafe { adapter.as_hal::() }?; + let instance = hal.shared_instance().raw_instance(); + // Safety: the adapter's own physical device on its own instance. + let offered = + unsafe { instance.enumerate_device_extension_properties(hal.raw_physical_device()) } + .ok()? + .iter() + .any(|e| e.extension_name_as_c_str() == Ok(ash::ext::hdr_metadata::NAME)); + if !offered { + return None; + } + // Safety: what wgpu's own request_device does, with one more extension. + unsafe { + hal.open_with_callback( + desc.required_features, + &desc.required_limits, + &desc.memory_hints, + Some(Box::new( + |args: wgpu::hal::vulkan::CreateDeviceCallbackArgs| { + args.extensions.push(ash::ext::hdr_metadata::NAME); + }, + )), + ) + } + .ok()? + }; + // Safety: opened from this adapter with exactly `desc`'s features. + Some(unsafe { adapter.create_device_from_hal(open, desc) }) +} + +/// Tells the compositor, through `VK_EXT_hdr_metadata`, that the swapchain's +/// content is BT.709 and peaks at `peak` nits. Needs a device from +/// `open_vulkan_device` and a configured surface; does nothing otherwise. +pub fn set_metadata( + device: &wgpu::Device, + surface: &wgpu::Surface<'_>, + paper_white: f32, + peak: f32, +) { + #[cfg(not(target_os = "macos"))] + { + use wgpu::hal::api::Vulkan; + // Safety: read-only access to handles wgpu keeps alive while these guards live. + let (Some(hal_device), Some(hal_surface)) = + (unsafe { device.as_hal::() }, unsafe { + surface.as_hal::() + }) + else { + return; + }; + if !hal_device + .enabled_device_extensions() + .contains(&ash::ext::hdr_metadata::NAME) + { + return; + } + let Some(swapchain) = hal_surface.raw_native_swapchain() else { + return; + }; + let xy = |x, y| ash::vk::XYColorEXT { x, y }; + let metadata = ash::vk::HdrMetadataEXT::default() + .display_primary_red(xy(0.64, 0.33)) + .display_primary_green(xy(0.30, 0.60)) + .display_primary_blue(xy(0.15, 0.06)) + .white_point(xy(0.3127, 0.3290)) + .max_luminance(peak) + .min_luminance(0.0) + .max_content_light_level(peak) + .max_frame_average_light_level(paper_white.min(peak)); + let loader = ash::ext::hdr_metadata::Device::new( + hal_device.shared_instance().raw_instance(), + hal_device.raw_device(), + ); + // Safety: a live swapchain of this device, one metadata entry for it. + unsafe { loader.set_hdr_metadata(&[swapchain], &[metadata]) }; + } + #[cfg(target_os = "macos")] + let _ = (device, surface, paper_white, peak); +} diff --git a/crates/horizon-mod-registry/Cargo.lock b/crates/horizon-mod-registry/Cargo.lock index f80068fcc..59bd37134 100644 --- a/crates/horizon-mod-registry/Cargo.lock +++ b/crates/horizon-mod-registry/Cargo.lock @@ -294,6 +294,18 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + [[package]] name = "find-msvc-tools" version = "0.1.15" @@ -310,6 +322,12 @@ dependencies = [ "miniz_oxide", ] +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + [[package]] name = "foldhash" version = "0.2.0" @@ -394,17 +412,35 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ - "foldhash", + "foldhash 0.2.0", "serde", "serde_core", ] +[[package]] +name = "hashlink" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +dependencies = [ + "hashbrown 0.15.5", +] + [[package]] name = "hmac" version = "0.12.1" @@ -424,6 +460,7 @@ dependencies = [ "hmac", "horizon-mods", "http-body-util", + "rusqlite", "serde", "serde_json", "sha2", @@ -651,7 +688,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", - "hashbrown", + "hashbrown 0.17.1", "serde", "serde_core", ] @@ -674,6 +711,17 @@ version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" +[[package]] +name = "libsqlite3-sys" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "133c182a6a2c87864fe97778797e46c7e999672690dc9fa3ee8e241aa4a9c13f" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + [[package]] name = "litemap" version = "0.8.3" @@ -767,7 +815,7 @@ dependencies = [ "cfg_aliases", "codespan-reporting", "half", - "hashbrown", + "hashbrown 0.17.1", "indexmap", "libm", "log", @@ -786,7 +834,7 @@ version = "30.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49" dependencies = [ - "hashbrown", + "hashbrown 0.17.1", "indexmap", "rustc-hash", "thiserror", @@ -820,6 +868,12 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + [[package]] name = "potential_utf" version = "0.1.6" @@ -867,6 +921,20 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rusqlite" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "165ca6e57b20e1351573e3729b958bc62f0e48025386970b6e4d29e7a7e71f3f" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", +] + [[package]] name = "rustc-hash" version = "1.1.0" @@ -1316,6 +1384,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.5" @@ -1344,7 +1418,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c5ff8685b587722894b6f25958fc608d315b93b8d23647bfb567664e7006d757" dependencies = [ "bitflags", - "hashbrown", + "hashbrown 0.17.1", "indexmap", "semver", "serde", diff --git a/crates/horizon-mod-registry/Cargo.toml b/crates/horizon-mod-registry/Cargo.toml index affc08f62..959e84f91 100644 --- a/crates/horizon-mod-registry/Cargo.toml +++ b/crates/horizon-mod-registry/Cargo.toml @@ -23,6 +23,8 @@ hmac = "0.12" sha2 = "0.10" base64 = "0.22" getrandom = "0.3" +# Ratings: one SQLite file on a small volume, as the telemetry server keeps its data. +rusqlite = { version = "0.37", features = ["bundled"] } [dev-dependencies] tower = { version = "0.5", features = ["util"] } diff --git a/crates/horizon-mod-registry/Dockerfile b/crates/horizon-mod-registry/Dockerfile index 13522165a..ee2065008 100644 --- a/crates/horizon-mod-registry/Dockerfile +++ b/crates/horizon-mod-registry/Dockerfile @@ -4,11 +4,15 @@ WORKDIR /src # The root manifest only for the shared crate's workspace settings (edition, lints). COPY Cargo.toml Cargo.toml COPY crates/horizon-mods crates/horizon-mods +# horizon-mods' optional dependency: cargo needs its manifest even with the feature off. +COPY crates/horizon-shader-api crates/horizon-shader-api COPY crates/horizon-mod-registry crates/horizon-mod-registry RUN cargo build --release --locked --manifest-path crates/horizon-mod-registry/Cargo.toml FROM debian:stable-slim RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/* COPY --from=build /src/crates/horizon-mod-registry/target/release/horizon-mod-registry /usr/local/bin/ -USER nobody -CMD ["horizon-mod-registry"] +ENV REGISTRY_DB=/data/registry.sqlite3 +# Railway mounts the ratings' volume at /data owned by root: hand it to nobody, then run as nobody (setpriv is +# util-linux's, in every Debian image). +CMD ["sh", "-c", "mkdir -p /data && chown nobody:nogroup /data && exec setpriv --reuid=nobody --regid=nogroup --clear-groups horizon-mod-registry"] diff --git a/crates/horizon-mod-registry/README.md b/crates/horizon-mod-registry/README.md index f7cdc68c5..d609e6739 100644 --- a/crates/horizon-mod-registry/README.md +++ b/crates/horizon-mod-registry/README.md @@ -7,20 +7,26 @@ entry's fields), uploads it to the `staging` release of request adding or updating `mods/.toml`. That repository's CI checks it again, with a trial run of a mod in the sandbox; reviewers decide, and merging publishes. Formats and rules: [docs/api/mod-index.md](../../docs/api/mod-index.md). -It keeps no data: a session is a signed cookie holding the GitHub login, and the user's OAuth token is used once, to -read that login, and dropped. The sign-in asks for no scope. +Signed-in players also rate published projects, 1 to 5 stars: one rating per GitHub account and project, which they can +change, never their own project's. That is the only data it keeps, in one SQLite file (`REGISTRY_DB`); it only ever +shows totals, never who rated. A session is a signed cookie holding the GitHub login and id, and the user's OAuth token +is used once, to read them, and dropped. The sign-in asks for no scope. | Route | | | --- | --- | -| `GET /api/mods/auth/login` | Starts the GitHub sign-in | -| `GET /api/mods/auth/callback` | GitHub's redirect: sets the session, back to `/mods/submit` | +| `GET /api/mods/auth/login` | Starts the GitHub sign-in; `?back=/mods/` (or `/mods`) comes back to that page | +| `GET /api/mods/auth/callback` | GitHub's redirect: sets the session, back to `/mods/submit` or the `back` page | | `POST /api/mods/auth/logout` | Ends it | | `GET /api/mods/me` | `{login, csrf}`, or 401 | | `POST /api/mods/submit` | Multipart: `entry` (JSON: `id kind name summary description authors license source icon key signature version game changelog`) and `file`; `{pull_request}` or `{error}` | +| `GET /api/mods/ratings` | `{projects: {: {average, count}}}` for every rated project; cached a minute | +| `GET /api/mods//rating` | The signed-in account's own `{stars}` (null when it hasn't rated), or 401 | +| `POST /api/mods//rating` | JSON `{stars}`, 1 to 5: sets or changes it; `{stars, average, count}` or `{error}` | | `GET /healthz` | `ok` | -A submission must come from `REGISTRY_PUBLIC_URL`'s origin with the session's `X-CSRF-Token`. Six per account and sixty -in all per hour. Only an entry's `owners` publish its updates; a key change, an icon in the repository or anything else +A submission or a rating must come from `REGISTRY_PUBLIC_URL`'s origin with the session's `X-CSRF-Token`. Six +submissions per account and sixty in all per hour; thirty ratings per account and 600 in all. A project's owners can't +rate it, and only projects on the registry's `main` can be rated. Only an entry's `owners` publish its updates; a key change, an icon in the repository or anything else is a pull request by hand. ## Running it @@ -28,7 +34,7 @@ is a pull request by hand. ```sh cargo test # against a mock GitHub (tests/submit.rs) REGISTRY_PUBLIC_URL=http://localhost:4173 REGISTRY_SESSION_KEY=... GITHUB_CLIENT_ID=... GITHUB_CLIENT_SECRET=... \ - GITHUB_BOT_TOKEN=... REGISTRY_REPO=you/horizon-mods-test cargo run + GITHUB_BOT_TOKEN=... REGISTRY_REPO=you/horizon-mods-test REGISTRY_DB=/tmp/registry.sqlite3 cargo run ``` | Variable | | @@ -38,10 +44,12 @@ REGISTRY_PUBLIC_URL=http://localhost:4173 REGISTRY_SESSION_KEY=... GITHUB_CLIENT | `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET` | The OAuth app | | `GITHUB_BOT_TOKEN` | Fine-grained, the registry repository only: Contents and Pull requests read and write | | `REGISTRY_REPO` | Default `ludovic111/horizon-mods` | +| `REGISTRY_DB` | The ratings' SQLite file: default `/data/registry.sqlite3`, the volume | | `PORT` | Default 8080 | On Railway it is the service `horizon-mod-registry` of the project `horizon-site`, next to the website: built from -`main` with this `Dockerfile` from the repository root, health check `/healthz`, no public domain and no volume. The +`main` with this `Dockerfile` from the repository root, health check `/healthz`, no public domain, and the volume +`registry-data` at `/data` for the ratings. The website's Caddy sends `/api/mods/*` to it over Railway's private network (`REGISTRY_UPSTREAM` on the website service: `http://horizon-mod-registry.railway.internal:8080`). `railway.json` lists the same settings; Railway reads them from the service, not from the file. diff --git a/crates/horizon-mod-registry/src/lib.rs b/crates/horizon-mod-registry/src/lib.rs index 72970017a..661337c8c 100644 --- a/crates/horizon-mod-registry/src/lib.rs +++ b/crates/horizon-mod-registry/src/lib.rs @@ -2,13 +2,15 @@ //! `playhorizon.dev/api/mods/*` (docs/api/mod-index.md). A creator signs in //! with GitHub, sends a file and its page; the service runs the file's own //! checks, uploads it to the registry's `staging` release and opens a pull -//! request with the entry. Reviewers decide; merging publishes. It keeps no -//! data: sessions are signed cookies, and GitHub holds everything else. +//! request with the entry. Reviewers decide; merging publishes. Signed-in +//! players also rate published projects (`ratings`, its only data: sessions +//! are signed cookies, and GitHub holds everything else). pub mod github; +pub mod ratings; use axum::{ Json, Router, - extract::{DefaultBodyLimit, Multipart, Query, State}, + extract::{DefaultBodyLimit, Multipart, Path as UrlPath, Query, State}, http::{HeaderMap, StatusCode, header}, response::{IntoResponse, Redirect, Response}, routing::{get, post}, @@ -20,6 +22,7 @@ use horizon_mods::index::{ self, Kind, registry::{self, Entry, EntryVersion, Sources}, }; +use ratings::Ratings; use serde::Deserialize; use serde_json::json; use sha2::Sha256; @@ -37,6 +40,12 @@ const PER_ACCOUNT: usize = 6; const PER_HOUR: usize = 60; /// The page's JSON. const MAX_FORM: usize = 64 << 10; +/// Ratings set per account per hour, and by everyone. +const RATINGS_PER_ACCOUNT: usize = 30; +const RATINGS_PER_HOUR: usize = 600; +/// How long the ratings' totals are served from memory (and cached by +/// browsers and the launcher). +const TOTALS_FOR: Duration = Duration::from_secs(60); pub struct Config { /// `https://playhorizon.dev`: where the form is, and the only origin it @@ -47,11 +56,14 @@ pub struct Config { pub github: GitHub, /// Where files wait during a submission. pub scratch: PathBuf, + /// The ratings' SQLite file (a volume): `:memory:` keeps them in memory. + pub database: PathBuf, } impl Config { /// `REGISTRY_PUBLIC_URL`, `REGISTRY_SESSION_KEY`, `REGISTRY_REPO`, - /// `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `GITHUB_BOT_TOKEN`. + /// `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `GITHUB_BOT_TOKEN`, + /// `REGISTRY_DB` (default `/data/registry.sqlite3`). pub fn from_env() -> Result { let var = |name: &str| std::env::var(name).map_err(|_| format!("{name} is not set")); let key = var("REGISTRY_SESSION_KEY")?; @@ -69,6 +81,8 @@ impl Config { var("GITHUB_BOT_TOKEN")?, ), scratch: std::env::temp_dir().join("horizon-mod-registry"), + database: std::env::var_os("REGISTRY_DB") + .map_or_else(|| PathBuf::from("/data/registry.sqlite3"), PathBuf::from), }) } @@ -80,17 +94,31 @@ impl Config { #[derive(Clone)] pub struct App(Arc); +type Windows = Mutex>>; + struct Inner { config: Config, - recent: Mutex>>, + /// Submissions in the last hour, by account ("" for everyone's). + recent: Windows, + /// Ratings set in the last hour, the same way. + rated: Windows, + ratings: Mutex, + /// `GET /api/mods/ratings`' body, and when it was made. + totals: Mutex>, } impl App { - pub fn new(config: Config) -> App { - App(Arc::new(Inner { + /// Fails when the ratings' file can't be opened. + pub fn new(config: Config) -> Result { + let ratings = Ratings::open(&config.database) + .map_err(|e| format!("{}: {e}", config.database.display()))?; + Ok(App(Arc::new(Inner { config, - recent: Mutex::new(HashMap::new()), - })) + recent: Mutex::default(), + rated: Mutex::default(), + ratings: Mutex::new(ratings), + totals: Mutex::default(), + }))) } } @@ -101,6 +129,8 @@ pub fn router(app: App) -> Router { .route("/api/mods/auth/callback", get(callback)) .route("/api/mods/auth/logout", post(logout)) .route("/api/mods/me", get(me)) + .route("/api/mods/ratings", get(totals)) + .route("/api/mods/{id}/rating", get(my_rating).post(rate)) .route( "/api/mods/submit", post(submit).layer(DefaultBodyLimit::max( @@ -203,9 +233,29 @@ fn csrf(app: &Inner, headers: &HeaderMap) -> Option { Some(signed.rsplit('.').next()?.chars().take(32).collect()) } -async fn login(State(app): State) -> Response { +#[derive(Deserialize)] +struct Login { + /// The site's page to come back to: `/mods`, `/mods/submit` (the + /// default) or `/mods/`. + back: Option, +} + +/// Whether `path` is a registry page a sign-in may come back to. +fn registry_page(path: &str) -> bool { + match path.strip_prefix("/mods") { + Some("") => true, + Some(rest) => rest.strip_prefix('/').is_some_and(index::valid_id) || rest == "/submit", + None => false, + } +} + +async fn login(State(app): State, Query(q): Query) -> Response { let state = random_hex(); - let signed = sign(&app.0.config.session_key, &state); + let back = q + .back + .filter(|b| registry_page(b)) + .unwrap_or_else(|| "/mods/submit".into()); + let signed = sign(&app.0.config.session_key, &format!("{state}\n{back}")); let url = app .0 .config @@ -229,13 +279,17 @@ async fn callback( headers: HeaderMap, Query(q): Query, ) -> Result { - let expected = cookie(&headers, "hm_state").and_then(|v| unsign(&app.0.config.session_key, &v)); - if expected.as_deref() != Some(q.state.as_str()) { + let started = cookie(&headers, "hm_state").and_then(|v| unsign(&app.0.config.session_key, &v)); + let Some((_, back)) = started + .as_deref() + .and_then(|s| s.split_once('\n')) + .filter(|(state, _)| *state == q.state) + else { return Err(Refusal::new( StatusCode::FORBIDDEN, "the sign-in expired or didn't start here: try again", )); - } + }; let inner = app.0.clone(); let (login, id) = tokio::task::spawn_blocking(move || { inner @@ -250,7 +304,7 @@ async fn callback( &app.0.config.session_key, &format!("{login}\n{id}\n{}", now() + SESSION), ); - let back = format!("{}/mods/submit", app.0.config.public_url); + let back = format!("{}{back}", app.0.config.public_url); let mut response = Redirect::to(&back).into_response(); let headers = response.headers_mut(); headers.append( @@ -283,6 +337,131 @@ async fn me( )) } +fn database(e: rusqlite::Error) -> Refusal { + eprintln!("horizon-mod-registry: ratings: {e}"); + Refusal::new( + StatusCode::INTERNAL_SERVER_ERROR, + "the ratings can't be read right now", + ) +} + +/// A mean as the pages show it: two decimals. +fn rounded(average: f64) -> f64 { + (average * 100.0).round() / 100.0 +} + +/// `GET /api/mods/ratings`: `{"projects": {"": {"average", "count"}}}` for +/// every rated project. Totals only: never who rated. +async fn totals(State(app): State) -> Result { + let mut cached = app.0.totals.lock().unwrap(); + let body = match cached.as_ref().filter(|(at, _)| at.elapsed() < TOTALS_FOR) { + Some((_, body)) => body.clone(), + None => { + let all = app + .0 + .ratings + .lock() + .unwrap() + .summaries() + .map_err(database)?; + let projects: serde_json::Map = all + .into_iter() + .map(|(id, s)| (id, json!({"average": rounded(s.average), "count": s.count}))) + .collect(); + let body = json!({ "projects": projects }).to_string(); + *cached = Some((Instant::now(), body.clone())); + body + } + }; + Ok(( + [ + (header::CONTENT_TYPE, "application/json"), + (header::CACHE_CONTROL, "public, max-age=60"), + ], + body, + ) + .into_response()) +} + +/// `GET /api/mods/{id}/rating`: the signed-in account's own rating, +/// `{"stars": 1..5}` or `{"stars": null}`. +async fn my_rating( + State(app): State, + headers: HeaderMap, + UrlPath(id): UrlPath, +) -> Result, Refusal> { + let (_, account) = session(&app.0, &headers) + .ok_or_else(|| Refusal::new(StatusCode::UNAUTHORIZED, "not signed in"))?; + let stars = app + .0 + .ratings + .lock() + .unwrap() + .mine(&id, account) + .map_err(database)?; + Ok(Json(json!({ "stars": stars }))) +} + +#[derive(Deserialize)] +struct Rating { + stars: u8, +} + +/// `POST /api/mods/{id}/rating` with `{"stars": 1..5}`: sets or changes the +/// signed-in account's rating of a published project, not its own. Answers +/// the project's new totals and `stars`. +async fn rate( + State(app): State, + headers: HeaderMap, + UrlPath(id): UrlPath, + Json(rating): Json, +) -> Result, Refusal> { + let inner = app.0.clone(); + let (login, account) = signed_in_here(&inner, &headers)?; + if !(1..=5).contains(&rating.stars) { + return Err(bad("a rating is 1 to 5 stars")); + } + if !index::valid_id(&id) { + return Err(Refusal::new(StatusCode::NOT_FOUND, "no such project")); + } + if !allow(&inner.rated, &login, RATINGS_PER_ACCOUNT, RATINGS_PER_HOUR) { + return Err(Refusal::new( + StatusCode::TOO_MANY_REQUESTS, + "too many ratings this hour: try again later", + )); + } + let lookup = inner.clone(); + let wanted = id.clone(); + let entry = tokio::task::spawn_blocking(move || lookup.config.github.entry(&wanted)) + .await + .map_err(|_| Refusal::new(StatusCode::INTERNAL_SERVER_ERROR, "the check crashed"))? + .map_err(github_down)?; + let Some((entry, _)) = entry else { + return Err(Refusal::new( + StatusCode::NOT_FOUND, + format!("{id} isn't published in the registry"), + )); + }; + if entry.owners.iter().any(|o| o.eq_ignore_ascii_case(&login)) { + return Err(Refusal::new( + StatusCode::FORBIDDEN, + "you publish this project: its players rate it", + )); + } + let summary = { + let ratings = inner.ratings.lock().unwrap(); + ratings + .rate(&id, account, rating.stars, now()) + .map_err(database)?; + ratings.summary(&id).map_err(database)? + }; + *inner.totals.lock().unwrap() = None; + let (average, count) = summary.map_or((0.0, 0), |s| (rounded(s.average), s.count)); + Ok(Json( + json!({"stars": rating.stars, "average": average, "count": count}), + )) +} + /// The page a submission fills in: a project's fields, and the version's. #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] @@ -322,45 +501,56 @@ fn take(window: &mut VecDeque, max: usize) -> bool { window.len() < max } +/// A change sent by the site's own pages: from its origin, signed in, with +/// the session's CSRF token. The account: (login, id). +fn signed_in_here(app: &Inner, headers: &HeaderMap) -> Result<(String, u64), Refusal> { + let origin = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()); + if origin != Some(app.config.public_url.as_str()) { + return Err(Refusal::new( + StatusCode::FORBIDDEN, + "send it from the registry's pages", + )); + } + let account = session(app, headers) + .ok_or_else(|| Refusal::new(StatusCode::UNAUTHORIZED, "sign in with GitHub first"))?; + let sent = headers.get("x-csrf-token").and_then(|v| v.to_str().ok()); + if sent.is_none() || sent.map(str::to_owned) != csrf(app, headers) { + return Err(Refusal::new( + StatusCode::FORBIDDEN, + "reload the page and try again", + )); + } + Ok(account) +} + +/// Counts one more for `login` and for everyone, unless either is at its +/// hourly limit. +fn allow(windows: &Windows, login: &str, per_account: usize, per_hour: usize) -> bool { + let mut windows = windows.lock().unwrap(); + let account = login.to_lowercase(); + let ok = take(windows.entry(String::new()).or_default(), per_hour) + && take(windows.entry(account.clone()).or_default(), per_account); + if ok { + let at = Instant::now(); + windows.entry(String::new()).or_default().push_back(at); + windows.entry(account).or_default().push_back(at); + } + ok +} + async fn submit( State(app): State, headers: HeaderMap, mut multipart: Multipart, ) -> Result, Refusal> { let inner = app.0.clone(); - let origin = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()); - if origin != Some(inner.config.public_url.as_str()) { + let (login, user_id) = signed_in_here(&inner, &headers)?; + if !allow(&inner.recent, &login, PER_ACCOUNT, PER_HOUR) { return Err(Refusal::new( - StatusCode::FORBIDDEN, - "submit from the registry's form", + StatusCode::TOO_MANY_REQUESTS, + "too many submissions this hour: try again later", )); } - let (login, user_id) = session(&inner, &headers) - .ok_or_else(|| Refusal::new(StatusCode::UNAUTHORIZED, "sign in with GitHub first"))?; - let sent = headers.get("x-csrf-token").and_then(|v| v.to_str().ok()); - if sent.is_none() || sent.map(str::to_owned) != csrf(&inner, &headers) { - return Err(Refusal::new( - StatusCode::FORBIDDEN, - "reload the form and try again", - )); - } - { - let mut recent = inner.recent.lock().unwrap(); - let ok = take(recent.entry(String::new()).or_default(), PER_HOUR) - && take(recent.entry(login.to_lowercase()).or_default(), PER_ACCOUNT); - if !ok { - return Err(Refusal::new( - StatusCode::TOO_MANY_REQUESTS, - "too many submissions this hour: try again later", - )); - } - let at = Instant::now(); - recent.entry(String::new()).or_default().push_back(at); - recent - .entry(login.to_lowercase()) - .or_default() - .push_back(at); - } let dir = inner.config.scratch.join(random_hex()); std::fs::create_dir_all(&dir) .map_err(|e| Refusal::new(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; diff --git a/crates/horizon-mod-registry/src/main.rs b/crates/horizon-mod-registry/src/main.rs index 81fe1b7b6..a1e40a57a 100644 --- a/crates/horizon-mod-registry/src/main.rs +++ b/crates/horizon-mod-registry/src/main.rs @@ -1,5 +1,5 @@ //! `horizon-mod-registry`: serves on `PORT` (default 8080). Configured by the -//! environment (see `Config::from_env`); keeps no data. +//! environment (see `Config::from_env`); keeps the ratings in `REGISTRY_DB`. use std::net::SocketAddr; use horizon_mod_registry::{App, Config, router}; @@ -16,7 +16,8 @@ async fn main() { .await .unwrap_or_else(|e| panic!("port {port}: {e}")); eprintln!("horizon-mod-registry: listening on {port}, submitting to {repo}"); - axum::serve(listener, router(App::new(config))) + let app = App::new(config).unwrap_or_else(|e| panic!("horizon-mod-registry: {e}")); + axum::serve(listener, router(app)) .with_graceful_shutdown(async { let _ = tokio::signal::ctrl_c().await; }) diff --git a/crates/horizon-mod-registry/src/ratings.rs b/crates/horizon-mod-registry/src/ratings.rs new file mode 100644 index 000000000..0cba85142 --- /dev/null +++ b/crates/horizon-mod-registry/src/ratings.rs @@ -0,0 +1,129 @@ +//! Players' ratings of published projects, 1 to 5 stars: one per GitHub +//! account and project, which its rater can change. Stored in one SQLite +//! file (a Railway volume). Only totals leave it: never who rated what, +//! except a signed-in account's own rating, to that account. +use rusqlite::{Connection, OptionalExtension, params}; +use std::{collections::BTreeMap, path::Path}; + +const SCHEMA: &str = " +PRAGMA journal_mode = WAL; +PRAGMA synchronous = NORMAL; +CREATE TABLE IF NOT EXISTS ratings ( + project TEXT NOT NULL, + account INTEGER NOT NULL, + stars INTEGER NOT NULL CHECK (stars BETWEEN 1 AND 5), + updated INTEGER NOT NULL, + PRIMARY KEY (project, account) +) WITHOUT ROWID; +"; + +/// A project's ratings: their mean, and how many. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Summary { + pub average: f64, + pub count: u64, +} + +pub struct Ratings { + db: Connection, +} + +impl Ratings { + /// Opens (or creates) the file at `path`; `:memory:` for a test. + pub fn open(path: &Path) -> rusqlite::Result { + let db = Connection::open(path)?; + db.execute_batch(SCHEMA)?; + Ok(Ratings { db }) + } + + /// Sets `account`'s rating of `project`, replacing an earlier one. + pub fn rate(&self, project: &str, account: u64, stars: u8, now: u64) -> rusqlite::Result<()> { + self.db.execute( + "INSERT INTO ratings (project, account, stars, updated) VALUES (?1, ?2, ?3, ?4) + ON CONFLICT (project, account) DO UPDATE SET stars = excluded.stars, updated = excluded.updated", + params![project, account as i64, stars, now as i64], + )?; + Ok(()) + } + + /// `account`'s own rating of `project`. + pub fn mine(&self, project: &str, account: u64) -> rusqlite::Result> { + self.db + .query_row( + "SELECT stars FROM ratings WHERE project = ?1 AND account = ?2", + params![project, account as i64], + |r| r.get(0), + ) + .optional() + } + + /// `project`'s summary; None when nobody rated it. + pub fn summary(&self, project: &str) -> rusqlite::Result> { + self.db + .query_row( + "SELECT avg(stars), count(*) FROM ratings WHERE project = ?1 HAVING count(*) > 0", + [project], + |r| { + Ok(Summary { + average: r.get(0)?, + count: r.get::<_, i64>(1)? as u64, + }) + }, + ) + .optional() + } + + /// Every rated project's summary. + pub fn summaries(&self) -> rusqlite::Result> { + let mut statement = self + .db + .prepare("SELECT project, avg(stars), count(*) FROM ratings GROUP BY project")?; + let rows = statement.query_map([], |r| { + Ok(( + r.get::<_, String>(0)?, + Summary { + average: r.get(1)?, + count: r.get::<_, i64>(2)? as u64, + }, + )) + })?; + rows.collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_rating_per_account_and_project() { + let r = Ratings::open(Path::new(":memory:")).unwrap(); + r.rate("zoom", 1, 5, 10).unwrap(); + r.rate("zoom", 2, 2, 10).unwrap(); + r.rate("zoom", 1, 4, 11).unwrap(); + r.rate("minimap", 1, 3, 11).unwrap(); + assert_eq!(r.mine("zoom", 1).unwrap(), Some(4)); + assert_eq!(r.mine("zoom", 3).unwrap(), None); + let all = r.summaries().unwrap(); + assert_eq!( + all["zoom"], + Summary { + average: 3.0, + count: 2 + } + ); + assert_eq!( + all["minimap"], + Summary { + average: 3.0, + count: 1 + } + ); + assert_eq!(r.summary("zoom").unwrap(), Some(all["zoom"])); + assert_eq!(r.summary("nothing").unwrap(), None); + assert!( + r.rate("zoom", 1, 6, 12).is_err(), + "the table checks the range too" + ); + } +} diff --git a/crates/horizon-mod-registry/tests/submit.rs b/crates/horizon-mod-registry/tests/submit.rs index f27f18697..d5591d4fc 100644 --- a/crates/horizon-mod-registry/tests/submit.rs +++ b/crates/horizon-mod-registry/tests/submit.rs @@ -1,6 +1,6 @@ //! The whole submission against a mock GitHub: sign in, submit the sample //! signed mod (`crates/horizon-mods/tests/index`), and what lands on GitHub; -//! then what is refused. +//! then what is refused. Then ratings: who may rate what, and what is shown. use axum::{ Json, Router, body::{Body, Bytes}, @@ -55,7 +55,9 @@ async fn mock_github() -> (String, Shared) { .route( "/user", get(|State(s): State| async move { - Json(json!({"login": s.lock().unwrap().login, "id": 7})) + let login = s.lock().unwrap().login.clone(); + let id = if login == "alice" { 7 } else { 8 }; + Json(json!({"login": login, "id": id})) }), ) .route( @@ -174,7 +176,16 @@ impl Client { } async fn sign_in(&mut self) -> String { - let (status, _, location) = self.send(self.get("/api/mods/auth/login")).await; + self.sign_in_from("").await + } + + /// Signs in from the page `back` (`?back=` of the sign-in; "" for none). + async fn sign_in_from(&mut self, back: &str) -> String { + let login = match back { + "" => "/api/mods/auth/login".to_owned(), + back => format!("/api/mods/auth/login?back={back}"), + }; + let (status, _, location) = self.send(self.get(&login)).await; assert_eq!(status, StatusCode::SEE_OTHER); let location = location.unwrap(); assert!(location.contains( @@ -197,10 +208,11 @@ impl Client { .send(self.get(&format!("/api/mods/auth/callback?code=good&state={state}"))) .await; assert_eq!(status, StatusCode::SEE_OTHER); - assert_eq!( - location.as_deref(), - Some("https://playhorizon.test/mods/submit") - ); + let page = match back { + "/mods" | "/mods/zoom" => back, + _ => "/mods/submit", + }; + assert_eq!(location, Some(format!("https://playhorizon.test{page}"))); let (status, me, _) = self.send(self.get("/api/mods/me")).await; assert_eq!(status, StatusCode::OK); me["csrf"].as_str().unwrap().to_owned() @@ -265,9 +277,10 @@ async fn setup() -> (Client, Shared) { "bot".into(), ), scratch, + database: ":memory:".into(), }; let client = Client { - app: router(App::new(config)), + app: router(App::new(config).unwrap()), cookies: HashMap::new(), }; (client, mock) @@ -376,3 +389,95 @@ async fn what_the_form_refuses() { "nothing reached GitHub" ); } + +const ENTRY: &str = "kind = \"mod\"\nname = \"N\"\nsummary = \"s\"\nlicense = \"MIT\"\nsource = \"https://x.test\"\n\n[[versions]]\nversion = \"1.0.0\"\npublished = \"2026-01-01\"\ngame = \"26.3\"\nfile = \"f.hmod\"\nsha256 = \"0000000000000000000000000000000000000000000000000000000000000000\"\n"; + +impl Client { + async fn rate(&mut self, csrf: &str, id: &str, body: &str) -> (StatusCode, Value) { + let request = Request::post(format!("/api/mods/{id}/rating")) + .header(header::COOKIE, self.cookie_header()) + .header(header::ORIGIN, PUBLIC) + .header("x-csrf-token", csrf) + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(body.to_owned())) + .unwrap(); + let (status, json, _) = self.send(request).await; + (status, json) + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ratings() { + let (mut client, mock) = setup().await; + { + let mut m = mock.lock().unwrap(); + m.main.insert( + "mods/zoom.toml".into(), + format!("id = \"zoom\"\nowners = [\"bob\"]\n{ENTRY}"), + ); + m.main.insert( + "mods/mine.toml".into(), + format!("id = \"mine\"\nowners = [\"Alice\"]\n{ENTRY}"), + ); + } + // Nothing rated yet; signed out, no own rating and no rating at all. + let (status, json, _) = client.send(client.get("/api/mods/ratings")).await; + assert_eq!((status, json), (StatusCode::OK, json!({"projects": {}}))); + let (status, ..) = client.send(client.get("/api/mods/zoom/rating")).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + let (status, _) = client.rate("x", "zoom", r#"{"stars": 4}"#).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + + // A sign-in from a project's page comes back to it; anywhere else is the form. + client.sign_in_from("https://evil.test/").await; + let csrf = client.sign_in_from("/mods/zoom").await; + let (status, json) = client.rate("wrong", "zoom", r#"{"stars": 4}"#).await; + assert_eq!(status, StatusCode::FORBIDDEN, "{json}"); + for stars in ["0", "6"] { + let (status, json) = client + .rate(&csrf, "zoom", &format!(r#"{{"stars": {stars}}}"#)) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{json}"); + } + let (status, json) = client.rate(&csrf, "zoom", r#"{"stars": 4}"#).await; + assert_eq!(status, StatusCode::OK, "{json}"); + assert_eq!(json, json!({"stars": 4, "average": 4.0, "count": 1})); + // Changing it replaces it. + let (status, json) = client.rate(&csrf, "zoom", r#"{"stars": 2}"#).await; + assert_eq!(status, StatusCode::OK, "{json}"); + assert_eq!(json["count"], 1); + let (_, json, _) = client.send(client.get("/api/mods/zoom/rating")).await; + assert_eq!(json, json!({"stars": 2})); + let (_, json, _) = client.send(client.get("/api/mods/minimap/rating")).await; + assert_eq!(json, json!({"stars": null})); + + // Not one's own project, nor one that isn't published. + let (status, json) = client.rate(&csrf, "mine", r#"{"stars": 5}"#).await; + assert_eq!(status, StatusCode::FORBIDDEN, "{json}"); + let (status, json) = client.rate(&csrf, "nothing", r#"{"stars": 5}"#).await; + assert_eq!(status, StatusCode::NOT_FOUND, "{json}"); + + // Another account's rating counts once more; the totals never say whose. + let mut other = Client { + app: client.app.clone(), + cookies: HashMap::new(), + }; + mock.lock().unwrap().login = "carol".into(); + let carol = other.sign_in().await; + let (status, json) = other.rate(&carol, "zoom", r#"{"stars": 5}"#).await; + assert_eq!(status, StatusCode::OK, "{json}"); + assert_eq!(json, json!({"stars": 5, "average": 3.5, "count": 2})); + let (status, json, _) = client.send(client.get("/api/mods/ratings")).await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + json, + json!({"projects": {"zoom": {"average": 3.5, "count": 2}}}) + ); + + // The limit per account and hour. + let mut last = StatusCode::OK; + for _ in 0..40 { + (last, _) = client.rate(&csrf, "zoom", r#"{"stars": 3}"#).await; + } + assert_eq!(last, StatusCode::TOO_MANY_REQUESTS); +} diff --git a/crates/horizon-mod-sdk/examples/beacons/Cargo.toml b/crates/horizon-mod-sdk/examples/beacons/Cargo.toml new file mode 100644 index 000000000..c001614e8 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/beacons/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "beacons" +version = "0.1.0" +edition.workspace = true +license.workspace = true +publish = false +description = "Example Horizon server mod: /beacon lights a pillar beside you, /ground says what you stand on" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +horizon-mod-sdk = { path = "../.." } + +[lints] +workspace = true diff --git a/crates/horizon-mod-sdk/examples/beacons/horizon-mod.toml b/crates/horizon-mod-sdk/examples/beacons/horizon-mod.toml new file mode 100644 index 000000000..5b58273c6 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/beacons/horizon-mod.toml @@ -0,0 +1,8 @@ +id = "beacons" +name = "Beacons" +version = "0.1.0" +description = "/beacon [height] lights a pillar of glowstone beside you; /ground [pos] says what you are standing on (or what is at pos), and in which biome." +authors = ["Horizon"] +api = "0.3" +side = "server" +capabilities = ["players", "world"] diff --git a/crates/horizon-mod-sdk/examples/beacons/src/lib.rs b/crates/horizon-mod-sdk/examples/beacons/src/lib.rs new file mode 100644 index 000000000..4a4de5cc1 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/beacons/src/lib.rs @@ -0,0 +1,103 @@ +//! Example Horizon server mod (`docs/mods.md`, "Server mods") with +//! capability `world` and typed commands: `/beacon [height]` lights a +//! pillar of glowstone two blocks east of the player, `/ground [pos]` reads +//! the block under their feet (or at `pos`) and its biome. +use horizon_mod_sdk::server::{ + Args, Argument, BlockChange, Player, Registration, ServerMod, players, world, +}; + +/// How tall `/beacon` builds when no height is given. +const HEIGHT: i32 = 4; + +struct Beacons; + +/// The block the player stands in: their feet, floored. +fn feet(player: &Player) -> (i32, i32, i32) { + ( + player.x.floor() as i32, + player.y.floor() as i32, + player.z.floor() as i32, + ) +} + +/// The pillar beside `player`: `height` blocks of glowstone, from their feet up. +fn pillar(player: &Player, height: i32) -> Vec { + let (x, y, z) = feet(player); + (0..height) + .map(|dy| BlockChange { + x: x + 2, + y: y + dy, + z, + state: "minecraft:glowstone".into(), + }) + .collect() +} + +impl ServerMod for Beacons { + fn init() -> Result<(Self, Registration), String> { + Ok(( + Beacons, + Registration::new() + .command_with( + "beacon", + [Argument::integer("height", Some(1), Some(64)).optional()], + ) + .command_with("ground", [Argument::block_pos("pos").optional()]), + )) + } + + fn command( + &mut self, + player: &Player, + name: &str, + args: &Args, + ) -> Result, String> { + let (x, y, z) = feet(player); + if name == "beacon" { + let height = args.integer("height").unwrap_or(HEIGHT); + world::set_blocks(&player.dimension, &pillar(player, height))?; + players::broadcast(&format!( + "{} lit a beacon at {} {y} {z}", + player.name, + x + 2 + )); + return Ok(None); + } + let (bx, by, bz) = match args.block_pos("pos") { + Some(p) => (p.x, p.y, p.z), + None => (x, y - 1, z), + }; + let block = + world::get_block(&player.dimension, bx, by, bz).ok_or("That block isn't loaded")?; + let biome = world::get_biome(&player.dimension, bx, by, bz).unwrap_or_default(); + if args.block_pos("pos").is_some() { + return Ok(Some(format!("{bx} {by} {bz} is {block} in {biome}"))); + } + Ok(Some(format!("You are standing on {block} in {biome}"))) + } +} + +horizon_mod_sdk::export_server_mod!(Beacons); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_pillar_stands_two_blocks_east() { + let p = Player { + id: String::new(), + name: "Alex".into(), + x: -0.5, + y: 64.0, + z: 3.2, + dimension: "minecraft:overworld".into(), + game_mode: horizon_mod_sdk::server::GameMode::Survival, + health: 20.0, + }; + let blocks = pillar(&p, HEIGHT); + assert_eq!(blocks.len(), HEIGHT as usize); + assert_eq!((blocks[0].x, blocks[0].y, blocks[0].z), (1, 64, 3)); + assert_eq!(blocks[3].y, 67); + } +} diff --git a/crates/horizon-mod-sdk/examples/beacons/tests/beacons.toml b/crates/horizon-mod-sdk/examples/beacons/tests/beacons.toml new file mode 100644 index 000000000..bab4839f3 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/beacons/tests/beacons.toml @@ -0,0 +1,39 @@ +# /ground [pos] reads the block under the player (or at pos) and the biome; /beacon [height] sets glowstone two to the east. + +[[step]] +join = "Alex" +blocks = [{ x = 0, y = 63, z = 0, state = "minecraft:grass_block[snowy=false]" }] +command = "ground" +expect.feedback = "You are standing on minecraft:grass_block[snowy=false] in minecraft:plains" + +[[step]] +command = "beacon" +expect.broadcast = ["Alex lit a beacon at 2 64 0"] +expect.blocks = [ + { x = 2, y = 64, z = 0, state = "minecraft:glowstone" }, + { x = 2, y = 67, z = 0, state = "minecraft:glowstone" }, + { x = 2, y = 68, z = 0, state = "minecraft:air" }, +] + +# Anywhere the script set nothing is air. +[[step]] +player = { x = 10.5, z = 10.5 } +command = "ground" +expect.feedback = "You are standing on minecraft:air in minecraft:plains" + +# Typed arguments: a height, a position relative to the player. +[[step]] +player = { x = 5.5, y = 64.0, z = 5.5 } +command = "beacon 2" +expect.blocks = [ + { x = 7, y = 65, z = 5, state = "minecraft:glowstone" }, + { x = 7, y = 66, z = 5, state = "minecraft:air" }, +] + +[[step]] +command = "beacon 65" +expect.error = "Integer must not be more than 64, found 65" + +[[step]] +command = "ground ~2 ~1 ~" +expect.feedback = "7 65 5 is minecraft:glowstone in minecraft:plains" diff --git a/crates/horizon-mod-sdk/examples/welcome/src/lib.rs b/crates/horizon-mod-sdk/examples/welcome/src/lib.rs index c45712c88..e5a5ef13e 100644 --- a/crates/horizon-mod-sdk/examples/welcome/src/lib.rs +++ b/crates/horizon-mod-sdk/examples/welcome/src/lib.rs @@ -1,9 +1,10 @@ //! Example Horizon server mod (`docs/mods.md`, "Server mods"): greets each //! player who joins, announces a newcomer to everyone (the players it has //! seen are kept in `storage`), `/online` lists who is on and where, and -//! `/mined` counts the blocks the player broke since the server started. +//! `/mined [player]` counts the blocks a player broke since the server +//! started (typed arguments: the chat box completes the player's name). use horizon_mod_sdk::{ - server::{BlockPos, Player, Registration, ServerMod, players}, + server::{Args, Argument, BlockPos, Player, Registration, ServerMod, players}, storage, }; use std::collections::HashMap; @@ -25,8 +26,8 @@ impl ServerMod for Welcome { }) .unwrap_or_default(); let hooks = Registration::new() - .command("online") - .command("mined") + .command_with("online", []) + .command_with("mined", [Argument::player("player").optional()]) .on_joins() .on_blocks(); Ok(( @@ -55,7 +56,7 @@ impl ServerMod for Welcome { &mut self, player: &Player, name: &str, - _args: &str, + args: &Args, ) -> Result, String> { Ok(Some(match name { "online" => players::online() @@ -69,10 +70,16 @@ impl ServerMod for Welcome { }) .collect::>() .join(", "), - _ => { - let n = self.mined.get(&player.id).copied().unwrap_or(0); - format!("You broke {n} block(s)") - } + _ => match args.player("player") { + Some(other) if other.id != player.id => { + let n = self.mined.get(&other.id).copied().unwrap_or(0); + format!("{} broke {n} block(s)", other.name) + } + _ => { + let n = self.mined.get(&player.id).copied().unwrap_or(0); + format!("You broke {n} block(s)") + } + }, })) } diff --git a/crates/horizon-mod-sdk/examples/welcome/tests/commands.toml b/crates/horizon-mod-sdk/examples/welcome/tests/commands.toml index 5f0018346..a55bd421d 100644 --- a/crates/horizon-mod-sdk/examples/welcome/tests/commands.toml +++ b/crates/horizon-mod-sdk/examples/welcome/tests/commands.toml @@ -1,4 +1,4 @@ -# /online lists the players and their dimension; /mined counts the acting player's blocks. +# /online lists the players and their dimension; /mined [player] counts a player's blocks. [[step]] join = "Alex" @@ -29,3 +29,18 @@ expect.feedback = "You broke 2 block(s)" as = "Steve" command = "mined" expect.feedback = "You broke 0 block(s)" + +[[step]] +as = "Steve" +command = "mined alex" +expect.feedback = "Alex broke 2 block(s)" + +# The server parses the arguments before the mod: vanilla's errors. +[[step]] +as = "Steve" +command = "mined Herobrine" +expect.error = "No player was found" + +[[step]] +command = "online now" +expect.error = "Incorrect argument for command" diff --git a/crates/horizon-mod-sdk/src/lib.rs b/crates/horizon-mod-sdk/src/lib.rs index 679fdc7b8..1e7120091 100644 --- a/crates/horizon-mod-sdk/src/lib.rs +++ b/crates/horizon-mod-sdk/src/lib.rs @@ -39,7 +39,9 @@ wit_bindgen::generate!({ pub use exports::horizon::mods::events::{Guest as __Guest, Registration}; pub use exports::horizon::mods::ui_events::Guest as __UiEventsGuest; -pub use horizon::mods::{chat, command, game, hud, input, log, render, storage, ui}; +pub use horizon::mods::{ + browser, chat, command, game, hud, input, log, recipes, render, storage, ui, +}; /// The game's calls into a mod. Only the hooks [`Registration`] asks for /// are called; the others may stay as their defaults. @@ -192,8 +194,12 @@ pub mod server { }, }); - pub use exports::horizon::mods::server_events::{BlockPos, Guest as __Guest, Registration}; + pub use exports::horizon::mods::server_events::{ + Argument, ArgumentKind, ArgumentValue, BlockPos, Guest as __Guest, Registration, + ServerCommand, + }; pub use horizon::mods::players::{self, GameMode, Player}; + pub use horizon::mods::world::{self, BlockChange}; /// The server's calls into a mod. Only the hooks [`Registration`] asks /// for are called; the others may stay as their defaults. @@ -208,13 +214,14 @@ pub mod server { fn player_left(&mut self, _player: &Player) {} /// A chat message a player sent, when [`Registration::chat`] is set. fn chat(&mut self, _player: &Player, _text: &str) {} - /// `/name args` typed by `player`. `Ok(Some(text))` is their - /// feedback, `Err(text)` their error in red. + /// `/name args` typed by `player`, parsed as the command's + /// arguments say ([`Registration::command_with`]). `Ok(Some(text))` + /// is their feedback, `Err(text)` their error in red. fn command( &mut self, _player: &Player, _name: &str, - _args: &str, + _args: &Args, ) -> Result, String> { Err("This command does nothing".into()) } @@ -234,9 +241,23 @@ pub mod server { blocks: false, } } - /// Adds `/name`. - pub fn command(mut self, name: &str) -> Self { - self.commands.push(name.into()); + /// Adds `/name`, taking free text ([`Args::text`]): one optional + /// `text` argument named `args`. + pub fn command(self, name: &str) -> Self { + self.command_with(name, [Argument::text("args").optional()]) + } + /// Adds `/name` with typed arguments (none: nothing after the name): + /// players' chat boxes complete and check them, and the server + /// parses them into [`Args`]. + pub fn command_with( + mut self, + name: &str, + arguments: impl IntoIterator, + ) -> Self { + self.commands.push(ServerCommand { + name: name.into(), + arguments: arguments.into_iter().collect(), + }); self } pub fn on_tick(mut self) -> Self { @@ -261,6 +282,105 @@ pub mod server { Self::new() } } + + impl Argument { + fn of(name: &str, kind: ArgumentKind) -> Self { + Self { + name: name.into(), + kind, + optional: false, + } + } + /// One word: letters, digits and `_ - . +`. + pub fn word(name: &str) -> Self { + Self::of(name, ArgumentKind::Word) + } + /// The rest of the line: only last. + pub fn text(name: &str) -> Self { + Self::of(name, ArgumentKind::Text) + } + /// A whole number, at least `min` and at most `max` when given. + pub fn integer(name: &str, min: Option, max: Option) -> Self { + Self::of(name, ArgumentKind::Integer((min, max))) + } + pub fn number(name: &str) -> Self { + Self::of(name, ArgumentKind::Number) + } + pub fn boolean(name: &str) -> Self { + Self::of(name, ArgumentKind::Boolean) + } + /// One online player: a name, `@s` or `@p`. + pub fn player(name: &str) -> Self { + Self::of(name, ArgumentKind::Player) + } + /// `x y z`, each one also `~` or `~n`. + pub fn block_pos(name: &str) -> Self { + Self::of(name, ArgumentKind::BlockPos) + } + /// May be left out; optional arguments come after the required ones. + pub fn optional(mut self) -> Self { + self.optional = true; + self + } + } + + /// A command's arguments: the line as typed, and the values the server + /// parsed from it, by argument name. + #[derive(Clone, Debug, Default)] + pub struct Args { + text: String, + values: Vec<(String, ArgumentValue)>, + } + impl Args { + pub fn new(text: String, values: Vec<(String, ArgumentValue)>) -> Self { + Self { text, values } + } + /// The line after the command's name, as typed. + pub fn text(&self) -> &str { + &self.text + } + /// The value of argument `name`; `None` when it was left out. + pub fn get(&self, name: &str) -> Option<&ArgumentValue> { + self.values.iter().find(|(n, _)| n == name).map(|(_, v)| v) + } + pub fn integer(&self, name: &str) -> Option { + match self.get(name)? { + ArgumentValue::Integer(n) => Some(*n), + _ => None, + } + } + pub fn number(&self, name: &str) -> Option { + match self.get(name)? { + ArgumentValue::Number(n) => Some(*n), + _ => None, + } + } + /// A `word` or `text` argument. + pub fn string(&self, name: &str) -> Option<&str> { + match self.get(name)? { + ArgumentValue::Word(s) | ArgumentValue::Text(s) => Some(s), + _ => None, + } + } + pub fn boolean(&self, name: &str) -> Option { + match self.get(name)? { + ArgumentValue::Boolean(b) => Some(*b), + _ => None, + } + } + pub fn player(&self, name: &str) -> Option<&Player> { + match self.get(name)? { + ArgumentValue::Player(p) => Some(p), + _ => None, + } + } + pub fn block_pos(&self, name: &str) -> Option { + match self.get(name)? { + ArgumentValue::BlockPos(p) => Some(*p), + _ => None, + } + } + } } /// Exports a [`ServerMod`](server::ServerMod) as the component's @@ -270,7 +390,7 @@ macro_rules! export_server_mod { ($t:ty) => { const _: () = { use ::std::cell::RefCell; - use $crate::server::{BlockPos, Player, Registration, ServerMod}; + use $crate::server::{Args, ArgumentValue, BlockPos, Player, Registration, ServerMod}; ::std::thread_local! { static STATE: RefCell> = const { RefCell::new(None) }; } @@ -304,8 +424,10 @@ macro_rules! export_server_mod { player: Player, name: String, args: String, + values: Vec<(String, ArgumentValue)>, ) -> Result, String> { let mut out = Err("The mod is not running".to_string()); + let args = Args::new(args, values); with(|m| out = m.command(&player, &name, &args)); out } diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 84be4d4f0..e75bb3cac 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -18,7 +18,8 @@ interface log { write: func(level: level, message: string); } -/// Capability `game-read`: the local player and the world clock. +/// Capability `game-read`: the local player, the world clock and the block +/// the player looks at. interface game { record player { /// Feet position, in blocks. @@ -46,6 +47,24 @@ interface game { get-player: func() -> option; /// None on the title screen. get-clock: func() -> option; + /// A block along the player's view. + record hit { + /// The block hit. + block-x: s32, + block-y: s32, + block-z: s32, + /// The point on its face where the view meets it. + x: f64, + y: f64, + z: f64, + /// `minecraft:stone`, ... + block: string, + } + /// The first block along the player's view (fluids pass), up to + /// `distance` blocks (at most 1024; past the loaded chunks, across the + /// distant terrain when LOD Distance is on), as of this tick. None when + /// nothing is hit, and on the title screen. + raycast: func(distance: f32) -> option; } /// Capability `chat`: messages only the local player sees. @@ -92,6 +111,14 @@ interface storage { interface command { /// `line` without its slash; its feedback goes to the chat as if typed. run: func(line: string); + /// `lines` (each without its slash, at most 256 a call) as `run` does, + /// but with nothing in the chat: no feedback and no failure. In single + /// player and on Horizon's servers, each runs exactly as the player + /// typing it would (the same rights), in order, 64 a tick, and the + /// server logs one line a batch; one that carries a chat message (`say`, + /// `msg`) is refused. On any other server they go as chat commands, and + /// there their feedback shows: a mod running many should say so. + run-quiet: func(lines: list); } /// Capability `ui`: widgets the game draws with its own menus' widgets, for @@ -412,6 +439,181 @@ interface events { chat: func(text: string); } +/// Capability `recipes` (experimental): the recipes and items the game +/// knows, for recipe viewers. In single player and on Horizon's servers +/// they are the world's; on any other server they are vanilla 26.3's (a +/// client is sent no others), while `known` follows that server's book. +interface recipes { + /// An item of `items`, by its index there, with a count and the + /// components it has beyond the item's own, in vanilla's item syntax + /// (`[potion_contents={potion:"minecraft:swiftness"}]`), or "". + record stack { + item: u32, + count: u32, + components: string, + } + /// The station a recipe is made at. + enum kind { + crafting-shaped, + crafting-shapeless, + smelting, + blasting, + smoking, + campfire, + stonecutting, + smithing, + brewing, + } + record recipe { + /// `minecraft:oak_planks`. + id: string, + kind: kind, + /// The recipe book's tab (`crafting_building_blocks`, + /// `furnace_food`), or "". + category: string, + /// Recipes the book shows on one button share a group, or "". + group: string, + /// A shaped recipe's grid: `slots` holds its cells row by row. + /// 0 for the other kinds. + width: u32, + height: u32, + /// Each slot's stacks, any one of which fits; an empty list is an + /// empty cell. Cooking and stonecutting: the input. Smithing: the + /// template, the base, the addition. Brewing: the bottle, the + /// reagent. + slots: list>, + /// What it makes; several when that varies (a trim on any armour). + results: list, + /// Cooking: game ticks and experience; 0 for the other kinds. + cooking-time: u32, + experience: f32, + /// The recipe book's id for it (one per way the book shows it), as + /// `known` lists them; -1 for the kinds the book doesn't show + /// (campfire, stonecutting, smithing, brewing). + book-id: s32, + } + record item { + /// `minecraft:diamond`, `:`. + id: string, + /// In the player's language. + name: string, + /// Its item tags, without the `#`. + tags: list, + } + /// Every item, in the registry's order: `stack.item` indexes this list. + items: func() -> list; + /// Every recipe: the book's in its order, then campfire, stonecutting, + /// smithing and brewing. They don't change while a world is open. + all: func() -> list; + /// The `book-id`s of the recipes the player's recipe book holds now. + known: func() -> list; + /// Places a recipe in the open screen's grid as a click in the recipe + /// book does (`ServerboundPlaceRecipePacket`): the inventory's grid or + /// a crafting table. `all` places as many as the items allow, as with + /// Shift. Refused while no such screen is open, for a recipe the + /// player's book doesn't hold and for one that can't be placed; one + /// missing items shows as a ghost in the grid, as in the book. + place: func(book-id: s32, all: bool) -> result<_, string>; + /// Creative mode only: gives the player the stack, as taking it from + /// the creative inventory does (`ServerboundSetCreativeModeSlot`): the + /// selected slot first, then the hotbar, then the inventory. The count + /// is cut to one stack of the item (64, 16 or 1). + give: func(stack: stack) -> result<_, string>; +} + +/// Capability `ui` (experimental): a recipe viewer's panel beside the +/// game's inventory and container screens (not the creative inventory), on +/// the right of the screen. The game draws it with its own widgets and +/// slots, pages it and keeps its search box; the mod says what it holds. +/// The first loaded mod with a panel shows. +interface browser { + /// An item to show: its id, a count (1 draws none) and its components + /// beyond the item's own, in vanilla's item syntax, or "". + record stack { + item: string, + count: u32, + components: string, + } + /// A click on an item of the panel, by its index in `set-items`'s list. + record click { + index: u32, + right: bool, + } + /// A key the mod registered (`input.register-key`) went down while the + /// pointer was on an item: a slot of the screen's, or the panel's. + record item-key { + key: string, + stack: stack, + } + /// A click on a slot of a recipe the panel shows (`set-recipes`). + record slot-click { + /// The recipe's index in `set-recipes`'s list and the slot's in + /// it; the results come after the slots. + recipe: u32, + slot: u32, + /// The stack the slot showed at that moment. + stack: stack, + right: bool, + } + variant event { + clicked(click), + /// The search box's text, each time the player changes it. + search(string), + key(item-key), + slot-clicked(slot-click), + /// The action button of the recipe at this index in + /// `set-recipes`'s list. + action(u32), + /// The player turned the recipes' page (`set-recipes`): the index + /// of the first recipe now shown. + page(u32), + /// The back button of `set-recipes`. + back, + /// The player picked the tab at this index of `set-recipes`' tabs. + tab(u32), + } + /// How the game lays out a recipe of `set-recipes`. + enum layout { + /// A crafting grid of `width` x `height` slots, an arrow and the + /// result. + grid, + /// One input over a flame, an arrow and the result (furnaces, + /// smokers, campfires). + cooking, + /// One input, an arrow and the result (the stonecutter). + single, + /// Template, base and addition, an arrow and the result. + smithing, + /// A potion and an ingredient, an arrow and the result. + brewing, + } + /// A recipe to show. Each slot, and the result, cycles through its + /// stacks, one a second; an empty slot shows nothing. + record recipe-view { + layout: layout, + /// The grid's size (`grid` only), at most 3 x 3. + width: u32, + height: u32, + slots: list>, + results: list, + /// A short line under the recipe (a cooking time), or "". + note: string, + /// The action button beside it: none, enabled, or shown greyed. + action: option, + } + /// The panel's items, at most 8192 (an empty list hides the panel). + set-items: func(items: list); + /// Shows these recipes in the panel instead of its items, as many as + /// fit a page, under `title` and a back button, with a row of `tabs` + /// (each an icon; `tab` is the selected one) between them; an empty + /// list of recipes shows the items again. At most 256 recipes and 16 + /// tabs. + set-recipes: func(title: string, tabs: list, tab: u32, recipes: list); + /// What the player did on the panel since the last poll, at most 256 + /// kept. + poll: func() -> list; +} + /// Capability `players`, server mods only (manifest `api = "0.3"`, /// experimental): the players on the server, and messages to them. interface players { @@ -445,16 +647,94 @@ interface players { broadcast: func(text: string); } +/// Capability `world`, server mods only (manifest `api = "0.3"`, +/// experimental): the blocks of the server's loaded chunks, and changes to +/// them through the server's own block updates. +interface %world { + record block-change { + x: s32, + y: s32, + z: s32, + /// `minecraft:oak_log[axis=y]`; properties left out take the block's + /// defaults, `minecraft:stone` alone is the default state. + state: string, + } + /// The block state at a position in a dimension (`minecraft:overworld`, + /// ...), as `minecraft:oak_log[axis=y]`, as of this call: none where the + /// server has no chunk loaded there. + get-block: func(dimension: string, x: s32, y: s32, z: s32) -> option; + /// The biome at a position (`minecraft:plains`, ...), as the server + /// stores it (one per 4 x 4 x 4 cell): none where no chunk is loaded. + get-biome: func(dimension: string, x: s32, y: s32, z: s32) -> option; + /// Sets blocks as `/setblock` does: the old block entity removed, + /// neighbours and shapes updated, light, and every player told. Every + /// state is checked now (an error queues nothing); the changes are made + /// in order after this call returns, before that dimension's next tick; + /// one in a chunk not loaded then is skipped. At most 4096 per call. + set-blocks: func(dimension: string, blocks: list) -> result<_, string>; +} + /// What the server calls in a server mod (manifest `api = "0.3"`, /// experimental). Only the hooks `init` asks for are ever called. The player /// in each event is as the server saw them when it happened. interface server-events { use players.{player}; + record block-pos { + x: s32, + y: s32, + z: s32, + } + /// What an argument of a command takes. The server sends each command + /// and its arguments to players' games, whose chat box completes and + /// colours them as vanilla's; the server parses them before the mod's + /// `command` hook gets their values. + variant argument-kind { + /// One word: letters, digits and `_ - . +`. + word, + /// The rest of the line, spaces included: only last. + text, + /// A whole number, within the bounds given. + integer(tuple, option>), + /// A number with or without decimals. + number, + /// `true` or `false`. + boolean, + /// One online player: a name, or `@s` or `@p` (whoever typed it, + /// as vanilla picks for a player). + player, + /// A block position: three whole numbers, each one also `~` or + /// `~n`, relative to whoever typed it. + block-pos, + } + record argument { + /// Shown in the chat box's hint (``) and the key of its value. + name: string, + kind: argument-kind, + /// Optional arguments come after every required one. + optional: bool, + } + record server-command { + /// Without the slash. A name vanilla already uses is refused + /// (vanilla's command runs). + name: string, + /// In order; none: the command takes nothing after its name. Free + /// text is one optional `text` argument. + arguments: list, + } + /// An argument's value, parsed as its kind says. + variant argument-value { + word(string), + text(string), + integer(s32), + number(f64), + boolean(bool), + player(player), + block-pos(block-pos), + } record registration { - /// Commands players may type, without the slash. A name vanilla - /// already uses is refused (vanilla's command runs). - commands: list, + /// Commands players may type. + commands: list, /// Call `tick` every server tick (20 per second). tick: bool, /// Call `player-joined` and `player-left`. @@ -464,11 +744,6 @@ interface server-events { /// Call `block-broken` and `block-placed`. blocks: bool, } - record block-pos { - x: s32, - y: s32, - z: s32, - } /// Once, after loading. An error keeps the mod off and is logged. init: func() -> result; /// Each server tick, with the server's tick counter. @@ -480,8 +755,10 @@ interface server-events { /// A chat message a player sent, as plain text. chat: func(player: player, text: string); /// `/name args` typed by `player`: ok(some(text)) is their feedback, - /// err(text) their error in red. - command: func(player: player, name: string, args: string) -> result, string>; + /// err(text) their error in red. `values` holds each argument given, by + /// name, in order (an optional one left out isn't there); a line that + /// doesn't parse never reaches the mod: the player gets vanilla's error. + command: func(player: player, name: string, args: string, values: list>) -> result, string>; /// A player broke the block at `pos` in their dimension: `state` is what /// was there, as `minecraft:oak_log[axis=y]`. block-broken: func(player: player, pos: block-pos, state: string); @@ -507,6 +784,7 @@ world horizon-server-mod { import log; import storage; import players; + import %world; export server-events; } @@ -518,6 +796,8 @@ world horizon-ui-mod { import ui; import render; import input; + import recipes; + import browser; export ui-events; } @@ -532,3 +812,9 @@ world render-host { import render; import input; } + +/// The game's side of capability `recipes` (imports only). +world recipes-host { + import recipes; + import browser; +} diff --git a/crates/horizon-mods/src/api_level.rs b/crates/horizon-mods/src/api_level.rs index 9f00dc4a1..073262bf9 100644 --- a/crates/horizon-mods/src/api_level.rs +++ b/crates/horizon-mods/src/api_level.rs @@ -7,13 +7,13 @@ //! version's level so the launcher can tell before it installs. /// The newest level this Horizon serves. -pub const LEVEL: u32 = 1; +pub const LEVEL: u32 = 6; /// Every function the game offers mods, as `interface.function`, with its /// level. Level 0 is the contract of Horizon 0.2.67 to 0.2.69. A new /// function takes the next level and raises [`LEVEL`] (the `api_reference` /// test fails until it is listed here). -pub const FUNCTIONS: [(&str, u32); 32] = [ +pub const FUNCTIONS: [(&str, u32); 45] = [ ("log.write", 0), ("game.get-player", 0), ("game.get-clock", 0), @@ -46,6 +46,19 @@ pub const FUNCTIONS: [(&str, u32); 32] = [ ("players.online", 1), ("players.tell", 1), ("players.broadcast", 1), + ("game.raycast", 2), + ("command.run-quiet", 3), + ("world.get-block", 4), + ("world.get-biome", 4), + ("world.set-blocks", 4), + ("recipes.items", 5), + ("recipes.all", 5), + ("recipes.known", 5), + ("browser.set-items", 6), + ("browser.poll", 6), + ("browser.set-recipes", 6), + ("recipes.place", 6), + ("recipes.give", 6), ]; /// What the game's program carries so the launcher can read its level diff --git a/crates/horizon-mods/src/commands.rs b/crates/horizon-mods/src/commands.rs new file mode 100644 index 000000000..4421b47ba --- /dev/null +++ b/crates/horizon-mods/src/commands.rs @@ -0,0 +1,301 @@ +//! Server mods' typed commands: an argument line parsed as the command's +//! arguments say, the way vanilla's Brigadier parsers read them, with +//! vanilla's error messages. The game sends the same arguments to players' +//! command trees, so their chat box checks them before the server does. +use crate::runtime::{Argument, ArgumentKind, ArgumentValue, BlockPos, ServerPlayer}; + +/// The values of `args`, typed by `player`, for `arguments` (in order; +/// optional ones left out aren't there), or the error the player reads. +pub fn parse( + arguments: &[Argument], + args: &str, + player: &ServerPlayer, + online: &[ServerPlayer], +) -> Result, String> { + let mut values = Vec::new(); + let mut rest = args; + for (i, argument) in arguments.iter().enumerate() { + if i > 0 && !rest.is_empty() { + rest = rest.strip_prefix(' ').ok_or( + "Expected whitespace to end one argument, but found trailing data".to_string(), + )?; + } + if rest.is_empty() { + if argument.optional { + break; + } + return Err("Unknown or incomplete command, see below for error".into()); + } + let (value, after) = one(&argument.kind, rest, player, online)?; + values.push((argument.name.clone(), value)); + rest = after; + } + if !rest.is_empty() { + return Err("Incorrect argument for command".into()); + } + Ok(values) +} + +/// StringReader.isAllowedInUnquotedString. +fn unquoted(c: char) -> bool { + c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '+') +} + +/// The unquoted string at the start of `s`, and what follows it. +fn word(s: &str) -> (&str, &str) { + let end = s.find(|c: char| !unquoted(c)).unwrap_or(s.len()); + s.split_at(end) +} + +/// One argument from the start of `s`, and what follows it. +fn one<'a>( + kind: &ArgumentKind, + s: &'a str, + player: &ServerPlayer, + online: &[ServerPlayer], +) -> Result<(ArgumentValue, &'a str), String> { + Ok(match kind { + ArgumentKind::Word => { + let (w, rest) = word(s); + if w.is_empty() { + return Err("Expected string".into()); + } + (ArgumentValue::Word(w.into()), rest) + } + ArgumentKind::Text => (ArgumentValue::Text(s.into()), ""), + ArgumentKind::Integer((min, max)) => { + let (n, rest) = integer(s)?; + if let Some(min) = min.filter(|m| n < *m) { + return Err(format!("Integer must not be less than {min}, found {n}")); + } + if let Some(max) = max.filter(|m| n > *m) { + return Err(format!("Integer must not be more than {max}, found {n}")); + } + (ArgumentValue::Integer(n), rest) + } + ArgumentKind::Number => { + let (n, rest) = double(s)?; + (ArgumentValue::Number(n), rest) + } + ArgumentKind::Boolean => { + let (w, rest) = word(s); + let b = match w { + "true" => true, + "false" => false, + "" => return Err("Expected bool".into()), + _ => { + return Err(format!( + "Invalid boolean, expected 'true' or 'false' but found '{w}'" + )); + } + }; + (ArgumentValue::Boolean(b), rest) + } + ArgumentKind::Player => { + if let Some(selector) = s.strip_prefix('@') { + let (kind, rest) = word(selector); + return match kind { + // A player's @p is themselves (the nearest to where they are). + "s" | "p" => Ok((ArgumentValue::Player(player.clone()), rest)), + "a" | "e" | "r" | "n" => { + Err("Only one player is allowed, but the provided selector allows more than one".into()) + } + _ => Err(format!("Unknown selector type '@{kind}'")), + }; + } + let (name, rest) = word(s); + if name.is_empty() { + return Err("Invalid name or UUID".into()); + } + let found = online + .iter() + .find(|p| p.name.eq_ignore_ascii_case(name)) + .ok_or("No player was found")?; + (ArgumentValue::Player(found.clone()), rest) + } + ArgumentKind::BlockPos => { + let (x, rest) = coordinate(s, player.x)?; + let rest = rest + .strip_prefix(' ') + .ok_or("Incomplete (expected 3 coordinates)")?; + let (y, rest) = coordinate(rest, player.y)?; + let rest = rest + .strip_prefix(' ') + .ok_or("Incomplete (expected 3 coordinates)")?; + let (z, rest) = coordinate(rest, player.z)?; + (ArgumentValue::BlockPos(BlockPos { x, y, z }), rest) + } + }) +} + +/// StringReader.readInt. +fn integer(s: &str) -> Result<(i32, &str), String> { + let end = s + .find(|c: char| !(c.is_ascii_digit() || c == '-' || c == '.')) + .unwrap_or(s.len()); + let (n, rest) = s.split_at(end); + if n.is_empty() { + return Err("Expected integer".into()); + } + let n = n.parse().map_err(|_| format!("Invalid integer '{n}'"))?; + Ok((n, rest)) +} + +/// StringReader.readDouble. +fn double(s: &str) -> Result<(f64, &str), String> { + let end = s + .find(|c: char| !(c.is_ascii_digit() || c == '-' || c == '.')) + .unwrap_or(s.len()); + let (n, rest) = s.split_at(end); + if n.is_empty() { + return Err("Expected double".into()); + } + let n = n.parse().map_err(|_| format!("Invalid double '{n}'"))?; + Ok((n, rest)) +} + +/// WorldCoordinate.parseInt, then BlockPos.containing: `~` and `~n` from +/// `base`, a whole number as it is. +fn coordinate(s: &str, base: f64) -> Result<(i32, &str), String> { + if s.starts_with('^') { + return Err( + "Cannot mix world & local coordinates (everything must either use ^ or not)".into(), + ); + } + if let Some(offset) = s.strip_prefix('~') { + if offset.is_empty() || offset.starts_with(' ') { + return Ok((base.floor() as i32, offset)); + } + let (n, rest) = double(offset)?; + return Ok(((base + n).floor() as i32, rest)); + } + integer(s) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::runtime::GameMode; + + fn player(name: &str) -> ServerPlayer { + ServerPlayer { + id: format!("id-{name}"), + name: name.into(), + x: 10.7, + y: 64.0, + z: -3.2, + dimension: "minecraft:overworld".into(), + game_mode: GameMode::Survival, + health: 20.0, + } + } + fn arg(name: &str, kind: ArgumentKind, optional: bool) -> Argument { + Argument { + name: name.into(), + kind, + optional, + } + } + + #[test] + fn values_in_order_and_optional_ones_left_out() { + let alex = player("Alex"); + let online = [alex.clone(), player("Steve")]; + let args = [ + arg("who", ArgumentKind::Player, false), + arg("height", ArgumentKind::Integer((Some(1), Some(64))), true), + arg("note", ArgumentKind::Text, true), + ]; + let v = parse(&args, "steve 5 hello there", &alex, &online).unwrap(); + assert_eq!(v[0].0, "who"); + assert!(matches!(&v[0].1, ArgumentValue::Player(p) if p.name == "Steve")); + assert_eq!(v[1], ("height".into(), ArgumentValue::Integer(5))); + assert_eq!( + v[2], + ("note".into(), ArgumentValue::Text("hello there".into())) + ); + let v = parse(&args, "@s", &alex, &online).unwrap(); + assert_eq!(v.len(), 1); + assert!(matches!(&v[0].1, ArgumentValue::Player(p) if p.name == "Alex")); + } + + #[test] + fn vanilla_errors() { + let alex = player("Alex"); + let online = [alex.clone()]; + let height = [arg( + "height", + ArgumentKind::Integer((Some(1), Some(64))), + false, + )]; + let err = |a: &[Argument], s| parse(a, s, &alex, &online).unwrap_err(); + assert_eq!( + err(&height, "0"), + "Integer must not be less than 1, found 0" + ); + assert_eq!( + err(&height, "65"), + "Integer must not be more than 64, found 65" + ); + assert_eq!(err(&height, "x"), "Expected integer"); + assert_eq!(err(&height, "1.5"), "Invalid integer '1.5'"); + assert_eq!( + err(&height, ""), + "Unknown or incomplete command, see below for error" + ); + assert_eq!(err(&height, "3 4"), "Incorrect argument for command"); + let who = [arg("who", ArgumentKind::Player, false)]; + assert_eq!(err(&who, "Herobrine"), "No player was found"); + assert_eq!(err(&who, "@q"), "Unknown selector type '@q'"); + let flag = [arg("on", ArgumentKind::Boolean, false)]; + assert_eq!( + err(&flag, "yes"), + "Invalid boolean, expected 'true' or 'false' but found 'yes'" + ); + let pos = [arg("at", ArgumentKind::BlockPos, false)]; + assert_eq!(err(&pos, "1 2"), "Incomplete (expected 3 coordinates)"); + } + + #[test] + fn block_positions_relative_to_the_player() { + let alex = player("Alex"); + let pos = [arg("at", ArgumentKind::BlockPos, false)]; + let v = parse(&pos, "~ ~1 ~-0.5", &alex, &[]).unwrap(); + assert_eq!( + v[0].1, + ArgumentValue::BlockPos(BlockPos { + x: 10, + y: 65, + z: -4 + }) + ); + let v = parse(&pos, "-5 70 ~", &alex, &[]).unwrap(); + assert_eq!( + v[0].1, + ArgumentValue::BlockPos(BlockPos { + x: -5, + y: 70, + z: -4 + }) + ); + } + + #[test] + fn free_text_is_an_optional_text_argument() { + let alex = player("Alex"); + let free = [arg("args", ArgumentKind::Text, true)]; + assert_eq!(parse(&free, "", &alex, &[]), Ok(Vec::new())); + assert_eq!( + parse(&free, "anything at all", &alex, &[]), + Ok(vec![( + "args".into(), + ArgumentValue::Text("anything at all".into()) + )]) + ); + assert_eq!( + parse(&[], "more", &alex, &[]), + Err("Incorrect argument for command".into()) + ); + assert_eq!(parse(&[], "", &alex, &[]), Ok(Vec::new())); + } +} diff --git a/crates/horizon-mods/src/index.rs b/crates/horizon-mods/src/index.rs index 544c52980..4ef292a23 100644 --- a/crates/horizon-mods/src/index.rs +++ b/crates/horizon-mods/src/index.rs @@ -122,6 +122,14 @@ pub struct Project { pub key: Option, /// Newest first. pub versions: Vec, + /// Its files' downloads from their releases, all versions together: + /// GitHub's counts, added by the registry's publish job (hourly). + #[serde(default, skip_serializing_if = "is_zero")] + pub downloads: u64, +} + +fn is_zero(n: &u64) -> bool { + *n == 0 } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] diff --git a/crates/horizon-mods/src/index/registry.rs b/crates/horizon-mods/src/index/registry.rs index 90453c621..05fff7f14 100644 --- a/crates/horizon-mods/src/index/registry.rs +++ b/crates/horizon-mods/src/index/registry.rs @@ -231,6 +231,7 @@ pub fn project(entry: &Entry, src: &Sources) -> Result> { icon, key: entry.key.as_ref().map(|k| k.trim().to_owned()), versions, + downloads: 0, }) } diff --git a/crates/horizon-mods/src/index/tests.rs b/crates/horizon-mods/src/index/tests.rs index ef0299ad9..486704b7d 100644 --- a/crates/horizon-mods/src/index/tests.rs +++ b/crates/horizon-mods/src/index/tests.rs @@ -34,8 +34,14 @@ fn reads_the_sample_and_keeps_unknown_kinds() { [Capability::GameRead, Capability::Hud, Capability::Chat] ); // What CI writes reads back the same. - let again = Index::parse(&serde_json::to_string(&index).unwrap()).unwrap(); + let text = serde_json::to_string(&index).unwrap(); + let again = Index::parse(&text).unwrap(); assert_eq!(again, index); + // Download counts: the publish job adds them; none is left out. + assert_eq!(hud.downloads, 0); + assert!(!text.contains("downloads")); + let counted = text.replacen("\"versions\"", "\"downloads\":12345,\"versions\"", 1); + assert_eq!(Index::parse(&counted).unwrap().projects[0].downloads, 12345); } #[test] diff --git a/crates/horizon-mods/src/lib.rs b/crates/horizon-mods/src/lib.rs index 20f475165..983df73d4 100644 --- a/crates/horizon-mods/src/lib.rs +++ b/crates/horizon-mods/src/lib.rs @@ -6,6 +6,8 @@ //! Nothing here runs unless a mod is installed and turned on: an empty //! [`Mods`] makes no engine and every hook returns at once. pub mod api_level; +#[cfg(feature = "runtime")] +pub mod commands; pub mod content; #[cfg(feature = "index")] pub mod index; diff --git a/crates/horizon-mods/src/manifest.rs b/crates/horizon-mods/src/manifest.rs index 5ad7823aa..c2f2f61fc 100644 --- a/crates/horizon-mods/src/manifest.rs +++ b/crates/horizon-mods/src/manifest.rs @@ -97,9 +97,15 @@ pub enum Capability { Input, /// The players on the server and messages to them (server mods). Players, + /// Blocks in the server's loaded chunks, and changes to them (server + /// mods; client mods later, where the game runs the world). + World, + /// The recipes and items the game knows, for recipe viewers + /// (interface `recipes`). + Recipes, } impl Capability { - pub const ALL: [Capability; 10] = [ + pub const ALL: [Capability; 12] = [ Capability::GameRead, Capability::Chat, Capability::Hud, @@ -110,10 +116,15 @@ impl Capability { Capability::Render, Capability::Input, Capability::Players, + Capability::World, + Capability::Recipes, ]; /// Whether a server mod may have it: the others act on a local player. pub fn on_server(self) -> bool { - matches!(self, Capability::Storage | Capability::Players) + matches!( + self, + Capability::Storage | Capability::Players | Capability::World + ) } /// The WIT interface it grants, in `horizon:mods`. pub fn interface(self) -> &'static str { @@ -128,6 +139,8 @@ impl Capability { Capability::Render => "render", Capability::Input => "input", Capability::Players => "players", + Capability::World => "world", + Capability::Recipes => "recipes", } } /// May change in any release: a mod uses it only with @@ -135,7 +148,7 @@ impl Capability { pub fn is_experimental(self) -> bool { matches!( self, - Capability::Ui | Capability::Render | Capability::Input + Capability::Ui | Capability::Render | Capability::Input | Capability::Recipes ) } /// What the player reads before turning the mod on: "May ". @@ -153,6 +166,10 @@ impl Capability { "see the keys you hold and your clicks, take over the use button on its own items and the mouse wheel, and add keys" } Capability::Players => "see who is on the server and message them", + Capability::World => "read and change the world's blocks", + Capability::Recipes => { + "read the game's recipes and items and which recipes you know, place recipes in your crafting grid and, in creative mode, give you items" + } } } /// The capability a component import needs, `Ok(None)` for one every @@ -167,6 +184,10 @@ impl Capability { if interface == "log" { return Ok(None); } + // A recipe viewer's panel is part of capability `ui`. + if interface == "browser" { + return Ok(Some(Capability::Ui)); + } Capability::ALL .into_iter() .filter(|c| *c != Capability::Registries) @@ -188,6 +209,8 @@ impl fmt::Display for Capability { Capability::Render => "render", Capability::Input => "input", Capability::Players => "players", + Capability::World => "world", + Capability::Recipes => "recipes", }; f.write_str(name) } diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index f1859337d..a75dd5a43 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -1,12 +1,13 @@ //! Loading and calling mods with wasmtime's component model. use crate::manifest::{Manifest, Package, Side}; use server_bindings::{ - HorizonServerMod, exports::horizon::mods::server_events::Registration as ServerRegistration, - horizon::mods::players, + HorizonServerMod, + exports::horizon::mods::server_events::Registration as ServerRegistration, + horizon::mods::{players, world as mod_world}, }; use std::{ path::{Path, PathBuf}, - sync::Arc, + sync::{Arc, Mutex}, time::{Duration, Instant, SystemTime}, }; use wasmtime::{ @@ -25,6 +26,7 @@ mod server_bindings { wasmtime::component::bindgen!({ path: "../horizon-mod-sdk/wit", world: "horizon-server-mod", + additional_derives: [PartialEq], with: { "horizon:mods/log": super::bindings::horizon::mods::log, "horizon:mods/storage": super::bindings::horizon::mods::storage, @@ -41,7 +43,7 @@ mod ui_bindings { }); } pub use bindings::horizon::mods::{ - game::{Clock, Player}, + game::{Clock, Hit, Player}, hud::{Corner, Line}, }; use bindings::{ @@ -50,8 +52,11 @@ use bindings::{ horizon::mods::{chat, command, game, hud, log as mod_log, storage}, }; pub use server_bindings::{ - exports::horizon::mods::server_events::BlockPos, + exports::horizon::mods::server_events::{ + Argument, ArgumentKind, ArgumentValue, BlockPos, ServerCommand, + }, horizon::mods::players::{GameMode, Player as ServerPlayer}, + horizon::mods::world::BlockChange, }; type ClientEvents = bindings::exports::horizon::mods::events::Guest; type ServerEvents = server_bindings::exports::horizon::mods::server_events::Guest; @@ -78,6 +83,24 @@ pub use render_bindings::horizon::mods::render::{ Zoom as ModZoom, }; use render_bindings::{RenderHost, horizon::mods::render}; +/// Capability `recipes`'s imports (docs/mods.md): the game's recipes and items. +mod recipes_bindings { + wasmtime::component::bindgen!({ + path: "../horizon-mod-sdk/wit", + world: "recipes-host", + }); +} +/// Capability `ui`'s recipe viewer panel (WIT `interface browser`). +pub use recipes_bindings::horizon::mods::browser::{ + Click as BrowserClick, Event as BrowserEvent, ItemKey as BrowserItemKey, + Layout as BrowserLayout, RecipeView as BrowserRecipe, SlotClick as BrowserSlotClick, + Stack as BrowserStack, +}; +/// What capability `recipes` reads (WIT `interface recipes`). +pub use recipes_bindings::horizon::mods::recipes::{ + Item as RecipeItem, Kind as RecipeKind, Recipe, Stack as RecipeStack, +}; +use recipes_bindings::{RecipesHost, horizon::mods::browser, horizon::mods::recipes}; /// A mod's linear memory cap. const MEMORY: usize = 64 << 20; @@ -87,8 +110,15 @@ const FUEL_INIT: u64 = 2_000_000_000; const FUEL_TICK: u64 = 50_000_000; const FUEL_FRAME: u64 = 10_000_000; const FUEL_EVENT: u64 = 100_000_000; +/// Blocks a mod may set per `world.set-blocks` call. +pub const BLOCKS_PER_CALL: usize = 4096; /// Chat lines a mod may show per call, HUD lines and their length. const CHAT_PER_CALL: usize = 8; +/// `command.run-quiet` lines one call of a mod may queue (a quiet payload's +/// cap, `horizon_protocol::quiet::MAX_LINES`). +const QUIET_PER_CALL: usize = 256; +/// How far `game.raycast` sees, in blocks. +pub const RAYCAST_MAX: f32 = 1024.0; const HUD_LINES: usize = 16; const LINE_CHARS: usize = 256; /// Total bytes a mod's `storage` may hold on disk, across all its keys. @@ -124,6 +154,27 @@ pub struct Snapshot { pub font_widths: Arc<[f32]>, /// The players on the server, for server mods. pub players: Vec, + /// The first block along the player's view within [`RAYCAST_MAX`] and + /// its distance from the eye, for `game.raycast`; the game works it out + /// only while a mod calls it ([`Mods::wants_raycast`]). + pub view_hit: Option<(f32, Hit)>, + /// Every item and recipe, for capability `recipes`; the game makes them + /// once, and only while a mod reads them ([`Mods::wants_recipes`]). + pub recipes: Option>, + /// The `book-id`s of the recipes the player's book holds. + pub known_recipes: Arc<[i32]>, + /// The open screen takes recipes (`recipes.place`). + pub placing: bool, + /// The player is in creative mode (`recipes.give`). + pub creative: bool, +} + +/// Capability `recipes`'s tables: `items` in the registry's order, which +/// each [`RecipeStack::item`] indexes. +#[derive(Clone, Debug, Default)] +pub struct Recipes { + pub items: Vec, + pub recipes: Vec, } /// Which mods a game starts: the window's game the client mods, the game @@ -154,6 +205,9 @@ pub enum Output { /// `command.run`: a vanilla command line, without its slash, to run as /// the player. Command { line: String }, + /// `command.run-quiet`: vanilla command lines to run as the player with + /// nothing in the chat (`horizon_protocol::quiet` on a server). + QuietCommands { mod_id: String, lines: Vec }, /// The mod was turned off: it trapped, overran or failed to start. Stopped { name: String, reason: String }, /// `players.tell`: a line after the mod's name, to the player with this id. @@ -170,6 +224,13 @@ pub enum Output { text: String, error: bool, }, + /// `world.set-blocks`: changes to make in `dimension`, in order, each + /// state checked by the [`WorldView`] lent for the call. + SetBlocks { + name: String, + dimension: String, + blocks: Vec, + }, /// `ui.open-screen`: the mod's entry in `entries()`; what it shows is /// [`Mods::screen`]. OpenScreen { owner: usize }, @@ -177,8 +238,34 @@ pub enum Output { CloseScreen { owner: usize }, /// `render.shake`: strength 0 to 1, fading out over `seconds` (≤ 10). Shake { strength: f32, seconds: f32 }, + /// `recipes.place`: the recipe book's click on this display id, all of + /// it when `all`. + PlaceRecipe { book_id: i32, all: bool }, + /// `recipes.give`: a stack for a creative player. + Give { + item: String, + count: u32, + components: String, + }, } +/// The game's world as capability `world` reads it during a call: the +/// game lends one with [`Mods::lend_world`] and takes it back after. +pub trait WorldView: std::any::Any + Send { + /// The block state at a position, `minecraft:oak_log[axis=y]`; `None` + /// where no chunk of that dimension is loaded. + fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option; + /// The biome at a position, `minecraft:plains`; `None` as for blocks. + fn biome(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option; + /// Whether `dimension` is one the server has. + fn has_dimension(&self, dimension: &str) -> bool; + /// `Err` (why) for a state string that names no block state. + fn check_state(&self, state: &str) -> Result<(), String>; +} + +/// The view lent for the current calls, shared by every mod's store. +type WorldSlot = Arc>>>; + /// A mod's text panel, drawn every frame until it changes. #[derive(Clone, Debug)] pub struct Panel { @@ -227,6 +314,10 @@ struct Running { /// server mod. ui: Option, hooks: Hooks, + /// It imports `game.raycast`. + raycasts: bool, + /// It imports capability `recipes`. + reads_recipes: bool, } /// A running mod's exports and the hooks its `init` asked for. @@ -247,10 +338,10 @@ impl Hooks { Hooks::Client(..) => None, } } - fn commands(&self) -> &[String] { + fn commands(&self) -> Vec<&str> { match self { - Hooks::Client(_, r) => &r.commands, - Hooks::Server(_, r) => &r.commands, + Hooks::Client(_, r) => r.commands.iter().map(String::as_str).collect(), + Hooks::Server(_, r) => r.commands.iter().map(|c| c.name.as_str()).collect(), } } } @@ -268,6 +359,46 @@ struct UiState { close: bool, } +/// Capability `ui`'s panel beside container screens (`browser`). +#[derive(Default)] +struct BrowserState { + items: Vec, + /// Which `set-items` or `set-recipes` call the panel is from, unique + /// across mods and reloads, so the game converts them once. + version: u64, + /// `set-recipes`' title and recipes, shown instead of the items. + recipes: Option, + events: std::collections::VecDeque, +} +/// What `browser.set-recipes` shows: a title, tabs (`tab` the selected +/// one) and the recipes. +#[derive(Clone, Debug)] +pub struct RecipePage { + pub title: String, + pub tabs: Vec, + pub tab: u32, + pub recipes: Vec, +} +static BROWSER_VERSION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); +/// Items a panel may hold, and events kept for `browser.poll`. +const BROWSER_ITEMS: usize = 8192; +/// `recipes.place` and `give` calls a hook call may make. +const RECIPE_ACTIONS: usize = 36; +/// Recipes `set-recipes` may show, slots in one, and stacks a slot cycles. +const BROWSER_RECIPES: usize = 256; +const RECIPE_SLOTS: usize = 9; +const RECIPE_TABS: usize = 16; +const SLOT_STACKS: usize = 64; +const BROWSER_EVENTS: usize = 256; +impl BrowserState { + fn push(&mut self, event: BrowserEvent) { + if self.events.len() == BROWSER_EVENTS { + self.events.pop_front(); + } + self.events.push_back(event); + } +} + struct State { name: String, id: String, @@ -284,6 +415,7 @@ struct State { /// Capability `render`'s minimap, when the mod shows one. minimap: Option, input: InputState, + browser: BrowserState, /// Capability `storage`'s folder; made on first `set`. data_dir: PathBuf, /// Bytes `storage::set` may still write before this hook call ends @@ -292,6 +424,7 @@ struct State { /// needs its own budget. storage_budget: u64, limits: StoreLimits, + world: WorldSlot, } /// The installed mods and the engine running them. `Mods::default()` is @@ -302,9 +435,40 @@ pub struct Mods { entries: Vec, snapshot: Arc, out: Vec, + world: WorldSlot, + /// Moves on whenever a mod starts or stops: the game resends the server + /// mods' commands to players when it changes. + generation: u64, } impl Mods { + /// Changes whenever the running mods (so their commands) change. + pub fn generation(&self) -> u64 { + self.generation + } + /// Whether a running mod may use capability `world`: only then is a + /// view worth lending. + pub fn wants_world(&self) -> bool { + self.entries.iter().any(|e| { + e.status == Status::Running + && e.manifest + .as_ref() + .is_some_and(|m| m.capabilities.contains(&crate::Capability::World)) + }) + } + /// Lends the game's world to capability `world` for the calls until + /// [`Mods::take_world`]; with none lent, `get-block` finds nothing and + /// `set-blocks` checks only its count. + pub fn lend_world(&mut self, view: Box) { + if let Ok(mut slot) = self.world.lock() { + *slot = Some(view); + } + } + /// The view [`Mods::lend_world`] lent, back to the game. + pub fn take_world(&mut self) -> Option> { + self.world.lock().ok()?.take() + } + /// Reads every mod at `paths` and starts those `enabled` says are on, /// client and server mods alike. A command that `reserved` (vanilla's /// commands) or an earlier mod already uses is refused. @@ -374,10 +538,14 @@ impl Mods { .map_err(|e| e.to_string())?; players::add_to_linker::>(&mut linker, |s| s) .map_err(|e| e.to_string())?; + mod_world::add_to_linker::>(&mut linker, |s| s) + .map_err(|e| e.to_string())?; UiHost::add_to_linker::>(&mut linker, |s| s) .map_err(|e| e.to_string())?; RenderHost::add_to_linker::>(&mut linker, |s| s) .map_err(|e| e.to_string())?; + RecipesHost::add_to_linker::>(&mut linker, |s| s) + .map_err(|e| e.to_string())?; self.engine = Some((engine, linker)); } Ok(self.engine.as_ref().expect("made above")) @@ -412,9 +580,11 @@ impl Mods { .iter() .filter_map(|e| e.run.as_ref()) .filter(|r| r.hooks.server().is_some() == server) - .flat_map(|r| r.hooks.commands().iter().cloned()) + .flat_map(|r| r.hooks.commands()) + .map(str::to_owned) .collect(); let snapshot = self.snapshot.clone(); + let world = self.world.clone(); let (engine, linker) = self.engine()?; let component = Component::new(engine, wasm).map_err(|e| format!("not a component: {e}"))?; @@ -447,12 +617,14 @@ impl Mods { zoom: None, minimap: None, input: InputState::default(), + browser: BrowserState::default(), data_dir, storage_budget: STORAGE_WRITE_BUDGET, limits: StoreLimitsBuilder::new() .memory_size(MEMORY) .instances(16) .build(), + world, }; let mut store = Store::new(engine, state); store.limiter(|s| &mut s.limits); @@ -478,19 +650,38 @@ impl Mods { .map_err(|e| reason(&e))??; (Hooks::Client(exports, r), ui) }; - let commands = match &mut hooks { - Hooks::Client(_, r) => &mut r.commands, - Hooks::Server(_, r) => &mut r.commands, - }; - commands.retain(|c| { - let free = !reserved(c) && !taken.contains(c); + let free = |c: &str| { + let free = !reserved(c) && !taken.iter().any(|t| t == c); if !free { log::warn!("Horizon: mod {} cannot take /{c}: already a command", m.id); } free - }); + }; + match &mut hooks { + Hooks::Client(_, r) => r.commands.retain(|c| free(c)), + Hooks::Server(_, r) => { + r.commands.retain(|c| free(&c.name)); + for c in &mut r.commands { + if let Err(e) = check_arguments(&c.arguments) { + log::warn!( + "Horizon: mod {}'s /{}: {e}; it takes free text", + m.id, + c.name + ); + c.arguments.clear(); + } + } + } + } + self.generation += 1; self.out.append(&mut store.data_mut().out); - Ok(Some(Running { store, ui, hooks })) + Ok(Some(Running { + store, + ui, + hooks, + raycasts: functions.iter().any(|f| f == "game.raycast"), + reads_recipes: functions.iter().any(|f| f.starts_with("recipes.")), + })) } /// True when at least one mod runs: the game skips its mod work otherwise. @@ -600,6 +791,7 @@ impl Mods { }); entry.status = Status::Failed(reason); entry.run = None; + self.generation += 1; None } } @@ -624,7 +816,7 @@ impl Mods { fn command_owner(&self, server: bool, name: &str) -> Option { self.entries.iter().position(|e| { e.run.as_ref().is_some_and(|r| { - r.hooks.server().is_some() == server && r.hooks.commands().iter().any(|c| c == name) + r.hooks.server().is_some() == server && r.hooks.commands().contains(&name) }) }) } @@ -657,7 +849,7 @@ impl Mods { .iter() .filter_map(|e| e.run.as_ref()) .filter(move |r| r.hooks.server().is_some() == server) - .flat_map(|r| r.hooks.commands().iter().map(String::as_str)) + .flat_map(|r| r.hooks.commands()) } /// A server tick. @@ -700,9 +892,13 @@ impl Mods { |m, s| m.call_block_placed(s, player, pos, state), ); } - /// The commands running server mods own, for the server's command tree. - pub fn server_commands(&self) -> impl Iterator { - self.owned_commands(true) + /// The commands running server mods own and their arguments, for the + /// server's command tree. + pub fn server_commands(&self) -> impl Iterator { + self.entries + .iter() + .filter_map(|e| e.run.as_ref()?.hooks.server()) + .flat_map(|r| r.commands.iter()) } /// Runs `line` (without its slash), typed by `player`, if a server mod /// owns its command; its feedback is an [`Output::Reply`]. False when @@ -712,18 +908,35 @@ impl Mods { let Some(i) = self.command_owner(true, name) else { return false; }; - let result = self.call(i, FUEL_EVENT, |run| match &run.hooks { - Hooks::Server(m, _) => { - m.horizon_mods_server_events() - .call_command(&mut run.store, player, name, args) - } - Hooks::Client(..) => Ok(Ok(None)), - }); let reply = |text, error| Output::Reply { player: player.id.clone(), text, error, }; + let arguments = self.entries[i] + .run + .as_ref() + .and_then(|r| r.hooks.server()) + .and_then(|r| r.commands.iter().find(|c| c.name == name)) + .map(|c| c.arguments.as_slice()) + .unwrap_or_default(); + let values = match crate::commands::parse(arguments, args, player, &self.snapshot.players) { + Ok(values) => values, + Err(e) => { + self.out.push(reply(e, true)); + return true; + } + }; + let result = self.call(i, FUEL_EVENT, |run| match &run.hooks { + Hooks::Server(m, _) => m.horizon_mods_server_events().call_command( + &mut run.store, + player, + name, + args, + &values, + ), + Hooks::Client(..) => Ok(Ok(None)), + }); match result { Some(Ok(Some(text))) => self.out.push(reply(text, false)), Some(Err(text)) => self.out.push(reply(text, true)), @@ -743,6 +956,65 @@ impl Mods { .iter() .filter_map(|e| e.run.as_ref()?.store.data().corner.as_ref()) } + /// Some running mod calls `game.raycast`: the snapshot needs a + /// [`Snapshot::view_hit`]. + pub fn wants_raycast(&self) -> bool { + self.entries + .iter() + .any(|e| e.run.as_ref().is_some_and(|r| r.raycasts)) + } + /// The panel beside container screens (`browser.set-items`): the first + /// running mod with items or recipes, its index, the panel's version and + /// the items. + pub fn browser_items(&self) -> Option<(usize, u64, &[BrowserStack])> { + self.entries.iter().enumerate().find_map(|(i, e)| { + let b = &e.run.as_ref()?.store.data().browser; + (!b.items.is_empty() || b.recipes.is_some()).then_some(( + i, + b.version, + b.items.as_slice(), + )) + }) + } + /// What mod `owner`'s panel shows instead of its items + /// (`browser.set-recipes`). + pub fn browser_recipes(&self, owner: usize) -> Option<&RecipePage> { + let b = &self.entries.get(owner)?.run.as_ref()?.store.data().browser; + b.recipes.as_ref() + } + /// The player did `event` on mod `owner`'s panel. + pub fn browser_event(&mut self, owner: usize, event: BrowserEvent) { + if let Some(run) = self.entries.get_mut(owner).and_then(|e| e.run.as_mut()) { + run.store.data_mut().browser.push(event); + } + } + /// The key `key` went down with the pointer on `stack` in a container + /// screen: each mod with a key on it hears its own name for it. + pub fn browser_key(&mut self, key: &str, stack: &BrowserStack) { + for run in self.entries.iter_mut().filter_map(|e| e.run.as_mut()) { + let data = run.store.data_mut(); + let names: Vec = data + .input + .keys + .iter() + .filter(|k| k.key == key) + .map(|k| k.name.clone()) + .collect(); + for key in names { + data.browser.push(BrowserEvent::Key(BrowserItemKey { + key, + stack: stack.clone(), + })); + } + } + } + /// Some running mod reads capability `recipes`: the snapshot needs + /// [`Snapshot::recipes`] and [`Snapshot::known_recipes`]. + pub fn wants_recipes(&self) -> bool { + self.entries + .iter() + .any(|e| e.run.as_ref().is_some_and(|r| r.reads_recipes)) + } /// Some running mod has a `frame` hook: the game refreshes the snapshot /// every frame for it. pub fn wants_frames(&self) -> bool { @@ -990,6 +1262,7 @@ impl Mods { continue; } any = true; + self.generation += 1; self.entries[i].modified = now; self.entries[i].run = None; let path = self.entries[i].path.clone(); @@ -1015,6 +1288,34 @@ impl Mods { } } +/// A command's arguments are well formed: names given and distinct, +/// optional ones last, free text only last. +fn check_arguments(arguments: &[Argument]) -> Result<(), String> { + for (i, a) in arguments.iter().enumerate() { + if a.name.is_empty() + || !a + .name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_') + { + return Err(format!("argument name '{}' isn't [A-Za-z0-9_]+", a.name)); + } + if arguments[..i].iter().any(|b| b.name == a.name) { + return Err(format!("two arguments are named {}", a.name)); + } + if i > 0 && arguments[i - 1].optional && !a.optional { + return Err(format!("{} is required after an optional argument", a.name)); + } + if a.kind == ArgumentKind::Text && i + 1 < arguments.len() { + return Err(format!( + "{} takes the rest of the line, so it must be last", + a.name + )); + } + } + Ok(()) +} + fn modified(path: &Path) -> Option { let meta = std::fs::metadata(path).ok()?; if meta.is_dir() { @@ -1038,7 +1339,10 @@ fn reason(e: &wasmtime::Error) -> String { } fn clip(text: String) -> String { - match text.char_indices().nth(LINE_CHARS) { + clip_to(text, LINE_CHARS) +} +fn clip_to(text: String, chars: usize) -> String { + match text.char_indices().nth(chars) { Some((at, _)) => text[..at].to_string(), None => text, } @@ -1093,6 +1397,130 @@ impl game::Host for State { fn get_clock(&mut self) -> Option { self.snapshot.clock } + fn raycast(&mut self, distance: f32) -> Option { + let (at, hit) = self.snapshot.view_hit.as_ref()?; + // NaN compares false: no hit. + (*at <= distance.min(RAYCAST_MAX) && !distance.is_nan()).then(|| hit.clone()) + } +} +impl browser::Host for State { + fn set_items(&mut self, items: Vec) { + self.browser.items = items + .into_iter() + .take(BROWSER_ITEMS) + .map(|s| BrowserStack { + item: clip(s.item), + components: clip_to(s.components, 4096), + ..s + }) + .collect(); + self.browser.version = BROWSER_VERSION.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + fn set_recipes( + &mut self, + title: String, + tabs: Vec, + tab: u32, + recipes: Vec, + ) { + let stack = |s: BrowserStack| BrowserStack { + item: clip(s.item), + components: clip_to(s.components, 4096), + ..s + }; + let cycle = |list: Vec| -> Vec { + list.into_iter().take(SLOT_STACKS).map(stack).collect() + }; + self.browser.recipes = (!recipes.is_empty()).then(|| { + let recipes = recipes + .into_iter() + .take(BROWSER_RECIPES) + .map(|r| BrowserRecipe { + width: r.width.clamp(1, 3), + height: r.height.clamp(1, 3), + slots: r.slots.into_iter().take(RECIPE_SLOTS).map(cycle).collect(), + results: cycle(r.results), + note: clip(r.note), + ..r + }) + .collect(); + RecipePage { + title: clip(title), + tabs: tabs.into_iter().take(RECIPE_TABS).map(stack).collect(), + tab, + recipes, + } + }); + self.browser.version = BROWSER_VERSION.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + fn poll(&mut self) -> Vec { + self.browser.events.drain(..).collect() + } +} +impl recipes::Host for State { + fn items(&mut self) -> Vec { + self.snapshot + .recipes + .as_ref() + .map_or_else(Vec::new, |r| r.items.clone()) + } + fn all(&mut self) -> Vec { + self.snapshot + .recipes + .as_ref() + .map_or_else(Vec::new, |r| r.recipes.clone()) + } + fn known(&mut self) -> Vec { + self.snapshot.known_recipes.to_vec() + } + fn place(&mut self, book_id: i32, all: bool) -> Result<(), String> { + self.recipe_action()?; + if !self.snapshot.placing { + return Err("no screen that takes recipes is open".into()); + } + if !self.snapshot.known_recipes.contains(&book_id) { + return Err(format!( + "recipe {book_id} is not in the player's recipe book" + )); + } + self.out.push(Output::PlaceRecipe { book_id, all }); + Ok(()) + } + fn give(&mut self, stack: RecipeStack) -> Result<(), String> { + self.recipe_action()?; + if !self.snapshot.creative { + return Err("only in creative mode".into()); + } + let item = self + .snapshot + .recipes + .as_ref() + .and_then(|r| r.items.get(stack.item as usize)) + .ok_or_else(|| format!("no item {}", stack.item))? + .id + .clone(); + self.out.push(Output::Give { + item, + count: stack.count.clamp(1, 99), + components: clip_to(stack.components, 4096), + }); + Ok(()) + } +} +impl State { + /// `recipes.place` and `give` take at most [`RECIPE_ACTIONS`] a call. + fn recipe_action(&self) -> Result<(), String> { + let done = self + .out + .iter() + .filter(|o| matches!(o, Output::PlaceRecipe { .. } | Output::Give { .. })) + .count(); + if done < RECIPE_ACTIONS { + Ok(()) + } else { + Err(format!("at most {RECIPE_ACTIONS} places and gives a call")) + } + } } impl State { /// Queues a chat line unless the call already sent [`CHAT_PER_CALL`]. @@ -1122,6 +1550,40 @@ impl chat::Host for State { }); } } +impl mod_world::Host for State { + fn get_block(&mut self, dimension: String, x: i32, y: i32, z: i32) -> Option { + let view = self.world.lock().ok()?; + view.as_ref()?.block(&dimension, x, y, z) + } + fn get_biome(&mut self, dimension: String, x: i32, y: i32, z: i32) -> Option { + let view = self.world.lock().ok()?; + view.as_ref()?.biome(&dimension, x, y, z) + } + fn set_blocks(&mut self, dimension: String, blocks: Vec) -> Result<(), String> { + if blocks.len() > BLOCKS_PER_CALL { + return Err(format!( + "{} blocks: at most {BLOCKS_PER_CALL} per call", + blocks.len() + )); + } + if let Some(view) = self.world.lock().ok().as_ref().and_then(|v| v.as_ref()) { + if !view.has_dimension(&dimension) { + return Err(format!("no dimension {dimension}")); + } + for b in &blocks { + view.check_state(&b.state)?; + } + } + if !blocks.is_empty() { + self.out.push(Output::SetBlocks { + name: self.name.clone(), + dimension, + blocks, + }); + } + Ok(()) + } +} impl players::Host for State { fn online(&mut self) -> Vec { self.snapshot.players.clone() @@ -1383,6 +1845,23 @@ impl command::Host for State { self.out.push(Output::Command { line: clip(line) }); } } + fn run_quiet(&mut self, lines: Vec) { + let queued: usize = self + .out + .iter() + .map(|o| match o { + Output::QuietCommands { lines, .. } => lines.len(), + _ => 0, + }) + .sum(); + let room = QUIET_PER_CALL.saturating_sub(queued); + if room > 0 && !lines.is_empty() { + self.out.push(Output::QuietCommands { + mod_id: self.id.clone(), + lines: lines.into_iter().take(room).map(clip).collect(), + }); + } + } } impl hud::Host for State { fn set_panel(&mut self, corner: Corner, lines: Vec) { diff --git a/crates/horizon-mods/src/testing.rs b/crates/horizon-mods/src/testing.rs index 3a7422377..0fe821074 100644 --- a/crates/horizon-mods/src/testing.rs +++ b/crates/horizon-mods/src/testing.rs @@ -29,6 +29,54 @@ pub struct TestGame { /// Every name that joined, for their id. names: Vec, tick: u64, + /// Capability `world`'s Overworld: the blocks a script set or the mod + /// changed; every other block, and the other dimensions, are air. Every + /// biome is the dimension's plainest: plains, nether wastes, the end. + pub world: std::collections::BTreeMap<(i32, i32, i32), String>, +} + +/// The world a script's mod reads: [`TestGame::world`], copied for a step. +struct ScriptWorld(std::collections::BTreeMap<(i32, i32, i32), String>); + +impl crate::WorldView for ScriptWorld { + fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option { + let here = (dimension == "minecraft:overworld") + .then(|| self.0.get(&(x, y, z)).cloned()) + .flatten(); + Some(here.unwrap_or_else(|| "minecraft:air".into())) + } + fn biome(&self, dimension: &str, _x: i32, _y: i32, _z: i32) -> Option { + let biome = match dimension { + "minecraft:overworld" => "minecraft:plains", + "minecraft:the_nether" => "minecraft:nether_wastes", + "minecraft:the_end" => "minecraft:the_end", + _ => return None, + }; + Some(biome.into()) + } + fn has_dimension(&self, dimension: &str) -> bool { + matches!( + dimension, + "minecraft:overworld" | "minecraft:the_nether" | "minecraft:the_end" + ) + } + fn check_state(&self, state: &str) -> Result<(), String> { + // No registry here: the shape only (the game checks the names). + let name = state.split('[').next().unwrap_or_default(); + let plain = |t: &str| { + !t.is_empty() + && t.bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_.-/".contains(&b)) + }; + let ok = match name.split_once(':') { + Some((ns, path)) => plain(ns) && plain(path), + None => plain(name), + }; + let closed = !state.contains('[') || state.ends_with(']'); + (ok && closed) + .then_some(()) + .ok_or_else(|| format!("{state} is not a block state")) + } } /// Where a script starts: standing at 0.5 64 0.5 in the Overworld, facing @@ -71,6 +119,7 @@ impl TestGame { players: Vec::new(), names: Vec::new(), tick: 0, + world: Default::default(), }; copy_mod(hmod, ©)?; game.start()?; @@ -204,7 +253,7 @@ impl TestGame { } /// The commands the mod registered. pub fn commands(&self) -> Vec { - let server = self.mods.server_commands(); + let server = self.mods.server_commands().map(|c| c.name.as_str()); self.mods .commands() .chain(server) @@ -312,9 +361,10 @@ pub struct ClockSet { } /// One step. Its parts happen in this order: `reload`, `title-screen`, -/// `join`, `player`, `clock`, `ticks`, `frames`, `chat`, `command`, `break`, -/// `place`, `leave`; then `expect` is checked against what the mod showed -/// during the step. For a server mod, `player`, `chat`, `command`, `break` +/// `blocks`, `join`, `player`, `clock`, `ticks`, `frames`, `chat`, `command`, +/// `break`, `place`, `leave`; then the blocks the mod set are made, and +/// `expect` is checked against what the mod showed and changed during the +/// step. For a server mod, `player`, `chat`, `command`, `break` /// and `place` are the doing of the player named by `as`, or of the first /// player on. #[derive(Debug, Default, Deserialize)] @@ -341,6 +391,10 @@ pub struct Step { #[serde(rename = "break")] broken: Option, place: Option, + /// Blocks of the Overworld before the rest of the step (capability + /// `world`); every other block is air. + #[serde(default)] + blocks: Vec, #[serde(default)] expect: Expect, } @@ -363,6 +417,9 @@ pub struct Expect { /// The panel's lines (`[]`: no panel) and its corner. panel: Option>, corner: Option, + /// Blocks of the Overworld after the step, the mod's changes made + /// (capability `world`). + blocks: Option>, /// The mod is turned off during this step, for a reason holding this text. /// Without it, a mod that stops fails the test. stopped: Option, @@ -467,6 +524,11 @@ impl Step { game.player = None; game.clock = None; } + for b in &self.blocks { + game.world.insert((b.x, b.y, b.z), b.state.clone()); + } + game.mods + .lend_world(Box::new(ScriptWorld(game.world.clone()))); if let Some(name) = &self.join { game.join(name); } @@ -531,7 +593,19 @@ impl Step { { return Err(format!("{name} is not on the server")); } + game.mods.take_world(); let out = game.drain(); + for o in &out { + if let Output::SetBlocks { + dimension, blocks, .. + } = o + && dimension == "minecraft:overworld" + { + for b in blocks { + game.world.insert((b.x, b.y, b.z), b.state.clone()); + } + } + } let stopped = out.iter().find_map(|o| match o { Output::Stopped { reason, .. } => Some(reason.as_str()), _ => None, @@ -615,6 +689,18 @@ impl Step { .unwrap_or_default(); same("panel", want, &got)?; } + if let Some(want) = &e.blocks { + for b in want { + let got = game.world.get(&(b.x, b.y, b.z)); + let got = got.map_or("minecraft:air", String::as_str); + if got != b.state { + return Err(format!( + "block at {} {} {}: expected {}, got {got}", + b.x, b.y, b.z, b.state + )); + } + } + } if let Some(want) = &e.corner { let got = game.panel().map(|p| corner_name(p.corner).to_string()); same("corner", &Some(want.clone()), &got)?; diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index c04de3204..5ca3faf77 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -2,8 +2,8 @@ //! examples and a guest //! that misbehaves on command. Needs `rustup target add wasm32-unknown-unknown`. use horizon_mods::{ - BlockPos, Clock, Corner, GameMode, HeldItem, Mods, Output, Package, Player, Runs, ServerPlayer, - Shape, Snapshot, Status, + BlockPos, Clock, Corner, GameMode, HeldItem, Hit, Mods, Output, Package, Player, Runs, + ServerPlayer, Shape, Snapshot, Status, manifest::componentize, testing::{Script, TestGame}, }; @@ -26,8 +26,8 @@ id = "test_ui_guest" name = "Test UI Guest" version = "0.1.0" api = "0.1" -capabilities = ["chat", "ui", "render", "input"] -experimental = ["ui", "render", "input"] +capabilities = ["game-read", "chat", "command", "ui", "render", "input", "recipes"] +experimental = ["ui", "render", "input", "recipes"] "#; /// Builds the mods once and writes their `.hmod` files; returns the folder. @@ -47,6 +47,8 @@ fn mods_dir() -> &'static Path { "-p", "welcome", "-p", + "beacons", + "-p", "horizon-mods-test-guest", "-p", "horizon-mods-test-ui-guest", @@ -70,6 +72,7 @@ fn mods_dir() -> &'static Path { ("coords_hud", example("coords-hud")), ("predator_missile", example("predator-missile")), ("welcome", example("welcome")), + ("beacons", example("beacons")), ("horizon_mods_test_guest", GUEST_MANIFEST.to_string()), ("horizon_mods_test_ui_guest", UI_MANIFEST.to_string()), ]; @@ -202,7 +205,7 @@ fn undeclared_capabilities_are_refused() { /// from the functions they import. #[test] fn a_mod_for_a_newer_horizon_is_refused() { - use horizon_mods::api_level::{LEVEL, imports, needed}; + use horizon_mods::api_level::{imports, needed}; use wit_parser::{ManglingAndAbi, Resolve}; let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); let wit = std::fs::read_to_string(root.join("crates/horizon-mod-sdk/wit/horizon.wit")) @@ -238,8 +241,8 @@ id = "too_new" name = "Too New" version = "0.1.0" api = "0.1" -capabilities = ["game-read", "chat", "hud", "storage", "command", "ui", "render", "input"] -experimental = ["ui", "render", "input"] +capabilities = ["game-read", "chat", "hud", "storage", "command", "ui", "render", "input", "recipes"] +experimental = ["ui", "render", "input", "recipes"] "#; std::fs::write(dir.join("horizon-mod.toml"), manifest).unwrap(); std::fs::write(dir.join("mod.wasm"), wasm).unwrap(); @@ -252,8 +255,8 @@ experimental = ["ui", "render", "input"] needed(imports(&wasm).unwrap().iter().map(String::as_str)).0 }; assert_eq!(level("coords_hud.hmod"), 0); - // The UI guest shows a minimap (`render.set-minimap`). - assert_eq!(level("horizon_mods_test_ui_guest.hmod"), LEVEL); + // The UI guest fills a browser panel (`browser`, level 6). + assert_eq!(level("horizon_mods_test_ui_guest.hmod"), 6); } #[test] @@ -722,6 +725,73 @@ fn render_minimap_is_clamped_and_hidden() { assert_eq!(map(&mut mods, "off"), None); } +/// `game.raycast`: the view's hit the game worked out, up to the distance +/// asked for; the game works it out only while a mod imports the call. +#[test] +fn game_raycast_sees_the_view_hit_within_its_distance() { + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + assert!(mods.wants_raycast()); + assert!(!load("coords_hud.hmod").wants_raycast()); + let said = |mods: &mut Mods, args: &str| -> Vec { + assert!(mods.command(&format!("raycast {args}"))); + mods.drain() + .into_iter() + .filter_map(|o| match o { + Output::Chat { text, .. } => Some(text), + _ => None, + }) + .collect() + }; + assert_eq!(said(&mut mods, "100"), ["no hit"]); + mods.set_snapshot(Snapshot { + view_hit: Some(( + 40.5, + Hit { + block_x: 12, + block_y: 63, + block_z: -44, + x: 12.5, + y: 64.0, + z: -43.75, + block: "minecraft:grass_block".into(), + }, + )), + ..player() + }); + let hit = "hit minecraft:grass_block at 12 63 -44 (12.5 64.0 -43.8)"; + assert_eq!(said(&mut mods, "100"), [hit]); + assert_eq!(said(&mut mods, "40"), ["no hit"]); + // NaN asks for nothing; past 1024 is 1024. + assert_eq!(said(&mut mods, "x"), ["no hit"]); + assert_eq!(said(&mut mods, "1e9"), [hit]); +} + +#[test] +fn quiet_commands_come_out_as_one_batch_capped() { + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + let quiet = |mods: &mut Mods, command: &str| -> Vec<(String, Vec)> { + assert!(mods.command(command)); + mods.drain() + .into_iter() + .filter_map(|o| match o { + Output::QuietCommands { mod_id, lines } => Some((mod_id, lines)), + _ => None, + }) + .collect() + }; + assert_eq!( + quiet(&mut mods, "quiet setblock 0 0 0 stone;say hi"), + [( + "test_ui_guest".to_string(), + vec!["setblock 0 0 0 stone".to_string(), "say hi".to_string()] + )] + ); + let batches = quiet(&mut mods, "quiet_many 300"); + assert_eq!(batches.len(), 1); + assert_eq!(batches[0].1.len(), 256); + assert_eq!(batches[0].1[255], "setblock 255 300 0 stone"); +} + #[test] fn corner_panels_text_width_and_readings() { let mut mods = load("horizon_mods_test_ui_guest.hmod"); @@ -799,7 +869,12 @@ capabilities = ["registries"] fn the_examples_test_scripts_pass() { let examples = Path::new(env!("CARGO_MANIFEST_DIR")).join("../horizon-mod-sdk/examples"); let mut ran = 0; - for (example, hmod) in [("coords-hud", "coords_hud"), ("welcome", "welcome")] { + let examples_and_files = [ + ("coords-hud", "coords_hud"), + ("welcome", "welcome"), + ("beacons", "beacons"), + ]; + for (example, hmod) in examples_and_files { for entry in std::fs::read_dir(examples.join(example).join("tests")).unwrap() { let path = entry.unwrap().path(); let script = Script::parse(&std::fs::read_to_string(&path).unwrap()).unwrap(); @@ -810,7 +885,24 @@ fn the_examples_test_scripts_pass() { ran += 1; } } - assert_eq!(ran, 4); + assert_eq!(ran, 5); +} + +/// Capability `world` without a world lent (the registry's trial run): +/// `get-block` finds nothing, `set-blocks` checks its count and queues. +#[test] +fn a_server_mod_without_a_world_reads_nothing() { + let mut game = TestGame::load(&mods_dir().join("beacons.hmod")).unwrap(); + game.join("Alex"); + let alex = game.players[0].clone(); + assert!(game.player_command(&alex, "ground")); + let out = game.drain(); + assert!( + out.iter() + .any(|o| matches!(o, Output::Reply { text, error: true, .. } + if text == "That block isn't loaded")), + "{out:?}" + ); } #[test] @@ -907,10 +999,12 @@ fn a_server_mod_runs_only_where_the_world_does() { let mut mods = Mods::load_for(Runs::Server, paths, |_| true, |c| c == "give"); assert!(mods.runs_server()); - assert_eq!( - mods.server_commands().collect::>(), - ["online", "mined"] - ); + let commands: Vec<_> = mods.server_commands().map(|c| c.name.as_str()).collect(); + assert_eq!(commands, ["online", "mined"]); + // `/mined [player]`: its argument travels with it, for the command tree. + let mined = mods.server_commands().nth(1).unwrap(); + assert_eq!(mined.arguments[0].kind, horizon_mods::ArgumentKind::Player); + assert!(mined.arguments[0].optional); assert_eq!(mods.commands().count(), 0, "not the window's chat commands"); let alex = alex(); mods.set_snapshot(Snapshot { @@ -949,3 +1043,247 @@ fn a_server_mod_runs_only_where_the_world_does() { "a server command isn't the window's" ); } + +/// Capability `recipes`: the guest reads tables as big as vanilla's (1,500 +/// items, 1,600 recipes of nine five-item slots) within one command's fuel. +#[test] +fn recipes_reads_the_tables() { + use horizon_mods::{Recipe, RecipeItem, RecipeKind, RecipeStack, Recipes}; + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + let stack = |item| RecipeStack { + item, + count: 1, + components: String::new(), + }; + let items = (0..1500) + .map(|i| RecipeItem { + id: format!("minecraft:item_{i}"), + name: format!("Item {i}"), + tags: vec!["planks".into(), "logs".into()], + }) + .collect(); + let mut recipes: Vec = (0..1600) + .map(|i| Recipe { + id: format!("minecraft:recipe_{i}"), + kind: RecipeKind::CraftingShaped, + category: "crafting_misc".into(), + group: String::new(), + width: 3, + height: 3, + slots: (0..9) + .map(|k| (0..5).map(|j| stack((i + k + j) % 1500)).collect()) + .collect(), + results: vec![RecipeStack { + item: 7, + count: 4, + components: String::new(), + }], + cooking_time: 0, + experience: 0.0, + book_id: i as i32, + }) + .collect(); + recipes[1].kind = RecipeKind::Brewing; + recipes[1].results[0].components = + "[minecraft:potion_contents={potion:\"minecraft:swiftness\"}]".into(); + let mods_recipes = Some(std::sync::Arc::new(Recipes { items, recipes })); + mods.set_snapshot(Snapshot { + recipes: mods_recipes.clone(), + known_recipes: vec![1, 5, 9].into(), + ..Snapshot::default() + }); + let said = |mods: &mut Mods, command: &str| { + assert!(mods.command(command)); + mods.drain() + .into_iter() + .filter_map(|o| match o { + Output::Chat { text, .. } => Some(text), + _ => None, + }) + .collect::>() + }; + assert_eq!( + said(&mut mods, "recipes"), + ["1500 items, 1600 recipes, 3 known, 1 brewing"] + ); + assert_eq!( + said(&mut mods, "recipes minecraft:recipe_1"), + [ + "minecraft:recipe_1 Kind::Brewing 3x3 0t slots 9, the first 1 minecraft:item_1 -> \ + 4 minecraft:item_7[minecraft:potion_contents={potion:\"minecraft:swiftness\"}] known true" + ] + ); + assert!( + mods.entries() + .iter() + .all(|e| e.status == horizon_mods::Status::Running), + "it ran out of fuel" + ); + // Actions: refused without a crafting screen, for an unknown recipe, + // and outside creative mode. + assert_eq!( + said(&mut mods, "recipe_place minecraft:recipe_5"), + ["place minecraft:recipe_5: no screen that takes recipes is open"] + ); + let mut snap = Snapshot { + recipes: mods_recipes.clone(), + known_recipes: vec![1, 5, 9].into(), + placing: true, + ..Snapshot::default() + }; + mods.set_snapshot(snap.clone()); + assert_eq!( + said(&mut mods, "recipe_place minecraft:recipe_6"), + ["place minecraft:recipe_6: recipe 6 is not in the player's recipe book"] + ); + assert!(mods.command("recipe_place minecraft:recipe_5 all")); + assert_eq!( + mods.drain()[0], + Output::PlaceRecipe { + book_id: 5, + all: true + } + ); + assert_eq!( + said(&mut mods, "recipe_give minecraft:item_7 3"), + ["give minecraft:item_7: only in creative mode"] + ); + snap.creative = true; + mods.set_snapshot(snap); + assert!(mods.command("recipe_give minecraft:item_7 3")); + assert_eq!( + mods.drain()[0], + Output::Give { + item: "minecraft:item_7".into(), + count: 3, + components: String::new() + } + ); + // Without the game's tables (no mod read them yet): empty, not a trap. + mods.set_snapshot(Snapshot::default()); + assert_eq!( + said(&mut mods, "recipes"), + ["0 items, 0 recipes, 0 known, 0 brewing"] + ); +} + +#[test] +fn browser_lists_items_and_hears_the_player() { + use horizon_mods::{BrowserClick, BrowserEvent, BrowserStack}; + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + let said = |mods: &mut Mods, command: &str| { + assert!(mods.command(command)); + mods.drain() + .into_iter() + .filter_map(|o| match o { + Output::Chat { text, .. } => Some(text), + _ => None, + }) + .collect::>() + }; + assert!(mods.browser_items().is_none()); + let potion = "[minecraft:potion_contents={potion:\"minecraft:swiftness\"}]"; + assert_eq!( + said( + &mut mods, + &format!("browser minecraft:stone minecraft:potion{potion}") + ), + ["panel of 2"] + ); + let (owner, version, items) = mods.browser_items().unwrap(); + assert_eq!( + (items[0].item.as_str(), items[1].components.as_str()), + ("minecraft:stone", potion) + ); + mods.browser_event( + owner, + BrowserEvent::Clicked(BrowserClick { + index: 1, + right: true, + }), + ); + mods.browser_event(owner, BrowserEvent::Search("oak".into())); + let log = BrowserStack { + item: "minecraft:oak_log".into(), + count: 3, + components: String::new(), + }; + // R is the guest's `recipe`; X is none of its keys. + mods.browser_key("key.keyboard.r", &log); + mods.browser_key("key.keyboard.x", &log); + assert_eq!( + said(&mut mods, "browser_poll"), + [ + "3 events", + "clicked 1 right", + "search \"oak\"", + "key recipe on minecraft:oak_log x3" + ] + ); + // Each `set-items` is a new version; an empty list hides the panel. + said(&mut mods, "browser minecraft:dirt"); + assert_ne!(mods.browser_items().unwrap().1, version); + assert_eq!(said(&mut mods, "browser"), ["panel of 0"]); + assert!(mods.browser_items().is_none()); + // Recipes in the panel's place: the guest shows those making planks. + use horizon_mods::{BrowserLayout, Recipe, RecipeItem, RecipeKind, RecipeStack, Recipes}; + let item = |id: &str| RecipeItem { + id: id.into(), + name: id.into(), + tags: Vec::new(), + }; + let stack = |item| RecipeStack { + item, + count: 1, + components: String::new(), + }; + mods.set_snapshot(Snapshot { + recipes: Some(std::sync::Arc::new(Recipes { + items: vec![item("minecraft:oak_log"), item("minecraft:oak_planks")], + recipes: vec![Recipe { + id: "minecraft:oak_planks".into(), + kind: RecipeKind::CraftingShapeless, + category: "building".into(), + group: "planks".into(), + width: 0, + height: 0, + slots: vec![vec![stack(0)]], + results: vec![RecipeStack { + count: 4, + ..stack(1) + }], + cooking_time: 0, + experience: 0.0, + book_id: 1, + }], + })), + ..Snapshot::default() + }); + said(&mut mods, "browser minecraft:dirt"); + assert_eq!( + said(&mut mods, "browser_recipes minecraft:oak_planks"), + ["recipes shown: 1"] + ); + let page = mods.browser_recipes(owner).unwrap(); + assert_eq!(page.title, "Recipes for minecraft:oak_planks"); + assert_eq!( + (page.tabs[0].item.as_str(), page.tab), + ("minecraft:crafting_table", 0) + ); + let r = &page.recipes[0]; + assert_eq!( + (r.layout, r.width, r.height, r.action), + (BrowserLayout::Grid, 1, 1, Some(false)) + ); + assert_eq!( + (r.slots[0][0].item.as_str(), r.results[0].count), + ("minecraft:oak_log", 4) + ); + assert_eq!(said(&mut mods, "browser_recipes"), ["recipes shown: 0"]); + assert!(mods.browser_recipes(owner).is_none()); + // At most 256 events wait for a poll: the oldest go. + for _ in 0..300 { + mods.browser_event(owner, BrowserEvent::Page(1)); + } + assert_eq!(said(&mut mods, "browser_poll")[0], "256 events"); +} diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index 3d4c66076..7a69346ab 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -4,10 +4,21 @@ //! `/render_hud`, `/render_clear` and `/render_shake` test `render`; //! `/input_claim`, `/input_poll`, `/input_held` and `/input_wheel` test //! `input`; `/zoom FACTOR SMOOTH TURN` tests `render.set-zoom`; -//! `/corner` and `/readings` the calls the official extras mods use. +//! `/corner` and `/readings` the calls the official extras mods use; +//! `/raycast DISTANCE` says what `game.raycast` sees; `/quiet A;B` runs +//! lines with `command.run-quiet` (`/quiet_many N`: N of them). `/recipes` +//! counts what `recipes` reads; `/recipes ID` describes that recipe. +//! `/browser ID...` fills `browser`'s panel (`/browser N`: the first N +//! items, `/browser` alone empties it) and registers the keys `recipe` (R) +//! and `uses` (U); `/browser_poll` says what the player did on it; +//! `/browser_recipes ID` shows the recipes making ID (`/browser_recipes` +//! alone: the items again). `/recipe_place ID [all]` places that recipe +//! with `recipes.place`; `/recipe_give ITEM [COUNT]` gives with +//! `recipes.give`. use horizon_mod_sdk::{ - Mod, Registration, chat, + Mod, Registration, browser, chat, command, game, input::{self, Event}, + recipes, render::{self, FillShape, ItemShape, Point, QuadShape, Rect, Shape, SpriteShape, TextShape}, ui::{self, ItemWidget, ListWidget, Screen, TextWidget, Widget}, }; @@ -60,7 +71,11 @@ fn shapes() -> Vec { ] } -struct Guest; +struct Guest { + /// `/recipe_place ID [all] later`: placed on the first tick a crafting + /// screen is open. + pending: Option<(i32, bool, String)>, +} fn widgets() -> Vec { vec![ @@ -97,12 +112,22 @@ impl Mod for Guest { "input_wheel", "zoom", "minimap", + "raycast", + "quiet", + "quiet_many", + "recipes", + "browser", + "browser_poll", + "browser_recipes", + "recipe_place", + "recipe_give", "corner", "readings", ] .into_iter() - .fold(Registration::new(), Registration::command); - Ok((Guest, hooks)) + .fold(Registration::new(), Registration::command) + .on_tick(); + Ok((Guest { pending: None }, hooks)) } fn command(&mut self, name: &str, args: &str) -> Result, String> { match name { @@ -217,6 +242,222 @@ impl Mod for Guest { }); render::set_minimap(map); } + "quiet" => command::run_quiet(&args.split(';').map(str::to_owned).collect::>()), + "quiet_many" => { + let n: usize = args.parse().unwrap_or(0); + command::run_quiet( + &(0..n) + .map(|i| format!("setblock {i} 300 0 stone")) + .collect::>(), + ); + } + "raycast" => { + let distance = args.parse().unwrap_or(f32::NAN); + chat::show(&match game::raycast(distance) { + Some(h) => format!( + "hit {} at {} {} {} ({:.1} {:.1} {:.1})", + h.block, h.block_x, h.block_y, h.block_z, h.x, h.y, h.z + ), + None => "no hit".into(), + }); + } + "recipes" => { + let items = recipes::items(); + let all = recipes::all(); + let known = recipes::known(); + let name = |s: &recipes::Stack| { + let id = items.get(s.item as usize).map_or("?", |i| i.id.as_str()); + format!("{} {id}{}", s.count, s.components) + }; + chat::show(&match all.iter().find(|r| r.id == args) { + Some(r) => format!( + "{} {:?} {}x{} {}t slots {}, the first {} -> {} known {}", + r.id, + r.kind, + r.width, + r.height, + r.cooking_time, + r.slots.len(), + r.slots + .first() + .and_then(|s| s.first()) + .map_or("-".into(), name), + r.results.first().map_or("-".into(), name), + known.contains(&r.book_id) + ), + None => format!( + "{} items, {} recipes, {} known, {} brewing", + items.len(), + all.len(), + known.len(), + all.iter() + .filter(|r| r.kind == recipes::Kind::Brewing) + .count() + ), + }); + } + "browser" => { + let stack = |item: &str| { + let (item, components) = match item.find('[') { + Some(at) => (&item[..at], &item[at..]), + None => (item, ""), + }; + browser::Stack { + item: item.into(), + count: 1, + components: components.into(), + } + }; + let items: Vec = match args.parse::() { + Ok(n) => recipes::items() + .iter() + .skip(1) + .take(n) + .map(|i| stack(&i.id)) + .collect(), + Err(_) => args.split_whitespace().map(stack).collect(), + }; + browser::set_items(&items); + input::register_key("recipe", "Show recipes", "key.keyboard.r")?; + input::register_key("uses", "Show uses", "key.keyboard.u")?; + chat::show(&format!("panel of {}", items.len())); + } + "browser_recipes" => { + let items = recipes::items(); + let id = |i: u32| { + items + .get(i as usize) + .map_or(String::new(), |x| x.id.clone()) + }; + let stack = |s: &recipes::Stack| browser::Stack { + item: id(s.item), + count: s.count, + components: s.components.clone(), + }; + let views: Vec = recipes::all() + .iter() + .filter(|r| !args.is_empty() && r.results.iter().any(|s| id(s.item) == args)) + .map(|r| { + use recipes::Kind; + let crafting = + matches!(r.kind, Kind::CraftingShaped | Kind::CraftingShapeless); + let shapeless = (r.slots.len() as u32).clamp(1, 3); + browser::RecipeView { + layout: match r.kind { + Kind::CraftingShaped | Kind::CraftingShapeless => { + browser::Layout::Grid + } + Kind::Stonecutting => browser::Layout::Single, + Kind::Smithing => browser::Layout::Smithing, + Kind::Brewing => browser::Layout::Brewing, + _ => browser::Layout::Cooking, + }, + width: if r.width == 0 { shapeless } else { r.width }, + height: if r.height == 0 { + (r.slots.len() as u32).div_ceil(3).max(1) + } else { + r.height + }, + slots: r + .slots + .iter() + .map(|s| s.iter().map(stack).collect()) + .collect(), + results: r.results.iter().map(stack).collect(), + note: if r.cooking_time > 0 { + format!("{} ticks", r.cooking_time) + } else { + String::new() + }, + action: crafting.then_some(r.kind == Kind::CraftingShaped), + } + }) + .collect(); + // A tab per layout shown, the first selected. + let mut tabs: Vec = Vec::new(); + for v in &views { + let icon = match v.layout { + browser::Layout::Grid => "minecraft:crafting_table", + browser::Layout::Cooking => "minecraft:furnace", + browser::Layout::Single => "minecraft:stonecutter", + browser::Layout::Smithing => "minecraft:smithing_table", + browser::Layout::Brewing => "minecraft:brewing_stand", + }; + if !tabs.iter().any(|t| t.item == icon) { + tabs.push(browser::Stack { + item: icon.into(), + count: 1, + components: String::new(), + }); + } + } + browser::set_recipes(&format!("Recipes for {args}"), &tabs, 0, &views); + chat::show(&format!("recipes shown: {}", views.len())); + } + "recipe_place" => { + let mut words = args.split_whitespace(); + let id = words.next().unwrap_or_default(); + let rest: Vec<&str> = words.collect(); + let all = rest.contains(&"all"); + let book = recipes::all() + .iter() + .find(|r| r.id == id) + .map(|r| r.book_id); + if let Some(b) = book.filter(|_| rest.contains(&"later")) { + self.pending = Some((b, all, id.to_owned())); + chat::show(&format!("place {id}: waiting")); + return Ok(None); + } + chat::show(&match book.map(|b| recipes::place(b, all)) { + Some(Ok(())) => format!("place {id}: ok"), + Some(Err(e)) => format!("place {id}: {e}"), + None => format!("place {id}: no such recipe"), + }); + } + "recipe_give" => { + let mut words = args.split_whitespace(); + let id = words.next().unwrap_or_default(); + let count = words.next().and_then(|c| c.parse().ok()).unwrap_or(1); + let item = recipes::items().iter().position(|i| i.id == id); + let result = item.map(|i| { + recipes::give(&recipes::Stack { + item: i as u32, + count, + components: String::new(), + }) + }); + chat::show(&match result { + Some(Ok(())) => format!("give {id}: ok"), + Some(Err(e)) => format!("give {id}: {e}"), + None => format!("give {id}: no such item"), + }); + } + "browser_poll" => { + let stack = |s: &browser::Stack| format!("{} x{}{}", s.item, s.count, s.components); + // A hook shows at most 8 chat lines: the count, then the first 7. + let events = browser::poll(); + chat::show(&format!("{} events", events.len())); + for event in events.into_iter().take(7) { + chat::show(&match event { + browser::Event::Clicked(c) => { + format!( + "clicked {} {}", + c.index, + if c.right { "right" } else { "left" } + ) + } + browser::Event::Search(text) => format!("search {text:?}"), + browser::Event::Key(k) => format!("key {} on {}", k.key, stack(&k.stack)), + browser::Event::SlotClicked(c) => { + format!("slot {} {} {}", c.recipe, c.slot, stack(&c.stack)) + } + browser::Event::Action(i) => format!("action {i}"), + browser::Event::Page(first) => format!("page {first}"), + browser::Event::Back => "back".into(), + browser::Event::Tab(i) => format!("tab {i}"), + }); + } + } // Clamped to (1, 10); the two after it shake nothing. "render_shake" => { render::shake(2.0, 99.0); @@ -227,6 +468,15 @@ impl Mod for Guest { } Ok(None) } + fn tick(&mut self, _tick: u64) { + if let Some((book, all, id)) = self.pending.take() { + match recipes::place(book, all) { + Err(e) if e.starts_with("no screen") => self.pending = Some((book, all, id)), + Ok(()) => chat::show(&format!("place {id}: ok")), + Err(e) => chat::show(&format!("place {id}: {e}")), + } + } + } fn ui_select(&mut self, id: u32, row: u32) { chat::show(&format!("selected {id}:{row}")); } diff --git a/crates/horizon-port-pack/src/fetch.rs b/crates/horizon-port-pack/src/fetch.rs index f2803baa2..82c1ea794 100644 --- a/crates/horizon-port-pack/src/fetch.rs +++ b/crates/horizon-port-pack/src/fetch.rs @@ -143,7 +143,9 @@ pub fn fetch( 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")) + let checksum = format!("{url}.sha1"); + let sha1 = crate::net::agent(&checksum) + .get(&checksum) .set("User-Agent", modrinth::AGENT) .call() .ok() @@ -201,7 +203,8 @@ pub fn url_of(file: &PackFile, cache: &Cache) -> Option { /// Downloads `url` to `dest`, kept only if its SHA-1 is `sha1`. fn download(url: &str, sha1: Option<&str>, dest: &Path) -> Result<(), String> { - let response = ureq::get(url) + let response = crate::net::agent(url) + .get(url) .set("User-Agent", modrinth::AGENT) .call() .map_err(|e| format!("{url}: {e}"))?; diff --git a/crates/horizon-port-pack/src/lib.rs b/crates/horizon-port-pack/src/lib.rs index b47c93754..3b77aec63 100644 --- a/crates/horizon-port-pack/src/lib.rs +++ b/crates/horizon-port-pack/src/lib.rs @@ -16,6 +16,7 @@ pub mod jar; pub(crate) mod legacy_structure_mods; mod lithostitched; pub mod modrinth; +pub mod net; pub mod oracle; pub mod pipeline; pub mod processors; diff --git a/crates/horizon-port-pack/src/modrinth.rs b/crates/horizon-port-pack/src/modrinth.rs index 4e90c871a..17d6b3222 100644 --- a/crates/horizon-port-pack/src/modrinth.rs +++ b/crates/horizon-port-pack/src/modrinth.rs @@ -79,7 +79,8 @@ impl Cache { } fn post(url: &str, body: &Value) -> Result { - let response = ureq::post(url) + let response = crate::net::agent(url) + .post(url) .set("User-Agent", AGENT) .set("Content-Type", "application/json") .send_string(&body.to_string()) @@ -88,7 +89,8 @@ fn post(url: &str, body: &Value) -> Result { } fn get(url: &str) -> Result { - let response = ureq::get(url) + let response = crate::net::agent(url) + .get(url) .set("User-Agent", AGENT) .call() .map_err(|e| format!("{url}: {e}"))?; diff --git a/crates/horizon-port-pack/src/net.rs b/crates/horizon-port-pack/src/net.rs new file mode 100644 index 000000000..a441fb13a --- /dev/null +++ b/crates/horizon-port-pack/src/net.rs @@ -0,0 +1,389 @@ +//! The agents port-pack's downloads go through: the jars of an imported modpack come from the same +//! places as everything else, so they take the same proxy — and leave the same hosts alone. +//! +//! The launcher hands its own setting over (`set_proxy`, from `proxy.rs`); a run of the +//! `horizon-port-pack` command reads `HTTPS_PROXY`, `HTTP_PROXY` and `ALL_PROXY` instead (`env_for`), +//! taking the one that matches the address's scheme the way the launcher does. Either way a host in +//! `NO_PROXY`, or on this computer, is reached directly: a host that only answers without the proxy +//! would otherwise fail here while the launcher's own downloads worked. +//! +//! Which hosts those are is decided here and nowhere else. The launcher asks `direct`, `env_for`, +//! `host_of`, `scheme_of`, `socks` and `parse` for its own traffic, and keeps its agents here too +//! (`keep`), so the two agree whatever the player set — and there is one copy of the rules to +//! change when they need it. +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Mutex, MutexGuard}; + +/// What the launcher set, when it did. +static PROXY: Mutex> = Mutex::new(None); + +/// Agents kept for reuse, named by the part that asked and the proxy they use: a fresh `Agent` +/// starts a new connection pool, so building one per request costs a handshake per file. +static KEPT: Mutex>> = Mutex::new(None); + +/// The proxy to use from now on: the launcher's setting, or None to fall back to the environment. +/// The agents built so far are dropped when it changes, since they hold the address it replaces. +pub fn set_proxy(spec: Option) { + let spec = spec.map(|s| s.trim().to_owned()).filter(|s| !s.is_empty()); + let mut proxy = lock(&PROXY); + if *proxy == spec { + return; + } + *proxy = spec; + drop(proxy); + *lock(&KEPT) = None; +} + +/// The proxy address `url` is fetched through: what the launcher set, else the environment's for +/// its scheme, unless `url` is a host that must be reached directly. +fn spec_for(url: &str) -> Option { + if direct(url) { + return None; + } + lock(&PROXY) + .clone() + .or_else(|| env_for(scheme_of(url).unwrap_or("https"))) +} + +/// An agent for downloading `url`: through the proxy when one is set, unless `url` is a host that +/// must be reached directly. +pub fn agent(url: &str) -> ureq::Agent { + keep("port-pack", spec_for(url).as_deref(), |proxy| { + let builder = ureq::AgentBuilder::new(); + match proxy { + Some(proxy) => builder.proxy(proxy).build(), + None => builder.build(), + } + }) +} + +/// The agent `url` is fetched with, built by `build` and then kept for the next request that names +/// the same `slot` and proxy: a fresh `Agent` starts a new connection pool, so building one per +/// request is a handshake per file, and a modpack's jars are fetched one after another. +pub fn keep( + slot: &str, + spec: Option<&str>, + build: impl FnOnce(Option) -> ureq::Agent, +) -> ureq::Agent { + let proxy = spec.and_then(parse); + // An address that isn't a proxy is used as none, and remembered as none. + let key = format!( + "{slot} {}", + if proxy.is_some() { + spec.unwrap_or_default() + } else { + "" + } + ); + if let Some(agent) = lock(&KEPT).as_ref().and_then(|kept| kept.get(&key)) { + return agent.clone(); + } + let agent = build(proxy); + lock(&KEPT) + .get_or_insert_with(HashMap::new) + .insert(key, agent.clone()); + agent +} + +/// `spec` as a proxy, when it is one. An address that can't be used is said once: a download left +/// to go direct would otherwise fail with nothing pointing at the proxy. +pub fn parse(spec: &str) -> Option { + if socks(spec) { + say(&format!( + "{} is a SOCKS proxy; downloads go without one. Write the http:// address your \ + proxy app listens on as well.", + redacted(spec) + )); + return None; + } + match ureq::Proxy::new(spec) { + Ok(proxy) => Some(proxy), + Err(e) => { + say(&format!( + "The proxy address {} can't be used ({e}); downloads go without one.", + redacted(spec) + )); + None + } + } +} + +/// `spec` as it may be shown: a user name and password in it become `***`. An address that can't +/// be used is printed to stderr and shown in the launcher, and a proxy's credentials don't belong in +/// either. Everything up to the last `@` is the credentials, so a password with an unescaped `/` or +/// `@` is hidden too. +pub fn redacted(spec: &str) -> String { + let (scheme, rest) = match spec.split_once("://") { + Some((scheme, rest)) => (format!("{scheme}://"), rest), + None => (String::new(), spec), + }; + match rest.rfind('@') { + Some(at) => format!("{scheme}***@{}", &rest[at + 1..]), + None => spec.to_owned(), + } +} + +/// Whether `spec` names a SOCKS proxy, which these downloads don't go through: `ureq` reads a +/// SOCKS address happily and only fails when it connects through it. +pub fn socks(spec: &str) -> bool { + matches!( + spec.split_once("://") + .map(|(s, _)| s.to_ascii_lowercase()) + .as_deref(), + Some("socks" | "socks4" | "socks4a" | "socks5" | "socks5h") + ) +} + +/// Whether `url` is reached without the proxy: a local address, or a host `NO_PROXY` names. The +/// launcher asks this of its own requests, so both reach the same hosts directly. +pub fn direct(url: &str) -> bool { + host_of(url).is_some_and(|host| local(host) || excluded(host, &no_proxy())) +} + +/// `HTTPS_PROXY` (`HTTP_PROXY` for an http address), then `ALL_PROXY`, in the upper-case spelling +/// first and the lower-case one after, as the tools that write them do. +pub fn env_for(scheme: &str) -> Option { + let names: &[&str] = if scheme.eq_ignore_ascii_case("http") { + &["HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"] + } else { + &["HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"] + }; + names.iter().find_map(|name| { + std::env::var(name) + .ok() + .map(|v| v.trim().to_owned()) + .filter(|v| !v.is_empty()) + }) +} + +/// `NO_PROXY`'s list: the hosts reached directly whatever the proxy is. +fn no_proxy() -> String { + ["NO_PROXY", "no_proxy"] + .iter() + .find_map(|name| std::env::var(name).ok()) + .unwrap_or_default() +} + +/// The host part of a URL (`https://user@host:port/path` is `host`). +pub fn host_of(url: &str) -> Option<&str> { + let rest = url.split_once("://").map_or(url, |(_, rest)| rest); + let rest = rest.split(['/', '?', '#']).next()?; + let rest = rest.rsplit_once('@').map_or(rest, |(_, host)| host); + Some(match rest.rfind(':') { + // A port follows the last colon; an IPv6 literal keeps the colons inside its brackets. + Some(at) if !rest[at..].contains(']') => &rest[..at], + _ => rest, + }) +} + +/// `https` in `https://…`, or None for anything that isn't an absolute address. +pub fn scheme_of(url: &str) -> Option<&str> { + url.split_once("://").map(|(scheme, _)| scheme) +} + +/// Whether `host` is this computer: the game's own API and a server on the same machine. +fn local(host: &str) -> bool { + let host = bare(host); + host == "localhost" + || host.ends_with(".localhost") + || host == "::1" + || host == "0.0.0.0" + || host.starts_with("127.") +} + +/// Whether `host` is in `NO_PROXY`: `*`, `host`, `.domain`, `*.domain` and `host:port` entries. +fn excluded(host: &str, no_proxy: &str) -> bool { + let host = bare(host); + no_proxy + .split(',') + .map(str::trim) + .filter(|e| !e.is_empty()) + .any(|entry| { + if entry == "*" { + return true; + } + let entry = entry.trim_start_matches('*').trim_start_matches('.'); + let entry = match entry.rfind(':') { + Some(at) if !entry[at..].contains(']') => &entry[..at], + _ => entry, + }; + let entry = bare(entry); + !entry.is_empty() && (host == entry || host.ends_with(&format!(".{entry}"))) + }) +} + +/// A host without the brackets an IPv6 literal wears, lower case. +fn bare(host: &str) -> String { + host.trim().trim_matches(['[', ']']).to_ascii_lowercase() +} + +/// Said once, however many downloads follow: a wrong address is one thing to report, not one +/// report per file. +fn say(what: &str) { + static SAID: AtomicBool = AtomicBool::new(false); + if !SAID.swap(true, Ordering::Relaxed) { + eprintln!("{what}"); + } +} + +/// The lock, even after a thread panicked while holding it: an address lost to a panic is worse +/// than an old one kept. +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// What the tests below share, since the address and the agents are one of each for the whole + /// process: they take it in turn. + fn alone() -> MutexGuard<'static, ()> { + static TURN: Mutex<()> = Mutex::new(()); + lock(&TURN) + } + + #[test] + fn credentials_are_not_shown() { + assert_eq!(redacted("http://127.0.0.1:7890"), "http://127.0.0.1:7890"); + assert_eq!(redacted("proxy.local:3128"), "proxy.local:3128"); + assert_eq!( + redacted("http://user:pass@proxy.local:3128"), + "http://***@proxy.local:3128" + ); + assert_eq!( + redacted("socks5://u:p@10.0.0.1:1080"), + "socks5://***@10.0.0.1:1080" + ); + assert_eq!( + redacted("user:pass@proxy.local:3128"), + "***@proxy.local:3128" + ); + assert_eq!(redacted("http://u:p/a@ss@proxy:1"), "http://***@proxy:1"); + assert_eq!(redacted("http://user:pass@"), "http://***@"); + } + + #[test] + fn a_proxy_the_launcher_sets_is_trimmed_and_kept() { + let _turn = alone(); + set_proxy(Some(" http://127.0.0.1:7890 ".into())); + assert_eq!( + PROXY.lock().unwrap().as_deref(), + Some("http://127.0.0.1:7890") + ); + set_proxy(Some(" ".into())); + assert!(PROXY.lock().unwrap().is_none()); + } + + /// An address on this computer is reached directly whatever `NO_PROXY` says: what an import + /// needs when the launcher's own requests to it go direct. + #[test] + fn a_local_address_is_reached_directly() { + assert!(direct("http://127.0.0.1:8130/api/v1/status")); + assert!(direct("http://localhost/api/v1/status")); + assert!(direct("https://[::1]:25565/")); + } + + #[test] + fn a_host_is_read_out_of_the_address() { + assert_eq!( + host_of("https://cdn.modrinth.com/v2/x.jar"), + Some("cdn.modrinth.com") + ); + assert_eq!( + host_of("https://user:pass@piston-meta.mojang.com:8443/a"), + Some("piston-meta.mojang.com") + ); + assert_eq!( + host_of("http://127.0.0.1:8130/api/v1/status"), + Some("127.0.0.1") + ); + assert_eq!(host_of("https://[::1]:25565/"), Some("[::1]")); + assert_eq!(host_of("https://example.com?x=1"), Some("example.com")); + assert_eq!(host_of("https://example.com#top"), Some("example.com")); + } + + #[test] + fn only_absolute_addresses_have_a_scheme() { + assert_eq!(scheme_of("https://a.b"), Some("https")); + assert_eq!(scheme_of("http://a.b"), Some("http")); + assert_eq!(scheme_of("a.b/c"), None); + } + + #[test] + fn this_computer_is_never_proxied() { + for host in [ + "localhost", + "LOCALHOST", + "[::1]", + "::1", + "127.0.0.1", + "127.1.2.3", + ] { + assert!(local(host), "{host}"); + } + for host in ["playhorizon.dev", "api.minecraftservices.com", "10.0.0.1"] { + assert!(!local(host), "{host}"); + } + } + + /// What an import with `NO_PROXY=modrinth.com` needs: the launcher's own requests to it go + /// direct, so the jars fetched for it must too. + #[test] + fn no_proxy_lists_hosts_and_their_subdomains() { + assert!(excluded("anything.at.all", "*")); + assert!(excluded("cdn.modrinth.com", "modrinth.com")); + assert!(excluded("api.modrinth.com", "modrinth.com")); + assert!(excluded("piston-meta.mojang.com", "mojang.com")); + assert!(excluded( + "wiki.corp.example", + " .corp.example , other.host " + )); + assert!(excluded("github.com", "github.com:443")); + assert!(!excluded("notmodrinth.com", "modrinth.com")); + assert!(!excluded("modrinth.com", " .corp.example , mojang.com ")); + assert!(!excluded("edge.forgecdn.net", "modrinth.com")); + assert!(!excluded("modrinth.com", "")); + } + + #[test] + fn an_address_that_cant_be_used_becomes_no_proxy() { + assert!(parse("http://127.0.0.1:7890").is_some()); + assert!(parse("127.0.0.1:7890").is_some()); + // `ureq` reads a SOCKS address and only fails once it connects through it. + assert!(socks("socks5://127.0.0.1:7891")); + assert!(parse("socks5://127.0.0.1:7891").is_none()); + assert!(!socks("http://127.0.0.1:7890")); + } + + /// The agent a second request gets is the one the first built: one connection pool, not one + /// handshake per jar. + #[test] + fn an_agent_is_kept_for_the_next_request() { + let _turn = alone(); + set_proxy(None); + let mut built = 0; + for _ in 0..3 { + keep("kept", None, |_| { + built += 1; + ureq::AgentBuilder::new().build() + }); + } + assert_eq!(built, 1, "three requests, one agent"); + // Another address is another agent, and a new setting drops the ones before it. + keep("kept", Some("http://127.0.0.1:7890"), |proxy| { + assert!(proxy.is_some()); + built += 1; + ureq::AgentBuilder::new().build() + }); + assert_eq!(built, 2, "a second address needs a second agent"); + set_proxy(Some("http://127.0.0.1:7891".into())); + keep("kept", Some("http://127.0.0.1:7891"), |_| { + built += 1; + ureq::AgentBuilder::new().build() + }); + assert_eq!(built, 3, "a new setting drops the agents kept before it"); + set_proxy(None); + } +} diff --git a/crates/horizon-prepare/src/artifacts.rs b/crates/horizon-prepare/src/artifacts.rs index 994cb1a0d..533da0cce 100644 --- a/crates/horizon-prepare/src/artifacts.rs +++ b/crates/horizon-prepare/src/artifacts.rs @@ -1,5 +1,5 @@ //! The player's own game files: the pinned version JSON, client jar and libraries from their -//! official launcher install, and the server jar they downloaded, each checked against +//! official launcher or ATLauncher install, and the server jar they downloaded, each checked against //! research-lock.json before it is copied to `.local/minecraft/` (tools/lab.py's //! `prepare`, which the Python preparer ran first), then checked again on every run //! (tools/test_rust_parity.py's `verify_artifacts`). @@ -12,9 +12,10 @@ use std::path::{Component, Path, PathBuf}; const LAUNCHER_HINT: &str = "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."; +Minecraft Java Edition with so it downloads the game's files, then rerun. Horizon reads the \ +official launcher's folder, ATLauncher's and the CurseForge app's; for Prism Launcher, MultiMC, \ +the Modrinth App or GDLauncher, prepare from the Horizon launcher, which finds their files. If your 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."; @@ -23,11 +24,6 @@ fn hint(text: &str, version: &str) -> String { text.replace("{version}", version) } -/// What to do when the player's launcher install lacks the pinned version's files. -pub(crate) fn launcher_hint(version: &str) -> String { - hint(LAUNCHER_HINT, version) -} - /// research-lock.json and the folder the pinned version's files go to. pub struct Lock { pub json: Value, @@ -134,6 +130,137 @@ pub fn minecraft_dir(chosen: Option<&Path>) -> PathBuf { } } +/// One launcher's copy of the pinned version: its version JSON (Mojang's file, checked by its +/// sha1), the client jar, and the folder holding its `libraries` (at the version JSON's paths) +/// and `assets`. +pub struct GameFiles { + pub folder: PathBuf, + pub manifest: PathBuf, + pub client: PathBuf, + /// Mojang's Java runtimes the launcher downloaded (java::minecraft_runtimes). + pub runtimes: PathBuf, + /// The folders looked in, each with its launcher, when none held the version. + searched: Vec<(&'static str, PathBuf)>, +} + +impl GameFiles { + /// What to do when these files are missing, with the folders looked in. + pub(crate) fn hint(&self, version: &str) -> String { + let mut text = hint(LAUNCHER_HINT, version); + if !self.searched.is_empty() { + text += &format!(" Horizon looked for {version} in:"); + for (launcher, folder) in &self.searched { + text += &format!("\n {} ({launcher})", folder.display()); + } + } + text + } +} + +/// The layouts horizon-prepare reads in `folder`: the official launcher's, then ATLauncher's, +/// which saves Mojang's version JSON as is in `configs/json/minecraft` and the client jar as +/// the library `net.minecraft:client:`. +fn layouts(folder: &Path, version: &str) -> [GameFiles; 2] { + let files = |manifest: String, client: String, runtimes: &str| GameFiles { + folder: folder.to_path_buf(), + manifest: folder.join(manifest), + client: folder.join(client), + runtimes: folder.join(runtimes), + searched: Vec::new(), + }; + let v = version; + [ + files( + format!("versions/{v}/{v}.json"), + format!("versions/{v}/{v}.jar"), + "runtime", + ), + files( + format!("configs/json/minecraft/{v}.json"), + format!("libraries/net/minecraft/client/{v}/client-{v}.jar"), + "runtimes/minecraft", + ), + ] +} + +/// The launchers whose folders are looked in when none is chosen: the official launcher's +/// (`minecraft_dir`), ATLauncher's, then the CurseForge app's `Install` folder, where it runs +/// the official launcher (its default modding folder, `curseforge/minecraft`, is in the home +/// folder on Windows and in Documents elsewhere). ATLauncher keeps its files in its working folder: +/// where its Windows installer puts it, inside the macOS app, and the folders its Linux +/// packages and Flatpak start it in. +fn launcher_folders() -> Vec<(&'static str, PathBuf)> { + let mut folders = vec![("the official launcher", minecraft_dir(None))]; + // The same folders as the Horizon launcher's (launcher/src/sources.rs `known_folders`). + let atlauncher: Vec = if cfg!(target_os = "macos") { + let app = Path::new("Applications/ATLauncher.app/Contents/Java"); + vec![ + home().join("Library/Application Support/ATLauncher"), + Path::new("/").join(app), + home().join(app), + ] + } else if cfg!(windows) { + std::env::var_os("APPDATA") + .map(|d| PathBuf::from(d).join("ATLauncher")) + .into_iter() + .collect() + } else { + let data = std::env::var_os("XDG_DATA_HOME") + .filter(|d| !d.is_empty()) + .map_or_else(|| home().join(".local/share"), PathBuf::from); + let flatpak = home().join(".var/app/com.atlauncher.ATLauncher/data"); + vec![data.join("atlauncher"), flatpak.join("atlauncher"), flatpak] + }; + folders.extend(atlauncher.into_iter().map(|dir| ("ATLauncher", dir))); + let curseforge = if cfg!(windows) { "" } else { "Documents" }; + folders.push(( + "the CurseForge app", + home().join(curseforge).join("curseforge/minecraft/Install"), + )); + folders +} + +/// The pinned version's files in the chosen folder (`--minecraft-dir`, HORIZON_MINECRAFT_DIR), +/// or the launcher above it when an instance folder (`instances/`) is chosen; with no +/// folder chosen, in the first launcher folder that has them. When none does, the official +/// layout of the first folder is returned, for the errors to name, with the folders looked in. +pub fn game_files(chosen: Option<&Path>, version: &str) -> GameFiles { + let chosen = chosen + .filter(|d| !d.as_os_str().is_empty()) + .map(Path::to_path_buf) + .or_else(|| std::env::var_os("HORIZON_MINECRAFT_DIR").map(PathBuf::from)) + .filter(|d| !d.as_os_str().is_empty()) + .map(|d| expand_user(&d)); + let folders = match chosen { + Some(dir) => { + let launcher = dir + .ancestors() + .find(|a| a.file_name().is_some_and(|n| n == "instances")) + .and_then(Path::parent) + .map(Path::to_path_buf); + let mut folders = vec![("the folder chosen", dir)]; + folders.extend(launcher.map(|dir| ("the launcher above it", dir))); + folders + } + None => launcher_folders(), + }; + // A folder with both files first: a version JSON left without its jar is used, for the + // error to name the jar, only when no folder has both. + let complete = |files: &GameFiles| files.manifest.is_file() && files.client.is_file(); + let partial = |files: &GameFiles| files.manifest.is_file(); + for found in [complete, partial] { + let mut all = folders + .iter() + .flat_map(|(_, folder)| layouts(folder, version)); + if let Some(files) = all.find(found) { + return files; + } + } + let [mut files, _] = layouts(&folders[0].1, version); + files.searched = folders; + files +} + /// Copy one file from the player's install, checked like a download; an existing verified /// copy is kept. pub(crate) fn import_copy( @@ -156,17 +283,14 @@ pub(crate) fn import_copy( .commit() } -/// The pinned version JSON from the launcher's versions/ directory. The launcher's copy wins -/// over the cached one so the manifest matches the asset index installed alongside it. -pub(crate) fn import_manifest(lock: &Lock, minecraft: &Path) -> Result { +/// The pinned version JSON from the launcher's install. The launcher's copy wins over the +/// cached one so the manifest matches the asset index installed alongside it. +pub(crate) fn import_manifest(lock: &Lock, files: &GameFiles) -> Result { let version = &lock.version; let destination = lock.directory.join("manifest.json"); - let source = minecraft - .join("versions") - .join(version) - .join(format!("{version}.json")); + let source = &files.manifest; if source.is_file() { - let manifest = read_json(&source)?; + let manifest = read_json(source)?; let downloads = manifest.get("downloads"); let sha1 = |side: &str| { downloads @@ -183,7 +307,7 @@ pub(crate) fn import_manifest(lock: &Lock, minecraft: &Path) -> Result Result, log: Log, ) -> Result<(), String> { - let minecraft = minecraft_dir(minecraft); - let version = &lock.version; - let manifest = import_manifest(lock, &minecraft)?; + let files = game_files(minecraft, &lock.version); + let minecraft = &files.folder; + let manifest = import_manifest(lock, &files)?; let client = import_copy( - &minecraft - .join("versions") - .join(version) - .join(format!("{version}.jar")), + &files.client, &lock.directory.join("jars/client.jar"), lock.pin("client_sha1")?, "sha1", - &hint(LAUNCHER_HINT, version), + &files.hint(&lock.version), )?; let downloads = manifest.get("downloads"); if downloads.and_then(|d| d.get("client_mappings")).is_some() @@ -555,7 +676,7 @@ pub fn import( for (name, artifact) in client_library_artifacts(&manifest)? { let (path, sha1) = artifact_fields(artifact)?; let relative = safe_relative(path).ok_or("Unsafe library path")?; - let source = launcher_library(&minecraft, name, &relative); + let source = launcher_library(minecraft, name, &relative); let destination = lock.directory.join("libraries/client").join(&relative); if runs_without(name) && !source.is_file() && !destination.exists() { log(&format!( @@ -569,7 +690,7 @@ pub fn import( &destination, sha1, "sha1", - &hint(LAUNCHER_HINT, version), + &files.hint(&lock.version), )?); } write_import_metadata( @@ -1122,7 +1243,7 @@ mod tests { let lock = Lock::read(&root).unwrap(); let destination = lock.directory.join("manifest.json"); - let error = import_manifest(&lock, &minecraft).unwrap_err(); + let error = import_manifest(&lock, &game_files(Some(&minecraft), "9.9")).unwrap_err(); assert!(error.contains("may have rewritten it"), "{error}"); assert!( error.contains(&format!("packages/{pinned}/9.9.json")), @@ -1136,7 +1257,7 @@ mod tests { fs::create_dir_all(&lock.directory).unwrap(); fs::copy(root.join("mojang.json"), &destination).unwrap(); - let manifest = import_manifest(&lock, &minecraft).unwrap(); + let manifest = import_manifest(&lock, &game_files(Some(&minecraft), "9.9")).unwrap(); assert!(manifest.get("patches").is_none()); assert_eq!(digest(&destination, "sha1").unwrap(), pinned); fs::remove_dir_all(&root).unwrap(); @@ -1253,6 +1374,103 @@ mod tests { assert!(prepare().unwrap_err().starts_with("Missing ")); } + /// ATLauncher keeps Mojang's version JSON in `configs/json/minecraft` and the client jar as + /// a library; its folder, or one of its instances, prepares like the official launcher's, + /// with the same pins. + #[test] + fn an_atlauncher_install_prepares() { + let fixture = Imports::new(); + let old = fixture.imported(&fixture.source); + let atlauncher = fixture.directory.join("ATLauncher"); + let put = |path: &str, data: &[u8]| { + let path = atlauncher.join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, data).unwrap(); + }; + let client = fs::read(old.join("jars/client.jar")).unwrap(); + put("libraries/net/minecraft/client/9.9/client-9.9.jar", &client); + put("libraries/client.jar", b"client library"); + put("instances/Minecraft99/instance.json", b"{}"); + // A version JSON left without its jar does not hide the launcher's complete copy. + put("instances/Minecraft99/versions/9.9/9.9.json", b"{}"); + let manifest = fs::read_to_string(old.join("manifest.json")).unwrap(); + let manifest = manifest.replacen('{', r#"{"javaVersion":{"majorVersion":25},"#, 1); + put("configs/json/minecraft/9.9.json", manifest.as_bytes()); + let pinned = digest(&atlauncher.join("configs/json/minecraft/9.9.json"), "sha1").unwrap(); + let lock_path = fixture.target.join("research-lock.json"); + let text = fs::read_to_string(&lock_path).unwrap(); + let old_sha1 = digest(&old.join("manifest.json"), "sha1").unwrap(); + fs::write(&lock_path, text.replace(&old_sha1, &pinned)).unwrap(); + let lock = Lock::read(&fixture.target).unwrap(); + let server = old.join("jars/server.jar"); + let prepare = |dir: &Path| { + let _ = fs::remove_dir_all(&lock.directory); + import(&fixture.target, &lock, Some(dir), Some(&server), &|_| {}) + }; + + for chosen in [atlauncher.clone(), atlauncher.join("instances/Minecraft99")] { + prepare(&chosen).unwrap(); + let artifacts = verify(&lock).unwrap(); + assert_eq!(fs::read(&artifacts.jars["client"]).unwrap(), client); + assert_eq!( + client_libraries(&lock, &artifacts.manifest).unwrap().len(), + 1 + ); + } + let files = game_files(Some(&atlauncher), "9.9"); + assert_eq!(files.runtimes, atlauncher.join("runtimes/minecraft")); + + // The pins gate it as they gate the official layout. + put( + "libraries/net/minecraft/client/9.9/client-9.9.jar", + b"other", + ); + assert!(prepare(&atlauncher) + .unwrap_err() + .contains("is not the pinned file")); + put("libraries/net/minecraft/client/9.9/client-9.9.jar", &client); + put( + "configs/json/minecraft/9.9.json", + manifest.replace(',', ", ").as_bytes(), + ); + assert!(prepare(&atlauncher) + .unwrap_err() + .contains("may have rewritten it")); + } + + /// With no launcher's files in the chosen folder, the error names where Horizon looked and + /// the launchers it reads. + #[test] + fn the_error_names_the_folders_looked_in() { + let fixture = Imports::new(); + let empty = fixture.directory.join("instances/empty"); + fs::create_dir_all(&empty).unwrap(); + let lock = Lock::read(&fixture.target).unwrap(); + let error = import(&fixture.target, &lock, Some(&empty), None, &|_| {}).unwrap_err(); + assert!(error.starts_with(&format!( + "Missing {}", + empty.join("versions/9.9/9.9.json").display() + ))); + assert!(error.contains("Horizon looked for 9.9 in:"), "{error}"); + assert!(error.contains(&format!("\n {} (the folder chosen)", empty.display()))); + assert!(error.contains(&format!( + "\n {} (the launcher above it)", + fixture.directory.display() + ))); + assert!(error.contains("ATLauncher")); + } + + #[test] + fn every_launcher_horizon_reads_is_looked_in() { + let launchers: Vec<_> = launcher_folders() + .into_iter() + .map(|(name, _)| name) + .collect(); + for name in ["the official launcher", "ATLauncher", "the CurseForge app"] { + assert!(launchers.contains(&name), "{name}"); + } + } + #[test] fn runs_without_only_netty_native_transports() { assert!(runs_without( diff --git a/crates/horizon-prepare/src/lib.rs b/crates/horizon-prepare/src/lib.rs index 5d71e8448..830bc4118 100644 --- a/crates/horizon-prepare/src/lib.rs +++ b/crates/horizon-prepare/src/lib.rs @@ -434,7 +434,7 @@ fn prepare_impl(options: &Options, log: Log, compile_only: bool) -> Result = options.java_home.iter().cloned().collect(); homes.extend(java::minecraft_runtimes( - &artifacts::minecraft_dir(options.minecraft_dir.as_deref()).join("runtime"), + &artifacts::game_files(options.minecraft_dir.as_deref(), &lock.version).runtimes, )); let jdk = java::find_runtime(lock.java_major, &homes)?; let reused = if options.import { diff --git a/crates/horizon-prepare/src/sounds.rs b/crates/horizon-prepare/src/sounds.rs index fd171ec12..5c34d9504 100644 --- a/crates/horizon-prepare/src/sounds.rs +++ b/crates/horizon-prepare/src/sounds.rs @@ -1,5 +1,5 @@ //! The pinned version's sounds, title panorama, Unifont glyphs and built-in resource packs -//! from the player's own official launcher install, each object checked against the asset index's SHA-1, copied into +//! from the player's own launcher install, each object checked against the asset index's SHA-1, copied into //! `.local/horizon-client//assets` where the game reads them (tools/fetch_sounds.py and //! the tools/lab.py functions it called). Nothing is downloaded. @@ -18,11 +18,11 @@ use std::path::{Path, PathBuf}; fn launcher_assets( lock: &Lock, manifest: &Value, - minecraft: &Path, + files: &artifacts::GameFiles, cached_index: &Path, log: Log, ) -> Result<(PathBuf, PathBuf, Vec), String> { - let assets = minecraft.join("assets"); + let assets = files.folder.join("assets"); let info = manifest .get("assetIndex") .ok_or("The version JSON has no assetIndex")?; @@ -44,7 +44,7 @@ fn launcher_assets( return Err(format!( "Missing {}. {}", index.display(), - artifacts::launcher_hint(version) + files.hint(version) )); } let bytes = fs::read(&index).map_err(|e| format!("{}: {e}", index.display()))?; @@ -240,13 +240,13 @@ pub(crate) struct Assets { impl Assets { pub(crate) fn load(root: &Path, minecraft: Option<&Path>, log: Log) -> Result { let lock = Lock::read(root)?; - let minecraft = artifacts::minecraft_dir(minecraft); - let manifest = artifacts::import_manifest(&lock, &minecraft)?; + let files = artifacts::game_files(minecraft, &lock.version); + let manifest = artifacts::import_manifest(&lock, &files)?; let target = root.join(".local/horizon-client").join(&lock.version); let (store, index, bytes) = launcher_assets( &lock, &manifest, - &minecraft, + &files, &target.join("asset-index.json"), log, )?; @@ -677,7 +677,11 @@ mod tests { for missing in ["store", "install", "last-object"] { let f = Fixture::new(&format!("optional-panorama-{missing}")); // The JARs and manifest were imported earlier; the launcher need not remain. - artifacts::import_manifest(&Lock::read(&f.root).unwrap(), &f.minecraft).unwrap(); + artifacts::import_manifest( + &Lock::read(&f.root).unwrap(), + &artifacts::game_files(Some(&f.minecraft), "9.9"), + ) + .unwrap(); let target = f.root.join(".local/horizon-client/9.9/assets"); for name in PANORAMA { let path = target.join(name); diff --git a/crates/horizon-protocol/src/item.rs b/crates/horizon-protocol/src/item.rs index abc530278..3d5bacfe9 100644 --- a/crates/horizon-protocol/src/item.rs +++ b/crates/horizon-protocol/src/item.rs @@ -35,6 +35,7 @@ pub mod component { pub const MAP_ID: i32 = 48; pub const MAP_POST_PROCESSING: i32 = 50; pub const CHARGED_PROJECTILES: i32 = 51; + pub const BUNDLE_CONTENTS: i32 = 52; pub const POTION_CONTENTS: i32 = 53; pub const WRITABLE_BOOK_CONTENT: i32 = 56; pub const WRITTEN_BOOK_CONTENT: i32 = 57; @@ -163,7 +164,7 @@ pub struct Profile { pub properties: Vec<(String, String, Option)>, } impl Component { - fn read(kind: i32, r: &mut Reader) -> Result { + pub(crate) fn read(kind: i32, r: &mut Reader) -> Result { use component::*; Ok(match kind { MAX_STACK_SIZE | MAX_DAMAGE | DAMAGE | RARITY | REPAIR_COST | MAP_ID @@ -192,7 +193,7 @@ impl Component { resolved: r.bool()?, }) } - CHARGED_PROJECTILES => { + CHARGED_PROJECTILES | BUNDLE_CONTENTS => { let n = r.count(1024)?; Self::Stacks((0..n).map(|_| Template::read(r)).collect::>()?) } @@ -337,7 +338,7 @@ impl Component { } }) } - fn write(&self, kind: i32, w: &mut Writer) { + pub(crate) fn write(&self, kind: i32, w: &mut Writer) { match self { Self::Raw(bytes) => w.bytes(bytes), Self::Trim { material, pattern } => { @@ -784,6 +785,21 @@ mod tests { assert_eq!(w.data, bytes); } + #[test] + fn bundle_contents_are_item_stack_templates() { + // A bundle (id 7) holding 32 of item 9: BundleContents is a list of + // ItemStackTemplate, as ChargedProjectiles is. + let bytes = [1, 7, 1, 0, 52, 1, 9, 32, 0, 0]; + let stack = Slot::read(&mut Reader::new(&bytes)).unwrap().unwrap(); + assert_eq!( + stack.component(component::BUNDLE_CONTENTS), + Some(&Component::Stacks(vec![Stack::new(9, 32)])) + ); + let mut w = Writer::new(); + Slot::write(&Some(stack), &mut w); + assert_eq!(w.data, bytes); + } + #[test] fn filtered_book_pages_are_read_and_dropped() { // A writable book with one page "hi" and its filtered "**". diff --git a/crates/horizon-protocol/src/lib.rs b/crates/horizon-protocol/src/lib.rs index f0bea2ca2..299688560 100644 --- a/crates/horizon-protocol/src/lib.rs +++ b/crates/horizon-protocol/src/lib.rs @@ -11,6 +11,7 @@ pub mod frame; pub mod ids; pub mod item; pub mod packets; +pub mod quiet; pub mod registry; mod resolver; pub mod rsa; diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 1bdf43b08..7ab82720d 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -8,7 +8,7 @@ use crate::{ }, chunk::{ChunkData, LightData}, entity_data::{EntityData, Particle, Value}, - item::{Hashed, HashedSlot, Slot, Stack}, + item::{Component, Hashed, HashedSlot, Slot, Stack}, packet, packet_enum, packets::{ Empty, @@ -88,11 +88,31 @@ packet!(ContainerSetContent { carried: Option => Slot, }); /// ItemCost.STREAM_CODEC: item, count, then the exact component predicate -/// (Horizon sends and reads it as a component patch without removals). +/// (a list of typed component values, with no patch removal count). #[derive(Clone, Debug, PartialEq)] pub struct NetCost { pub item: i32, pub count: i32, + pub components: Vec<(i32, Component)>, +} +impl From for NetCost { + fn from(stack: Stack) -> Self { + Self { + item: stack.item, + count: stack.count, + components: stack.added, + } + } +} +impl From for Stack { + fn from(cost: NetCost) -> Self { + Self { + item: cost.item, + count: cost.count, + added: cost.components, + removed: Vec::new(), + } + } } /// MerchantOffer.STREAM_CODEC. #[derive(Clone, Debug, PartialEq)] @@ -114,10 +134,17 @@ impl Codec> for Offers { fn cost(r: &mut Reader) -> Result { let item = r.varint()?; let count = r.varint()?; - if r.varint()? != 0 { - return Err(Error::new("item cost components are not supported")); + let n = r.count(r.remaining())?; + let mut components = Vec::with_capacity(n.min(64)); + for _ in 0..n { + let kind = r.varint()?; + components.push((kind, Component::read(kind, r)?)); } - Ok(NetCost { item, count }) + Ok(NetCost { + item, + count, + components, + }) } let n = r.count(r.remaining())?; let mut out = Vec::with_capacity(n.min(64)); @@ -144,7 +171,11 @@ impl Codec> for Offers { fn cost(c: &NetCost, w: &mut Writer) { w.varint(c.item); w.varint(c.count); - w.varint(0); + w.varint(c.components.len() as i32); + for (kind, value) in &c.components { + w.varint(*kind); + value.write(*kind, w); + } } w.varint(v.len() as i32); for o in v { @@ -2218,6 +2249,11 @@ packet!( /// Input flags: forward 1, backward 2, left 4, right 8, jump 16, shift 32, sprint 64. PlayerInput { flags: u8 => UByte } ); +packet!( + /// ServerboundSelectBundleItemPacket: the menu slot of a bundle and the + /// index of its selected item (-1: none). + SelectBundleItem { slot: i32 => VarInt, index: i32 => VarInt } +); packet!(SetCarriedItem { slot: i16 => Short }); packet!(SetCreativeModeSlot { slot: i16 => Short, item: Option => Slot }); packet!(UseItem { hand: i32 => VarInt, sequence: i32 => VarInt, yaw: f32 => Float, pitch: f32 => Float }); @@ -2286,6 +2322,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { ContainerSlotStateChanged(ContainerSlotStateChanged) = CONTAINER_SLOT_STATE_CHANGED, Punch(Empty) = PUNCH, ResourcePack(ResourcePackResponse) = RESOURCE_PACK, + SelectBundleItem(SelectBundleItem) = BUNDLE_ITEM_SELECTED, SelectTrade(SelectTrade) = SELECT_TRADE, SetBeacon(SetBeacon) = SET_BEACON, SetCarriedItem(SetCarriedItem) = SET_CARRIED_ITEM, @@ -2300,6 +2337,39 @@ mod tests { use super::*; use crate::{chunk::BlockEntityInfo, packets::round_trip, text::literal}; + #[test] + fn merchant_cost_predicate_is_a_typed_list_without_patch_counts() { + // ItemCost.STREAM_CODEC: item=7, count=1, one typed component, + // potion_contents=53, potion present (water=0), no color/effects/name. + // Result: count=1, item=8, empty component patch. Secondary cost: + // item=9, count=2, empty predicate, followed by the offer fields. + let mut bytes = vec![1, 7, 1, 1, 53, 1, 0, 0, 0, 0, 1, 8, 0, 0, 1, 9, 2, 0, 0]; + bytes.extend_from_slice(&[0; 4]); // uses + bytes.extend_from_slice(&2i32.to_be_bytes()); // max uses + bytes.extend_from_slice(&[0; 16]); // xp, special price, multiplier, demand + let mut r = Reader::new(&bytes); + let offers = Offers::read(&mut r).unwrap(); + assert_eq!(r.remaining(), 0); + assert_eq!( + offers[0].cost_a.components, + vec![( + 53, + Component::Potion { + potion: Some(0), + color: None, + rest: Vec::new() + } + )] + ); + assert!(offers[0].cost_b.as_ref().unwrap().components.is_empty()); + let mut w = Writer::new(); + Offers::write(&offers, &mut w); + assert_eq!(w.data, bytes); + for len in 0..bytes.len() { + assert!(Offers::read(&mut Reader::new(&bytes[..len])).is_err()); + } + } + #[test] fn serverbound_abilities_carry_only_flying() { // ServerboundPlayerAbilitiesPacket.write: one byte, 2 when flying. @@ -2576,9 +2646,9 @@ mod tests { Clientbound::MerchantOffers(MerchantOffers { container: 3, offers: vec![NetOffer { - cost_a: NetCost { item: 5, count: 24 }, + cost_a: Stack::new(5, 24).into(), result: Stack::new(7, 1), - cost_b: Some(NetCost { item: 9, count: 1 }), + cost_b: Some(Stack::new(9, 1).into()), out_of_stock: false, uses: 2, max_uses: 16, diff --git a/crates/horizon-protocol/src/quiet.rs b/crates/horizon-protocol/src/quiet.rs new file mode 100644 index 000000000..dcf48dbee --- /dev/null +++ b/crates/horizon-protocol/src/quiet.rs @@ -0,0 +1,166 @@ +//! Quiet commands: a client mod's batch of commands that a Horizon server runs +//! as the player who sent them, at that player's own permission level, with +//! no feedback in the chat (docs/mods.md, `command.run-quiet`). +//! +//! The server announces it understands them with an empty [`CHANNEL`] payload +//! in the configuration phase (a vanilla client ignores it); a client that +//! hears it sends each batch as a serverbound [`CHANNEL`] payload, and falls +//! back to chat commands on any other server. A payload is the mod's id, then +//! the lines without their slash. +use crate::{ + Error, Result, + buf::{Reader, Writer}, +}; + +/// The custom payload channel, both ways. +pub const CHANNEL: &str = "horizon:quiet_commands"; +/// Lines in one payload at most; a payload with more is refused whole. +pub const MAX_LINES: usize = 256; +/// Characters in a line at most (a chat command's limit). +pub const MAX_LINE: usize = 256; +/// Characters in a mod id at most. +pub const MAX_MOD_ID: usize = 64; +/// Bytes of a serverbound custom payload's data at most +/// (ServerboundCustomPayloadPacket.MAX_PAYLOAD_SIZE). +pub const MAX_PAYLOAD: usize = 32767; + +/// A batch as the server reads it. +#[derive(Clone, Debug, PartialEq)] +pub struct Batch { + pub mod_id: String, + pub lines: Vec, +} + +/// `lines` as few payloads as fit [`MAX_PAYLOAD`] and [`MAX_LINES`], in +/// order. Lines longer than [`MAX_LINE`] are cut, as a chat command's are. +pub fn encode(mod_id: &str, lines: &[String]) -> Vec> { + let mod_id: String = mod_id.chars().take(MAX_MOD_ID).collect(); + let mut payloads = Vec::new(); + let mut rest = lines + .iter() + .map(|l| -> String { l.chars().take(MAX_LINE).collect() }); + let mut next = rest.next(); + while next.is_some() { + let mut batch = Vec::new(); + // The id, the count (a varint of at most 2 bytes for 256). + let mut size = string_size(&mod_id) + 2; + while let Some(line) = next.take() { + let more = string_size(&line); + if !batch.is_empty() && (batch.len() == MAX_LINES || size + more > MAX_PAYLOAD) { + next = Some(line); + break; + } + size += more; + batch.push(line); + next = rest.next(); + } + let mut w = Writer::new(); + w.string(&mod_id); + w.varint(batch.len() as i32); + for line in &batch { + w.string(line); + } + payloads.push(w.data); + } + payloads +} + +fn string_size(s: &str) -> usize { + crate::buf::varint_size(s.len() as i32) + s.len() +} + +/// A payload's batch; an error for one that breaks a cap. +pub fn decode(data: &[u8]) -> Result { + if data.len() > MAX_PAYLOAD { + return Err(Error::new("quiet commands: payload too big")); + } + let mut r = Reader::new(data); + let mod_id = r.string(MAX_MOD_ID)?; + let count = r.varint()?; + if !(0..=MAX_LINES as i32).contains(&count) { + return Err(Error::new(format!("quiet commands: {count} lines"))); + } + let lines = (0..count) + .map(|_| r.string(MAX_LINE)) + .collect::>>()?; + if r.remaining() > 0 { + return Err(Error::new("quiet commands: trailing bytes")); + } + Ok(Batch { mod_id, lines }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_batch_round_trips() { + let lines = vec!["fill 0 0 0 1 1 1 stone".to_string(), "say hi".to_string()]; + let payloads = encode("orbital", &lines); + assert_eq!(payloads.len(), 1); + assert_eq!( + decode(&payloads[0]).unwrap(), + Batch { + mod_id: "orbital".into(), + lines + } + ); + } + + #[test] + fn big_batches_split_by_lines_and_bytes() { + let lines: Vec = (0..600) + .map(|i| format!("setblock {i} 0 0 stone")) + .collect(); + let payloads = encode("m", &lines); + let decoded: Vec = payloads.iter().map(|p| decode(p).unwrap()).collect(); + assert_eq!( + decoded.iter().map(|b| b.lines.len()).collect::>(), + [256, 256, 88] + ); + assert_eq!( + decoded + .into_iter() + .flat_map(|b| b.lines) + .collect::>(), + lines + ); + let long: Vec = (0..256).map(|_| "x".repeat(300)).collect(); + for p in encode("m", &long) { + assert!(p.len() <= MAX_PAYLOAD); + assert!( + decode(&p) + .unwrap() + .lines + .iter() + .all(|l| l.len() == MAX_LINE) + ); + } + } + + #[test] + fn payloads_over_the_caps_are_refused() { + let mut w = Writer::new(); + w.string("m"); + w.varint(MAX_LINES as i32 + 1); + for _ in 0..=MAX_LINES { + w.string("say"); + } + assert!(decode(&w.data).is_err()); + let mut w = Writer::new(); + w.string("m"); + w.varint(1); + w.string(&"x".repeat(MAX_LINE + 1)); + assert!(decode(&w.data).is_err()); + let mut w = Writer::new(); + w.string("m"); + w.varint(-1); + assert!(decode(&w.data).is_err()); + assert!(decode(&[0xFF]).is_err()); + let mut w = Writer::new(); + w.string("m"); + w.varint(0); + w.u8(1); + assert!(decode(&w.data).is_err()); + } +} diff --git a/crates/horizon-server/panel/panel.css b/crates/horizon-server/panel/panel.css index 7946b5f8f..994f5eac6 100644 --- a/crates/horizon-server/panel/panel.css +++ b/crates/horizon-server/panel/panel.css @@ -1,4 +1,4 @@ -/* The Horizon server panel. Colours and spacing are horizon-theme's tokens (website/src/tokens.css). */ +/* The Horizon server panel. Colours and spacing are horizon-theme's tokens (crates/horizon-theme/tokens.css). */ :root { --page: #fafafc; --plate-soft: #f3f3f8; diff --git a/crates/horizon-telemetry-server/README.md b/crates/horizon-telemetry-server/README.md index a401a72b0..c364e20c4 100644 --- a/crates/horizon-telemetry-server/README.md +++ b/crates/horizon-telemetry-server/README.md @@ -30,7 +30,7 @@ The totals are grouped per version, OS, GPU vendor and render distance. Each gro ## Benchmarks summary -`src/summary.rs` makes it with the same rules as `website/scripts/benchmarks.mjs`, which bakes the page's fallback copy; both are tested against the same fixtures (`website/scripts/fixtures/benchmarks/`). +`src/summary.rs` makes it with the same rules as the website's `scripts/benchmarks.mjs` (ludovic111/horizon-site), which bakes the page's fallback copy; both are tested against the same fixtures (`tests/fixtures/benchmarks/` here, copied in the site's repository). - Only reports that compare: a version 1 `horizon-benchmark-report` of the standard flight over the four scenes, VSync off, no frame cap, on screen, from Horizon or plain vanilla, naming its GPU and CPU. - A group (GPU, CPU, render distance, game) is published only with **at least 3 different installs**. Each install counts once: the median of its runs, then the median across installs. diff --git a/crates/horizon-telemetry-server/src/classes.rs b/crates/horizon-telemetry-server/src/classes.rs index fce2826fd..e39154b57 100644 --- a/crates/horizon-telemetry-server/src/classes.rs +++ b/crates/horizon-telemetry-server/src/classes.rs @@ -1,6 +1,6 @@ //! The hardware classes the public output breaks results down by. Coarse on purpose: a class //! holds many machines, and a published cell still needs `MIN_INSTALLS` different installs. -//! `website/scripts/benchmarks.mjs` has the same functions, tested on the same fixtures. +//! The website's `scripts/benchmarks.mjs` (ludovic111/horizon-site) has the same functions, tested on the same fixtures. //! //! The raw values (the exact memory, the driver, the screen) stay in the database for the //! retention period and are never published. diff --git a/crates/horizon-telemetry-server/src/summary.rs b/crates/horizon-telemetry-server/src/summary.rs index 05f94f5a0..deb3564dd 100644 --- a/crates/horizon-telemetry-server/src/summary.rs +++ b/crates/horizon-telemetry-server/src/summary.rs @@ -1,7 +1,7 @@ //! `GET /v1/benchmarks/summary`: players' benchmark uploads, grouped for the website's Benchmarks page. //! -//! The same rules as `website/scripts/benchmarks.mjs` (which builds the page's baked copy), checked against the -//! same fixtures (`website/scripts/fixtures/benchmarks/`): +//! The same rules as the website's `scripts/benchmarks.mjs` (ludovic111/horizon-site; it builds the page's baked +//! copy), checked against the same fixtures (`tests/fixtures/benchmarks/`, which the site's test keeps a copy of): //! //! - Only reports that compare: `horizon-benchmark-report` version 1, kind `game`, Horizon or plain vanilla, the //! standard flight over the four scenes, VSync off, no frame cap, drawn on a screen, with a GPU and CPU name. @@ -198,7 +198,7 @@ struct Group { versions: BTreeSet, } -/// Players' groups of at least `min_installs` installs, as `website/scripts/benchmarks.mjs` makes them. +/// Players' groups of at least `min_installs` installs, as the website's `scripts/benchmarks.mjs` makes them. pub fn groups(uploads: &[Upload], min_installs: usize) -> Vec { let mut by: BTreeMap<(String, String, i64, &str), Group> = BTreeMap::new(); for u in uploads { diff --git a/website/scripts/fixtures/benchmarks/README.md b/crates/horizon-telemetry-server/tests/fixtures/benchmarks/README.md similarity index 72% rename from website/scripts/fixtures/benchmarks/README.md rename to crates/horizon-telemetry-server/tests/fixtures/benchmarks/README.md index 562646a6f..51ebb9aac 100644 --- a/website/scripts/fixtures/benchmarks/README.md +++ b/crates/horizon-telemetry-server/tests/fixtures/benchmarks/README.md @@ -1,7 +1,8 @@ # Benchmark summary fixtures -Shared by the website's aggregator test (`website/scripts/benchmarks.test.mjs`) and the telemetry server's -`GET /v1/benchmarks/summary` test: the same `benchmark` items in, the same groups out. +Used by the telemetry server's `GET /v1/benchmarks/summary` test (`tests/summary.rs`) and, as a copy, by the +website's aggregator test (`scripts/benchmarks.test.mjs` in ludovic111/horizon-site, which checks its copy against +this one on main): the same `benchmark` items in, the same groups out. Change both together. - `items.jsonl`: one stored item per line (`install_id`, `day`, `version`, `data`: a benchmark report). Group RTX 4080 + i7-13700KF at render distance 12 has three installs (one with two runs); the same install at 32, diff --git a/website/scripts/fixtures/benchmarks/expected.json b/crates/horizon-telemetry-server/tests/fixtures/benchmarks/expected.json similarity index 100% rename from website/scripts/fixtures/benchmarks/expected.json rename to crates/horizon-telemetry-server/tests/fixtures/benchmarks/expected.json diff --git a/website/scripts/fixtures/benchmarks/items.jsonl b/crates/horizon-telemetry-server/tests/fixtures/benchmarks/items.jsonl similarity index 100% rename from website/scripts/fixtures/benchmarks/items.jsonl rename to crates/horizon-telemetry-server/tests/fixtures/benchmarks/items.jsonl diff --git a/crates/horizon-telemetry-server/tests/summary.rs b/crates/horizon-telemetry-server/tests/summary.rs index 3232b4f87..88ae2b283 100644 --- a/crates/horizon-telemetry-server/tests/summary.rs +++ b/crates/horizon-telemetry-server/tests/summary.rs @@ -1,5 +1,5 @@ -//! `GET /v1/benchmarks/summary` against the website's fixtures (website/scripts/fixtures/benchmarks/): the same -//! uploads must give the groups `website/scripts/benchmarks.mjs` gives. +//! `GET /v1/benchmarks/summary` against the shared fixtures (tests/fixtures/benchmarks/): the same uploads must +//! give the groups the website's `scripts/benchmarks.mjs` (ludovic111/horizon-site) gives on its copy of them. use std::sync::Arc; use std::sync::atomic::AtomicU32; @@ -15,10 +15,7 @@ use http_body_util::BodyExt; use serde_json::Value; use tower::ServiceExt; -const FIXTURES: &str = concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../website/scripts/fixtures/benchmarks" -); +const FIXTURES: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/benchmarks"); fn items() -> Vec { std::fs::read_to_string(format!("{FIXTURES}/items.jsonl")) diff --git a/crates/horizon-theme/icons/pixel/star.svg b/crates/horizon-theme/icons/pixel/star.svg new file mode 100644 index 000000000..a27348730 --- /dev/null +++ b/crates/horizon-theme/icons/pixel/star.svg @@ -0,0 +1,3 @@ + + + diff --git a/crates/horizon-theme/src/lib.rs b/crates/horizon-theme/src/lib.rs index dac5bf8d2..b41536e5e 100644 --- a/crates/horizon-theme/src/lib.rs +++ b/crates/horizon-theme/src/lib.rs @@ -1,6 +1,6 @@ //! Horizon's design tokens, the one source of truth for the launcher (`launcher/src/theme.rs`), -//! the game's on-screen keyboard (`horizon-client`'s `ui_theme`) and the website (`website/src/tokens.css`, -//! generated from [`css`] by `cargo run -p xtask -- tokens`). Change a value here and all three +//! the game's on-screen keyboard (`horizon-client`'s `ui_theme`) and the website (`tokens.css` in this crate, +//! generated from [`css`] by `cargo run -p xtask -- tokens`, which the site's build reads from main). Change a value here and all three //! follow. The system is described in `docs/design-system.md`. //! //! Cool neutrals in two appearances and one violet accent; Geist and Geist Mono only, bundled @@ -67,6 +67,8 @@ pub mod icons { "search", "server", "sliders", + // Not Pixelarticons': drawn for Horizon's ratings, in the same 2-unit grid. + "star", "terminal", "trash", "user", @@ -526,7 +528,7 @@ pub fn contrast(a: u32, b: u32) -> f32 { (x.max(y) + 0.05) / (x.min(y) + 0.05) } -/// `website/src/tokens.css`: every token as a CSS custom property, the light palette by +/// `tokens.css`: every token as a CSS custom property, the light palette by /// default, the dark one when the system asks for it or the page sets `data-theme="dark"`. pub fn css() -> String { let mut s = String::new(); @@ -769,15 +771,15 @@ mod tests { assert!((bezier([0., 0., 1., 1.], 0.3) - 0.3).abs() < 1e-3); } - /// `website/src/tokens.css` is what [`css`] writes; regenerate it with - /// `cargo run -p xtask -- tokens`. + /// `tokens.css` (beside Cargo.toml, read by the website's build) is what [`css`] writes; + /// regenerate it with `cargo run -p xtask -- tokens`. #[test] - fn website_tokens_are_up_to_date() { - let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../website/src/tokens.css"); + fn tokens_css_is_up_to_date() { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/tokens.css"); let written = std::fs::read_to_string(path).unwrap_or_default(); assert!( written == css(), - "website/src/tokens.css is out of date: run `cargo run -p xtask -- tokens`" + "crates/horizon-theme/tokens.css is out of date: run `cargo run -p xtask -- tokens`" ); } } diff --git a/website/src/tokens.css b/crates/horizon-theme/tokens.css similarity index 100% rename from website/src/tokens.css rename to crates/horizon-theme/tokens.css diff --git a/crates/horizon-threads/src/lib.rs b/crates/horizon-threads/src/lib.rs index 90c8d128e..917c3b502 100644 --- a/crates/horizon-threads/src/lib.rs +++ b/crates/horizon-threads/src/lib.rs @@ -126,6 +126,38 @@ fn idle() -> bool { false } +/// Give back to the OS the memory the allocator holds free, after something +/// large was dropped: glibc keeps freed pages in the arena of the thread that +/// allocated them, and macOS in its zones until memory runs short. Nothing +/// elsewhere. +pub fn release_free_memory() { + release(); +} + +#[cfg(all(target_os = "linux", target_env = "gnu"))] +fn release() { + // SAFETY: returns free heap pages of every arena to the OS; no live + // allocation moves. + unsafe { + libc::malloc_trim(0); + } +} + +#[cfg(target_vendor = "apple")] +fn release() { + unsafe extern "C" { + fn malloc_zone_pressure_relief(zone: *mut std::ffi::c_void, goal: usize) -> usize; + } + // SAFETY: a null zone means every zone and a goal of 0 as much as it can; + // it frees only pages no allocation uses. + unsafe { + malloc_zone_pressure_relief(std::ptr::null_mut(), 0); + } +} + +#[cfg(not(any(all(target_os = "linux", target_env = "gnu"), target_vendor = "apple")))] +fn release() {} + #[cfg(test)] mod tests { /// The hint holds on the platforms that take it. diff --git a/crates/horizon-world/examples/probe/main.rs b/crates/horizon-world/examples/probe/main.rs index 479a3ed23..b87e5620a 100644 --- a/crates/horizon-world/examples/probe/main.rs +++ b/crates/horizon-world/examples/probe/main.rs @@ -169,6 +169,7 @@ mod stored_effect_attributes_fixture; mod stored_effect_notifications_fixture; mod structure_density_fixture; mod structure_pieces; +mod structure_start_nbt; mod suffocation_fixture; mod swimming_fixture; mod synced_bytes_fixture; @@ -340,6 +341,7 @@ probes! { stored_effect_notifications_fixture, structure_density_fixture, structure_pieces, + structure_start_nbt, suffocation_fixture, swimming_fixture, synced_bytes_fixture, diff --git a/crates/horizon-world/examples/probe/structure_pieces.rs b/crates/horizon-world/examples/probe/structure_pieces.rs index ebbad9c7a..3b1415da5 100644 --- a/crates/horizon-world/examples/probe/structure_pieces.rs +++ b/crates/horizon-world/examples/probe/structure_pieces.rs @@ -21,7 +21,7 @@ use std::{fs, path::Path}; type Error = Box; -fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> { +pub fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> { let facts: Value = serde_json::from_str(&fs::read_to_string(resources.join("facts.json"))?)?; let states = facts["states"].as_array().ok_or("facts states")?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/probe/structure_start_nbt.rs b/crates/horizon-world/examples/probe/structure_start_nbt.rs new file mode 100644 index 000000000..daea17314 --- /dev/null +++ b/crates/horizon-world/examples/probe/structure_start_nbt.rs @@ -0,0 +1,74 @@ +//! The structure starts a chunk owns, as `StructureStart.createTag` saves them. +//! +//! structure_start_nbt ... +//! prints `nbt CX CZ TAG` for every start whose chunk is a target, the tag +//! with sorted keys and typed numbers (VanillaStructureStartOracle's +//! `canonical`), or `unsaved CX CZ ID` when Horizon cannot save it yet. +use horizon_core::position::ChunkPos; +use horizon_world::{ + nbt::Tag, + worldgen::generator::{GeneratorData, OverworldGenerator}, +}; + +type Error = Box; + +/// `VanillaStructureStartOracle.canonical`. +fn canonical(tag: &Tag) -> String { + let join = |parts: Vec| parts.join(","); + match tag { + Tag::Compound(c) => { + let mut keys: Vec<_> = c.keys().map(|k| (k.to_string_lossy(), k)).collect(); + keys.sort_by(|a, b| a.0.encode_utf16().cmp(b.0.encode_utf16())); + let parts = keys + .into_iter() + .map(|(name, key)| format!("{name}:{}", canonical(&c[key]))) + .collect(); + format!("{{{}}}", join(parts)) + } + Tag::List(l) => format!("[{}]", join(l.iter().map(canonical).collect())), + Tag::Byte(v) => format!("{v}b"), + Tag::Short(v) => format!("{v}s"), + Tag::Int(v) => v.to_string(), + Tag::Long(v) => format!("{v}L"), + Tag::Float(bits) => format!("{}f", *bits as i32), + Tag::Double(bits) => format!("{}d", *bits as i64), + Tag::String(s) => format!( + "\"{}\"", + s.to_string_lossy() + .replace('\\', "\\\\") + .replace('"', "\\\"") + ), + Tag::IntArray(a) => format!("[I;{}]", join(a.iter().map(i32::to_string).collect())), + Tag::LongArray(a) => format!("[L;{}]", join(a.iter().map(i64::to_string).collect())), + Tag::ByteArray(a) => format!( + "[B;{}]", + join(a.iter().map(|b| (*b as i8).to_string()).collect()) + ), + Tag::End => "END".into(), + } +} + +pub fn main() -> Result<(), Error> { + let mut args = crate::args().skip(1); + let resources = std::path::PathBuf::from(args.next().ok_or("client resource directory")?); + let seed: i64 = args.next().ok_or("seed")?.parse()?; + let dimension = format!("minecraft:{}", args.next().ok_or("dimension")?); + let registry = crate::structure_pieces::registry(&resources)?; + let data = GeneratorData::load(&resources.join("worldgen"), registry)?; + let generator = OverworldGenerator::for_dimension(data, seed, "minecraft:normal", &dimension)?; + let mut worker = generator.worker(); + for target in args { + let (x, z) = target.split_once(',').ok_or("target cx,cz")?; + let chunk = ChunkPos::new(x.parse()?, z.parse()?); + for start in worker.structure_starts(chunk) { + if start.chunk != chunk { + continue; + } + match start.save() { + Some(tag) => println!("nbt {} {} {}", chunk.x, chunk.z, canonical(&tag)), + None => println!("unsaved {} {} {}", chunk.x, chunk.z, start.name), + } + } + } + Ok(()) +} diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs index e0ef0dca1..4635e8b05 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -16,7 +16,7 @@ use serde_json::Value; use std::{ collections::HashMap, fs::{self, File}, - io::{self, BufReader}, + io, path::Path, sync::Arc, }; @@ -582,8 +582,10 @@ fn fail(message: &str) -> io::Error { invalid(message) } +/// From the file's bytes in memory: several times faster than through a +/// reader on gameplay-facts.json (55 MB), which a first start parses. fn read_json(path: &Path) -> io::Result { - serde_json::from_reader(BufReader::new(File::open(path)?)).map_err(|e| invalid(e.to_string())) + serde_json::from_slice(&fs::read(path)?).map_err(|e| invalid(e.to_string())) } fn interned(cache: &mut HashMap>, text: &str) -> Arc { diff --git a/crates/horizon-world/src/level/hooks.rs b/crates/horizon-world/src/level/hooks.rs index 7f9e8d19a..f716449f5 100644 --- a/crates/horizon-world/src/level/hooks.rs +++ b/crates/horizon-world/src/level/hooks.rs @@ -447,6 +447,13 @@ impl Sim<'_, L> { if !b.table.bool(state, b.props.powered) { self.detector_rail_check_pressed(pos, state); } + } else if data.is(Class::Button) { + // ButtonBlock.entityInside: a wooden button an arrow is inside. + if data.set_type.as_ref().is_some_and(|s| s.arrows) + && !b.table.bool(state, b.props.powered) + { + self.button_check_pressed(pos, state); + } } else if data.is(Class::TripWire) && !b.table.bool(state, b.props.powered) && !self.ticks.has_block_tick(pos, b.block(state)) diff --git a/crates/horizon-world/src/level/interact.rs b/crates/horizon-world/src/level/interact.rs index 7b2195c34..831dea544 100644 --- a/crates/horizon-world/src/level/interact.rs +++ b/crates/horizon-world/src/level/interact.rs @@ -195,6 +195,7 @@ impl Sim<'_, L> { let next = table.cycle(state, p.inverted); self.set_block(pos, next, 2); self.game_event(pos, "minecraft:block_change"); + self.daylight_detector_update_signal(pos, next); Success } Class::Cake => { @@ -227,19 +228,7 @@ impl Sim<'_, L> { if table.int(state, p.level) != 8 { return Pass; } - self.player_effect( - pos, - state, - PlayerEffect::DropItem("minecraft:bone_meal".into()), - ); - self.set_block_and_update(pos, table.set_int(state, p.level, 0)); - self.game_event(pos, "minecraft:block_change"); - self.emit(LevelEvent::Sound { - pos, - sound: "minecraft:block.composter.empty".into(), - volume: 1.0, - pitch: 1.0, - }); + self.composter_extract_produce(pos, state); Success } Class::CaveVines | Class::CaveVinesPlant => { @@ -435,6 +424,25 @@ impl Sim<'_, L> { InteractionResult::Success } + /// `ComposterBlock.extractProduce`: the bone meal pops out, the composter + /// empties and its sound plays. + fn composter_extract_produce(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + self.player_effect( + pos, + state, + PlayerEffect::DropItem("minecraft:bone_meal".into()), + ); + self.set_block_and_update(pos, b.table.set_int(state, b.props.level, 0)); + self.game_event(pos, "minecraft:block_change"); + self.emit(LevelEvent::Sound { + pos, + sound: "minecraft:block.composter.empty".into(), + volume: 1.0, + pitch: 1.0, + }); + } + /// `ComposterBlock.addLayer` once its `compostable` provider gave /// `layers`: the new state (the old one when no layer is added). fn composter_add_layer(&mut self, pos: BlockPos, layers: i32) -> BlockStateId { @@ -499,6 +507,44 @@ impl Behaviours { next } + /// `ComposterBlock.addLayer` without level event 1500, for a villager + /// that composts several items and sends the event once at the end + /// (`WorkAtComposter.compostItems`). The new state. + pub fn composter_layer( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + layers: i32, + ) -> BlockStateId { + self.sim(level, ticks).composter_add_layer(pos, layers) + } + + /// `ComposterBlock.extractProduce` by a villager (`WorkAtComposter`). + pub fn composter_extract( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) { + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + sim.composter_extract_produce(pos, state); + } + + /// Level event 1500 (`WorkAtComposter.spawnComposterFillEffects`): data 1 + /// when the composter's state changed. + pub fn composter_fill_effects( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + changed: bool, + ) { + self.sim(level, ticks) + .level_event(1500, pos, i32::from(changed)); + } + /// `ComposterBlock.empty`: the hopper output container took the bone meal. pub fn composter_empty( &self, diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 3831efbd6..0a8e160cd 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -114,6 +114,7 @@ mod place; mod portal; pub mod portal_travel; mod query; +pub(crate) use query::data_2d; mod rails; mod redstone; pub mod removal; @@ -180,6 +181,8 @@ pub struct GameRules { pub max_snow_accumulation_height: i32, pub spawn_mobs: bool, pub spawn_monsters: bool, + /// `fire_spread_radius_around_player`: -1 spreads everywhere. + pub fire_spread_radius_around_player: i32, } impl Default for GameRules { fn default() -> Self { @@ -192,6 +195,7 @@ impl Default for GameRules { max_snow_accumulation_height: 1, spawn_mobs: true, spawn_monsters: true, + fire_spread_radius_around_player: 128, } } } @@ -205,6 +209,9 @@ pub enum EntityQuery { Mobs, /// Minecarts only (detector rails). Minecart, + /// Arrows only (`AbstractArrow`, thrown tridents included): the entities + /// a wooden button senses. + Arrows, } /// Side effects reported to the caller, in vanilla call order. @@ -287,6 +294,11 @@ pub enum LevelEvent { /// The world as seen by block behaviour. Implemented by the game and tests. pub trait LevelAccess { + /// `Level.isClientSide`: this level is a client's copy (false on a + /// server, a host or the test harness). + fn is_client_side(&self) -> bool { + false + } /// `getBlockState`. Unloaded or out-of-bounds positions read as air. fn block_state(&self, pos: BlockPos) -> BlockStateId; /// Storage write (`LevelChunkSection.setBlockState`). Returns the previous @@ -319,6 +331,10 @@ pub trait LevelAccess { fn sky_darken(&self) -> i32 { 0 } + /// `EnvironmentAttributes.SUN_ANGLE` at `pos`, in degrees (0 at noon). + fn sun_angle(&self, _pos: BlockPos) -> f32 { + 0.0 + } fn is_raining(&self) -> bool { false } @@ -342,6 +358,11 @@ pub trait LevelAccess { fn can_spread_fire_around(&self, _pos: BlockPos) -> bool { true } + /// The `INCREASED_FIRE_BURNOUT` environment attribute at `pos` (a biome + /// attribute). + fn increased_fire_burnout(&self, _pos: BlockPos) -> bool { + false + } /// `Level.isUnobstructed(state, pos, context)`: whether the state's /// collision shape at `pos` would intersect an entity. fn is_unobstructed(&self, _pos: BlockPos, _state: BlockStateId) -> bool { @@ -749,6 +770,24 @@ impl Behaviours { ) { self.sim(level, ticks).entity_inside(pos); } + /// `DaylightDetectorBlock.tickEntity` of the daylight detector at `pos`: + /// its signal follows the sky every 20 game ticks. The detector's ticker + /// exists only where the dimension has sky light. + pub fn tick_daylight_detector( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) { + if level.dimension() == Dimension::Nether || level.game_time() % 20 != 0 { + return; + } + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + if sim.b.data(state).is(classes::Class::DaylightDetector) { + sim.daylight_detector_update_signal(pos, state); + } + } /// `BigDripleafBlock.entityInside` for an entity whose box is inside /// `pos`: whether it is on the ground and its feet's y (`canEntityTilt`). pub fn entity_on_big_dripleaf( @@ -779,6 +818,22 @@ impl Behaviours { ) -> i32 { self.sim(level, ticks).best_neighbor_signal(pos) } + /// `BlockState.onProjectileHit` of a target block (`TargetBlock`) hit by + /// a projectile at `location` on the face with normal `face`; `arrow` + /// for an `AbstractArrow`. Returns the output strength, or None when the + /// block at `pos` is not a target block. + pub fn target_projectile_hit( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + location: [f64; 3], + face: [i32; 3], + arrow: bool, + ) -> Option { + self.sim(level, ticks) + .target_projectile_hit(pos, location, face, arrow) + } } /// One mutable view used by the ported behaviour code. diff --git a/crates/horizon-world/src/level/pistons.rs b/crates/horizon-world/src/level/pistons.rs index 648d6d543..45e469efd 100644 --- a/crates/horizon-world/src/level/pistons.rs +++ b/crates/horizon-world/src/level/pistons.rs @@ -27,6 +27,9 @@ pub struct MovingPiston { pub progress: f32, pub progress_o: f32, pub last_ticked: i64, + /// `PistonMovingBlockEntity.deathTicks`: on a client the entity waits + /// five ticks past progress 1.0 before placing the block itself. + pub death_ticks: i32, /// Identity of this block entity (a replaced entity is a new ticker). pub id: u64, } @@ -126,11 +129,8 @@ impl Sim<'_, L> { self.note_trigger_event(pos, state); true } else if data.is(super::classes::Class::Bell) { - // BellBlockEntity.triggerEvent handles event 1; the server - // broadcasts handled events to the clients. - if a == 1 { - self.emit(LevelEvent::BlockEntityEvent { pos, state, a, b }); - } + // BellBlockEntity.triggerEvent handles event 1; the caller + // reports handled events (`runBlockEvents` broadcasts them). a == 1 } else { false @@ -164,7 +164,9 @@ impl Sim<'_, L> { let Some(piston) = self.moving_piston(pos) else { return; }; - if piston.progress_o >= 1.0 { + // finalTick: `progressO < 1.0 || level.isClientSide` — a client + // finishes its copy even at full progress. + if piston.progress_o >= 1.0 && !self.level.is_client_side() { return; } self.remove_moving_piston(pos); @@ -189,6 +191,20 @@ impl Sim<'_, L> { piston.last_ticked = self.level.game_time(); piston.progress_o = piston.progress; if piston.progress_o >= 1.0 { + if self.level.is_client_side() && piston.death_ticks < 5 { + // The client's copy waits for the server's state before + // placing the block itself (deathTicks < 5). + piston.death_ticks += 1; + if let Some(entry) = self + .ticks + .moving_pistons + .iter_mut() + .find(|(p, _)| *p == pos) + { + entry.1 = piston; + } + return; + } self.remove_moving_piston(pos); if b.is_block(self.state(pos), b.named.moving_piston) { let mut new = self.update_from_neighbour_shapes(piston.moved_state, pos); @@ -241,8 +257,13 @@ impl Sim<'_, L> { direction != Direction::Down && self.has_signal(rel(up, direction), direction) }) } - /// `PistonBaseBlock.checkIfExtend`. + /// `PistonBaseBlock.checkIfExtend`, which `neighborChanged`, `onPlace` + /// and `setPlacedBy` call only server-side: a client moves its pistons on + /// the server's block events alone. pub(crate) fn piston_check_if_extend(&mut self, pos: BlockPos, state: BlockStateId) { + if self.level.is_client_side() { + return; + } let b = self.b; let direction = b.facing(state); let extend = self.piston_neighbor_signal(pos, direction); @@ -527,6 +548,12 @@ impl Sim<'_, L> { for pos in to_destroy.iter().rev() { let state = self.state(*pos); self.drop_resources(state, *pos); + // The client's copy plays the destroy effect itself (the + // server sends no 2001 for piston moves). + let fire = b.is_block(state, b.named.fire) || b.is_block(state, b.named.soul_fire); + if !fire && self.level.is_client_side() { + self.level_event(2001, *pos, state.0 as i32); + } self.set_block(*pos, b.air(), 18); self.game_event(*pos, "minecraft:block_destroy"); to_update.push(state); @@ -551,6 +578,7 @@ impl Sim<'_, L> { progress: 0.0, progress_o: 0.0, last_ticked: 0, + death_ticks: 0, id: 0, }, ); @@ -576,6 +604,7 @@ impl Sim<'_, L> { progress: 0.0, progress_o: 0.0, last_ticked: 0, + death_ticks: 0, id: 0, }, ); @@ -624,13 +653,17 @@ impl Sim<'_, L> { let direction = b.facing(state); let extended_state = b.table.set_bool(state, p.extended, true); let sticky = self.is_sticky_piston(state); - let extend = self.piston_neighbor_signal(pos, direction); - if extend && (a == 1 || a == 2) { - self.set_block(pos, extended_state, 2); - return false; - } - if !extend && a == 0 { - return false; + // The signal re-check is server-only (`!level.isClientSide`): a + // client trusts the event as sent. + if !self.level.is_client_side() { + let extend = self.piston_neighbor_signal(pos, direction); + if extend && (a == 1 || a == 2) { + self.set_block(pos, extended_state, 2); + return false; + } + if !extend && a == 0 { + return false; + } } if a == 0 { if !self.piston_move_blocks(pos, direction, true, sticky) { @@ -664,6 +697,7 @@ impl Sim<'_, L> { progress: 0.0, progress_o: 0.0, last_ticked: 0, + death_ticks: 0, id: 0, }, ); @@ -748,8 +782,18 @@ impl Behaviours { } let mut sim = self.sim(level, ticks); let state = sim.state(event.pos); - if self.block(state) == event.block { - sim.trigger_event(state, event.pos, event.param_a, event.param_b); + if self.block(state) == event.block + && sim.trigger_event(state, event.pos, event.param_a, event.param_b) + { + // ServerLevel.runBlockEvents broadcasts a handled event to + // the clients (`ClientboundBlockEventPacket`); their copy of + // the block re-runs `triggerEvent` (a piston's `moveBlocks`). + sim.emit(LevelEvent::BlockEntityEvent { + pos: event.pos, + state, + a: event.param_a, + b: event.param_b, + }); } } for event in reschedule { @@ -779,4 +823,85 @@ impl Behaviours { self.sim(level, ticks).moving_piston_tick(pos); } } + /// `ClientLevel.blockEvent`: the client re-runs the block's + /// `triggerEvent` on its own level (a piston's `moveBlocks` builds the + /// moving block entities it then animates) instead of waiting for the + /// server's states. No queue and no ticking-chunk gate: a client runs + /// the event where the packet lands. + pub fn client_block_event( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + a: i32, + b: i32, + ) -> bool { + let triggered = { + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + let triggered = sim.trigger_event(state, pos, a, b); + if triggered { + // The client's copy of a handled event reaches the client + // copy of the block entity (a bell's ring). + sim.emit(LevelEvent::BlockEntityEvent { pos, state, a, b }); + } + triggered + }; + self.client_drain_block_events(level, ticks); + triggered + } + /// `ClientLevel.tickBlockEntities` for moving pistons: the client copy of + /// [`Behaviours::tick_block_entities`], without the server's + /// ticking-chunk gate (a client ticks every loaded block entity). One + /// whose block was replaced is dropped (`TickingBlockEntity.isRemoved`). + pub fn client_tick_block_entities( + &self, + level: &mut L, + ticks: &mut Ticks, + ) { + let tickers: Vec<(BlockPos, u64)> = ticks + .moving_pistons + .iter() + .map(|(p, m)| (*p, m.id)) + .collect(); + for (pos, id) in tickers { + if !ticks + .moving_pistons + .iter() + .any(|(p, m)| *p == pos && m.id == id) + { + continue; + } + { + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + if sim.b.is_block(state, sim.b.named.moving_piston) { + sim.moving_piston_tick(pos); + } else { + sim.remove_moving_piston(pos); + } + } + self.client_drain_block_events(level, ticks); + } + } + /// Block events a client-side `triggerEvent` queued + /// (`PistonBaseBlock.checkIfExtend` in a neighbour update): a client + /// runs them as they come (`ClientLevel.blockEvent`), not in a tick pass. + fn client_drain_block_events(&self, level: &mut L, ticks: &mut Ticks) { + while let Some(event) = ticks.block_events.first().copied() { + ticks.block_events.remove(0); + let mut sim = self.sim(level, ticks); + let state = sim.state(event.pos); + if self.block(state) == event.block + && sim.trigger_event(state, event.pos, event.param_a, event.param_b) + { + sim.emit(LevelEvent::BlockEntityEvent { + pos: event.pos, + state, + a: event.param_a, + b: event.param_b, + }); + } + } + } } diff --git a/crates/horizon-world/src/level/redstone.rs b/crates/horizon-world/src/level/redstone.rs index 92f9059e5..42ba42634 100644 --- a/crates/horizon-world/src/level/redstone.rs +++ b/crates/horizon-world/src/level/redstone.rs @@ -11,7 +11,10 @@ use super::{ }; use crate::registry::BlockStateId; use horizon_core::{ - geometry::Direction, position::BlockPos, random::RandomSource, ticks::TickPriority, + geometry::{Direction, trig}, + position::BlockPos, + random::RandomSource, + ticks::TickPriority, }; const SIGNAL_ORDER: [Direction; 6] = [ @@ -879,18 +882,109 @@ impl Sim<'_, L> { } self.game_event(pos, "minecraft:block_activate"); } - /// `ButtonBlock.checkPressed` with no arrows present. + /// `ButtonBlock.tick`. pub(crate) fn button_tick(&mut self, pos: BlockPos, state: BlockStateId) { let b = self.b; - if !b.table.bool(state, b.props.powered) { - return; + if b.table.bool(state, b.props.powered) { + self.button_check_pressed(pos, state); } - self.set_block_and_update(pos, b.table.set_bool(state, b.props.powered, false)); - self.attached_update_neighbours(pos, state); - if let Some(set) = b.data(state).set_type.clone() { - self.sound(pos, &set.button_off, 1.0, 1.0); + } + /// `ButtonBlock.checkPressed`: a button whose type allows arrows is + /// pressed while an arrow is inside its shape, and stays pressed (the + /// release is scheduled again) as long as one is. + pub(crate) fn button_check_pressed(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let data = b.data(state); + let should_be_pressed = data.set_type.as_ref().is_some_and(|s| s.arrows) + && self + .level + .count_entities(self.button_bounds(pos, state), super::EntityQuery::Arrows) + > 0; + let was_pressed = b.table.bool(state, b.props.powered); + if should_be_pressed != was_pressed { + self.set_block_and_update( + pos, + b.table.set_bool(state, b.props.powered, should_be_pressed), + ); + self.attached_update_neighbours(pos, state); + if let Some(set) = data.set_type.clone() { + let sound = if should_be_pressed { + &set.button_on + } else { + &set.button_off + }; + self.sound(pos, sound, 1.0, 1.0); + } + self.game_event( + pos, + if should_be_pressed { + "minecraft:block_activate" + } else { + "minecraft:block_deactivate" + }, + ); + } + if should_be_pressed { + self.schedule_tick(pos, b.block(state), data.ticks_to_stay_pressed); + } + } + /// `ButtonBlock.getShape(...).bounds().move(pos)`: a 6 by 4 plate on the + /// face it is attached to, 2 pixels thick (1 when pressed). + fn button_bounds(&self, pos: BlockPos, state: BlockStateId) -> horizon_core::geometry::Aabb { + use horizon_core::geometry::{Aabb, Vec3}; + let b = self.b; + let thickness = if b.table.bool(state, b.props.powered) { + 1.0 / 16.0 + } else { + 2.0 / 16.0 + }; + let attached = self.face_attached_connected(state).opposite().normal(); + let thick = attached.iter().position(|&n| n != 0).unwrap_or(1); + // The 6 pixel side lies across the button's facing. + let wide = if b.facing(state).normal()[2] != 0 { + 0 + } else { + 2 + }; + let tall = 3 - thick - wide; + let (mut lo, mut hi) = ([0.0; 3], [1.0; 3]); + if attached[thick] > 0 { + lo[thick] = 1.0 - thickness; + } else { + hi[thick] = thickness; + } + (lo[wide], hi[wide]) = (5.0 / 16.0, 11.0 / 16.0); + (lo[tall], hi[tall]) = (6.0 / 16.0, 10.0 / 16.0); + let origin = [f64::from(pos.x), f64::from(pos.y), f64::from(pos.z)]; + Aabb::new( + Vec3::new(origin[0] + lo[0], origin[1] + lo[1], origin[2] + lo[2]), + Vec3::new(origin[0] + hi[0], origin[1] + hi[1], origin[2] + hi[2]), + ) + } + /// `DaylightDetectorBlock.updateSignalStrength`: the effective sky light + /// at the detector, shaped by the sun's angle (or inverted), as its + /// power. + pub(crate) fn daylight_detector_update_signal(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let mut target = (self.level.sky_light(pos) - self.level.sky_darken()).max(0); + if b.table.bool(state, b.props.inverted) { + target = 15 - target; + } else if target > 0 { + let mut sun_angle = self.level.sun_angle(pos) * trig::DEG_TO_RAD; + let offset = if sun_angle < std::f32::consts::PI { + 0.0 + } else { + std::f32::consts::TAU + }; + sun_angle += (offset - sun_angle) * 0.2; + // Math.round(float). + let scaled = target as f32 * trig::cos(f64::from(sun_angle)); + target = (f64::from(scaled) + 0.5).floor() as i32; + } + let target = target.clamp(0, 15); + if b.table.int(state, b.props.power) != target { + self.set_block_and_update(pos, b.table.set_int(state, b.props.power, target)); } - self.game_event(pos, "minecraft:block_deactivate"); } /// `LeverBlock.pull`. pub(crate) fn lever_pull(&mut self, pos: BlockPos, state: BlockStateId) { @@ -1080,7 +1174,8 @@ impl Sim<'_, L> { self.game_event(pos, "minecraft:note_block_play"); } } - /// `NoteBlock.triggerEvent`: the note's sound. + /// `NoteBlock.triggerEvent`: the note's particle (tunable instruments) + /// and sound. pub(crate) fn note_trigger_event(&mut self, pos: BlockPos, state: BlockStateId) { let b = self.b; let instrument = b.table.text(state, b.props.instrument).to_owned(); @@ -1092,6 +1187,12 @@ impl Sim<'_, L> { let pitch = if mob_head { 1.0 } else { + // `isTunable`: the client adds the NOTE particle above the block. + self.emit(LevelEvent::BlockEvent { + pos, + state, + kind: "note_particle", + }); horizon_core::jmath::pow(2.0, f64::from(note - 12) / 12.0) as f32 }; let sound = match instrument.as_str() { @@ -1187,6 +1288,43 @@ impl Sim<'_, L> { self.set_block(pos, next, 2); } } + /// `TargetBlock.onProjectileHit` for a projectile that hit `face` of the + /// block at `pos` at `location`: the output power from how near the + /// face's centre it landed (1 to 15), reset after 20 ticks for an arrow + /// and 8 for anything else, unless a reset is already scheduled. None + /// when the block is not a target block, else the strength. + pub(crate) fn target_projectile_hit( + &mut self, + pos: BlockPos, + location: [f64; 3], + face: [i32; 3], + arrow: bool, + ) -> Option { + let b = self.b; + let state = self.state(pos); + if !b.data(state).is(Class::Target) { + return None; + } + // `getRedstoneStrength`: the distance from the centre along the + // face's two other axes (Mth.frac of the location, minus a half). + let off = |v: f64| (v - v.floor() - 0.5).abs(); + let [dx, dy, dz] = [off(location[0]), off(location[1]), off(location[2])]; + let distance = if face[1] != 0 { + dx.max(dz) + } else if face[2] != 0 { + dx.max(dy) + } else { + dy.max(dz) + }; + let strength = ((15.0 * ((0.5 - distance) / 0.5).clamp(0.0, 1.0)).ceil() as i32).max(1); + let block = b.block(state); + if !self.ticks.has_block_tick(pos, block) { + // `setOutputPower`. + self.set_block_and_update(pos, b.table.set_int(state, b.props.power, strength)); + self.schedule_tick(pos, block, if arrow { 20 } else { 8 }); + } + Some(strength) + } } /// Order `positions` as a `java.util.HashSet` of capacity 16 would diff --git a/crates/horizon-world/src/level/tests.rs b/crates/horizon-world/src/level/tests.rs index 8a4b6c34f..da75083d2 100644 --- a/crates/horizon-world/src/level/tests.rs +++ b/crates/horizon-world/src/level/tests.rs @@ -47,6 +47,8 @@ pub(crate) struct TestLevel { pub day_time: i64, pub events: Vec, pub block_light: HashMap, + /// `Level.isClientSide`. + pub client_side: bool, } impl TestLevel { fn new(b: &Behaviours) -> Self { @@ -58,10 +60,14 @@ impl TestLevel { day_time: 0, events: Vec::new(), block_light: HashMap::new(), + client_side: false, } } } impl LevelAccess for TestLevel { + fn is_client_side(&self) -> bool { + self.client_side + } fn block_state(&self, pos: BlockPos) -> BlockStateId { self.blocks.get(&pos).copied().unwrap_or(self.air) } @@ -919,6 +925,100 @@ fn pistons_push_and_sticky_pistons_pull() { assert_eq!(w.get(BlockPos::new(2, 1, 0)), air); } +/// `ServerLevel.runBlockEvents` reports a handled event for the clients +/// (`ClientboundBlockEventPacket`), carrying the block the event named. +#[test] +fn a_handled_block_event_reaches_the_clients() { + let mut w = world!(); + w.floor(0, 10, "stone"); + let piston = w.id("piston", &[("facing", "east")]); + let block = w.id("redstone_block", &[]); + w.set(BlockPos::new(0, 1, 0), piston); + w.set(BlockPos::new(-1, 1, 0), block); + w.level.events.clear(); + w.full_tick(); + assert!(w.level.events.iter().any(|e| matches!( + e, + LevelEvent::BlockEntityEvent { + pos, + state, + a: 0, + .. + } if *pos == BlockPos::new(0, 1, 0) && *state == piston + ))); +} + +/// `ClientLevel.blockEvent`: the client re-runs `triggerEvent` on its own +/// level, which builds the moving block entities a piston's `moveBlocks` +/// makes, and ticks them to the placed block. +#[test] +fn a_client_replays_a_pistons_block_event() { + let mut w = world!(); + w.floor(0, 10, "stone"); + let piston = w.id("sticky_piston", &[("facing", "east")]); + let dirt = w.id("dirt", &[]); + let block = w.id("redstone_block", &[]); + w.put(BlockPos::new(0, 1, 0), piston); + w.put(BlockPos::new(1, 1, 0), dirt); + w.put(BlockPos::new(-1, 1, 0), block); + w.f.behaviours.client_block_event( + &mut w.level, + &mut w.ticks, + BlockPos::new(0, 1, 0), + 0, + Direction::East as i32, + ); + assert!( + w.ticks + .moving_pistons + .iter() + .any(|(p, _)| *p == BlockPos::new(2, 1, 0)) + ); + for _ in 0..3 { + w.level.time += 1; + w.f.behaviours + .client_tick_block_entities(&mut w.level, &mut w.ticks); + } + assert_eq!(w.get(BlockPos::new(2, 1, 0)), dirt); + assert_eq!( + w.name(BlockPos::new(1, 1, 0)), + "piston_head[facing=east,short=false,type=sticky]" + ); + assert!(w.ticks.moving_pistons.is_empty()); +} + +/// A client's copy of a move doesn't start the pistons the moved block +/// powers (`checkIfExtend` is server-only): their own block events come from +/// the server. +#[test] +fn a_client_replay_starts_no_other_piston() { + let mut w = world!(); + w.floor(0, 10, "stone"); + w.level.client_side = true; + let piston = w.id("piston", &[("facing", "east")]); + let block = w.id("redstone_block", &[]); + let up = w.id("piston", &[("facing", "up")]); + w.put(BlockPos::new(0, 1, 0), piston); + w.put(BlockPos::new(1, 1, 0), block); + w.put(BlockPos::new(2, 2, 0), up); + w.f.behaviours.client_block_event( + &mut w.level, + &mut w.ticks, + BlockPos::new(0, 1, 0), + 0, + Direction::East as i32, + ); + for _ in 0..10 { + w.level.time += 1; + w.f.behaviours + .client_tick_block_entities(&mut w.level, &mut w.ticks); + } + assert_eq!(w.get(BlockPos::new(2, 1, 0)), block); + assert_eq!(w.get(BlockPos::new(2, 2, 0)), up); + assert!(w.ticks.moving_pistons.is_empty()); + assert!(w.ticks.block_events.is_empty()); +} + #[test] fn pistons_pop_fragile_blocks_and_refuse_obsidian() { let mut w = world!(); diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs index 29f53e053..25e2a19d3 100644 --- a/crates/horizon-world/src/level/tick.rs +++ b/crates/horizon-world/src/level/tick.rs @@ -565,9 +565,8 @@ impl Sim<'_, L> { return; } } - // FireBlock.tick reads the INCREASED_FIRE_BURNOUT environment attribute - // (jungles, swamps, peaks, mushroom fields); Horizon doesn't yet. - let burnout = false; + // FireBlock.tick: the INCREASED_FIRE_BURNOUT environment attribute. + let burnout = self.level.increased_fire_burnout(pos); let extra = if burnout { -50 } else { 0 }; for (direction, chance) in [ (Direction::East, 300), diff --git a/crates/horizon-world/src/living_motion.rs b/crates/horizon-world/src/living_motion.rs index b44da8b7b..9c496ed63 100644 --- a/crates/horizon-world/src/living_motion.rs +++ b/crates/horizon-world/src/living_motion.rs @@ -122,3 +122,119 @@ pub fn air_drag(world: &mut W) -> Result { }; Ok(modified_friction(drag, world.air_drag_modifier()? as f32)) } + +#[cfg(test)] +mod tests { + use super::*; + use horizon_core::geometry::{Vec3, trig}; + + struct Jumper { + velocity: Vec3, + sprinting: bool, + yaw: f32, + synced: bool, + } + impl LivingMotionWorld for Jumper { + type Error = (); + fn velocity(&self) -> Vec3 { + self.velocity + } + fn set_velocity(&mut self, velocity: Vec3) -> Result<(), ()> { + self.velocity = velocity; + Ok(()) + } + fn jump_strength(&mut self) -> Result { + Ok(0.42) + } + fn block_jump_factor(&mut self) -> Result { + Ok(1.0) + } + fn has_jump_boost(&mut self) -> Result { + Ok(false) + } + fn jump_boost_amplifier(&mut self) -> Result { + Ok(0) + } + fn sprinting(&mut self) -> Result { + Ok(self.sprinting) + } + fn yaw(&mut self) -> Result { + Ok(self.yaw) + } + fn mark_needs_sync(&mut self) { + self.synced = true; + } + fn no_gravity(&mut self) -> Result { + Ok(false) + } + fn gravity_attribute(&mut self) -> Result { + Ok(0.08) + } + fn has_slow_falling(&mut self) -> Result { + Ok(false) + } + fn controlling_passenger_is_player(&mut self) -> Result { + Ok(false) + } + fn speed(&mut self) -> Result { + Ok(0.1) + } + fn omnidirectional_air_mover(&mut self) -> Result { + Ok(false) + } + fn air_drag_modifier(&mut self) -> Result { + Ok(0.0) + } + } + + fn impulse(yaw: f32) -> (f64, f64) { + let angle = f64::from(yaw * trig::DEG_TO_RAD); + ( + f64::from(-trig::sin(angle)) * 0.2, + f64::from(trig::cos(angle)) * 0.2, + ) + } + + /// LivingEntity.jumpFromGround: a sprint adds ~0.2 along look; a walk does not. + #[test] + fn sprint_jump_adds_look_direction_impulse() { + for yaw in [0.0, 45.0, 90.0, 180.0, 270.0, 300.0] { + let before = Vec3::new(0.13, -0.08, -0.05); + let mut sprinting = Jumper { + velocity: before, + sprinting: true, + yaw, + synced: false, + }; + jump_from_ground(&mut sprinting).unwrap(); + let (dx, dz) = impulse(yaw); + let horizontal = ((dx * dx) + (dz * dz)).sqrt(); + assert!( + (horizontal - 0.2).abs() < 1.0e-4, + "yaw {yaw}: impulse length {horizontal}" + ); + assert!( + (sprinting.velocity.x - (before.x + dx)).abs() < 1.0e-9, + "yaw {yaw}: x {:?} expected {}", + sprinting.velocity, + before.x + dx + ); + assert!((sprinting.velocity.z - (before.z + dz)).abs() < 1.0e-9); + // jump_power narrows the 0.42 strength through float, as vanilla does. + let jump_y = f64::from(0.42_f32); + assert!((sprinting.velocity.y - jump_y).abs() < 1.0e-9); + assert!(sprinting.synced); + + let mut walking = Jumper { + velocity: before, + sprinting: false, + yaw, + synced: false, + }; + jump_from_ground(&mut walking).unwrap(); + assert_eq!(walking.velocity.x, before.x); + assert_eq!(walking.velocity.z, before.z); + assert!((walking.velocity.y - jump_y).abs() < 1.0e-9); + } + } +} diff --git a/crates/horizon-world/src/loot.rs b/crates/horizon-world/src/loot.rs index 96ca5bdee..399c76f69 100644 --- a/crates/horizon-world/src/loot.rs +++ b/crates/horizon-world/src/loot.rs @@ -31,6 +31,9 @@ pub struct LootStack { pub exploration: Option>, /// Set by set_ominous_bottle_amplifier. pub ominous_amplifier: Option, + /// Added by set_stew_effect (the `suspicious_stew_effects` component): + /// (effect id, duration in ticks). + pub stew_effects: Vec<(String, i32)>, } /// `ExplorationMapFunction`'s settings. #[derive(Clone, Debug, PartialEq, Eq)] @@ -74,6 +77,7 @@ impl LootStack { map: false, exploration: None, ominous_amplifier: None, + stew_effects: Vec::new(), } } pub fn is_empty(&self) -> bool { @@ -150,6 +154,8 @@ pub struct LootEntity { pub captain: Option, /// A frog's variant id (`minecraft:warm`). pub frog_variant: Option, + /// A chicken's variant id (`minecraft:warm`). + pub chicken_variant: Option, /// A charged creeper (`Creeper.isPowered`). pub powered: bool, /// Worn and held items by `EquipmentSlot` name (mainhand, offhand, @@ -678,6 +684,13 @@ impl LootData { } } +/// `MobEffect.isInstantaneous`. +fn is_instantaneous(effect: &str) -> bool { + matches!( + effect, + "minecraft:saturation" | "minecraft:instant_health" | "minecraft:instant_damage" + ) +} /// The level of one enchantment on a stack (its `enchantments` component). fn item_level(stack: &LootStack, enchantment: &str) -> i32 { stack @@ -851,6 +864,9 @@ impl Context<'_, R> { "minecraft:frog/variant" => { e.frog_variant.is_some() && want.as_str() == e.frog_variant.as_deref() } + "minecraft:chicken/variant" => { + e.chicken_variant.is_some() && want.as_str() == e.chicken_variant.as_deref() + } _ => false, }), "minecraft:type_specific/sheep" => e @@ -1134,7 +1150,14 @@ impl Context<'_, R> { .random .next_int_bound(effects.len() as i32) .unwrap_or(0) as usize; - self.int(&effects[pick]["duration"]); + let effect = effects[pick]["type"].as_str().unwrap_or(""); + let mut duration = self.int(&effects[pick]["duration"]); + // Seconds, unless the effect is instantaneous. + if !is_instantaneous(effect) { + duration *= 20; + } + // SuspiciousStewEffects.withEffectAdded + stack.stew_effects.push((effect.to_owned(), duration)); } } "minecraft:set_ominous_bottle_amplifier" => { diff --git a/crates/horizon-world/src/worldgen/decoration_order.rs b/crates/horizon-world/src/worldgen/decoration_order.rs index 6b0fb2252..0e53e7d09 100644 --- a/crates/horizon-world/src/worldgen/decoration_order.rs +++ b/crates/horizon-world/src/worldgen/decoration_order.rs @@ -29,7 +29,7 @@ //! overlap), so a chunk may be decorated as soon as no lower-ranked chunk //! within two of it is still waiting: [`DecorationOrder::blocked`]. Chunks //! further apart still decorate in parallel. -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; #[derive(Default)] pub struct DecorationOrder { @@ -121,7 +121,6 @@ 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, VecDeque}; let mut tickets: Vec<(i32, i32)> = (-radius..=radius) .flat_map(|dx| (-radius..=radius).map(move |dz| (center.0 + dx, center.1 + dz))) .collect(); @@ -132,16 +131,31 @@ pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { Reverse(ticket_hash(x, z) & (TICKET_SET_CAPACITY - 1)), ) }); - 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. + // one more ring. + let half = radius.max(0) + LIGHT_LEVEL - TICKET_LEVEL + 1; + ticket_order( + tickets.into(), + TICKETS_IN_FLIGHT, + (center.0 - half, center.1 - half), + (2 * half + 1) as usize, + ) +} + +/// The decoration order of `tickets` (level 31) added in turn, at most +/// `in_flight` at a time. Dense grids of `side` chunks from `origin` hold +/// every chunk this touches, in place of hash maps. +fn ticket_order( + mut tickets: VecDeque<(i32, i32)>, + in_flight: usize, + origin: (i32, i32), + side: usize, +) -> Vec<(i32, i32)> { + use std::cmp::Reverse; + use std::collections::BinaryHeap; 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 cell = |(x, z): (i32, i32)| ((x - origin.0) as usize) * side + (z - origin.1) as usize; let mut active: Vec<(i32, i32)> = Vec::new(); // Queued task per chunk (level, sequence), `NONE` when there is none; // stale heap entries are skipped. @@ -177,10 +191,9 @@ pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { } } }; - for _ in 0..TICKETS_IN_FLIGHT { - if let Some(t) = tickets.pop_front() { - add(t, &mut active, &mut queued, &mut heap, &full); - } + while active.len() < in_flight { + let Some(t) = tickets.pop_front() else { break }; + add(t, &mut active, &mut queued, &mut heap, &full); } while let Some(Reverse((l, s, chunk))) = heap.pop() { let i = cell(chunk); @@ -202,7 +215,7 @@ pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { full[i] = true; } 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 { + while active.len() < in_flight { let Some(t) = tickets.pop_front() else { break }; add(t, &mut active, &mut queued, &mut heap, &full); } @@ -210,10 +223,36 @@ pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { order } +/// The chunks `/forceload add` over chunks `(x0, z0)..=(x1, z1)` decorates, +/// in vanilla's order: ForceLoadCommand adds a FORCED ticket (level 31) per +/// chunk, x-outer, z-inner, all at once. +pub fn forced_order(x0: i32, z0: i32, x1: i32, z1: i32) -> Vec<(i32, i32)> { + let tickets = (x0..=x1) + .flat_map(|x| (z0..=z1).map(move |z| (x, z))) + .collect(); + let pad = LIGHT_LEVEL - TICKET_LEVEL + 1; + let side = ((x1 - x0).max(z1 - z0) + 2 * pad + 1) as usize; + ticket_order(tickets, usize::MAX, (x0 - pad, z0 - pad), side) +} + #[cfg(test)] mod tests { use super::*; + /// Seed 8675309's geodes in chunks (-26, -1) and (14, -20) run into the + /// trial chambers of (-26, 0) and (14, -19); vanilla decorates the lower + /// z first, wherever the batch lies, so the chambers are drawn over them. + #[test] + fn forced_chunks_decorate_x_outer_z_inner() { + let rank = |order: &[(i32, i32)], c| order.iter().position(|&o| o == c).unwrap(); + let west = forced_order(-32, -16, -17, -1); + assert!(rank(&west, (-26, -1)) < rank(&west, (-26, 0))); + let east = forced_order(0, -32, 15, -17); + assert!(rank(&east, (14, -20)) < rank(&east, (14, -19))); + assert_eq!(west[0], (-33, -17)); + assert_eq!(west.len(), 22 * 22); + } + /// 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; diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 316bd837c..f3bf7cab7 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -23,6 +23,7 @@ use super::{ climate::{ClimateSampler, decode_parameter, quantize}, decode_noise, density::DensityRegistry, + generator_structures::Starts, material_condition::{ MaterialConditionRegistry, MaterialConditions, MaterialDensitySources, MaterialRule, MaterialRuleError, MaterialRuleLibrary, MaterialSurfaceQueries, @@ -269,6 +270,20 @@ fn quantize_parameter_report(json: &str) -> Result { } Ok(Value::Array(entries).to_string()) } +/// `load` on a thread of its own ("Worldgen loader"). +fn loading( + load: impl FnOnce() -> T + Send + 'static, +) -> io::Result> { + std::thread::Builder::new() + .name("Worldgen loader".into()) + .spawn(load) +} +/// A loading thread's result; its panic goes on in this thread. +fn joined(thread: std::thread::JoinHandle) -> T { + thread + .join() + .unwrap_or_else(|panic| std::panic::resume_unwind(panic)) +} impl GeneratorData { /// Load a worldgen bundle directory. Required files are JSON objects mapping /// resource identifiers to the resource's JSON text: `noises`, `densities`, @@ -290,6 +305,50 @@ impl GeneratorData { let block_tags = build_tags(&read_bundle(dir, "block_tags")?, |id| { registry.default_state(id).is_some() })?; + let fluid_tags = match read_optional_bundle(dir, "fluid_tags")? { + Some(raw) => build_tags(&raw, |id| { + matches!( + id, + "minecraft:water" + | "minecraft:flowing_water" + | "minecraft:lava" + | "minecraft:flowing_lava" + | "minecraft:empty" + ) + })?, + None => BTreeMap::new(), + }; + // The three biggest reads (the block tables, the structure templates + // and the block behaviours) need only the tags: they run on threads of + // their own while this one reads the rest. A new world's first chunks + // wait for all of it, with the chunk workers idle. + let blocks = loading({ + let (dir, tags, fluids) = (dir.join("blocks"), block_tags.clone(), fluid_tags.clone()); + move || super::generator_blocks::BlockBehavior::load(&dir, registry, &tags, &fluids) + })?; + let structures = loading({ + let (dir, tags) = (dir.to_owned(), block_tags.clone()); + move || -> Result<_, GeneratorError> { + let Ok(json) = fs::read_to_string(dir.join("blocks/structure-blocks.json")) else { + return Ok(None); + }; + Ok(Some(Arc::new(super::structure::StructureResources::new( + registry, + super::structure::StateTransforms::from_json(&json, registry.len())?, + &dir.join("structure"), + read_optional_bundle(&dir, "processor_lists")?.unwrap_or_default(), + &tags, + )))) + } + })?; + let behaviours = loading({ + let root = dir.parent().map(Path::to_owned); + move || { + root.filter(|root| root.join("block-behaviours.json").exists()) + .and_then(|root| crate::level::Behaviours::load(registry, &root).ok()) + .map(Arc::new) + } + })?; let tag_set = |name: &str| -> Result, GeneratorError> { Ok(block_tags .get(name) @@ -382,47 +441,17 @@ impl GeneratorData { read_optional_bundle(dir, "features")?, read_optional_bundle(dir, "placed_features")?, ) { - (Some(features), Some(placed)) => { - let fluid_tags = match read_optional_bundle(dir, "fluid_tags")? { - Some(raw) => build_tags(&raw, |id| { - matches!( - id, - "minecraft:water" - | "minecraft:flowing_water" - | "minecraft:lava" - | "minecraft:flowing_lava" - | "minecraft:empty" - ) - })?, - None => BTreeMap::new(), - }; - Some(FeatureResources { - features, - placed, - feature_tags: read_optional_bundle(dir, "feature_tags")?.unwrap_or_default(), - blocks: super::generator_blocks::BlockBehavior::load( - &dir.join("blocks"), - registry, - &block_tags, - &fluid_tags, - )?, - fluid_tags, - state_providers: read_optional_bundle(dir, "state_providers")? - .unwrap_or_default(), - }) - } + (Some(features), Some(placed)) => Some(FeatureResources { + features, + placed, + feature_tags: read_optional_bundle(dir, "feature_tags")?.unwrap_or_default(), + blocks: joined(blocks)?, + fluid_tags, + state_providers: read_optional_bundle(dir, "state_providers")?.unwrap_or_default(), + }), _ => None, }; - let structures = match fs::read_to_string(dir.join("blocks/structure-blocks.json")) { - Ok(json) => Some(Arc::new(super::structure::StructureResources::new( - registry, - super::structure::StateTransforms::from_json(&json, registry.len())?, - &dir.join("structure"), - read_optional_bundle(dir, "processor_lists")?.unwrap_or_default(), - &block_tags, - ))), - Err(_) => None, - }; + let structures = joined(structures)?; let structure_resources = match ( read_optional_bundle(dir, "structures")?, read_optional_bundle(dir, "structure_sets")?, @@ -435,11 +464,7 @@ impl GeneratorData { }), _ => None, }; - let behaviours = dir - .parent() - .filter(|root| root.join("block-behaviours.json").exists()) - .and_then(|root| crate::level::Behaviours::load(registry, root).ok()) - .map(Arc::new); + let behaviours = joined(behaviours); Ok(Arc::new(Self { behaviours, structure_resources, @@ -543,6 +568,9 @@ pub struct ProtoChunk { pub block_entities: Vec<([i32; 3], crate::nbt::Compound)>, /// Structure starts referencing this chunk (STRUCTURE_REFERENCES). pub(super) structure_starts: Vec>, + /// The starts made in this chunk (STRUCTURE_STARTS), also those none of + /// whose pieces reach it (a giant ruined portal next door). + own_starts: Starts, /// Entities placed by structures (`ProtoChunk.addEntity`), as NBT with /// absolute `Pos`. pub entities: Vec, @@ -594,6 +622,10 @@ impl ProtoChunk { pub fn is_decorated(&self) -> bool { self.decorated } + /// The structure starts this chunk holds itself (`structures.starts`). + pub fn own_starts(&self) -> Vec> { + self.own_starts.to_vec() + } /// Also restores a saved proto chunk that was decorated before it was saved. pub fn set_decorated(&mut self) { self.decorated = true; @@ -1081,16 +1113,19 @@ where ) .map_err(stage("noise"))?; chunk.set_generation_stage(PreLightChunkStage::Biomes); - let references = match &self.structures { - Some(structures) => structures.references( - &mut StructureQueries { + let (references, own_starts) = match &self.structures { + Some(structures) => { + let mut queries = StructureQueries { pipeline: self, worker, valid: BTreeSet::new(), - }, - pos, - ), - None => Vec::new(), + }; + ( + structures.references(&mut queries, pos), + structures.starts_at(&mut queries, pos), + ) + } + None => (Vec::new(), Starts::default()), }; if let Some(beard) = self .structures @@ -1226,6 +1261,7 @@ where decorated: false, block_entities: Vec::new(), structure_starts: references, + own_starts, entities: Vec::new(), }) } @@ -1615,6 +1651,22 @@ pub(super) struct WorkerState { heights: HashMap<(i32, i32, u8), i32>, /// Decorate with structure pieces only (for structure parity checks). pub(super) structures_only: bool, + pub(super) structure_mobs: Option>, +} +/// `Mob.finalizeSpawn(level, difficulty, STRUCTURE, null)` of the entities a +/// structure places with finalizeEntities, run by the game, which owns mobs. +pub trait StructureMobs: Send + Sync { + /// Finalizes the entity in `nbt` if it is a mob, drawing from the + /// region's random. `biome` is the biome at its block, `structures` the + /// structures with a piece there. False when it could not: the entity + /// keeps its `horizon:finalize` for the game to finish on load. + fn finalize( + &self, + nbt: &mut crate::nbt::Compound, + biome: &str, + structures: &[String], + random: &mut dyn super::structure::legacy::PieceRandom, + ) -> bool; } trait SeededPipeline: Send + Sync { @@ -2431,6 +2483,7 @@ impl OverworldGenerator { carver_biomes: HashMap::new(), timings: StageTimings::default(), structures_only: false, + structure_mobs: None, heights: HashMap::new(), }, } @@ -2557,6 +2610,9 @@ impl GeneratorWorker { pub fn set_structures_only(&mut self, only: bool) { self.state.structures_only = only; } + pub fn set_structure_mobs(&mut self, mobs: Arc) { + self.state.structure_mobs = Some(mobs); + } } #[cfg(test)] @@ -2942,6 +2998,26 @@ mod tests { } } + /// Seed 8675309's giant ruined portal starts in chunk (-26, 23) and lies + /// wholly in (-26, 24): its own chunk still holds the start, as vanilla's + /// getAllStarts does, though no piece reaches it. + #[test] + fn a_chunk_holds_its_starts_whose_pieces_lie_elsewhere() { + let Some(data) = prepared_data() else { + return; + }; + let generator = OverworldGenerator::new(data, 8675309).expect("generator"); + let mut worker = generator.worker(); + let proto = worker + .generate_proto(ChunkPos::new(-26, 23)) + .expect("proto"); + let own: Vec<_> = proto.own_starts().iter().map(|s| s.name.clone()).collect(); + assert!( + own.iter().any(|n| n == "minecraft:ruined_portal_mountain"), + "{own:?}" + ); + } + /// Chunks no ring search can end near are decided without the rings, /// which stay unsearched, and get the starts they get with them. #[test] diff --git a/crates/horizon-world/src/worldgen/generator_blocks.rs b/crates/horizon-world/src/worldgen/generator_blocks.rs index ed1182f36..7498b9e66 100644 --- a/crates/horizon-world/src/worldgen/generator_blocks.rs +++ b/crates/horizon-world/src/worldgen/generator_blocks.rs @@ -108,15 +108,26 @@ impl BlockBehavior { let json = |name: &str| -> Result { Ok(serde_json::from_str(&fs::read_to_string(dir.join(name))?)?) }; - let collisions = - 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")?, - )?); + // The support table reads on its own thread while the collision and + // property tables (which need the collisions) read on this one. + let (collisions, properties, support) = std::thread::scope(|scope| { + let support = scope.spawn(|| -> Result<_, GeneratorError> { + Ok(BlockSupportRegistry::from_table( + read("cached-support.nbt")?.table("support")?, + )?) + }); + let collisions = CachedCollisionRegistry::from_table( + read("cached-collision.nbt")?.table("collision")?, + )?; + let properties = BlockPropertiesRegistry::from_table( + read("block-properties.nbt")?.table("block property")?, + &collisions, + )?; + let support = support + .join() + .unwrap_or_else(|panic| std::panic::resume_unwind(panic))?; + Ok::<_, GeneratorError>((collisions, properties, Arc::new(support))) + })?; let collision = Arc::new(BlockCollisionRegistry::new(Arc::new(collisions))?); let rules = json("survival-rules.json")? .as_object() diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs index fc1cd8bcf..0f3ea6810 100644 --- a/crates/horizon-world/src/worldgen/generator_decoration.rs +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -310,6 +310,7 @@ impl Decoration { Err(e) => return Err(resource(e.to_string())), }; let structures_only = worker.structures_only; + let references = region[4].structure_starts.clone(); let mut block_entities = Vec::new(); for chunk in region.iter_mut() { block_entities.append(&mut chunk.block_entities); @@ -318,6 +319,9 @@ impl Decoration { block_entities, entities: Vec::new(), level_random, + structure_mobs: worker.structure_mobs.clone(), + starts: references.clone(), + biome_names: data.biome_names(), blocks: data .feature_resources .as_ref() @@ -334,7 +338,6 @@ impl Decoration { }; let mut stats = DecorateStats::default(); let blocks = self.blocks; - let references = region[4].structure_starts.clone(); // ChunkGenerator.getWritableArea: the chunk's minimum Y + 1 to its maximum Y. let chunk_box = BoundingBox::new( [center.x * 16, min_y + 1, center.z * 16], @@ -419,15 +422,11 @@ impl Decoration { } // WorldGenRegion.addFreshEntity: into the chunk holding the position. for nbt in std::mem::take(&mut world.entities) { - let Some(crate::nbt::Tag::List(p)) = nbt.get(&"Pos".into()) else { + let Some(at) = block_of(&nbt) else { continue; }; - let coord = |i: usize| match p.get(i) { - Some(crate::nbt::Tag::Double(b)) => f64::from_bits(*b).floor() as i32, - _ => 0, - }; - let index = ((coord(2) >> 4).wrapping_sub(center.z) + 1) * 3 - + (coord(0) >> 4).wrapping_sub(center.x) + let index = ((at[2] >> 4).wrapping_sub(center.z) + 1) * 3 + + (at[0] >> 4).wrapping_sub(center.x) + 1; if let Some(chunk) = usize::try_from(index).ok().and_then(|i| region.get_mut(i)) { chunk.entities.push(nbt); @@ -454,6 +453,9 @@ struct World<'a> { block_entities: Vec<([i32; 3], crate::nbt::Compound)>, entities: Vec, level_random: &'a mut dyn super::structure::legacy::PieceRandom, + structure_mobs: Option>, + starts: Vec>, + biome_names: &'a [Arc], blocks: Option<&'a BlockBehavior>, region: TerrainRegion<'static, GenBlockStates>, biomes: BiomeRegion, @@ -847,10 +849,57 @@ impl PlacementContext for World<'_> { (0..ny).all(|y| (0..nz).all(|z| shape.is_full(x as i32, y as i32, z as i32))) })) } - fn add_entity(&mut self, nbt: crate::nbt::Compound) -> Result<(), PlacementQueryError> { + fn add_entity(&mut self, mut nbt: crate::nbt::Compound) -> Result<(), PlacementQueryError> { + if let Some(mobs) = self.structure_mobs.clone() + && nbt.contains_key(&"horizon:finalize".into()) + { + let at = block_of(&nbt).unwrap_or([0; 3]); + let biome = self + .biome_identity(at) + .ok() + .and_then(|b| self.biome_names.get(b.0 as usize)) + .map_or("", |n| &**n) + .to_owned(); + let structures: Vec = self + .starts + .iter() + .filter(|s| s.pieces.iter().any(|p| p.bounding_box().is_inside(at))) + .map(|s| s.name.clone()) + .collect(); + if mobs.finalize(&mut nbt, &biome, &structures, self.level_random) { + nbt.remove(&"horizon:finalize".into()); + } + } self.entities.push(nbt); Ok(()) } + /// SpikeFeature.placeSpike: the crystal is a fresh entity of the region, + /// saved with the chunk. + fn spawn_end_crystal( + &mut self, + position: [f64; 3], + yaw: f32, + beam_target: Option<[i32; 3]>, + invulnerable: bool, + ) -> Result<(), PlacementQueryError> { + use crate::nbt::Tag; + let mut nbt = crate::nbt::Compound::new(); + nbt.insert("id".into(), Tag::String("minecraft:end_crystal".into())); + nbt.insert( + "Pos".into(), + Tag::List(position.iter().map(|v| Tag::Double(v.to_bits())).collect()), + ); + nbt.insert( + "Rotation".into(), + Tag::List(vec![Tag::Float(yaw.to_bits()), Tag::Float(0)]), + ); + nbt.insert("Invulnerable".into(), Tag::Byte(i8::from(invulnerable))); + nbt.insert("ShowBottom".into(), Tag::Byte(1)); + if let Some(b) = beam_target { + nbt.insert("beam_target".into(), Tag::IntArray(b.to_vec())); + } + self.add_entity(nbt) + } fn set_block_entity( &mut self, position: [i32; 3], @@ -1167,3 +1216,14 @@ impl PlacementContext for World<'_> { Ok(Some(false)) } } + +/// The block an entity's `Pos` is in. +fn block_of(nbt: &crate::nbt::Compound) -> Option<[i32; 3]> { + let Some(crate::nbt::Tag::List(p)) = nbt.get(&"Pos".into()) else { + return None; + }; + Some(std::array::from_fn(|i| match p.get(i) { + Some(crate::nbt::Tag::Double(b)) => f64::from_bits(*b).floor() as i32, + _ => 0, + })) +} diff --git a/crates/horizon-world/src/worldgen/structure.rs b/crates/horizon-world/src/worldgen/structure.rs index e0ac4d9e8..c998cc3be 100644 --- a/crates/horizon-world/src/worldgen/structure.rs +++ b/crates/horizon-world/src/worldgen/structure.rs @@ -79,6 +79,15 @@ impl Rotation { pub fn get_rotated(self, other: Self) -> Self { Self::ALL[(self as usize + other as usize) % 4] } + /// `Rotation.name()`, as structure pieces save it. + pub fn saved_name(self) -> &'static str { + match self { + Self::None => "NONE", + Self::Clockwise90 => "CLOCKWISE_90", + Self::Clockwise180 => "CLOCKWISE_180", + Self::Counterclockwise90 => "COUNTERCLOCKWISE_90", + } + } } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Mirror { @@ -86,6 +95,16 @@ pub enum Mirror { LeftRight, FrontBack, } +impl Mirror { + /// `Mirror.name()`, as structure pieces save it. + pub fn saved_name(self) -> &'static str { + match self { + Self::None => "NONE", + Self::LeftRight => "LEFT_RIGHT", + Self::FrontBack => "FRONT_BACK", + } + } +} /// Inclusive integer box (vanilla BoundingBox). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] diff --git a/crates/horizon-world/src/worldgen/structure/end_city.rs b/crates/horizon-world/src/worldgen/structure/end_city.rs index 225f810f5..b440fc832 100644 --- a/crates/horizon-world/src/worldgen/structure/end_city.rs +++ b/crates/horizon-world/src/worldgen/structure/end_city.rs @@ -381,19 +381,22 @@ pub fn pieces( } else { vec!["minecraft:structure_block".into(), "minecraft:air".into()] }; - EndCityPiece(TemplatePiece::new( - "minecraft:ecp", - &format!("minecraft:end_city/{}", d.name), - d.template, - d.position, - d.rotation, - Mirror::None, - [0; 3], - Arc::new(ProcessorList::default()), - true, - ignore, - TemplateHandler::Plain, - )) + EndCityPiece( + TemplatePiece::new( + "minecraft:ecp", + &format!("minecraft:end_city/{}", d.name), + d.template, + d.position, + d.rotation, + Mirror::None, + [0; 3], + Arc::new(ProcessorList::default()), + true, + ignore, + TemplateHandler::Plain, + ), + d.depth, + ) }) .collect(), ) @@ -401,11 +404,21 @@ pub fn pieces( /// EndCityPieces.EndCityPiece. #[derive(Debug)] -pub struct EndCityPiece(TemplatePiece); +/// The template piece and its genDepth (the collision tag of its batch). +pub struct EndCityPiece(TemplatePiece, i32); impl LegacyPiece for EndCityPiece { fn bounding_box(&self) -> BoundingBox { self.0.bounding_box } + /// `EndCityPiece`: the template piece's tag, `OW` for the pieces that + /// overwrite air (only structure blocks ignored). + fn save(&self) -> Option { + let mut tag = self.0.saved(); + tag.insert("GD".into(), crate::nbt::Tag::Int(self.1)); + let overwrite = self.0.ignore.len() == 1; + tag.insert("OW".into(), crate::nbt::Tag::Byte(i8::from(overwrite))); + Some(tag) + } fn type_name(&self) -> &'static str { "minecraft:ecp" } diff --git a/crates/horizon-world/src/worldgen/structure/enhanced_terrain.rs b/crates/horizon-world/src/worldgen/structure/enhanced_terrain.rs index 24c3b9a82..04f14e969 100644 --- a/crates/horizon-world/src/worldgen/structure/enhanced_terrain.rs +++ b/crates/horizon-world/src/worldgen/structure/enhanced_terrain.rs @@ -294,6 +294,8 @@ mod tests { source_x: junction[0], source_ground_y: junction[1], source_z: junction[2], + delta_y: 0, + dest_projection: Projection::Rigid, }], waterlogging: false, }) @@ -303,6 +305,7 @@ mod tests { Arc::new(PoolElement::Single { template: Arc::new(StructureTemplate::empty()), processors: Default::default(), + processors_source: serde_json::Value::Null, legacy: false, projection, waterlogging: None, diff --git a/crates/horizon-world/src/worldgen/structure/fortress.rs b/crates/horizon-world/src/worldgen/structure/fortress.rs index 4d3704413..521dac872 100644 --- a/crates/horizon-world/src/worldgen/structure/fortress.rs +++ b/crates/horizon-world/src/worldgen/structure/fortress.rs @@ -871,6 +871,29 @@ impl LegacyPiece for FortressPiece { fn bounding_box(&self) -> BoundingBox { self.frame.bounding_box } + fn save(&self) -> Option { + use crate::nbt::Tag; + let mut tag = super::legacy::piece_tag( + self.type_name(), + self.frame.bounding_box, + self.frame.orientation, + self.depth, + ); + let flag = Tag::Byte(i8::from(*self.flag.lock().unwrap())); + match self.kind { + Kind::BridgeEndFiller => { + tag.insert("Seed".into(), Tag::Int(self.seed)); + } + Kind::SmallCorridorLeftTurn | Kind::SmallCorridorRightTurn => { + tag.insert("Chest".into(), flag); + } + Kind::MonsterThrone => { + tag.insert("Mob".into(), flag); + } + _ => {} + } + Some(tag) + } fn type_name(&self) -> &'static str { match self.kind { // StartPiece is built through the BridgeCrossing constructor. diff --git a/crates/horizon-world/src/worldgen/structure/jigsaw.rs b/crates/horizon-world/src/worldgen/structure/jigsaw.rs index a6cf7a22a..6fd935024 100644 --- a/crates/horizon-world/src/worldgen/structure/jigsaw.rs +++ b/crates/horizon-world/src/worldgen/structure/jigsaw.rs @@ -5,6 +5,7 @@ use super::{ }; use crate::{ heightmap::HeightmapType, + nbt::{Compound, Tag}, worldgen::{ DecodeError, block_feature::FeatureBlockBindings, @@ -30,12 +31,24 @@ pub enum Projection { Rigid, TerrainMatching, } +impl Projection { + /// `StructureTemplatePool.Projection.getSerializedName`. + pub fn saved_name(self) -> &'static str { + match self { + Self::Rigid => "rigid", + Self::TerrainMatching => "terrain_matching", + } + } +} #[derive(Clone, Debug)] pub enum PoolElement { Empty, Single { template: Arc, processors: ProcessorList, + /// The element's `processors` as written: a list id or an inline list, + /// saved back as it was. + processors_source: Value, legacy: bool, projection: Projection, waterlogging: Option, @@ -136,6 +149,7 @@ impl PoolElement { resources, bindings, )?, + processors_source: value["processors"].clone(), legacy: kind == "minecraft:legacy_single_pool_element", projection: projection()?, waterlogging: match value @@ -178,6 +192,64 @@ impl PoolElement { _ => return Err(DecodeError::Field("pool element type")), }) } + /// `StructurePoolElement.CODEC`'s encoding, as a jigsaw piece saves it. + pub fn save(&self) -> Tag { + let text = |s: &str| Tag::String(s.into()); + match self { + Self::Empty => Tag::compound([("element_type", text("minecraft:empty_pool_element"))]), + Self::Single { + template, + processors_source, + legacy, + projection, + waterlogging, + .. + } => { + let kind = if *legacy { + "minecraft:legacy_single_pool_element" + } else { + "minecraft:single_pool_element" + }; + let mut entries = vec![ + ("element_type", text(kind)), + ("location", text(&template.location)), + ( + "processors", + super::processor::json_to_nbt(processors_source), + ), + ("projection", text(projection.saved_name())), + ]; + if let Some(apply) = waterlogging { + let settings = if *apply { + "apply_waterlogging" + } else { + "ignore_waterlogging" + }; + entries.push(("override_liquid_settings", text(settings))); + } + Tag::compound(entries) + } + Self::Feature { + feature, + projection, + } => Tag::compound([ + ("element_type", text("minecraft:feature_pool_element")), + ("feature", text(feature)), + ("projection", text(projection.saved_name())), + ]), + Self::List { + elements, + projection, + } => Tag::compound([ + ("element_type", text("minecraft:list_pool_element")), + ( + "elements", + Tag::List(elements.iter().map(Self::save).collect()), + ), + ("projection", text(projection.saved_name())), + ]), + } + } pub fn projection(&self) -> Projection { match self { Self::Empty => Projection::TerrainMatching, @@ -466,6 +538,9 @@ pub struct Junction { pub source_x: i32, pub source_ground_y: i32, pub source_z: i32, + /// Saved only (`JigsawJunction.deltaY`, `destProjection`). + pub delta_y: i32, + pub dest_projection: Projection, } #[derive(Debug)] pub struct PoolPiece { @@ -517,6 +592,12 @@ impl PoolPiece { source_x: int(j, "source_x")?, source_ground_y: int(j, "source_ground_y")?, source_z: int(j, "source_z")?, + delta_y: int(j, "delta_y")?, + dest_projection: match j["dest_proj"].as_str() { + Some("rigid") => Projection::Rigid, + Some("terrain_matching") => Projection::TerrainMatching, + _ => return Err(DecodeError::Field("dest_proj")), + }, }) }) .collect::>()?; @@ -535,6 +616,45 @@ impl PoolPiece { waterlogging: v["liquid_settings"].as_str() != Some("ignore_waterlogging"), }) } + /// `PoolElementStructurePiece`'s tag (always genDepth 0, no orientation). + pub fn save(&self) -> Compound { + let mut tag = super::legacy::piece_tag("minecraft:jigsaw", self.bounding_box, None, 0); + let junctions = self + .junctions + .iter() + .map(|j| { + Tag::compound([ + ("source_x", Tag::Int(j.source_x)), + ("source_ground_y", Tag::Int(j.source_ground_y)), + ("source_z", Tag::Int(j.source_z)), + ("delta_y", Tag::Int(j.delta_y)), + ( + "dest_proj", + Tag::String(j.dest_projection.saved_name().into()), + ), + ]) + }) + .collect(); + for (key, value) in [ + ("PosX", Tag::Int(self.position[0])), + ("PosY", Tag::Int(self.position[1])), + ("PosZ", Tag::Int(self.position[2])), + ("ground_level_delta", Tag::Int(self.ground_level_delta)), + ("pool_element", self.element.save()), + ("rotation", Tag::String(self.rotation.saved_name().into())), + ("junctions", Tag::List(junctions)), + ] { + tag.insert(key.into(), value); + } + // LiquidSettings.APPLY_WATERLOGGING, the default, is not written. + if !self.waterlogging { + tag.insert( + "liquid_settings".into(), + Tag::String("ignore_waterlogging".into()), + ); + } + tag + } pub(super) fn moved(&mut self, dy: i32) { self.position[1] += dy; self.bounding_box = self.bounding_box.moved([0, dy, 0]); @@ -1204,6 +1324,8 @@ impl Placer<'_, '_> { source_x: target_pos[0], source_ground_y: junction_y - local_y + source_ground, source_z: target_pos[2], + delta_y, + dest_projection: target.projection(), }); self.pieces.push(PoolPiece { element: target.clone(), @@ -1215,6 +1337,12 @@ impl Placer<'_, '_> { source_x: jigsaw.pos[0], source_ground_y: junction_y - target_local_y + target_ground, source_z: jigsaw.pos[2], + delta_y: -delta_y, + dest_projection: if source_rigid { + Projection::Rigid + } else { + Projection::TerrainMatching + }, }], waterlogging: self.config.waterlogging, }); diff --git a/crates/horizon-world/src/worldgen/structure/legacy.rs b/crates/horizon-world/src/worldgen/structure/legacy.rs index f558081ee..19d121718 100644 --- a/crates/horizon-world/src/worldgen/structure/legacy.rs +++ b/crates/horizon-world/src/worldgen/structure/legacy.rs @@ -31,14 +31,19 @@ pub type Markers = Vec<(String, [i32; 3])>; pub trait PieceRandom: ProcessorRandom { fn boolean(&mut self) -> bool; fn double(&mut self) -> f64; + /// The concrete random, for callers that need all of `RandomSource`. + fn as_any(&mut self) -> &mut dyn std::any::Any; } -impl PieceRandom for R { +impl PieceRandom for R { fn boolean(&mut self) -> bool { self.next_boolean() } fn double(&mut self) -> f64 { self.next_double() } + fn as_any(&mut self) -> &mut dyn std::any::Any { + self + } } /// Object-safe world access for piece post-processing. @@ -282,6 +287,11 @@ pub trait LegacyPiece: std::fmt::Debug + Send + Sync { fn bounding_box(&self) -> BoundingBox; /// The vanilla StructurePieceType id, for diagnostics and comparisons. fn type_name(&self) -> &'static str; + /// `StructurePiece.createTag`; None while Horizon cannot save this type, + /// and then its start is not saved. + fn save(&self) -> Option { + None + } fn post_process(&self, context: &mut PieceContext<'_>) -> Result<()>; /// Structure.afterPlace, run on the first piece once per chunk after all /// pieces were placed, with every piece's current box. @@ -290,6 +300,31 @@ pub trait LegacyPiece: std::fmt::Debug + Send + Sync { } } +/// `StructurePiece.createTag`'s own fields: the type, `BB`, `O` (the +/// orientation's 2D data value, -1 for none) and `GD` (genDepth). +pub fn piece_tag( + id: &str, + b: BoundingBox, + orientation: Option, + gen_depth: i32, +) -> Compound { + let o = orientation.map_or(-1, crate::level::data_2d); + [ + ("id", Tag::String(id.into())), + ( + "BB", + Tag::IntArray(vec![ + b.min[0], b.min[1], b.min[2], b.max[0], b.max[1], b.max[2], + ]), + ), + ("O", Tag::Int(o)), + ("GD", Tag::Int(gen_depth)), + ] + .into_iter() + .map(|(k, v)| (JavaString::from(k), v)) + .collect() +} + /// StructurePiece's orientation transform and block helpers. #[derive(Clone, Copy, Debug)] pub struct PieceFrame { diff --git a/crates/horizon-world/src/worldgen/structure/mineshaft.rs b/crates/horizon-world/src/worldgen/structure/mineshaft.rs index 1173c03bf..0c2d32c08 100644 --- a/crates/horizon-world/src/worldgen/structure/mineshaft.rs +++ b/crates/horizon-world/src/worldgen/structure/mineshaft.rs @@ -732,6 +732,57 @@ impl LegacyPiece for MineshaftPiece { fn bounding_box(&self) -> BoundingBox { self.frame.bounding_box } + fn save(&self) -> Option { + use crate::nbt::Tag; + let flag = |b: bool| Tag::Byte(i8::from(b)); + let mut tag = super::legacy::piece_tag( + self.type_name(), + self.frame.bounding_box, + self.frame.orientation, + self.depth, + ); + // MineshaftStructure.Type's ordinal: NORMAL, MESA. + let mesa = self.wood.log == MESA.log; + let mut entries = vec![("MST", Tag::Int(i32::from(mesa)))]; + match &self.kind { + Kind::Room(entrances) => entries.push(( + "Entrances", + Tag::List( + entrances + .iter() + .map(|b| { + Tag::IntArray(vec![ + b.min[0], b.min[1], b.min[2], b.max[0], b.max[1], b.max[2], + ]) + }) + .collect(), + ), + )), + Kind::Corridor { + rails, + spider, + sections, + placed_spider, + } => entries.extend([ + ("hr", flag(*rails)), + ("sc", flag(*spider)), + ("hps", flag(*placed_spider.lock().unwrap())), + ("Num", Tag::Int(*sections)), + ]), + Kind::Crossing { + direction, + two_floored, + } => { + let d = crate::level::data_2d(*direction) as i8; + entries.extend([("tf", flag(*two_floored)), ("D", Tag::Byte(d))]); + } + Kind::Stairs => {} + } + for (key, value) in entries { + tag.insert(key.into(), value); + } + Some(tag) + } fn type_name(&self) -> &'static str { match self.kind { Kind::Room(_) => "minecraft:msroom", diff --git a/crates/horizon-world/src/worldgen/structure/monument.rs b/crates/horizon-world/src/worldgen/structure/monument.rs index 39959557e..ababac969 100644 --- a/crates/horizon-world/src/worldgen/structure/monument.rs +++ b/crates/horizon-world/src/worldgen/structure/monument.rs @@ -463,6 +463,16 @@ impl LegacyPiece for MonumentBuilding { fn type_name(&self) -> &'static str { "minecraft:omb" } + /// `MonumentBuilding`: the base fields only; vanilla builds its rooms + /// again after loading (`OceanMonumentStructure.regeneratePiecesAfterLoad`). + fn save(&self) -> Option { + Some(super::legacy::piece_tag( + "minecraft:omb", + self.frame.bounding_box, + self.frame.orientation, + 0, + )) + } fn post_process(&self, c: &mut PieceContext<'_>) -> Result<()> { let sea = c.world.sea_level()?; let water = c.state("water"); diff --git a/crates/horizon-world/src/worldgen/structure/nether_fossil.rs b/crates/horizon-world/src/worldgen/structure/nether_fossil.rs index 48e4de58a..b80b8c1a8 100644 --- a/crates/horizon-world/src/worldgen/structure/nether_fossil.rs +++ b/crates/horizon-world/src/worldgen/structure/nether_fossil.rs @@ -73,6 +73,9 @@ impl LegacyPiece for NetherFossilPiece { fn bounding_box(&self) -> BoundingBox { self.0.bounding_box } + fn save(&self) -> Option { + Some(self.0.saved()) + } fn type_name(&self) -> &'static str { "minecraft:nefos" } diff --git a/crates/horizon-world/src/worldgen/structure/ocean_ruin.rs b/crates/horizon-world/src/worldgen/structure/ocean_ruin.rs index 9d0ce8923..bf15dc372 100644 --- a/crates/horizon-world/src/worldgen/structure/ocean_ruin.rs +++ b/crates/horizon-world/src/worldgen/structure/ocean_ruin.rs @@ -325,6 +325,8 @@ pub fn post_process(piece: &TemplatePiece, c: &mut PieceContext<'_>) -> Result<( new_y = min_y + 1; } position[1] = new_y; + // OceanRuinPiece.postProcess keeps the height in templatePosition. + *piece.state.lock().unwrap() = Some(new_y); if let Some(markers) = piece.place_at(c, position, &[])? { for (marker, pos) in markers { if marker == "chest" { diff --git a/crates/horizon-world/src/worldgen/structure/piece_limited.rs b/crates/horizon-world/src/worldgen/structure/piece_limited.rs index 6977ebc88..8b3a6d7de 100644 --- a/crates/horizon-world/src/worldgen/structure/piece_limited.rs +++ b/crates/horizon-world/src/worldgen/structure/piece_limited.rs @@ -910,6 +910,8 @@ impl Assembler<'_> { source_x: slot.target_pos[0], source_ground_y: junction_y - local_y + source_ground, source_z: slot.target_pos[2], + delta_y, + dest_projection: target.projection(), }); slot.free.borrow_mut().removed.push(target_box); self.pieces.push(PoolPiece { @@ -922,6 +924,12 @@ impl Assembler<'_> { source_x: jigsaw.pos[0], source_ground_y: junction_y - target_local[1] + target_ground, source_z: jigsaw.pos[2], + delta_y: -delta_y, + dest_projection: if source_rigid { + Projection::Rigid + } else { + Projection::TerrainMatching + }, }], waterlogging: self.config.waterlogging, }); @@ -1022,6 +1030,7 @@ mod tests { let element = Arc::new(PoolElement::Single { template, processors: Default::default(), + processors_source: serde_json::Value::Null, legacy: false, projection: Projection::Rigid, waterlogging: None, @@ -1038,6 +1047,8 @@ mod tests { source_x: 1, source_ground_y: 2, source_z: 3, + delta_y: 0, + dest_projection: Projection::Rigid, }], waterlogging: true, }; diff --git a/crates/horizon-world/src/worldgen/structure/processor.rs b/crates/horizon-world/src/worldgen/structure/processor.rs index b0a0622b7..0665f785d 100644 --- a/crates/horizon-world/src/worldgen/structure/processor.rs +++ b/crates/horizon-world/src/worldgen/structure/processor.rs @@ -706,7 +706,7 @@ fn holder_set( } Ok(Arc::new(out)) } -fn json_to_nbt(value: &Value) -> Tag { +pub(super) fn json_to_nbt(value: &Value) -> Tag { match value { Value::Bool(b) => Tag::Byte(i8::from(*b)), Value::Number(n) => match n.as_i64() { diff --git a/crates/horizon-world/src/worldgen/structure/ruined_portal.rs b/crates/horizon-world/src/worldgen/structure/ruined_portal.rs index 76010aa86..4f87cdd10 100644 --- a/crates/horizon-world/src/worldgen/structure/ruined_portal.rs +++ b/crates/horizon-world/src/worldgen/structure/ruined_portal.rs @@ -25,6 +25,17 @@ pub enum Vertical { InNether, } impl Vertical { + /// `RuinedPortalPiece.VerticalPlacement.getSerializedName`. + fn saved_name(self) -> &'static str { + match self { + Self::OnLandSurface => "on_land_surface", + Self::PartlyBuried => "partly_buried", + Self::OnOceanFloor => "on_ocean_floor", + Self::InMountain => "in_mountain", + Self::Underground => "underground", + Self::InNether => "in_nether", + } + } fn heightmap(self) -> HeightmapType { if self == Self::OnOceanFloor { HeightmapType::OceanFloorWg @@ -70,6 +81,9 @@ impl Setup { #[derive(Clone, Copy, Debug)] pub struct PortalProps { placement: Vertical, + mossiness: f32, + air_pocket: bool, + blackstone: bool, cold: bool, overgrown: bool, vines: bool, @@ -182,6 +196,9 @@ pub fn start( }; let props = PortalProps { placement: setup.placement, + mossiness: setup.mossiness, + air_pocket, + blackstone: setup.blackstone, cold, overgrown: setup.overgrown, vines: setup.vines, @@ -379,3 +396,28 @@ pub fn post_process(piece: &TemplatePiece, c: &mut PieceContext<'_>) -> Result<( } Ok(()) } + +impl PortalProps { + /// `RuinedPortalPiece`'s `VerticalPlacement` and `Properties` tags. + pub fn save(&self) -> [(&'static str, crate::nbt::Tag); 2] { + use crate::nbt::Tag; + let flag = |b: bool| Tag::Byte(i8::from(b)); + [ + ( + "VerticalPlacement", + Tag::String(self.placement.saved_name().into()), + ), + ( + "Properties", + Tag::compound([ + ("cold", flag(self.cold)), + ("mossiness", Tag::Float(self.mossiness.to_bits())), + ("air_pocket", flag(self.air_pocket)), + ("overgrown", flag(self.overgrown)), + ("vines", flag(self.vines)), + ("replace_with_blackstone", flag(self.blackstone)), + ]), + ), + ] + } +} diff --git a/crates/horizon-world/src/worldgen/structure/simple.rs b/crates/horizon-world/src/worldgen/structure/simple.rs index 72aab4710..d05aab20f 100644 --- a/crates/horizon-world/src/worldgen/structure/simple.rs +++ b/crates/horizon-world/src/worldgen/structure/simple.rs @@ -18,11 +18,22 @@ fn empty_processors() -> Arc { #[derive(Debug)] pub struct BuriedTreasurePiece { pub position: [i32; 3], + /// Where the chest went: the box vanilla saves once placed. + pub found: Mutex>, } impl LegacyPiece for BuriedTreasurePiece { fn bounding_box(&self) -> BoundingBox { BoundingBox::new(self.position, self.position) } + fn save(&self) -> Option { + let at = self.found.lock().unwrap().unwrap_or(self.position); + Some(super::legacy::piece_tag( + "minecraft:btp", + BoundingBox::new(at, at), + None, + 0, + )) + } fn type_name(&self) -> &'static str { "minecraft:btp" } @@ -58,6 +69,7 @@ impl LegacyPiece for BuriedTreasurePiece { } } } + *self.found.lock().unwrap() = Some(pos); create_chest(c, pos, "minecraft:chests/buried_treasure", None)?; return Ok(()); } @@ -193,10 +205,87 @@ pub fn shipwreck_too_big(template: &StructureTemplate) -> bool { template.size[0] > 32 || template.size[1] > 32 } +impl TemplatePiece { + /// `TemplateStructurePiece.addAdditionalSaveData` and its subclasses', + /// with the height a shipwreck settled on once placed. + pub fn saved(&self) -> crate::nbt::Compound { + use crate::nbt::Tag; + let flag = |b: bool| Tag::Byte(i8::from(b)); + let adjusted = match self.handler { + TemplateHandler::Shipwreck { .. } + | TemplateHandler::OceanRuin { .. } + | TemplateHandler::Igloo => *self.state.lock().unwrap(), + _ => None, + }; + let dy = adjusted.map_or(0, |y| y - self.position[1]); + let template_dy = if matches!(self.handler, TemplateHandler::Igloo) { + 0 + } else { + dy + }; + let mut tag = super::legacy::piece_tag( + self.type_name, + self.bounding_box.moved([0, dy, 0]), + Some(Direction::North), + 0, + ); + // Mansion and End City pieces keep the name inside their folder. + let name = self + .template_name + .strip_prefix("minecraft:woodland_mansion/") + .or_else(|| self.template_name.strip_prefix("minecraft:end_city/")) + .unwrap_or(&self.template_name); + let rotation = || Tag::String(self.rotation.saved_name().into()); + let mut entries = vec![ + ("TPX", Tag::Int(self.position[0])), + ("TPY", Tag::Int(self.position[1] + template_dy)), + ("TPZ", Tag::Int(self.position[2])), + ("Template", Tag::String(name.into())), + ]; + match self.handler { + TemplateHandler::Igloo => entries.push(("Rot", rotation())), + TemplateHandler::Shipwreck { beached } => entries.extend([ + ("isBeached", flag(beached)), + ("Rot", rotation()), + ("height_adjusted", flag(adjusted.is_some())), + ]), + TemplateHandler::OceanRuin { + warm, + large, + integrity, + } => entries.extend([ + ("Rot", rotation()), + ("Integrity", Tag::Float(integrity.to_bits())), + ( + "BiomeType", + Tag::String(if warm { "WARM" } else { "COLD" }.into()), + ), + ("IsLarge", flag(large)), + ]), + TemplateHandler::RuinedPortal(props) => { + entries.push(("Rotation", rotation())); + entries.push(("Mirror", Tag::String(self.mirror.saved_name().into()))); + entries.extend(props.save()); + } + TemplateHandler::Mansion => entries.extend([ + ("Rot", rotation()), + ("Mi", Tag::String(self.mirror.saved_name().into())), + ]), + TemplateHandler::Plain => entries.push(("Rot", rotation())), + } + for (key, value) in entries { + tag.insert(key.into(), value); + } + tag + } +} impl LegacyPiece for TemplatePiece { fn bounding_box(&self) -> BoundingBox { self.bounding_box } + fn save(&self) -> Option { + Some(self.saved()) + } fn after_place(&self, c: &mut PieceContext<'_>, pieces: &[BoundingBox]) -> Result<()> { match self.handler { TemplateHandler::Mansion => super::mansion::after_place(c, pieces), @@ -232,6 +321,8 @@ impl LegacyPiece for TemplatePiece { self.position[1] + height - 90 - 1, self.position[2], ]; + // The box stays moved; templatePosition goes back after placing. + *self.state.lock().unwrap() = Some(position[1]); if let Some(markers) = self.place_at(c, position, &[])? { for (marker, pos) in markers { if marker == "chest" { @@ -362,6 +453,21 @@ impl Scattered { pub fn frame(&self) -> PieceFrame { *self.frame.lock().unwrap() } + /// `ScatteredFeaturePiece`'s tag: the box and the height it settled on. + pub fn saved(&self, id: &str) -> crate::nbt::Compound { + use crate::nbt::Tag; + let f = self.frame(); + let mut tag = super::legacy::piece_tag(id, f.bounding_box, f.orientation, 0); + for (key, value) in [ + ("Width", self.width), + ("Height", self.height), + ("Depth", self.depth), + ("HPos", *self.height_position.lock().unwrap()), + ] { + tag.insert(key.into(), Tag::Int(value)); + } + tag + } /// updateAverageGroundHeight over the part of the box inside the chunk. pub fn average_ground(&self, c: &mut PieceContext<'_>, offset: i32) -> Result { if *self.height_position.lock().unwrap() >= 0 { @@ -419,12 +525,15 @@ impl Scattered { #[derive(Debug)] pub struct SwampHutPiece { pub base: Scattered, + /// spawnedWitch and spawnedCat: both spawn in the same chunk. + spawned: Mutex, } impl SwampHutPiece { pub fn new(random: &mut impl RandomSource, west: i32, north: i32) -> Self { let direction = random_horizontal(random); Self { base: Scattered::new(west, 64, north, 7, 7, 9, direction), + spawned: Mutex::new(false), } } } @@ -432,6 +541,13 @@ impl LegacyPiece for SwampHutPiece { fn bounding_box(&self) -> BoundingBox { self.base.frame().bounding_box } + fn save(&self) -> Option { + let mut tag = self.base.saved("minecraft:tesh"); + let spawned = crate::nbt::Tag::Byte(i8::from(*self.spawned.lock().unwrap())); + tag.insert("Witch".into(), spawned.clone()); + tag.insert("Cat".into(), spawned); + Some(tag) + } fn type_name(&self) -> &'static str { "minecraft:tesh" } @@ -500,6 +616,7 @@ impl LegacyPiece for SwampHutPiece { c.world .entity(super::legacy::spawn_nbt(id, pos, true, true))?; } + *self.spawned.lock().unwrap() = true; } Ok(()) } diff --git a/crates/horizon-world/src/worldgen/structure/start.rs b/crates/horizon-world/src/worldgen/structure/start.rs index ea4549131..f84a953a1 100644 --- a/crates/horizon-world/src/worldgen/structure/start.rs +++ b/crates/horizon-world/src/worldgen/structure/start.rs @@ -275,16 +275,15 @@ fn terrain(name: Option<&str>) -> TerrainAdjustment { _ => TerrainAdjustment::None, } } -fn pair(value: Option<&Value>, a: &str, b: &str, default: i32) -> [i32; 2] { +/// A jigsaw field given as one number or as an object of two. In the object a +/// missing `a` is 0 and a missing `b` is `missing_b` (`JigsawStructure.MaxDistance` +/// and `DimensionPadding` default their second value, not copy the first). +fn pair(value: Option<&Value>, a: &str, b: &str, default: i32, missing_b: i32) -> [i32; 2] { match value { Some(Value::Number(n)) => [n.as_i64().unwrap_or(0) as i32; 2], Some(Value::Object(o)) => { - let get = |k: &str| o.get(k).and_then(Value::as_i64).unwrap_or(0) as i32; - let first = get(a); - [ - first, - o.get(b).and_then(Value::as_i64).map_or(first, |v| v as i32), - ] + let get = |k: &str| o.get(k).and_then(Value::as_i64).map(|v| v as i32); + [get(a).unwrap_or(0), get(b).unwrap_or(missing_b)] } _ => [default; 2], } @@ -326,9 +325,11 @@ impl StructureRegistry { "horizontal", "vertical", 80, + // DimensionType.Y_SIZE. + 4064, ), aliases: v["pool_aliases"].as_array().cloned().unwrap_or_default(), - padding: pair(v.get("dimension_padding"), "bottom", "top", 0), + padding: pair(v.get("dimension_padding"), "bottom", "top", 0, 0), waterlogging: v["liquid_settings"].as_str() != Some("ignore_waterlogging"), checks: super::start_checks::StartChecks::decode(v.get("horizon:start_checks")), piece_limited: v @@ -694,6 +695,13 @@ impl Piece { Self::Legacy(p) => p.type_name(), } } + /// `StructurePiece.createTag`; None for a type Horizon cannot save yet. + pub fn save(&self) -> Option { + match self { + Self::Pool(p) => Some(p.save()), + Self::Legacy(p) => p.save(), + } + } } fn legacy(pieces: Vec) -> Vec { pieces @@ -735,6 +743,26 @@ pub struct StructureStart { /// Piece union, inflated by 12 for terrain-adapting structures. pub bounding_box: BoundingBox, } +impl StructureStart { + /// `StructureStart.createTag` in its own chunk; None while one of its + /// pieces cannot be saved. `references` counts `addReference` calls, + /// which only locating structures makes: 0 in a freshly made world. + pub fn save(&self) -> Option { + use crate::nbt::Tag; + let children: Option> = self + .pieces + .iter() + .map(|p| p.save().map(Tag::Compound)) + .collect(); + Some(Tag::compound([ + ("id", Tag::String(self.name.as_str().into())), + ("ChunkX", Tag::Int(self.chunk.x)), + ("ChunkZ", Tag::Int(self.chunk.z)), + ("references", Tag::Int(0)), + ("Children", Tag::List(children?)), + ])) + } +} /// A block of a noise column (ChunkGenerator.getBaseColumn), by what /// structures ask of it. @@ -935,6 +963,7 @@ fn try_generate( let stub = top_of_chunk_center(context, chunk, HeightmapType::OceanFloorWg)?; let piece = super::simple::BuriedTreasurePiece { position: [chunk.x * 16 + 9, 90, chunk.z * 16 + 9], + found: std::sync::Mutex::new(None), }; (stub, legacy(vec![piece])) } diff --git a/crates/horizon-world/src/worldgen/structure/stronghold.rs b/crates/horizon-world/src/worldgen/structure/stronghold.rs index 94042ba6f..29f7cd149 100644 --- a/crates/horizon-world/src/worldgen/structure/stronghold.rs +++ b/crates/horizon-world/src/worldgen/structure/stronghold.rs @@ -1075,6 +1075,48 @@ impl LegacyPiece for StrongholdPiece { fn bounding_box(&self) -> BoundingBox { self.frame.bounding_box } + fn save(&self) -> Option { + use crate::nbt::Tag; + let flag = |b: bool| Tag::Byte(i8::from(b)); + let mut tag = super::legacy::piece_tag( + self.type_name(), + self.frame.bounding_box, + self.frame.orientation, + self.depth, + ); + // SmallDoorType.LEGACY_CODEC: the enum name. + let door = match self.door { + Door::Opening => "OPENING", + Door::Wood => "WOOD_DOOR", + Door::Grates => "GRATES", + Door::Iron => "IRON_DOOR", + }; + let placed = *self.placed.lock().unwrap(); + let [a, b, c, d] = self.flags; + let mut entries = vec![("EntryDoor", Tag::String(door.into()))]; + match self.kind { + Kind::ChestCorridor => entries.push(("Chest", flag(placed))), + Kind::Filler => entries.push(("Steps", Tag::Int(self.value))), + Kind::FiveCrossing => entries.extend([ + ("leftLow", flag(a)), + ("leftHigh", flag(b)), + ("rightLow", flag(c)), + ("rightHigh", flag(d)), + ]), + Kind::Library => entries.push(("Tall", flag(a))), + Kind::PortalRoom => entries.push(("Mob", flag(placed))), + Kind::RoomCrossing => entries.push(("Type", Tag::Int(self.value))), + // StartPiece is a StairsDown that is the source. + Kind::StairsDown => entries.push(("Source", flag(false))), + Kind::Start => entries.push(("Source", flag(true))), + Kind::Straight => entries.extend([("Left", flag(a)), ("Right", flag(b))]), + _ => {} + } + for (key, value) in entries { + tag.insert(key.into(), value); + } + Some(tag) + } fn type_name(&self) -> &'static str { match self.kind { Kind::Straight => "minecraft:shs", diff --git a/crates/horizon-world/src/worldgen/structure/temple.rs b/crates/horizon-world/src/worldgen/structure/temple.rs index 195f37791..c328f0f55 100644 --- a/crates/horizon-world/src/worldgen/structure/temple.rs +++ b/crates/horizon-world/src/worldgen/structure/temple.rs @@ -82,6 +82,16 @@ impl LegacyPiece for DesertPyramidPiece { fn bounding_box(&self) -> BoundingBox { self.base.frame().bounding_box } + fn save(&self) -> Option { + let mut tag = self.base.saved("minecraft:tedp"); + for (i, placed) in self.placed_chest.lock().unwrap().iter().enumerate() { + tag.insert( + format!("hasPlacedChest{i}").as_str().into(), + crate::nbt::Tag::Byte(i8::from(*placed)), + ); + } + Some(tag) + } fn type_name(&self) -> &'static str { "minecraft:tedp" } @@ -448,6 +458,22 @@ impl LegacyPiece for JungleTemplePiece { fn bounding_box(&self) -> BoundingBox { self.base.frame().bounding_box } + fn save(&self) -> Option { + let mut tag = self.base.saved("minecraft:tejp"); + let placed = *self.placed.lock().unwrap(); + for (key, value) in [ + "placedMainChest", + "placedHiddenChest", + "placedTrap1", + "placedTrap2", + ] + .into_iter() + .zip(placed) + { + tag.insert(key.into(), crate::nbt::Tag::Byte(i8::from(value))); + } + Some(tag) + } fn type_name(&self) -> &'static str { "minecraft:tejp" } diff --git a/docs/agent-control.md b/docs/agent-control.md index 903a48b2f..8573bb711 100644 --- a/docs/agent-control.md +++ b/docs/agent-control.md @@ -3,7 +3,7 @@ A player's own AI agent (Claude Code, Codex, Cursor, any MCP client) or a script can do everything a player does with the mouse and keyboard, in the launcher and in the game. This page covers developers: the surfaces, the full inventory, and the rules every new command follows. -Players read [Control Horizon with your AI agent](../website/docs/agents.md) +Players read [Control Horizon with your AI agent](https://playhorizon.dev/docs/agents) (playhorizon.dev/docs/agents). The command lists are generated, so they can't drift: diff --git a/docs/api/README.md b/docs/api/README.md index ef3649105..ce28dc262 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -53,4 +53,4 @@ Every page has the same parts: **Overview** (what you can build), **Guide** (whe The website shows these pages at [playhorizon.dev/docs/api](https://playhorizon.dev/docs/api), built from this folder, and a summary for players and authors at [playhorizon.dev/docs/apis](https://playhorizon.dev/docs/apis) -(`website/docs/apis.md`). +(in the website's repository, ludovic111/horizon-site). diff --git a/docs/api/mod-index.md b/docs/api/mod-index.md index e8476cdf0..ea605fbc7 100644 --- a/docs/api/mod-index.md +++ b/docs/api/mod-index.md @@ -18,7 +18,7 @@ Level: preview ([stability.md](stability.md)). Schema 1. "projects": [{ "id": "coords_hud", "kind": "mod", "name": "Coordinates HUD", "summary": "One line.", "description": "Markdown.", "authors": ["Horizon"], "owners": ["ludovic111"], - "license": "MIT", "source": "https://github.com/...", "icon": "https://...png", "key": "RWT...", + "license": "MIT", "source": "https://github.com/...", "icon": "https://...png", "key": "RWT...", "downloads": 1234, "versions": [{ "version": "0.1.0", "published": "2026-10-24", "changelog": "", "api": "0.1", "side": "client", "capabilities": ["game-read", "hud", "chat"], "api_level": 0, "game": "26.3", @@ -41,6 +41,7 @@ Level: preview ([stability.md](stability.md)). Schema 1. | `icon` | `https://`, optional. | | `key` | The author's [minisign](https://jedisct1.github.io/minisign/) public key. When set, every version must be signed with it; an update signed with another key is refused. Absent: the project is unsigned and the launcher says so. | | `versions` | Newest first, at least one. | +| `downloads` | How many times its files were downloaded, every version together: GitHub's count of each release asset, summed by the publish job, which runs every hour. Absent until a file is downloaded. Read-only: never in an entry. | | `api` | A mod's API line (its manifest's `api`); a modpack's manifest format (`1`). | | `side`, `capabilities` | A mod's, read from its manifest by CI, never typed by hand. | | `api_level` | The mod API level a mod's code needs ([stability.md](stability.md#mod-api-levels)): its newest imported function's, read from the file by CI. Absent for content-only mods and in indexes built before levels. Installers take the newest version whose level the running game serves. | @@ -167,6 +168,7 @@ opens. ## Changelog +- 2026-10-26: `projects[].downloads`, GitHub's download counts of a project's files, refreshed every hour. - 2026-10-26: the launcher installs `shader` files into `shaderpacks/`; the sample index lists one (`glow`). - 2026-10-25: `shader` opens, checked by `horizon_shader_api::check`; its files are `.hshader`. - Schema 1 (2026-10-24): kinds `mod`, `modpack`, `resourcepack`, `shader`; `.hpack` format 1. diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index d7bf879b8..3956b6457 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -17,6 +17,8 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`, | `render` | [`render`](#render) | draw on your screen, shake and zoom the camera | | `input` | [`input`](#input) | see the keys you hold and your clicks, take over the use button on its own items and the mouse wheel, and add keys | | `players` | [`players`](#players) | see who is on the server and message them | +| `world` | [`world`](#world) | read and change the world's blocks | +| `recipes` | [`recipes`](#recipes) | read the game's recipes and items and which recipes you know, place recipes in your crafting grid and, in creative mode, give you items | ## World `horizon-mod` @@ -29,14 +31,14 @@ A client mod: runs in the player's game. A server mod (manifest `side = "server"`, `api = "0.3"`, experimental): runs where the world is simulated, on the dedicated server, a LAN host and single player's own server. -- Imports (what the game offers): `log`, `storage`, `players` +- Imports (what the game offers): `log`, `storage`, `players`, `world` - Exports (what the mod provides): `server-events` ## World `horizon-ui-mod` A mod with widgets (capability `ui`): the SDK builds every mod against this world. Mods built for `horizon-mod` alone (no `ui-events` export) still load and simply hear nothing of their widgets. -- Imports (what the game offers): `ui`, `render`, `input`, `log`, `game`, `chat`, `hud`, `storage`, `command` +- Imports (what the game offers): `ui`, `render`, `input`, `recipes`, `browser`, `log`, `game`, `chat`, `hud`, `storage`, `command` - Exports (what the mod provides): `ui-events`, `events` ## World `ui-host` @@ -53,6 +55,13 @@ The game's side of capability `render` (imports only). - Imports (what the game offers): `render`, `input` - Exports (what the mod provides): +## World `recipes-host` + +The game's side of capability `recipes` (imports only). + +- Imports (what the game offers): `recipes`, `browser` +- Exports (what the mod provides): + ## `log` Access: always granted. @@ -76,7 +85,7 @@ The mod's log, in the game's log under the mod's id. Always granted. Access: capability `game-read`. -Capability `game-read`: the local player and the world clock. +Capability `game-read`: the local player, the world clock and the block the player looks at. ### record `player` @@ -98,10 +107,25 @@ Capability `game-read`: the local player and the world clock. | `game-time` | `u64` | Ticks since the world was created. | | `day-time` | `u64` | 24000 ticks per day; 0 is 6:00 on the first day. | +### record `hit` + +A block along the player's view. + +| Field | Type | | +| --- | --- | --- | +| `block-x` | `s32` | The block hit. | +| `block-y` | `s32` | | +| `block-z` | `s32` | | +| `x` | `f64` | The point on its face where the view meets it. | +| `y` | `f64` | | +| `z` | `f64` | | +| `block` | `string` | `minecraft:stone`, ... | + | Function | Signature | What it does | | --- | --- | --- | | `get-player` | `func() -> option` | None on the title screen. | | `get-clock` | `func() -> option` | None on the title screen. | +| `raycast` | `func(distance: f32) -> option` | The first block along the player's view (fluids pass), up to `distance` blocks (at most 1024; past the loaded chunks, across the distant terrain when LOD Distance is on), as of this tick. None when nothing is hit, and on the title screen. | ## `chat` @@ -161,6 +185,7 @@ Capability `command`: vanilla commands run as the player, with the player's perm | Function | Signature | What it does | | --- | --- | --- | | `run` | `func(line: string)` | `line` without its slash; its feedback goes to the chat as if typed. | +| `run-quiet` | `func(lines: list)` | `lines` (each without its slash, at most 256 a call) as `run` does, but with nothing in the chat: no feedback and no failure. In single player and on Horizon's servers, each runs exactly as the player typing it would (the same rights), in order, 64 a tick, and the server logs one line a batch; one that carries a chat message (`say`, `msg`) is refused. On any other server they go as chat commands, and there their feedback shows: a mod running many should say so. | ## `ui` @@ -445,6 +470,160 @@ What the game calls. Only the hooks `init` asks for are ever called. | `command` | `func(name: string, args: string) -> result, string>` | `/name args`: ok(some(text)) is shown as feedback, err(text) in red. | | `chat` | `func(text: string)` | Each chat line the player receives, as plain text. | +## `recipes` + +Access: capability `recipes`. + +Capability `recipes` (experimental): the recipes and items the game knows, for recipe viewers. In single player and on Horizon's servers they are the world's; on any other server they are vanilla 26.3's (a client is sent no others), while `known` follows that server's book. + +### record `stack` + +An item of `items`, by its index there, with a count and the components it has beyond the item's own, in vanilla's item syntax (`[potion_contents={potion:"minecraft:swiftness"}]`), or "". + +| Field | Type | | +| --- | --- | --- | +| `item` | `u32` | | +| `count` | `u32` | | +| `components` | `string` | | + +### enum `kind` + +The station a recipe is made at. + +| Case | | +| --- | --- | +| `crafting-shaped` | | +| `crafting-shapeless` | | +| `smelting` | | +| `blasting` | | +| `smoking` | | +| `campfire` | | +| `stonecutting` | | +| `smithing` | | +| `brewing` | | + +### record `recipe` + +| Field | Type | | +| --- | --- | --- | +| `id` | `string` | `minecraft:oak_planks`. | +| `kind` | `kind` | | +| `category` | `string` | The recipe book's tab (`crafting_building_blocks`, `furnace_food`), or "". | +| `group` | `string` | Recipes the book shows on one button share a group, or "". | +| `width` | `u32` | A shaped recipe's grid: `slots` holds its cells row by row. 0 for the other kinds. | +| `height` | `u32` | | +| `slots` | `list>` | Each slot's stacks, any one of which fits; an empty list is an empty cell. Cooking and stonecutting: the input. Smithing: the template, the base, the addition. Brewing: the bottle, the reagent. | +| `results` | `list` | What it makes; several when that varies (a trim on any armour). | +| `cooking-time` | `u32` | Cooking: game ticks and experience; 0 for the other kinds. | +| `experience` | `f32` | | +| `book-id` | `s32` | The recipe book's id for it (one per way the book shows it), as `known` lists them; -1 for the kinds the book doesn't show (campfire, stonecutting, smithing, brewing). | + +### record `item` + +| Field | Type | | +| --- | --- | --- | +| `id` | `string` | `minecraft:diamond`, `:`. | +| `name` | `string` | In the player's language. | +| `tags` | `list` | Its item tags, without the `#`. | + +| Function | Signature | What it does | +| --- | --- | --- | +| `items` | `func() -> list` | Every item, in the registry's order: `stack.item` indexes this list. | +| `all` | `func() -> list` | Every recipe: the book's in its order, then campfire, stonecutting, smithing and brewing. They don't change while a world is open. | +| `known` | `func() -> list` | The `book-id`s of the recipes the player's recipe book holds now. | +| `place` | `func(book-id: s32, all: bool) -> result<_, string>` | Places a recipe in the open screen's grid as a click in the recipe book does (`ServerboundPlaceRecipePacket`): the inventory's grid or a crafting table. `all` places as many as the items allow, as with Shift. Refused while no such screen is open, for a recipe the player's book doesn't hold and for one that can't be placed; one missing items shows as a ghost in the grid, as in the book. | +| `give` | `func(stack: stack) -> result<_, string>` | Creative mode only: gives the player the stack, as taking it from the creative inventory does (`ServerboundSetCreativeModeSlot`): the selected slot first, then the hotbar, then the inventory. The count is cut to one stack of the item (64, 16 or 1). | + +## `browser` + +Access: not granted by any capability. + +Capability `ui` (experimental): a recipe viewer's panel beside the game's inventory and container screens (not the creative inventory), on the right of the screen. The game draws it with its own widgets and slots, pages it and keeps its search box; the mod says what it holds. The first loaded mod with a panel shows. + +### record `stack` + +An item to show: its id, a count (1 draws none) and its components beyond the item's own, in vanilla's item syntax, or "". + +| Field | Type | | +| --- | --- | --- | +| `item` | `string` | | +| `count` | `u32` | | +| `components` | `string` | | + +### record `click` + +A click on an item of the panel, by its index in `set-items`'s list. + +| Field | Type | | +| --- | --- | --- | +| `index` | `u32` | | +| `right` | `bool` | | + +### record `item-key` + +A key the mod registered (`input.register-key`) went down while the pointer was on an item: a slot of the screen's, or the panel's. + +| Field | Type | | +| --- | --- | --- | +| `key` | `string` | | +| `stack` | `stack` | | + +### record `slot-click` + +A click on a slot of a recipe the panel shows (`set-recipes`). + +| Field | Type | | +| --- | --- | --- | +| `recipe` | `u32` | The recipe's index in `set-recipes`'s list and the slot's in it; the results come after the slots. | +| `slot` | `u32` | | +| `stack` | `stack` | The stack the slot showed at that moment. | +| `right` | `bool` | | + +### variant `event` + +| Case | Payload | | +| --- | --- | --- | +| `clicked` | `click` | | +| `search` | `string` | The search box's text, each time the player changes it. | +| `key` | `item-key` | | +| `slot-clicked` | `slot-click` | | +| `action` | `u32` | The action button of the recipe at this index in `set-recipes`'s list. | +| `page` | `u32` | The player turned the recipes' page (`set-recipes`): the index of the first recipe now shown. | +| `back` | | The back button of `set-recipes`. | +| `tab` | `u32` | The player picked the tab at this index of `set-recipes`' tabs. | + +### enum `layout` + +How the game lays out a recipe of `set-recipes`. + +| Case | | +| --- | --- | +| `grid` | A crafting grid of `width` x `height` slots, an arrow and the result. | +| `cooking` | One input over a flame, an arrow and the result (furnaces, smokers, campfires). | +| `single` | One input, an arrow and the result (the stonecutter). | +| `smithing` | Template, base and addition, an arrow and the result. | +| `brewing` | A potion and an ingredient, an arrow and the result. | + +### record `recipe-view` + +A recipe to show. Each slot, and the result, cycles through its stacks, one a second; an empty slot shows nothing. + +| Field | Type | | +| --- | --- | --- | +| `layout` | `layout` | | +| `width` | `u32` | The grid's size (`grid` only), at most 3 x 3. | +| `height` | `u32` | | +| `slots` | `list>` | | +| `results` | `list` | | +| `note` | `string` | A short line under the recipe (a cooking time), or "". | +| `action` | `option` | The action button beside it: none, enabled, or shown greyed. | + +| Function | Signature | What it does | +| --- | --- | --- | +| `set-items` | `func(items: list)` | The panel's items, at most 8192 (an empty list hides the panel). | +| `set-recipes` | `func(title: string, tabs: list, tab: u32, recipes: list)` | Shows these recipes in the panel instead of its items, as many as fit a page, under `title` and a back button, with a row of `tabs` (each an icon; `tab` is the selected one) between them; an empty list of recipes shows the items again. At most 256 recipes and 16 tabs. | +| `poll` | `func() -> list` | What the player did on the panel since the last poll, at most 256 kept. | + ## `players` Access: capability `players`. @@ -479,6 +658,27 @@ Capability `players`, server mods only (manifest `api = "0.3"`, experimental): t | `tell` | `func(player: string, text: string) -> bool` | A system message to one player, after the mod's name; false when no player with that id is online. Up to 8 messages per call. | | `broadcast` | `func(text: string)` | A system message to every player and the server's log, after the mod's name. Counts toward the same 8 per call. | +## `world` + +Access: capability `world`. + +Capability `world`, server mods only (manifest `api = "0.3"`, experimental): the blocks of the server's loaded chunks, and changes to them through the server's own block updates. + +### record `block-change` + +| Field | Type | | +| --- | --- | --- | +| `x` | `s32` | | +| `y` | `s32` | | +| `z` | `s32` | | +| `state` | `string` | `minecraft:oak_log[axis=y]`; properties left out take the block's defaults, `minecraft:stone` alone is the default state. | + +| Function | Signature | What it does | +| --- | --- | --- | +| `get-block` | `func(dimension: string, x: s32, y: s32, z: s32) -> option` | The block state at a position in a dimension (`minecraft:overworld`, ...), as `minecraft:oak_log[axis=y]`, as of this call: none where the server has no chunk loaded there. | +| `get-biome` | `func(dimension: string, x: s32, y: s32, z: s32) -> option` | The biome at a position (`minecraft:plains`, ...), as the server stores it (one per 4 x 4 x 4 cell): none where no chunk is loaded. | +| `set-blocks` | `func(dimension: string, blocks: list) -> result<_, string>` | Sets blocks as `/setblock` does: the old block entity removed, neighbours and shapes updated, light, and every player told. Every state is checked now (an error queues nothing); the changes are made in order after this call returns, before that dimension's next tick; one in a chunk not loaded then is skipped. At most 4096 per call. | + ## `server-events` Access: exported by the mod: the game calls it. @@ -489,16 +689,6 @@ What the server calls in a server mod (manifest `api = "0.3"`, experimental). On `type player = player` -### record `registration` - -| Field | Type | | -| --- | --- | --- | -| `commands` | `list` | Commands players may type, without the slash. A name vanilla already uses is refused (vanilla's command runs). | -| `tick` | `bool` | Call `tick` every server tick (20 per second). | -| `joins` | `bool` | Call `player-joined` and `player-left`. | -| `chat` | `bool` | Call `chat` for each chat message a player sends. | -| `blocks` | `bool` | Call `block-broken` and `block-placed`. | - ### record `block-pos` | Field | Type | | @@ -507,6 +697,59 @@ What the server calls in a server mod (manifest `api = "0.3"`, experimental). On | `y` | `s32` | | | `z` | `s32` | | +### variant `argument-kind` + +What an argument of a command takes. The server sends each command and its arguments to players' games, whose chat box completes and colours them as vanilla's; the server parses them before the mod's `command` hook gets their values. + +| Case | Payload | | +| --- | --- | --- | +| `word` | | One word: letters, digits and `_ - . +`. | +| `text` | | The rest of the line, spaces included: only last. | +| `integer` | `tuple, option>` | A whole number, within the bounds given. | +| `number` | | A number with or without decimals. | +| `boolean` | | `true` or `false`. | +| `player` | | One online player: a name, or `@s` or `@p` (whoever typed it, as vanilla picks for a player). | +| `block-pos` | | A block position: three whole numbers, each one also `~` or `~n`, relative to whoever typed it. | + +### record `argument` + +| Field | Type | | +| --- | --- | --- | +| `name` | `string` | Shown in the chat box's hint (``) and the key of its value. | +| `kind` | `argument-kind` | | +| `optional` | `bool` | Optional arguments come after every required one. | + +### record `server-command` + +| Field | Type | | +| --- | --- | --- | +| `name` | `string` | Without the slash. A name vanilla already uses is refused (vanilla's command runs). | +| `arguments` | `list` | In order; none: the command takes nothing after its name. Free text is one optional `text` argument. | + +### variant `argument-value` + +An argument's value, parsed as its kind says. + +| Case | Payload | | +| --- | --- | --- | +| `word` | `string` | | +| `text` | `string` | | +| `integer` | `s32` | | +| `number` | `f64` | | +| `boolean` | `bool` | | +| `player` | `player` | | +| `block-pos` | `block-pos` | | + +### record `registration` + +| Field | Type | | +| --- | --- | --- | +| `commands` | `list` | Commands players may type. | +| `tick` | `bool` | Call `tick` every server tick (20 per second). | +| `joins` | `bool` | Call `player-joined` and `player-left`. | +| `chat` | `bool` | Call `chat` for each chat message a player sends. | +| `blocks` | `bool` | Call `block-broken` and `block-placed`. | + | Function | Signature | What it does | | --- | --- | --- | | `init` | `func() -> result` | Once, after loading. An error keeps the mod off and is logged. | @@ -514,6 +757,6 @@ What the server calls in a server mod (manifest `api = "0.3"`, experimental). On | `player-joined` | `func(player: player)` | A player joined the server; they are in `players.online` already. | | `player-left` | `func(player: player)` | A player left the server; they are no longer in `players.online`. | | `chat` | `func(player: player, text: string)` | A chat message a player sent, as plain text. | -| `command` | `func(player: player, name: string, args: string) -> result, string>` | `/name args` typed by `player`: ok(some(text)) is their feedback, err(text) their error in red. | +| `command` | `func(player: player, name: string, args: string, values: list>) -> result, string>` | `/name args` typed by `player`: ok(some(text)) is their feedback, err(text) their error in red. `values` holds each argument given, by name, in order (an optional one left out isn't there); a line that doesn't parse never reaches the mod: the player gets vanilla's error. | | `block-broken` | `func(player: player, pos: block-pos, state: string)` | A player broke the block at `pos` in their dimension: `state` is what was there, as `minecraft:oak_log[axis=y]`. | | `block-placed` | `func(player: player, pos: block-pos, state: string)` | A player placed `state` at `pos` in their dimension. | diff --git a/docs/api/mods.md b/docs/api/mods.md index 59f4221a3..55f890cc1 100644 --- a/docs/api/mods.md +++ b/docs/api/mods.md @@ -1,7 +1,7 @@ # Mod API -Mods are Rust crates compiled to sandboxed WebAssembly components. They run in the player's game and, once server -mods land, wherever a world is simulated. Design and the runtime: [mods.md](../mods.md). +Mods are Rust crates compiled to sandboxed WebAssembly components. Client mods run in the player's game; server mods +(experimental) run wherever a world is simulated: single player, a LAN host, the dedicated server. Design and the runtime: [mods.md](../mods.md). ## Overview @@ -18,7 +18,7 @@ the player before the mod is turned on, and checked against the component's real | Hooks a mod exports | 5: `init`, `tick`, `frame`, `command`, `chat`; a server mod 8: `init`, `tick`, `player-joined`, `player-left`, `chat`, `command`, `block-broken`, `block-placed` | | Capabilities | 6: `game-read`, `chat`, `hud`, `storage`, `registries`, `players` | | Manifest `api` lines served | 3: `0.1` (code), `0.2` (content), `0.3` (server mods, experimental) | -| SDK | the `Mod` trait (5 methods), `Registration` (4 builders), `export_mod!`, log helpers; `server::ServerMod` (8 methods), `server::Registration` (5 builders), `export_server_mod!` | +| SDK | the `Mod` trait (5 methods), `Registration` (4 builders), `export_mod!`, log helpers; `server::ServerMod` (8 methods), `server::Registration` (6 builders), `server::Argument`, `server::Args`, `export_server_mod!` | | `cargo horizon-mod` | `new` (templates `code` and `content`), `build`, `run`, `test`, `check` | | Example mods | `coords-hud` (code), `ruby-content` (content), `welcome` (server) | @@ -87,11 +87,12 @@ release. What real mods need next, in the order modpacks and servers need it: -- **Server mods in the game** (`api = "0.3"`, [Server mods](../mods.md#server-mods-api-03-experimental)): the - contract, runtime and SDK are here; next the server thread, LAN host and dedicated server start them and call - their hooks, then entity events, game rules and server commands with typed arguments. -- **World and blocks**: read blocks, block states and biomes in loaded chunks; change them through the server's block - log, so clients and the parity harnesses see vanilla's updates. +- **More for server mods** (`api = "0.3"`, [Server mods](../mods.md#server-mods-api-03-experimental)): they run + on the server thread, a LAN host and the dedicated server today, with joins, chat, typed commands in players' + command trees, players' block breaking and placing, and `world` (read blocks and biomes, set blocks as `/setblock` + does); next entity events, game rules, entity, item and block-state arguments. +- **World and blocks**: blocks, block states and biomes are there for server mods (`world`); next block entities, + and `world` for client mods (raycasts, single player and LAN hosts). - **Items and inventories**: the player's inventory, held item and open container; item stacks with components. - **Entities**: query and change entities near a position; spawn from a mod's own entity types (data first). - **Block entities and menus**: ticking machines with slots and their screens. @@ -105,6 +106,12 @@ What real mods need next, in the order modpacks and servers need it: ## Changelog +- API 0.3: typed server commands: `registration.commands` lists each command's arguments (`argument-kind`: word, + text, integer, number, boolean, player, block-pos), sent in players' command trees and parsed by the server; + `command` gets their values. SDK `Registration::command_with`, `Argument`, `Args`. +- API 0.3: capability `world` (`get-block`, `get-biome`, `set-blocks`); example `beacons`; test scripts' `blocks` and + `expect.blocks`. +- Server mods run in the game: single player (server thread and in-frame), LAN hosts, the dedicated server. - API 0.3 (server mods, experimental): world `horizon-server-mod`, capability `players`, the `server-events` hooks; SDK `server::ServerMod`; example `welcome`. - SDK: `cargo horizon-mod test` and `horizon_mods::testing`, test scripts in TOML; the template has one. diff --git a/docs/api/shaders.md b/docs/api/shaders.md index 7461332e4..faf662b0e 100644 --- a/docs/api/shaders.md +++ b/docs/api/shaders.md @@ -91,11 +91,12 @@ pack exist ([stability.md](stability.md)). ## Not there yet -The material stage in the game (the sky and post stages run, with hot reload), option values other than the defaults, -then the overlay, lighting and shadow stages. +Option values other than the defaults (the three stages run, with hot reload), then the overlay, lighting and shadow +stages. ## Changelog +- 2026-10-26: the material stage in the game: terrain's surfaces through the pack's `material`. - 2026-10-26: the sky stage in the game: the pack's `sky` gets vanilla's colour along each ray. - 2026-10-26: the post stage in the game (`HORIZON_SHADER_PACK`, hot reload with the last good pack kept). - 2026-10-25: `horizon-shader` (`new`, `check`, `pack`), three templates, the example pack and the guide. diff --git a/docs/api/stability.md b/docs/api/stability.md index 65cfc0c13..9911b79e9 100644 --- a/docs/api/stability.md +++ b/docs/api/stability.md @@ -38,7 +38,7 @@ don't import it); faster, or fixing behaviour to what the reference already says A new WIT function doesn't break older mods, but a mod that calls it can't run on a Horizon from before it. So every function the game offers mods has an **API level**, the one it arrived at (`crates/horizon-mods/src/api_level.rs`): -level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`. A mod needs the level of +level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`, level 2 `game.raycast`, level 3 `command.run-quiet`, level 4 server mods' `world`, level 5 `recipes` (`items`, `all`, `known`), level 6 `browser` (`set-items`, `poll`, `set-recipes`) and `recipes.place` and `recipes.give`. A mod needs the level of the newest function it imports (a component imports only the functions it calls). The level is read from the file, never declared: @@ -108,7 +108,7 @@ Deprecations and breaking changes are in bold. The release notes of the game rel | Mod API: `render` (HUD shapes, camera shake and zoom; drawn by the game, no mod shaders) | experimental | manifest `experimental = ["render"]` | | Mod API: `input` (claimed items' use, the mod's keys, the mouse wheel) | experimental | manifest `experimental = ["input"]` | | Content mods (`registries`: data-driven blocks and items) | preview | manifest `api = "0.2"` | -| Server mods: world `horizon-server-mod`, `players`, `server-events` | experimental | manifest `api = "0.3"` | +| Server mods: world `horizon-server-mod`, `players`, `server-events`, `world`, typed `server-command`s | experimental | manifest `api = "0.3"` | | Script mods (Lua run by an interpreter mod, [mods.md](mods.md#ways-in)) | not started | | | `cargo horizon-mod` (`new`, `build`, `run`), `horizon-mod-sdk` | preview | 0.1.0 | | Shader API | not started | | diff --git a/docs/architecture.md b/docs/architecture.md index 0350bd1ea..3aec2338b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -5,8 +5,9 @@ counted only for the game loop because nearly every gameplay change touches it). organised and how to build and test are in [AGENTS.md](../AGENTS.md). Paths: `L/` = `crates/horizon-client/src/`, `G/` = `crates/horizon-client/src/game/`, `W/` = -`crates/horizon-world/src/`. Checks: a bare name is a harness (`python3 tools/parity.py `, script -`tools/test__parity.py`); `lan_e2e ` is `python3 tools/lan_e2e.py --check `. +`crates/horizon-world/src/`, `K/` = `crates/horizon-client-core/src/`, `C/` = `crates/horizon-command/src/`. +Checks: a bare name is a harness (`python3 tools/parity.py `, script `tools/test__parity.py`); +`lan_e2e ` is `python3 tools/lan_e2e.py --check `. For the full set of harnesses a file can affect, ask the runner: `printf '%s\n' > /tmp/p.txt && python3 tools/parity.py --changed-files /tmp/p.txt --list`. @@ -17,7 +18,7 @@ file selects ~103. |---|---|---|---| | 1 | Game loop, tick order, frame pacing (554) | `L/game.rs` (`fn tick`, `fn tick_world`, `fn render`, `about_to_wait`), `L/clock.rs`, `L/window.rs`, `L/spans.rs` | game_loop, frame_limiter, interaction_input, tick | | 2 | Mobs in the game loop, spawning (166) | `G/creatures.rs`, `G/natural_spawning.rs`, `L/mobs/spawning.rs`, `L/mobs/spawn_rules.rs`, `L/mobs/spawn_selection.rs`, `L/mobs/finalize.rs`, `G/spawner.rs`, `G/trial_spawner.rs` | natural_spawn, spawn_rules, finalize_spawn, spawner, trial_spawner, mob_ai | -| 3 | World save and load (163) | `L/save.rs`, `G/saving.rs`, `G/persist.rs` (entities), `L/entity_nbt.rs`, `L/block_entity_nbt.rs`, `W/region.rs`, `W/nbt.rs` | save_roundtrip, world_reopen, world, datafix | +| 3 | World save and load (163) | `L/save.rs`, `G/saving.rs`, `G/persist.rs` (entities), `L/entity_nbt.rs`, `K/block_entity_nbt.rs`, `W/region.rs`, `W/nbt.rs` | save_roundtrip, world_reopen, world, datafix | | 4 | World generation (153) | `W/worldgen.rs`, `W/worldgen/` (`generator*.rs`, `feature_graph.rs`, `structure/`, `placement/`), `L/vanillagen.rs` | chunk_generation, worldgen, server_world_gen, world_spawn, feature_graph, feature_placement, decoration and the other worldgen harnesses | | 5 | Multiplayer client, packets in (145) | `G/remote.rs` (`fn handle_packet`, `fn tick_remote`), `G/remote_*.rs`, `L/net.rs` | dedicated_server, server_entities, lan_e2e (all) | | 6 | Agent control, horizon-ctl (145) | `L/control.rs`, `L/bin/horizon-ctl/`, `G/control.rs`, `G/agent.rs`, `G/events.rs`, `G/ui_control.rs` | `python3 tools/agent_control_e2e.py`; `cargo test -p horizon-client --bin horizon-ctl` | @@ -32,7 +33,7 @@ file selects ~103. | 15 | Items and item use (96) | `L/items.rs`, `L/item_data.rs`, `G/hand.rs`, `G/consume.rs`, `G/potions.rs`, `L/effects.rs`; game.rs `fn use_hand`, `fn use_item` | use_item_on, item_use, item_use_lifecycle, consumable, consume_effect, status_effect | | 16 | Options and settings screens (93) | `L/options_ui.rs`, `G/options.rs`, `L/settings.rs`, `L/options_file.rs`, `L/graphics_ui.rs`, `L/graphics.rs` | options, toggle_keys | | 17 | HUD, chat, tab list (93) | `L/hud.rs`, `L/hud_layout.rs`, `L/hud_overlays.rs`, `L/chat.rs`, `G/chat.rs`, `L/tab_list.rs`, `L/locator_bar.rs`, `G/locator_bar.rs` | hud, tab_list, locator_bar, chat_screen, secure_chat | -| 18 | Command execution (88) | `G/commands.rs`, `G/commands/*.rs`, `L/scoreboard_cmd.rs`, `L/data_cmd.rs`, `G/functions.rs` | command_exec (corpus `tools/command_exec_corpus.py`), scoreboard, server_ops_feedback, lan_e2e commands | +| 18 | Command execution (88) | `G/commands.rs`, `G/commands/*.rs`, `L/scoreboard_cmd.rs`, `L/data_cmd.rs`, `K/scoreboard.rs`, `G/functions.rs` | command_exec (corpus `tools/command_exec_corpus.py`), scoreboard, server_ops_feedback, lan_e2e commands | | 19 | Chunk streaming, light, tickets (85) | `L/streaming.rs`, `L/world.rs`, `L/chunk.rs`, `L/chunk_map.rs`, `L/light.rs`, `L/ticket_levels.rs`, `L/tick_chunk_membership.rs`, `G/world_loading.rs` | light, chunk_status, random_tick_sections; `cargo test -p horizon-client --test streaming_meshes` | | 20 | Mob models and animation (78) | `L/mobs/render.rs`, `L/mobs/anim.rs`, `L/mobs/body_anim.rs`, `L/mobs/keyframes.rs`, `L/entity.wgsl` | entity_model | | 21 | Block behaviour, server side (78) | `W/level/` (`mod.rs`, `tick.rs`, `hooks.rs`, `data.rs`, `redstone.rs`, `place.rs`), `G/block_entity_ticks.rs`, `G/moving_pistons.rs` | block_update, redstone, random_tick, simple_block, piston_movement, block_entity_tickers | @@ -46,12 +47,12 @@ file selects ~103. | 29 | Title, worlds, startup (49) | `L/title.rs` + `L/title/`, `G/startup_menu.rs`, `L/title_edition.rs` | world_options; `cargo test -p horizon-client --lib title` | | 30 | Dedicated server, horizon-server (48) | `G/dedicated.rs`, `G/dedicated/status.rs`, `crates/horizon-server/`, `crates/horizon-server-files/` | dedicated_server, server_files, user_cache, online_mode, server_ops_feedback | | 31 | Particles and client effects (46) | `L/particles.rs`, `G/render_tick.rs`, `G/level_particles.rs`, `L/animate_tick.rs` | particle_providers, block_particles, entity_particles, emitter_particles, marker_particles | -| 32 | Bosses and the End (45) | `G/dragon.rs`, `G/wither.rs`, `G/end.rs` | server_dragon, end_podium, end_gateway | +| 32 | Bosses and the End (45) | `G/dragon.rs`, `G/wither.rs`, `G/end.rs` | server_dragon, forced_end, end_podium, end_gateway | | 33 | Protocol and packets (44) | `crates/horizon-protocol/src/` (`packets/play.rs`, `entity_data.rs`, `connection.rs`) | dedicated_server, online_mode, secure_chat; `cargo test -p horizon-protocol` | | 34 | Multiplayer and LAN screens, friends (44) | `L/multiplayer.rs`, `G/lan_screen.rs`, `G/friends.rs`, `L/friends_screen.rs`, `crates/horizon-friends/`, `crates/horizon-relay/` | lan, world_options; `python3 tools/test_friends.py` | | 35 | Dispensers (43) | `G/dispenser.rs`, `G/dispense_fixture.rs` (the harness side) | dispenser | | 36 | Audio and music (38) | `L/audio.rs`, `L/sound_engine.rs`, `L/sound_events.rs`, `L/music.rs`, `G/music.rs`, `L/ambience.rs`, `G/subtitle_hud.rs` | sound_engine, sound_event, music, situational_music, ambient_sound, subtitle | | 37 | Integrated server and levels (34) | `G/integrated.rs`, `G/levels.rs`, `G/server_travel.rs` | server_dimension_players, `lan_e2e` (server-thread by default; portals, levels, distance, lava) | -| 38 | Command parsing (34) | `L/command/` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`) | command_parse (corpus `tools/command_parse_corpus.py`) | +| 38 | Command parsing (34) | `C/` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`); `cargo test -p horizon-command` | command_parse (corpus `tools/command_parse_corpus.py`) | | 39 | Benchmarks and telemetry (34) | `L/benchmark.rs`, `tools/perf_bench.py`, `L/telemetry.rs`, `crates/horizon-telemetry*/`, `crates/horizon-bench/` | `python3 -m unittest tests.test_perf_bench`; [benchmark.md](benchmark.md) | | 40 | Explosions and TNT (31) | `G/explosion.rs`, `G/tnt.rs` | lan_e2e blast; no dedicated harness yet | diff --git a/docs/design-system.md b/docs/design-system.md index e1417f749..0b171d4c2 100644 --- a/docs/design-system.md +++ b/docs/design-system.md @@ -8,8 +8,8 @@ Horizon's own settings are pages built from vanilla's widgets, the way mods add The tokens live in one place, `crates/horizon-theme`. The launcher (`launcher/src/theme.rs`) and the game (`crates/horizon-client/src/ui_theme.rs`) read them as Rust constants, and the website reads them as CSS custom properties generated from the same crate -(`cargo run -p xtask -- tokens` writes `website/src/tokens.css`; a test fails when the file is -out of date). Change a value in the crate and all three follow. +(`cargo run -p xtask -- tokens` writes `crates/horizon-theme/tokens.css`, which the website's build +reads from main; a test fails when the file is out of date). Change a value in the crate and all three follow. ## Where it comes from @@ -140,7 +140,7 @@ Geist (400, 500, 600) and Geist Mono (400), bundled under the SIL Open Font Lice landscape banner with the hero, the version picker and Play; Mods holds the mod, resource pack and modpack tabs; Versions and Patch notes are lists of panels; Settings is grouped panels of rows. Dark by default, Light or System in Settings (Appearance). -- **Website** (`website/`): the Blocks look below. The same page structure as before (what it +- **Website** (ludovic111/horizon-site): the Blocks look below. The same page structure as before (what it is, screenshots, parity, launcher, patch notes, community), headings in Pixelify Sans, lists as stacks of panels, the stone texture behind the page and Horizon's pixel landscape (a dawn or a sunset) behind the hero. Light and dark follow the system, with a toggle. A giant wordmark in @@ -168,11 +168,16 @@ of the main action. The game's menus keep `LIGHT` and `DARK`. ships no third-party pictures. The Horizon instance shows a grass block drawn from the player's own prepared Minecraft textures. Sources are named in text ("from Modrinth"): Modrinth's logo is all rights reserved, so it is not shown. +- **Partner banner**: the one exception to shipping no third-party pictures. Sculk, a server host, + sponsors Horizon: its banner (`launcher/assets/sculk-banner.webp`, `launcher/src/partner.rs`) sits + under a muted mono "Partner" label at the end of the Servers page and of Home, below Play, and opens + Sculk's page in the browser. The website shows the same banner the same way on Home and the hosting + docs, as a `rel="sponsored"` link. - **Pixel art drawn in code.** The stone behind the pages is close shades of the page colour (`TILE_SHADES`), never Minecraft's stone; the landscape is a banded sky, a sun cut in slices like the mark, hills and square trees (a sunset in dark, a dawn in light). The launcher bakes them in `launcher/src/art.rs` at the window's scale so each texel covers whole device pixels; the website - draws them in `website/scripts/art.mjs`. + draws them in its `scripts/art.mjs`. - **Icons**: Pixelarticons (MIT), 24 unit pixel SVGs in `crates/horizon-theme/icons/pixel/`, tinted with the text colour. - **Contrast**: every text colour meets WCAG AA (4.5:1) on the panels, the page and the lightest diff --git a/docs/graphics.md b/docs/graphics.md index d4261df81..dcba29773 100644 --- a/docs/graphics.md +++ b/docs/graphics.md @@ -21,14 +21,16 @@ Every row has a one-line description and its cost in frame time (none, low, medi | Quality | smooth lighting, mipmap levels, biome blend, clouds, cloud distance, weather radius, particles, entity shadows, cutout leaves | `options.txt` | | | sky, fog, weather, animated textures | `horizon-graphics.txt` | | Display | FOV, max framerate, VSync, fullscreen, GUI scale | `options.txt` | -| | resolution scale, anti-aliasing (FXAA), present mode, frame pacing | `horizon-graphics.txt` | +| | resolution scale, anti-aliasing (FXAA), HDR, paper white, peak brightness, present mode, frame pacing | `horizon-graphics.txt` | | Performance | battery mode, worker threads, upload budget per frame | `horizon-graphics.txt` | | Overlay | performance overlay: FPS, frame/CPU/GPU times, frame-time graph | `horizon-graphics.txt` | -`options.txt` keeps exactly vanilla's keys and values, so the options harness still compares it with vanilla; Horizon's settings live in `horizon-graphics.txt` beside it. Their defaults render as vanilla does: cave culling on, no upload budgets, sky, fog and weather on, 100% resolution, no FXAA, the present mode following VSync. VSync on always waits for the display (Fifo), in a window and in fullscreen, as in vanilla; the present mode setting chooses how frames are shown only while VSync is off. Frame pacing defaults to Efficient: the limiter sleeps through the last half millisecond where vanilla spins, which changes timing, not pixels. +`options.txt` keeps exactly vanilla's keys and values, so the options harness still compares it with vanilla; Horizon's settings live in `horizon-graphics.txt` beside it. Their defaults render as vanilla does: cave culling on, no upload budgets, sky, fog and weather on, 100% resolution, no FXAA, HDR off, the present mode following VSync. VSync on always waits for the display (Fifo), in a window and in fullscreen, as in vanilla; the present mode setting chooses how frames are shown only while VSync is off. Frame pacing defaults to Efficient: the limiter sleeps through the last half millisecond where vanilla spins, which changes timing, not pixels. **Battery mode** (Performance, off by default) is for laptops and handhelds: at most 60 frames per second in a world, 30 in menus without a world or while another window has focus, and half the automatic worker threads (chunks load slower). It changes only when frames are drawn: what they show and the game's 20 ticks per second stay as they are. +**HDR** (Display, off by default) presents to an scRGB swapchain (`Rgba16Float`, extended linear sRGB) on displays and compositors that offer it. The frame is drawn exactly as in SDR, in vanilla's gamma space, and a last pass (`hdr.wgsl`) decodes it to linear light at the **Paper White** and lifts light sources (blocks that emit light, lava, the sun and the moon) towards the **Peak Brightness**; everything else stays as in SDR. The mesher puts the light a block's face emits in its vertex colour's alpha (`EMISSION_BITS`), the frame's alpha carries the mark, and only pixels that still show the world before the hand and HUD are lifted. On Vulkan, `horizon-hdr` sends HDR metadata (MaxCLL, mastering luminance), which wgpu doesn't: without it a compositor may clip everything above SDR white. KWin maps the content's reference white onto the desktop's SDR brightness, so on Linux the default Paper White matches SDR mode. `HORIZON_HDR_DEBUG=1` paints lifted pixels magenta. Not lifted yet: glowing particles, distant LOD terrain. + Which settings each screen shows, their descriptions and costs are in `crates/horizon-client/src/graphics_ui.rs` (`rows`); `graphics_style.rs` draws them. ## Distant terrain diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index f3ef37977..432b76e72 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -50,9 +50,11 @@ Start the client. horizon-launcher play +- `--instance`: The instance to play (its name or id; default: the selected one) - `--world`: Open or create this world (a folder under saves) at once - `--creative`: Creative mode for a new world - `--join`: Join a friend's world with its invite code +- `--server`: Join this server at once: an address, or a server of the list by name or position - `--arg`: An extra argument for the game, passed through as-is (repeatable), for example --server-thread MCP: `play`, then the `game_*` tools. @@ -132,11 +134,11 @@ MCP: `account_offline`. ## `horizon-launcher settings` -Show the launcher's settings, or set one (the Settings page): selected-version TAG, minecraft-dir PATH, server-dir PATH ("default" resets a folder), install-new-versions on|off, opening-animation on|off. +Show the launcher's settings, or set one (the Settings page): selected-version TAG, minecraft-dir PATH, server-dir PATH ("default" resets a folder), install-new-versions on|off, opening-animation on|off, proxy http://host:port ("default" removes it), while-playing stay|minimize|hide (what the window does while the game runs). horizon-launcher settings [KEY] [VALUE] -- `KEY` (selected-version, minecraft-dir, server-dir, install-new-versions, opening-animation) +- `KEY` (selected-version, minecraft-dir, server-dir, install-new-versions, opening-animation, proxy, while-playing) - `VALUE`: The new value (with KEY) MCP: `settings`. @@ -151,6 +153,26 @@ Show or set the extra arguments the game starts with (for example --server-threa MCP: `game_args`. +## `horizon-launcher share-log` + +Upload an instance's latest.log to mclo.gs (a paste service for Minecraft logs) and print its link, for a bug report: only when the player asks. The home folder, the user name and the account names are taken out first; the link expires after 90 days unread. + + horizon-launcher share-log + +- `--instance`: The instance (default: the selected one) + +MCP: `share_log`, only when the player asks. + +## `horizon-launcher unshare-log` + +Delete a log shared with share-log: the ":" it printed. + + horizon-launcher unshare-log + +- `SHARED` + +MCP: `unshare_log`, needs `confirm: true`. + ## `horizon-launcher logs` Print the end of the game's log (logs/latest.log in the game folder), or its newest crash report. @@ -257,6 +279,292 @@ Upload a benchmark report (docs/benchmark-report.md); it is printed first. MCP: `data_benchmark`, only when the player asks. +## `horizon-launcher instance list` + +The instances, each with its game folder (* = the one Play starts). + + horizon-launcher instance list + +MCP: `instance_list`. + +## `horizon-launcher instance create` + +Make an instance: empty but for your options and name, or a copy of another one's worlds, options and packs. + + horizon-launcher instance create + +- `NAME` +- `--copy`: The instance to copy (its name or id) + +MCP: `instance_create`. + +## `horizon-launcher instance rename` + +Rename an instance (its folder stays). + + horizon-launcher instance rename + +- `INSTANCE` +- `NAME` + +MCP: `instance_rename`. + +## `horizon-launcher instance icon` + +Set an instance's icon: a block or item name from your prepared files (grass_block), a colour (#3fa7d6), or none. + + horizon-launcher instance icon + +- `INSTANCE` +- `ICON` + +MCP: `instance_icon`. + +## `horizon-launcher instance group` + +Put an instance in a sidebar group, or take it out with no group. + + horizon-launcher instance group [GROUP] + +- `INSTANCE` +- `GROUP` + +MCP: `instance_group`. + +## `horizon-launcher instance select` + +Make Play start this instance. + + horizon-launcher instance select + +- `INSTANCE` + +MCP: `instance_select`. + +## `horizon-launcher instance version` + +Keep an instance on one installed Horizon version, or "latest" to follow updates again. + + horizon-launcher instance version + +- `INSTANCE` + +MCP: `instance_version`. + +## `horizon-launcher instance export` + +Export an instance (or a port) to share: its settings, packs, Horizon mods and the worlds named, as a .mrpack (resource packs from Modrinth listed by download) or a zip. Never logs, screenshots or account data; worlds go without their per-player files. + + horizon-launcher instance export [INSTANCE] + +- `INSTANCE`: The instance (default: the selected one) +- `--format` (mrpack, zip) +- `--world`: A world to put in it (its name or folder); repeat for more +- `--out`: Where to write it (default: ".mrpack" in the current folder) + +MCP: `instance_export`. + +## `horizon-launcher instance import` + +Import what a file is, as dropping it on the window does: a shared instance (a .mrpack without mod loaders, such as `instance export` writes, or a game folder zip) becomes a new instance; a Java modpack goes to the Modpacks import; a resource or shader pack into the instance (default: the selected one). + + horizon-launcher instance import + +- `FILE` +- `--instance`: The instance a pack goes into + +MCP: `instance_import`. + +## `horizon-launcher worlds list` + +The worlds: name, mode, version, last played and size (the default). + + horizon-launcher worlds list + +- `--instance`: The instance (default: the selected one) + +MCP: `worlds_list`. + +## `horizon-launcher worlds backup` + +Zip a world into the instance's backups/ folder, as the game's Make Backup does. + + horizon-launcher worlds backup + +- `WORLD`: Its folder or name +- `--instance` + +MCP: `worlds_backup`. + +## `horizon-launcher worlds copy` + +Copy a world beside it, as " (1)". + + horizon-launcher worlds copy + +- `WORLD` +- `--instance` + +MCP: `worlds_copy`. + +## `horizon-launcher worlds delete` + +Move a world to the system's trash. + + horizon-launcher worlds delete + +- `WORLD` +- `--instance` + +MCP: `worlds_delete`, needs `confirm: true`. + +## `horizon-launcher worlds datapack-list` + +A world's data packs, and which are on. + + horizon-launcher worlds datapack-list + +- `WORLD` +- `--instance` + +MCP: `worlds_datapack_list`. + +## `horizon-launcher worlds datapack-add` + +Copy a data pack zip into a world (the game turns it on when the world opens). + + horizon-launcher worlds datapack-add + +- `WORLD` +- `FILE` +- `--instance` + +MCP: `worlds_datapack_add`. + +## `horizon-launcher worlds datapack-remove` + +Move a world's data pack to the system's trash. + + horizon-launcher worlds datapack-remove + +- `WORLD` +- `PACK`: Its file name, with or without .zip +- `--instance` + +MCP: `worlds_datapack_remove`, needs `confirm: true`. + +## `horizon-launcher packs list` + +The resource and shader packs, and which are on (the default). + + horizon-launcher packs list + +- `--kind` (resource, shader): Only this kind +- `--instance`: The instance (default: the selected one) + +MCP: `packs_list`. + +## `horizon-launcher packs add` + +Copy a pack file in: a resource pack .zip, a shader pack .zip or a .hshader. + + horizon-launcher packs add + +- `FILE` +- `--instance` + +MCP: `packs_add`. + +## `horizon-launcher packs on` + +Turn a pack on (a resource pack goes on top; a shader pack replaces the one that was on). + + horizon-launcher packs on + +- `PACK`: Its file name or title +- `--kind` (resource, shader) +- `--instance` + +MCP: `packs_on`. + +## `horizon-launcher packs off` + +Turn a pack off. + + horizon-launcher packs off + +- `PACK` +- `--kind` (resource, shader) +- `--instance` + +MCP: `packs_off`. + +## `horizon-launcher packs remove` + +Turn a pack off and move it to the system's trash. + + horizon-launcher packs remove + +- `PACK` +- `--kind` (resource, shader) +- `--instance` + +MCP: `packs_remove`, needs `confirm: true`. + +## `horizon-launcher screenshots list` + +The screenshots, the newest first, with their files (the default). + + horizon-launcher screenshots list + +- `--instance`: The instance (default: the selected one) + +MCP: `screenshots_list`. + +## `horizon-launcher screenshots delete` + +Move a screenshot to the system's trash. + + horizon-launcher screenshots delete + +- `SCREENSHOT`: Its file name, with or without .png +- `--instance` + +MCP: `screenshots_delete`, needs `confirm: true`. + +## `horizon-launcher multiplayer list` + +The servers of the game's Multiplayer screen (the default). + + horizon-launcher multiplayer list + +- `--instance`: The instance (default: the selected one) + +MCP: `multiplayer_list`. + +## `horizon-launcher multiplayer add` + +Add a server to the list. + + horizon-launcher multiplayer add
+ +- `ADDRESS`: Its address, as in the game's Add Server (host or host:port) +- `--name`: Its name in the list (default: Minecraft Server) +- `--instance` + +MCP: `multiplayer_add`. + +## `horizon-launcher multiplayer remove` + +Remove a server from the list: its position from 1, name or address. + + horizon-launcher multiplayer remove + +- `SERVER` +- `--instance` + +MCP: `multiplayer_remove`, needs `confirm: true`. + ## `horizon-launcher modpack list` The imported packs and their coverage (the default). @@ -308,10 +616,12 @@ MCP: `modpack_remove`, needs `confirm: true`. ## `horizon-launcher mods list` -What the browser installed (the default). +What the browser installed in an instance (the default). horizon-launcher mods list +- `--instance`: The instance (default: the selected one) + MCP: `mods_list`. ## `horizon-launcher mods search` @@ -321,7 +631,7 @@ Search for packs Horizon loads. horizon-launcher mods search [TEXT]... - `TEXT` -- `--kind` (mod, resource, modpack, shader) +- `--kind` (mod, resource, modpack, shader, datapack) - `--everything`: Also what was made for other versions or runs only partly, each marked - `--source` (modrinth, curseforge, horizon) @@ -341,11 +651,13 @@ MCP: `mods_check`. ## `horizon-launcher mods install` -Install a pack and what it needs, by its id or slug (checksums checked); a Java mod is ported into horizon-mods and turned on; a modpack is imported. +Install a pack and what it needs into an instance, by its id or slug (checksums checked); a Java mod is ported into horizon-mods and turned on; a modpack is imported as an instance of its own; a data pack goes into the world `--world` names. horizon-launcher mods install - `PROJECT` +- `--world`: Install the project's data pack into this world of the instance (its name or folder) +- `--instance`: The instance (default: the selected one) - `--everything`: Allow a version made for another Minecraft version - `--source` (modrinth, curseforge, horizon) @@ -359,6 +671,7 @@ Update what the browser installed (or one pack). - `PROJECT` - `--check`: Only say what is newer +- `--instance`: The instance (default: the selected one) MCP: `mods_update`. @@ -369,6 +682,7 @@ Remove a pack the browser installed. horizon-launcher mods remove - `PROJECT` +- `--instance`: The instance (default: the selected one) MCP: `mods_remove`, needs `confirm: true`. @@ -379,6 +693,7 @@ Turn on a mod the browser installed (horizon-mods.txt, as the game's Options > M horizon-launcher mods enable - `PROJECT` +- `--instance`: The instance (default: the selected one) MCP: `mods_enable`. @@ -389,6 +704,7 @@ Turn off a mod the browser installed; it stays installed. horizon-launcher mods disable - `PROJECT` +- `--instance`: The instance (default: the selected one) MCP: `mods_disable`. diff --git a/docs/media/banner.html b/docs/media/banner.html index 47037a7e2..2f727e8bd 100644 --- a/docs/media/banner.html +++ b/docs/media/banner.html @@ -1,10 +1,10 @@ + Rendered with Playwright (see docs/media/brand/README.md). --> - - -
- -
HorizonPLAYHORIZON.DEV
-

The game you know, rebuilt in Rust.

-

Minecraft: Java Edition 26.3, checked against vanilla by differential harnesses. Unofficial; not associated with Mojang or Microsoft.

-
- - diff --git a/website/public/og.png b/website/public/og.png deleted file mode 100644 index 1b9f270e7..000000000 Binary files a/website/public/og.png and /dev/null differ diff --git a/website/public/robots.txt b/website/public/robots.txt deleted file mode 100644 index 7cd2cc71e..000000000 --- a/website/public/robots.txt +++ /dev/null @@ -1,4 +0,0 @@ -User-agent: * -Allow: / - -Sitemap: https://playhorizon.dev/sitemap.xml diff --git a/website/railway.json b/website/railway.json deleted file mode 100644 index 3bbe9dfb3..000000000 --- a/website/railway.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "$schema": "https://railway.com/railway.schema.json", - "build": { - "builder": "DOCKERFILE", - "dockerfilePath": "Dockerfile", - "watchPatterns": ["/website/**", "/README.md", "/launcher/links.json", "/docs/api/**"] - }, - "deploy": { - "healthcheckPath": "/", - "healthcheckTimeout": 60, - "restartPolicyType": "ON_FAILURE", - "restartPolicyMaxRetries": 5 - } -} diff --git a/website/scripts/art.mjs b/website/scripts/art.mjs deleted file mode 100644 index 160d64914..000000000 --- a/website/scripts/art.mjs +++ /dev/null @@ -1,151 +0,0 @@ -// Horizon's pixel art for the website, drawn in code like the launcher's (launcher/src/art.rs): -// the stone tile behind the pages and the landscape behind the hero, in both appearances. -// Each texel is one pixel of the PNG; the CSS scales them up with `image-rendering: pixelated`. -// Written by `npm run assets` (or `node scripts/art.mjs`) into public/media/. -import { readFile } from "node:fs/promises"; -import { join, dirname } from "node:path"; -import { fileURLToPath } from "node:url"; -import sharp from "sharp"; - -const site = join(dirname(fileURLToPath(import.meta.url)), ".."); -const repo = join(site, ".."); - -// The same small fixed random sequence as art.rs (xorshift), so the art is the same every time. -function rng(seed) { - let x = seed >>> 0; - return () => { - x = (x ^ (x << 13)) >>> 0; - x = (x ^ (x >>> 17)) >>> 0; - x = (x ^ (x << 5)) >>> 0; - return Math.fround((x >>> 8) / (1 << 24)); - }; -} - -const channels = (c) => [(c >> 16) & 255, (c >> 8) & 255, c & 255]; -const shade = (c, by) => channels(c).reduce((out, v) => (out << 8) | Math.min(255, Math.max(0, v + by)), 0); -const mix = (a, b, t) => { - const [x, y] = [channels(a), channels(b)]; - return x.reduce((out, v, i) => (out << 8) | Math.round(v + (y[i] - v) * t), 0); -}; - -// `n` by `n` texels of stone: the page colour in a few close shades, with darker flecks. -export function stone(page, shades, n) { - const s = shades.map((by) => shade(page, by)); - const next = rng(0x9e3779b9); - const out = Array.from({ length: n * n }, () => { - const v = next(); - return s[v < 0.5 ? 0 : v < 0.78 ? 1 : v < 0.93 ? 2 : 3]; - }); - for (let k = 0; k < Math.floor((n * n) / 50); k++) { - const x = Math.floor(next() * n); - const y = Math.floor(next() * n); - const len = 1 + Math.floor(next() * 3); - for (let i = 0; i < len; i++) { - out[y * n + ((x + i) % n)] = s[4]; - out[((y + 1) % n) * n + ((x + i + 1) % n)] = s[4]; - } - } - return out; -} - -export const SUNSET = { - sky: [0x0a0f2c, 0x26206a, 0x4b2a7e, 0x7c3a88, 0xc4527a, 0xee6e5a, 0xffb25e], - sun: [0xfff6cf, 0xffd272, 0xff9a44], - far: 0x4a2f7e, mid: 0x2b1f5e, near: 0x151a45, top: 0x3d2f80, trees: 0x0e1236, -}; -export const DAWN = { - sky: [0x8d7fd8, 0xa596e2, 0xbcaeea, 0xd2c4f0, 0xe7d2ee, 0xf6dce4, 0xffe6d6], - sun: [0xffffff, 0xfff1d0, 0xffd9a8], - far: 0xa898dc, mid: 0x8676c8, near: 0x6a5ab4, top: 0x9a8ae0, trees: 0x4c3e94, -}; - -// A blocky landscape, `w` by `h` texels: banded sky, a sun half set behind the far hills and cut -// into slices like Horizon's mark, flat clouds, three ridges of hills and a few square trees. -export function scene(p, seed, w, h) { - const next = rng((Math.imul(seed, 0x2545f491) | 1) >>> 0); - const out = new Array(w * h).fill(0); - const horizon = Math.floor((h * 62) / 100); - const band = horizon / p.sky.length; - for (let y = 0; y < h; y++) { - const f = y / band; - const i = Math.min(Math.floor(f), p.sky.length - 1); - const dither = f - i > 0.88 && i + 1 < p.sky.length; - for (let x = 0; x < w; x++) out[y * w + x] = dither && (x + y) % 2 === 1 ? p.sky[i + 1] : p.sky[i]; - } - const rect = (x, y, rw, rh, c) => { - for (let yy = Math.max(y, 0); yy < Math.min(y + rh, h); yy++) - for (let xx = Math.max(x, 0); xx < Math.min(x + rw, w); xx++) out[yy * w + xx] = c; - }; - for (let k = 0; k < 4; k++) { - const cx = Math.floor(next() * w); - const cy = Math.floor(horizon * (0.12 + next() * 0.4)); - const cw = 10 + Math.floor(next() * 14); - const under = p.sky[Math.min(Math.floor(cy / band) + 1, p.sky.length - 1)]; - const c = mix(under, 0xffffff, 0.12); - rect(cx, cy, cw, 2, c); - rect(cx + 3, cy - 2, Math.max(cw - 6, 0), 2, c); - } - const r = Math.floor(h * 0.2); - const [cx, cy] = [Math.floor(w * 0.68), horizon - Math.floor(h * 0.11)]; - for (let dy = -r; dy <= 0; dy++) { - const half = Math.round(Math.sqrt(r * r - dy * dy)); - const t = (dy + r) / r; - const c = p.sun[t < 0.4 ? 0 : t < 0.75 ? 1 : 2]; - if ((cy + dy) % 5 !== 0 || dy < -r * 0.6) rect(cx - half, cy + dy, half * 2, 1, c); - } - const ridge = (base, amp, rough) => { - let [y, v] = [base, 0]; - return Array.from({ length: w }, (_, x) => { - if (x % 2 === 0) { - v = (v + (next() - 0.5) * rough) * 0.86; - y += v + (base - y) * 0.06; - } - return Math.max(Math.round(Math.min(Math.max(y, base - amp), base + amp)), 0); - }); - }; - const layers = [ - [p.far, horizon - h * 0.1, h * 0.12, 3.2, null], - [p.mid, horizon + h * 0.02, h * 0.09, 2.6, null], - [p.near, horizon + h * 0.18, h * 0.07, 2.2, p.top], - ]; - let near = []; - for (const [c, base, amp, rough, top] of layers) { - const hs = ridge(base, amp, rough); - hs.forEach((y, x) => { - for (let yy = Math.min(y, h); yy < h; yy++) out[yy * w + x] = c; - if (top !== null && y < h) out[y * w + x] = top; - }); - near = hs; - } - for (let k = 0; k < Math.floor(w / 26); k++) { - const tx = 4 + Math.floor(next() * (w - 10)); - const ty = near[tx]; - rect(tx - 2, ty - 8, 5, 5, p.trees); - rect(tx - 1, ty - 10, 3, 2, p.trees); - rect(tx, ty - 3, 1, 3, p.trees); - } - return out; -} - -const png = (texels, w, h, file) => - sharp(Buffer.from(texels.flatMap(channels)), { raw: { width: w, height: h, channels: 3 } }) - .png({ compressionLevel: 9, palette: true }) - .toFile(file); - -// The page colours and the stone's shades come from crates/horizon-theme, like tokens.css. -export async function writeArt(media) { - const theme = await readFile(join(repo, "crates/horizon-theme/src/lib.rs"), "utf8"); - const page = (name) => parseInt(theme.match(new RegExp(`pub const ${name}: Blocks = Blocks \\{\\s*page: 0x([0-9a-f]{6})`))[1], 16); - const shades = JSON.parse(`[${theme.match(/TILE_SHADES: \[i16; 5\] = \[([^\]]*)\]/)[1]}]`); - const texels = Number(theme.match(/TILE_TEXELS: usize = (\d+)/)[1]) * 4; - await png(stone(page("BLOCKS_DARK"), shades, texels), texels, texels, join(media, "stone-dark.png")); - await png(stone(page("BLOCKS_LIGHT"), shades, texels), texels, texels, join(media, "stone-light.png")); - const [w, h] = [240, 72]; - await png(scene(SUNSET, 3, w, h), w, h, join(media, "scene-dark.png")); - await png(scene(DAWN, 3, w, h), w, h, join(media, "scene-light.png")); -} - -if (process.argv[1] === fileURLToPath(import.meta.url)) { - await writeArt(join(site, "public", "media")); - console.log("pixel art written to public/media/"); -} diff --git a/website/scripts/assets.mjs b/website/scripts/assets.mjs deleted file mode 100644 index 92b197e7e..000000000 --- a/website/scripts/assets.mjs +++ /dev/null @@ -1,60 +0,0 @@ -// Copies the launcher's fonts and the repo's screenshots into public/, draws the pixel art, -// converted for the web (woff2, webp in two widths). Run it after any of them change: -// `npm run assets`. Its output is committed, because Railway builds only website/. -import { mkdir, readFile, writeFile, copyFile } from "node:fs/promises"; -import { join, dirname } from "node:path"; -import { fileURLToPath } from "node:url"; -import sharp from "sharp"; -import wawoff2 from "wawoff2"; -import { writeArt } from "./art.mjs"; - -const site = join(dirname(fileURLToPath(import.meta.url)), ".."); -const repo = join(site, ".."); -const pub = join(site, "public"); - -const fonts = [ - "Geist-Regular.ttf", - "Geist-Medium.ttf", - "Geist-SemiBold.ttf", - "GeistMono-Regular.ttf", - "PixelifySans-Medium.ttf", - "PixelifySans-SemiBold.ttf", - "PixelifySans-Bold.ttf", -]; - -// [source, name]; every image becomes media/.webp and media/-800.webp. -export const images = [ - ["docs/media/sunset.jpg", "sunset"], - ["docs/media/village.jpg", "village"], - ["docs/media/survival.jpg", "survival"], - ["docs/media/nether.jpg", "nether"], - ["docs/media/night.jpg", "night"], - ["docs/media/underwater.jpg", "underwater"], - ["docs/media/settings-simple.png", "settings"], - ["docs/media/launcher-play.png", "launcher"], -]; - -await mkdir(join(pub, "fonts"), { recursive: true }); -await mkdir(join(pub, "media"), { recursive: true }); - -for (const font of fonts) { - const ttf = await readFile(join(repo, "crates/horizon-theme/fonts", font)); - await writeFile(join(pub, "fonts", font.replace(".ttf", ".woff2")), await wawoff2.compress(ttf)); -} -for (const licence of ["OFL-Geist.txt", "OFL-PixelifySans.txt"]) { - await copyFile(join(repo, "crates/horizon-theme/fonts", licence), join(pub, "fonts", licence)); -} - -for (const [source, name] of images) { - const input = join(repo, source); - await sharp(input).resize({ width: 1600, withoutEnlargement: true }).webp({ quality: 82 }).toFile(join(pub, "media", `${name}.webp`)); - await sharp(input).resize({ width: 800 }).webp({ quality: 78 }).toFile(join(pub, "media", `${name}-800.webp`)); -} - -// The stone tile and the hero's landscape, drawn in code (scripts/art.mjs). -await writeArt(join(pub, "media")); - -// The icons (favicon.svg, favicon-32.png, apple-touch-icon.png) come from Horizon's mark: -// `cargo run -p xtask -- icons` writes them with the rest of the brand (docs/media/brand). - -console.log("assets written to public/"); diff --git a/website/scripts/benchmarks.mjs b/website/scripts/benchmarks.mjs deleted file mode 100644 index 724834ea7..000000000 --- a/website/scripts/benchmarks.mjs +++ /dev/null @@ -1,240 +0,0 @@ -// Benchmark results for the site: benchmark reports (docs/benchmark-report.md) in, the summary the Benchmarks page -// reads out (public/benchmarks.json, and the telemetry server's GET /v1/benchmarks/summary in the same shape). -// -// node scripts/benchmarks.mjs --ours fleet.json [--telemetry items.jsonl] [-o public/benchmarks.json] -// -// --ours lists our own runs (tools/perf_bench.py reports, Horizon and vanilla, one machine each); --telemetry holds -// players' `benchmark` items as the server stores them ({ install_id, day, version, data: } per line). -// Players' results are grouped by GPU, CPU, render distance and game, and a group is published only with at least -// MIN_INSTALLS installs, so nobody can be picked out. install_id is used to count installs and to weigh each install -// once, and never leaves this script; neither do the day, OS version, driver, the exact RAM and VRAM, or the screen. -// A group also says how its installs split by hardware class (RAM, VRAM, drive, OS, integrated or discrete GPU), -// each class only with at least MIN_INSTALLS installs. The classes are the server's (src/classes.rs). -import { readFile, writeFile } from "node:fs/promises"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -export const FORMAT = "horizon-benchmark-summary"; -export const MIN_INSTALLS = 3; -export const SCENES = ["village", "forest", "ocean", "mountain"]; -export const FIELDS = ["avg_fps", "low_1pct_fps", "p95_ms", "world_ms", "chunk_load_ms", "rss_peak_mb", "rss_steady_mb"]; - -const mean = (xs) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : null); -const finite = (x) => typeof x === "number" && Number.isFinite(x); -export function median(xs) { - const v = xs.filter(finite).sort((a, b) => a - b); - if (!v.length) return null; - const m = v.length >> 1; - return v.length % 2 ? v[m] : (v[m - 1] + v[m]) / 2; -} -// fps to integers, milliseconds to a tenth under 10 and to integers above, megabytes to integers. -export function round(field, x) { - if (!finite(x)) return null; - if (field.endsWith("_ms")) return x < 10 ? Math.round(x * 10) / 10 : Math.round(x); - return Math.round(x); -} -const trim = (s) => (typeof s === "string" ? s.replace(/\(R\)|\(TM\)|\(tm\)/g, "").replace(/\s+/g, " ").trim() : ""); -const gameOf = (app) => (app?.name === "horizon-client" ? "horizon" : app?.name === "minecraft" && !(app.mods || []).some((m) => m.name !== "fabric-loader") ? "vanilla" : null); - -// --- Hardware classes: coarse, so that a class holds many machines --------------------------- - -export const DIMENSIONS = ["ram", "vram", "storage", "os", "gpu_kind"]; -export function ramClass(gb) { - if (!(gb > 0)) return null; - return gb <= 5 ? "4 GB or less" : gb <= 10 ? "8 GB" : gb <= 20 ? "16 GB" : gb <= 40 ? "32 GB" : "64 GB or more"; -} -export function gpuKindClass(s) { - return s === "integrated" || s === "IntegratedGpu" ? "integrated" : s === "discrete" || s === "DiscreteGpu" ? "discrete" : null; -} -// A GPU's own memory in MiB; an integrated GPU shares the system's. -export function vramClass(mb, kind) { - if (gpuKindClass(kind) === "integrated") return "shared"; - if (!(mb > 0)) return null; - for (const [max, name] of [[2560, "2 GB or less"], [4608, "4 GB"], [6656, "6 GB"], [8704, "8 GB"], [12800, "12 GB"], [16896, "16 GB"]]) if (mb <= max) return name; - return "more than 16 GB"; -} -const oneOf = (list) => (s) => (list.includes(s) ? s : null); -export const storageClass = oneOf(["nvme", "ssd", "hdd"]); -export const osClass = oneOf(["linux", "macos", "windows"]); -// A report's classes, in DIMENSIONS order. -export function classesOf(report) { - const hw = report?.hardware || {}; - const kind = hw.gpu?.kind; - return [ramClass(finite(hw.ram_mb) ? hw.ram_mb / 1024 : 0), vramClass(hw.gpu?.vram_mb, kind), storageClass(hw.storage), osClass(hw.os), gpuKindClass(kind)]; -} -// Per dimension, the classes with at least minInstalls installs, most first; dimensions without one are left out. -export function breakdowns(classes, minInstalls) { - const out = {}; - DIMENSIONS.forEach((dim, i) => { - const cells = [...classes[i]].map(([c, set]) => ({ class: c, installs: set.size })).filter((c) => c.installs >= minInstalls); - cells.sort((a, b) => b.installs - a.installs || (a.class < b.class ? -1 : a.class > b.class ? 1 : 0)); - if (cells.length) out[dim] = cells; - }); - return out; -} - -// Why a report can't be compared with the others, or null when it can: the standard flight over the four scenes, -// VSync off, no frame cap, drawn on a screen. -export function rejection(report) { - if (!report || report.format !== "horizon-benchmark-report" || report.version !== 1) return "not a version 1 benchmark report"; - if (report.kind !== "game") return "not a game run"; - if (!gameOf(report.app)) return "not Horizon or plain vanilla"; - const c = report.conditions || {}; - if (!(c.scenario === "standard" || c.scenario === "flight" || String(c.scenario || "").startsWith("perf_bench:"))) return "not the standard flight"; - if (c.vsync !== false) return "VSync on or unknown"; - if (c.fps_cap != null) return "frame rate capped"; - if (c.offscreen === true) return "offscreen"; - if (!finite(c.render_distance)) return "no render distance"; - const phases = new Set((report.frames || []).map((f) => f.phase)); - if (!SCENES.every((s) => phases.has(s))) return "not every scene"; - if (!trim(report.hardware?.gpu?.name) || !trim(report.hardware?.cpu)) return "no GPU or CPU name"; - return null; -} - -// One report's figures: frame figures averaged over every flight (scene and repeat), the rest from its metrics. -export function figures(report) { - const frames = report.frames || []; - const m = report.metrics || {}; - const metric = (name) => (finite(m[name]?.mean) ? m[name].mean : null); - const loads = Object.keys(m).filter((k) => /^chunks\.[^.]+\.load_ms$/.test(k)).map(metric).filter(finite); - const avg = (key) => mean(frames.map((f) => f[key]).filter(finite)); - return { - avg_fps: avg("avg_fps"), - low_1pct_fps: avg("low_1pct_fps"), - p95_ms: avg("p95_ms"), - world_ms: metric("startup.world_ms"), - chunk_load_ms: mean(loads), - rss_peak_mb: metric("memory.rss_peak_mb"), - rss_steady_mb: metric("memory.rss_steady_mb"), - cpu_p50_ms: avg("cpu_p50_ms"), - gpu_p50_ms: avg("gpu_p50_ms"), - }; -} - -const roundAll = (fig, fields) => Object.fromEntries(fields.map((f) => [f, round(f, fig[f])])); - -// Players' items -> groups of at least minInstalls installs. Each install counts once: its median first, then the -// median across installs. -export function aggregatePlayers(items, { minInstalls = MIN_INSTALLS } = {}) { - const groups = new Map(); - for (const item of items) { - const report = item?.data; - if (!item?.install_id || rejection(report)) continue; - const key = JSON.stringify([trim(report.hardware.gpu.name), trim(report.hardware.cpu), report.conditions.render_distance, gameOf(report.app)]); - if (!groups.has(key)) groups.set(key, { installs: new Map(), reports: 0, versions: new Set(), classes: DIMENSIONS.map(() => new Map()) }); - const g = groups.get(key); - g.reports++; - if (item.version) g.versions.add(item.version); - if (!g.installs.has(item.install_id)) g.installs.set(item.install_id, []); - g.installs.get(item.install_id).push(figures(report)); - classesOf(report).forEach((c, i) => { - if (!c) return; - if (!g.classes[i].has(c)) g.classes[i].set(c, new Set()); - g.classes[i].get(c).add(item.install_id); - }); - } - const out = []; - for (const [key, g] of groups) { - if (g.installs.size < minInstalls) continue; - const [gpu, cpu, render_distance, game] = JSON.parse(key); - const perInstall = [...g.installs.values()].map((runs) => Object.fromEntries(FIELDS.map((f) => [f, median(runs.map((r) => r[f]))]))); - const medians = Object.fromEntries(FIELDS.map((f) => [f, round(f, median(perInstall.map((r) => r[f])))])); - out.push({ gpu, cpu, render_distance, game, source: "players", installs: g.installs.size, reports: g.reports, versions: [...g.versions].sort(byVersionDesc).slice(0, 3), medians, breakdowns: breakdowns(g.classes, minInstalls) }); - } - // Most installs first, then by GPU, CPU, render distance and game, compared as plain strings (as the server does). - const cmp = (x, y) => (x < y ? -1 : x > y ? 1 : 0); - return out.sort((a, b) => b.installs - a.installs || cmp(a.gpu, b.gpu) || cmp(a.cpu, b.cpu) || a.render_distance - b.render_distance || cmp(a.game, b.game)); -} - -// "v0.2.10" after "v0.2.9", dated tags by their numbers; good enough to list the newest three. -function byVersionDesc(a, b) { - const n = (v) => (v.match(/\d+/g) || []).map(Number); - const [x, y] = [n(a), n(b)]; - for (let i = 0; i < Math.max(x.length, y.length); i++) if ((x[i] ?? -1) !== (y[i] ?? -1)) return (y[i] ?? -1) - (x[i] ?? -1); - return 0; -} - -// Our own runs: one row per machine, game and render distance, with what was measured and how. An entry holds one -// report (its runs are the report's repeats) or several (one game each); figures are medians over the reports. -export function ourRows(runs) { - const rows = []; - for (const { report, reports, machine, note, version, capped_fps } of runs) { - const list = reports || [report]; - for (const r of list) { - const why = rejection(r); - if (why) throw new Error(`${machine}: ${r?.label || "report"} can't be published: ${why}`); - } - const [first] = list; - const c = first.conditions; - if (list.some((r) => r.conditions.render_distance !== c.render_distance || gameOf(r.app) !== gameOf(first.app) || r.app.version !== first.app.version)) - throw new Error(`${machine}: reports of different games, versions or render distances in one entry`); - const figs = list.map(figures); - const fig = Object.fromEntries(Object.keys(figs[0]).map((k) => [k, median(figs.map((f) => f[k]))])); - const scenes = Object.fromEntries( - SCENES.map((s) => { - const fs = list.flatMap((r) => r.frames.filter((f) => f.phase === s)); - const loads = list.map((r) => r.metrics?.[`chunks.${s}.load_ms`]?.mean); - return [s, { avg_fps: round("avg_fps", mean(fs.map((f) => f.avg_fps))), low_1pct_fps: round("low_1pct_fps", mean(fs.map((f) => f.low_1pct_fps))), chunk_load_ms: round("chunk_load_ms", median(loads)) }]; - }), - ); - rows.push({ - gpu: trim(first.hardware.gpu.name), - cpu: trim(first.hardware.cpu), - render_distance: c.render_distance, - game: gameOf(first.app), - source: "us", - machine, - measured: list.map((r) => (r.created || "").slice(0, 10)).sort().at(-1), - // A release build reports its crate version; the entry can name the release it was. - version: version || first.app.version, - backend: first.hardware.gpu.backend || null, - os: first.hardware.os || null, - window: c.window || null, - repeats: list.reduce((n, r) => n + (r.conditions.repeats || 1), 0), - load_avg_1m: Math.max(...list.map((r) => r.conditions.load_avg_1m ?? 0)), - ...(note ? { note } : {}), - // The frame rate the display held this game to (a present mode VSync off doesn't lift): its average is a floor. - ...(capped_fps ? { capped_fps } : {}), - // A split of 0 means the backend gave no timing (Metal has no GPU timer here): unknown, not free. - medians: { ...roundAll(fig, FIELDS), cpu_p50_ms: fig.cpu_p50_ms > 0 ? round("cpu_p50_ms", fig.cpu_p50_ms) : null, gpu_p50_ms: fig.gpu_p50_ms > 0 ? round("gpu_p50_ms", fig.gpu_p50_ms) : null }, - scenes, - }); - } - return rows; -} - -export function summary({ ours = [], players = [], generated = new Date() } = {}) { - return { format: FORMAT, version: 1, generated: generated.toISOString().replace(/\.\d+Z$/, "Z"), min_installs: MIN_INSTALLS, groups: [...ours, ...players] }; -} - -// --- The command line ---------------------------------------------------------------------- - -async function main(argv) { - const arg = (name) => { - const i = argv.indexOf(name); - return i >= 0 ? argv[i + 1] : null; - }; - const site = resolve(dirname(fileURLToPath(import.meta.url)), ".."); - const out = arg("-o") || resolve(site, "public/benchmarks.json"); - let ours = []; - if (arg("--ours")) { - // [{ "machine": "Mac mini", "reports": ["path/to/report.json", ...], "version": "v…", "note": "..." }], paths - // relative to the list; "version" names the release when the report only has the crate version. - const listPath = resolve(arg("--ours")); - const list = JSON.parse(await readFile(listPath, "utf8")); - const load = async (path) => JSON.parse(await readFile(resolve(dirname(listPath), path), "utf8")); - const runs = []; - for (const entry of list) runs.push({ ...entry, reports: await Promise.all((entry.reports || [entry.report]).map(load)), report: undefined }); - ours = ourRows(runs); - } - let players = []; - if (arg("--telemetry")) { - const text = await readFile(resolve(arg("--telemetry")), "utf8"); - players = aggregatePlayers(text.split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l))); - } - const result = summary({ ours, players }); - await writeFile(out, JSON.stringify(result, null, 1) + "\n"); - console.log(`${out}: ${ours.length} rows measured by us, ${players.length} player groups`); -} - -if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await main(process.argv.slice(2)); diff --git a/website/scripts/benchmarks.test.mjs b/website/scripts/benchmarks.test.mjs deleted file mode 100644 index 87aec484b..000000000 --- a/website/scripts/benchmarks.test.mjs +++ /dev/null @@ -1,91 +0,0 @@ -// node --test (npm test in website/). The fixtures are shared with the telemetry server's summary test. -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import { aggregatePlayers, median, osClass, ourRows, ramClass, rejection, round, storageClass, summary, vramClass, gpuKindClass } from "./benchmarks.mjs"; - -const fixture = (name) => new URL(`./fixtures/benchmarks/${name}`, import.meta.url); -const items = readFileSync(fixture("items.jsonl"), "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)); -const expected = JSON.parse(readFileSync(fixture("expected.json"), "utf8")); - -test("players' items give the expected groups", () => { - const s = summary({ players: aggregatePlayers(items) }); - assert.equal(s.format, "horizon-benchmark-summary"); - assert.equal(s.min_installs, expected.min_installs); - assert.deepEqual(s.groups, expected.groups); -}); - -test("nothing that identifies an install is published", () => { - const text = JSON.stringify(aggregatePlayers(items, { minInstalls: 1 })); - for (const secret of ["a1", "a2", "install_id", "secret-os-version", "secret-driver", "20394", "ram_mb", "2560", "16376", "32768", "vram_mb"]) assert.ok(!text.includes(secret), secret); -}); - -test("a group needs three installs, not three runs", () => { - const one = items.filter((i) => i.install_id === "a1"); - assert.equal(aggregatePlayers([...one, ...one, ...one]).length, 0); - assert.equal(aggregatePlayers(items, { minInstalls: 2 }).length, 2); -}); - -test("hardware classes are coarse, as the server's", () => { - assert.equal(ramClass(15.6), "16 GB"); - assert.equal(ramClass(31), "32 GB"); - assert.equal(ramClass(64), "64 GB or more"); - assert.equal(ramClass(0), null); - assert.equal(vramClass(16376, "discrete"), "16 GB"); - assert.equal(vramClass(8192, "DiscreteGpu"), "8 GB"); - assert.equal(vramClass(0, "integrated"), "shared"); - assert.equal(vramClass(0, ""), null); - assert.equal(storageClass("nvme"), "nvme"); - assert.equal(storageClass("tape"), null); - assert.equal(osClass("windows"), "windows"); - assert.equal(gpuKindClass("virtual"), null); -}); - -test("a breakdown cell needs three installs too", () => { - const [group] = aggregatePlayers(items); - assert.equal(group.breakdowns.ram, undefined); // 32 GB has two installs, 16 GB one - assert.equal(group.breakdowns.storage, undefined); - const [all] = aggregatePlayers(items, { minInstalls: 1 }); - assert.deepEqual(all.breakdowns.ram, [{ class: "32 GB", installs: 2 }, { class: "16 GB", installs: 1 }]); - assert.deepEqual(all.breakdowns.storage, [{ class: "nvme", installs: 2 }, { class: "ssd", installs: 1 }]); -}); - -test("only comparable runs count", () => { - const reasons = items.map((i) => rejection(i.data)); - assert.deepEqual(reasons.filter(Boolean), ["VSync on or unknown", "offscreen", "frame rate capped", "not every scene", "not the standard flight", "not a version 1 benchmark report"]); -}); - -test("medians and rounding", () => { - assert.equal(median([3, 1, 2]), 2); - assert.equal(median([4, 1, 2, 3]), 2.5); - assert.equal(median([null, NaN]), null); - assert.equal(round("p95_ms", 3.46), 3.5); - assert.equal(round("world_ms", 4512.4), 4512); - assert.equal(round("avg_fps", 99.5), 100); -}); - -test("our runs keep the machine and how it was measured", () => { - const [row] = ourRows([{ machine: "Desktop", report: items[0].data }]); - assert.equal(row.source, "us"); - assert.equal(row.machine, "Desktop"); - assert.equal(row.game, "horizon"); - assert.equal(row.medians.avg_fps, 415); - assert.equal(row.scenes.ocean.avg_fps, 420); - assert.throws(() => ourRows([{ machine: "x", report: items[4].data }]), /VSync/); - // Several one-game reports: medians over them. - const [both] = ourRows([{ machine: "Desktop", reports: [items[0].data, items[1].data] }]); - assert.equal(both.medians.avg_fps, 515); - assert.equal(both.repeats, 2); - assert.throws(() => ourRows([{ machine: "x", reports: [items[0].data, items[9].data] }]), /different/); -}); - -test("a display cap on our run is kept, and the comparison says at least", async () => { - const [row] = ourRows([{ machine: "Mac", report: items[0].data, capped_fps: 144, version: "v1" }]); - assert.equal(row.capped_fps, 144); - assert.equal(row.version, "v1"); - const { compareRows, METRICS } = await import("../src/bench.js"); - const fps = METRICS[0]; - const h = { capped_fps: 144, medians: { avg_fps: 144 } }; - assert.equal(compareRows(fps, h, { medians: { avg_fps: 120 } }).text, "at least 1.2x faster"); - assert.equal(compareRows(fps, h, { medians: { avg_fps: 200 } }).wins, "none"); -}); diff --git a/website/scripts/shots.mjs b/website/scripts/shots.mjs deleted file mode 100644 index c0b86f40d..000000000 --- a/website/scripts/shots.mjs +++ /dev/null @@ -1,99 +0,0 @@ -// Full-page screenshots of the built site at every width that matters, plus the social -// preview image. Run `npm run build` first; `npm run shots` serves dist/ and writes -// shots/*.png (gitignored: full-page PNGs are too heavy for the repo), 390-menu.png (the open -// menu) and 1440-hero.png, and public/og.png (rebuild after). It also checks each width for -// horizontal scroll, small tap targets and line lengths. `SHOTS=dir` writes them elsewhere. -import { chromium } from "playwright"; -import { spawn } from "node:child_process"; -import { mkdir } from "node:fs/promises"; -import { join, dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -const site = join(dirname(fileURLToPath(import.meta.url)), ".."); -const port = 4199; -const url = `http://localhost:${port}/`; -const server = spawn(process.execPath, [join(site, "serve.mjs")], { env: { ...process.env, PORT: String(port) }, stdio: "ignore" }); -await new Promise((r) => setTimeout(r, 400)); - -const widths = [360, 390, 430, 768, 1024, 1180, 1250, 1280, 1366, 1440, 1680, 1920]; -const sizes = [...widths.map((w) => [w, w < 900 ? 800 : 900]), [1250, 700]]; -const only = process.argv.slice(2); -const out = process.env.SHOTS ? resolve(process.env.SHOTS) : join(site, "shots"); - -await mkdir(out, { recursive: true }); -const browser = await chromium.launch(); -let problems = 0; - -for (const [width, height] of sizes) { - const name = height === 700 ? `${width}x${height}` : `${width}`; - if (only.length && !only.includes(name)) continue; - const touch = width < 900; - const page = await browser.newPage({ viewport: { width, height }, deviceScaleFactor: 1, hasTouch: touch, isMobile: touch }); - await page.goto(url, { waitUntil: "networkidle" }); - // Reveal every section, as scrolling would, and let the fades finish. - await page.evaluate(async () => { - for (let y = 0; y < document.body.scrollHeight; y += 400) { - scrollTo({ top: y, behavior: "instant" }); - await new Promise((r) => setTimeout(r, 30)); - } - scrollTo({ top: 0, behavior: "instant" }); - }); - await page.waitForTimeout(800); - const report = await page.evaluate((touch) => { - const out = []; - const doc = document.documentElement; - if (doc.scrollWidth > innerWidth) out.push(`horizontal scroll: ${doc.scrollWidth} > ${innerWidth}`); - for (const el of document.querySelectorAll("body *")) { - const r = el.getBoundingClientRect(); - if (r.width && r.right > innerWidth + 1 && !el.closest(".lightbox, .menu, .hero-media, .footer-word")) { - out.push(`overflows: ${el.tagName.toLowerCase()}.${el.className} right ${Math.round(r.right)}`); - } - } - if (touch) { - for (const el of document.querySelectorAll("a, button, summary")) { - if (el.closest(".menu, .lightbox, .skip") || el.closest(".prose, .footer-cols, .fact p, .system-detail, .download-meta, .meta")) continue; - const r = el.getBoundingClientRect(); - if (r.width && r.height < 44) out.push(`small target: ${el.textContent.trim().slice(0, 30)} (${Math.round(r.height)}px)`); - } - } - // Characters per line of the longest running-text paragraphs. - const lengths = [...document.querySelectorAll(".prose p, .lede, .hero-line, .fact p, .features p, .system-detail, .count-label, .footer-cols p")] - .filter((p) => p.textContent.length > 160) - .map((p) => { - const lh = parseFloat(getComputedStyle(p).lineHeight); - const n = Math.round(p.textContent.length / Math.max(1, Math.round(p.getBoundingClientRect().height / lh))); - return [n, `${p.parentElement.id || p.parentElement.className}>${p.className || p.tagName}`]; - }) - .sort((a, b) => a[0] - b[0]); - const [lo, hi] = [lengths[0], lengths[lengths.length - 1]]; - out.push(`chars per line: ${lo[0]} (${lo[1]})–${hi[0]} (${hi[1]})`); - return out.slice(0, 12); - }, touch); - const issues = report.filter((l) => !l.startsWith("chars")); - problems += issues.length; - console.log(`${name}: ${issues.length ? issues.join("; ") : "ok"} · ${report.find((l) => l.startsWith("chars"))}`); - await page.screenshot({ path: join(out, `${name}.png`), fullPage: height !== 700 }); - if (width === 1440) await page.screenshot({ path: join(out, "1440-hero.png") }); - if (width === 390) { - await page.click(".menu-button"); - await page.waitForTimeout(800); - await page.screenshot({ path: join(out, "390-menu.png") }); - } - await page.close(); -} - -if (!only.length || only.includes("og")) { - const page = await browser.newPage({ viewport: { width: 1200, height: 630 } }); - await page.goto(`${url}og.html`, { waitUntil: "networkidle" }); - await page.waitForTimeout(700); - await page.screenshot({ path: join(site, "public/og.png") }); - await page.close(); -} - -await browser.close(); -server.kill(); - -if (problems) { - console.log(`${problems} problems`); - process.exitCode = 1; -} diff --git a/website/serve.mjs b/website/serve.mjs deleted file mode 100644 index 553a3ff9b..000000000 --- a/website/serve.mjs +++ /dev/null @@ -1,42 +0,0 @@ -// A dependency-free static server for dist/, for local checks (`npm run dev`). -// Railway uses Caddy instead (see Dockerfile). -import { createServer } from "node:http"; -import { readFile, stat } from "node:fs/promises"; -import { join, extname, normalize } from "node:path"; -import { fileURLToPath } from "node:url"; - -const root = join(fileURLToPath(new URL(".", import.meta.url)), "dist"); -const types = { ".html": "text/html; charset=utf-8", ".css": "text/css", ".js": "text/javascript", ".webp": "image/webp", ".png": "image/png", ".svg": "image/svg+xml", ".woff2": "font/woff2", ".txt": "text/plain; charset=utf-8", ".md": "text/plain; charset=utf-8", ".json": "application/json", ".xml": "application/xml" }; -const port = Number(process.env.PORT) || 4173; - -createServer(async (req, res) => { - let path = normalize(decodeURIComponent(new URL(req.url, "http://x").pathname)).replace(/^(\.\.[/\\])+/, ""); - if (path === "/docs/api/") { - res.writeHead(301, { Location: "/docs/api" }); - return res.end(); - } - if (path.endsWith("/")) path += "index.html"; - // The server guide is part of the docs now, as the Caddyfile redirects it. - if (path === "/server" || path === "/server.html") { - res.writeHead(301, { Location: "/docs/hosting" }); - return res.end(); - } - // The roadmap page became the hub's Roadmap tab. - if (path === "/roadmap") { - res.writeHead(301, { Location: "/hub#roadmap" }); - return res.end(); - } - if (path === "/docs") path = "/docs/index.html"; - // /privacy, /docs/ and /docs/api/ are .html files, as the Caddyfile rewrites them. - if (!extname(path)) path += ".html"; - let file = join(root, path); - let status = 200; - try { - if (!(await stat(file)).isFile()) throw 0; - } catch { - file = join(root, "404.html"); - status = 404; - } - res.writeHead(status, { "Content-Type": types[extname(file)] || "application/octet-stream" }); - res.end(await readFile(file)); -}).listen(port, () => console.log(`http://localhost:${port}`)); diff --git a/website/src/404.html b/website/src/404.html deleted file mode 100644 index 3ac1e017a..000000000 --- a/website/src/404.html +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - Not found · Horizon - - - - - - - - - -
-
-

404Not found

-

Not here.

-

This page doesn't exist. The rest of Horizon is one page away.

- -

Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

-
-
- - - diff --git a/website/src/bench.js b/website/src/bench.js deleted file mode 100644 index 40185c79d..000000000 --- a/website/src/bench.js +++ /dev/null @@ -1,167 +0,0 @@ -// The Benchmarks page's tables, from the summary (public/benchmarks.json, or the telemetry server's -// GET /v1/benchmarks/summary in the same shape). Shared by build.mjs (baked) and benchmarks-page.js (live). -import { escape } from "./markdown.js"; - -export const METRICS = [ - { key: "avg_fps", label: "Average FPS", kind: "fps", better: "high" }, - { key: "low_1pct_fps", label: "1% low FPS", kind: "fps", better: "high", hint: "the slowest 1% of frames, as FPS" }, - { key: "p95_ms", label: "Frame time, 95th percentile", kind: "ms", better: "low" }, - { key: "world_ms", label: "Start to in-world", kind: "ms", better: "low", hint: "process start to the spawn area loaded and drawn" }, - { key: "chunk_load_ms", label: "Chunk load after a teleport", kind: "ms", better: "low", hint: "the four scenes' average" }, - { key: "rss_steady_mb", label: "Memory while playing", kind: "mb", better: "low" }, - { key: "rss_peak_mb", label: "Memory, peak", kind: "mb", better: "low" }, -]; - -export function format(kind, x) { - if (x == null || !Number.isFinite(x)) return "–"; - if (kind === "fps") return x >= 100 ? Math.round(x).toLocaleString("en") : x.toFixed(x >= 10 ? 0 : 1); - if (kind === "ms") return x >= 1000 ? `${(x / 1000).toFixed(x >= 10000 ? 0 : 1)} s` : `${x < 10 ? x.toFixed(1) : Math.round(x)} ms`; - if (kind === "mb") return x >= 1000 ? `${(x / 1024).toFixed(1)} GB` : `${Math.round(x)} MB`; - return String(x); -} - -// "2.4x faster", "1.3x slower", "2.0x less" (memory), from Horizon's side. -export function compare(metric, horizon, java) { - if (horizon == null || java == null || !horizon || !java) return null; - const ratio = metric.better === "high" ? horizon / java : java / horizon; - if (Math.abs(ratio - 1) < 0.05) return { text: "about the same", wins: "tie" }; - const word = metric.kind === "mb" ? (ratio > 1 ? "less" : "more") : ratio > 1 ? "faster" : "slower"; - const r = ratio > 1 ? ratio : 1 / ratio; - return { text: `${r.toFixed(r >= 10 ? 0 : 1)}x ${word}`, wins: ratio > 1 ? "horizon" : "java" }; -} - -// The game's average frame rate sat at a display cap (`capped_fps`): the real one is at least that. -export const capped = (row) => Boolean(row?.capped_fps && row.medians?.avg_fps >= row.capped_fps * 0.97); - -// compare() between two rows, saying "at least" where Horizon's average sat at a cap. -export function compareRows(metric, h, j) { - const c = compare(metric, h?.medians?.[metric.key], j?.medians?.[metric.key]); - if (!c || metric.key !== "avg_fps" || !capped(h)) return c; - return c.wins === "horizon" ? { ...c, text: `at least ${c.text}` } : { text: "capped, can't tell", wins: "none" }; -} - -export const cell = (metric, row) => { - const v = format(metric.kind, row?.medians?.[metric.key]); - return metric.key === "avg_fps" && capped(row) ? `${v} (cap)` : v; -}; - -const machines = (groups) => { - const by = new Map(); - for (const g of groups.filter((g) => g.source === "us")) { - if (!by.has(g.machine)) by.set(g.machine, []); - by.get(g.machine).push(g); - } - return by; -}; - -const pick = (rows, game, rd) => rows.find((r) => r.game === game && r.render_distance === rd); - -// One machine we measured: Horizon and Java side by side at each render distance. -export function machineHtml(name, rows) { - const first = rows[0]; - const distances = [...new Set(rows.map((r) => r.render_distance))].sort((a, b) => a - b); - const horizon = rows.find((r) => r.game === "horizon"); - const java = rows.find((r) => r.game === "vanilla"); - const head = distances.map((rd) => `Render distance ${rd}`).join(""); - const sub = distances.map(() => `HorizonJavaHorizon against Java`).join(""); - const body = METRICS.map((m) => { - const cells = distances - .map((rd) => { - const h = pick(rows, "horizon", rd); - const j = pick(rows, "vanilla", rd); - const c = compareRows(m, h, j); - return `${cell(m, h)}${cell(m, j)}${c ? escape(c.text) : ""}`; - }) - .join(""); - return `${escape(m.label)}${m.hint ? `${escape(m.hint)}` : ""}${cells}`; - }).join(""); - const javaWins = METRICS.flatMap((m) => - distances.filter((rd) => compareRows(m, pick(rows, "horizon", rd), pick(rows, "vanilla", rd))?.wins === "java").map((rd) => `${m.label.toLowerCase()} at ${rd}`), - ); - // Per scene too: an average that Horizon wins can hide a scene where Java is faster. - const sceneName = { village: "the village", forest: "the forest", ocean: "the ocean", mountain: "the mountain" }; - for (const rd of distances) { - const h = pick(rows, "horizon", rd); - const j = pick(rows, "vanilla", rd); - for (const [scene, js] of Object.entries(j?.scenes || {})) { - const hs = h?.scenes?.[scene]; - if (!hs?.avg_fps || !js?.avg_fps || (h.capped_fps && hs.avg_fps >= h.capped_fps * 0.97)) continue; - if (js.avg_fps > hs.avg_fps * 1.05) javaWins.push(`average FPS over ${sceneName[scene] || scene} at ${rd} (${format("fps", js.avg_fps)} against ${format("fps", hs.avg_fps)})`); - } - } - const facts = [ - ["CPU", first.cpu], - ["GPU", first.gpu], - ["Horizon", horizon ? `${horizon.version} · ${horizon.backend || "?"}` : "not measured"], - ["Java", java ? `${java.version} (vanilla) · ${java.backend || "?"}` : "not measured"], - ["Measured", `${first.measured}${first.repeats ? ` · ${first.repeats} runs of each` : ""}${first.window ? ` · ${first.window.join("x")} window` : ""}`], - ]; - return `
-
-

Measured by us

-

${escape(name)}

-
${facts.map(([k, v]) => `
${k}
${escape(String(v))}
`).join("")}
- ${rows.find((r) => r.note) ? `

${escape(rows.find((r) => r.note).note)}

` : ""} -
-
- ${head}${sub} - ${body} -
- ${javaWins.length ? `

Where Java is ahead: ${escape(javaWins.join("; "))}.

` : `

Horizon is ahead on every figure here.

`} -
`; -} - -export function machinesHtml(summary) { - const by = machines(summary?.groups || []); - if (!by.size) return `

No measurements are published yet.

`; - return [...by].map(([name, rows]) => machineHtml(name, rows)).join("\n"); -} - -// The hardware breakdowns (the server's classes), in words. -export const DIMENSIONS = [ - { key: "ram", label: "Memory", word: (c) => `${c} RAM` }, - { key: "vram", label: "Graphics memory", word: (c) => (c === "shared" ? "shared graphics memory" : `${c} graphics memory`) }, - { key: "storage", label: "Drive", word: (c) => ({ nvme: "NVMe", ssd: "SSD", hdd: "hard disk" })[c] || c }, - { key: "os", label: "System", word: (c) => ({ linux: "Linux", macos: "macOS", windows: "Windows" })[c] || c }, - { key: "gpu_kind", label: "Graphics", word: (c) => (c === "integrated" ? "integrated GPU" : c === "discrete" ? "separate GPU" : c) }, -]; - -// A group's breakdowns in one line: "32 GB RAM (3) · NVMe (3) · Linux (3)". Empty without any. -export function breakdownLine(breakdowns) { - return DIMENSIONS.flatMap((d) => (breakdowns?.[d.key] || []).map((c) => `${d.word(c.class)} (${c.installs})`)).join(" · "); -} - -// GET /v1/aggregate's breakdowns: players' play sessions per hardware class. Empty without any. -export function hardwareHtml(aggregate) { - const b = aggregate?.breakdowns || {}; - const dims = DIMENSIONS.filter((d) => b[d.key]?.length); - if (!dims.length) return ""; - const rows = dims - .flatMap((d) => - b[d.key].map( - (c, i) => - `${i === 0 ? `${escape(d.label)}` : ""}${escape(d.word(c.class))}${c.installs}${Math.round(c.hours).toLocaleString("en")}${format("ms", c.p50_ms)}${format("ms", c.p99_ms)}`, - ), - ) - .join(""); - return `
- - ${rows} -
ByClassInstallsHours playedFrame time, medianFrame time, 99th percentile
`; -} - -// Players' groups: one row each, at least `min_installs` installs. -export function playersHtml(summary) { - const groups = (summary?.groups || []).filter((g) => g.source === "players"); - if (!groups.length) - return `

No player results yet. A GPU and CPU pair shows here once at least ${summary?.min_installs || 3} different installs have shared a benchmark with it.

`; - const rows = groups - .map( - (g) => `${escape(g.gpu)}${escape(g.cpu)}${g.render_distance}${g.game === "vanilla" ? "Java" : "Horizon"}${["avg_fps", "low_1pct_fps", "p95_ms", "world_ms", "rss_steady_mb"].map((k) => `${format(METRICS.find((m) => m.key === k).kind, g.medians?.[k])}`).join("")}From ${g.installs} players${breakdownLine(g.breakdowns) ? `${escape(breakdownLine(g.breakdowns))}` : ""}`, - ) - .join(""); - return `
- - ${rows} -
GPU and CPURender distanceGameAverage FPS1% lowp95To in-worldMemorySource
`; -} diff --git a/website/src/benchmarks-page.js b/website/src/benchmarks-page.js deleted file mode 100644 index 5d05848e3..000000000 --- a/website/src/benchmarks-page.js +++ /dev/null @@ -1,108 +0,0 @@ -// The Benchmarks page: players' results from the telemetry server (the baked summary when it doesn't answer) -// and the hardware picker (a measurement when there is one, else an estimate from src/estimate.js). -import { escape } from "./markdown.js"; -import { METRICS, cell, compareRows, format, hardwareHtml, playersHtml } from "./bench.js"; -import { estimate, measured, memoryNotes } from "./estimate.js"; -import { findCpu, findGpu } from "./hardware.js"; -import { setUpMenu, setUpTheme } from "./chrome.js"; - -const TELEMETRY = "https://telemetry.playhorizon.dev"; -const baked = JSON.parse(document.getElementById("bench-data").textContent); -let groups = baked.groups || []; - -async function live() { - try { - const res = await fetch(`${TELEMETRY}/v1/benchmarks/summary`, { signal: AbortSignal.timeout(3000) }); - if (!res.ok) throw new Error(String(res.status)); - const summary = await res.json(); - if (summary.format !== "horizon-benchmark-summary" || summary.version !== 1 || !Array.isArray(summary.groups)) throw new Error("format"); - // Our own rows stay the baked ones; players' come from the server. - const players = summary.groups.filter((g) => g.source === "players" && g.installs >= (summary.min_installs || 3)); - groups = [...groups.filter((g) => g.source === "us"), ...players]; - document.getElementById("players-table").innerHTML = playersHtml({ ...summary, groups: players }); - document.querySelector("[data-players-source]").textContent = `Live from the telemetry server, aggregated ${summary.generated.slice(0, 16).replace("T", " ")} UTC.`; - render(); - } catch { - // The baked results stay; the line under the heading already says when they were made. - } -} - -// Players' play sessions per hardware class (last 30 days); the section stays hidden until there are some. -async function hardware() { - try { - const res = await fetch(`${TELEMETRY}/v1/aggregate?days=30`, { signal: AbortSignal.timeout(3000) }); - if (!res.ok) return; - const html = hardwareHtml(await res.json()); - if (!html) return; - document.getElementById("players-hardware-table").innerHTML = html; - document.getElementById("players-hardware").hidden = false; - } catch { - // Nothing to show. - } -} - -const picker = document.getElementById("picker"); -const out = document.getElementById("pick-result"); - -const range = (kind, e) => { - if (!e) return "–"; - if (e.atLeast) return `at least ${format(kind, e.low)}`; - return e.low != null ? `${format(kind, e.low)} to ${format(kind, e.high)}` : format(kind, e.value); -}; - -function sourceBadge(row) { - return row.source === "us" ? `Measured by us · ${escape(row.machine)}` : `From ${row.installs} players`; -} - -function measuredTable(h, j) { - return `${METRICS.map((m) => { - const c = compareRows(m, h, j); - return ``; - }).join("")}
HorizonJavaHorizon against Java
${escape(m.label)}${cell(m, h)}${cell(m, j)}${c ? escape(c.text) : ""}
`; -} - -function estimateTable(h, j) { - return `${METRICS.map( - (m) => ``, - ).join("")}
Horizon (estimate)Java (estimate)
${escape(m.label)}${range(m.kind, h?.[m.key])}${range(m.kind, j?.[m.key])}
`; -} - -function render() { - const gpu = findGpu(picker.gpu.value); - const cpu = findCpu(picker.cpu.value); - const rd = Number(picker.rd.value); - const ramGb = Number(picker.ram.value) || null; - if (!gpu || !cpu) return; - // Horizon's and Java's notes, each once (the players' hardware is the same for both). - const notesHtml = (...lists) => { - const notes = [...new Set(lists.flat())]; - return notes.length ? `
    ${notes.map((n) => `
  • ${escape(n)}
  • `).join("")}
` : ""; - }; - const mh = measured(groups, gpu, cpu, rd, "horizon"); - const mj = measured(groups, gpu, cpu, rd, "vanilla"); - if (mh.length || mj.length) { - const h = mh[0]; - const j = mj[0]; - out.innerHTML = `

${[h, j].filter(Boolean).map(sourceBadge).join(" ")}

${measuredTable(h, j)}${notesHtml(...[h, j].filter(Boolean).map((row) => memoryNotes(row, gpu, ramGb)))}${ - h && h.source === "us" && h.measured ? `

Measured ${escape(h.measured)} with Horizon ${escape(h.version)}. The full table is under Measured by us.

` : "" - }`; - return; - } - const h = estimate(groups, gpu, cpu, rd, "horizon", { ramGb }); - const j = estimate(groups, gpu, cpu, rd, "vanilla", { ramGb }); - if (!h && !j) { - out.innerHTML = `

Nothing measured at render distance ${rd} to estimate from yet.

`; - return; - } - const base = (h || j).base; - const f = (h || j).factors; - const times = (x) => `${x >= 1 ? x.toFixed(x >= 10 ? 0 : 1) : x.toFixed(2)}x`; - out.innerHTML = `

Estimate From ${escape(base.source === "us" ? base.machine : `${base.gpu} with ${base.cpu}`)} (${escape(base.gpu)}, ${escape(base.cpu)}): GPU factor ${times(f.gpu)}, CPU factor ${times(f.cpu)}. How

${estimateTable(h, j)}${notesHtml(h?.notes || [], j?.notes || [])}

Ranges, not measurements: the real figure depends on drivers, the graphics API and cooling too. Memory is the measured machine's.

`; -} - -setUpTheme(); -setUpMenu(); -picker.addEventListener("change", render); -render(); -live(); -hardware(); diff --git a/website/src/benchmarks.html b/website/src/benchmarks.html deleted file mode 100644 index 41e270c5b..000000000 --- a/website/src/benchmarks.html +++ /dev/null @@ -1,105 +0,0 @@ - - - - - - Benchmarks: Horizon against Java Edition · Horizon - - - - - - - - - - - - - - - - - - - - -{{SITE_NAV}} -
-
-

BenchmarksHorizon against Java Edition 26.3

-

Same machine, same world, same flight.

-

We run Horizon and vanilla Minecraft: Java Edition 26.3 one after the other on the same computer: a fresh world from the same seed, the same settings, and the same four flights over a village, a forest, the ocean and a mountain. Every figure comes from the same code for both games. Where Java does better, the tables say so.

- -
-

Measured by us

-

The project's own machines, at render distance 12 (vanilla's default) and 32. VSync off, no frame cap, a 1280x720 window, simulation distance 12, everything else at vanilla's defaults. Each figure is the median over the runs; the frame figures are averaged over the four flights.

-
-{{MACHINES}} -
-
- -
-

Your hardware

-

Pick a graphics card, a processor and, if you know it, your memory. If we or at least three players have measured that pair, you see what was measured; otherwise an estimate from the nearest measured machine, as a range.

-
- - - -
Render distance - - -
-
-

The picker needs JavaScript; the tables above and the method below work without it.

-
- -
-

From players

-

Players who allow benchmark uploads in the launcher's data collection settings share the report of horizon-client --benchmark standard. Results are grouped by graphics card, processor and render distance, and a group shows only once at least 3 different installs are in it, so no one can be picked out. Only medians are published, with how the group's installs split by memory, graphics memory, drive and system in coarse classes (each class only with at least 3 installs too): no install ID, date, driver, exact memory or screen.

-

{{PLAYERS_SOURCE}}

-
-{{PLAYERS}} -
-
- - - -
-

How the estimates work

-
-

An estimate starts from the measured machine closest to the one you picked, then scales its figures with a small table of specifications we wrote ourselves (no benchmark database):

-
    -
  • GPU factor: the geometric mean of the two graphics cards' ratio of FP32 shader throughput (TFLOPS) and of memory bandwidth (GB/s), as their makers state them.
  • -
  • CPU factor: the ratio of the two processors' single-thread scores: top boost clock times a rough factor per chip generation (Zen 4 = 1).
  • -
  • Frame rate: when the measured run split each frame into CPU and GPU time, the slower side is scaled by its factor; otherwise by the geometric mean of both. Whatever the split, the real figure lies between the measured one scaled by the smaller and by the larger factor; we widen that by 15% for the roughness of the table, and show it as the range.
  • -
  • Load times are CPU work (generating, lighting and meshing chunks), scaled by the CPU factor. Memory is not scaled: it follows the world and the settings, not the speed.
  • -
  • Memory size: when players' results say how much memory and graphics memory their machines have, a measured group whose players have neither yours counts as further away, and the estimate says what they had. With your memory picked, it also says when the game's peak use is a large share of it.
  • -
-

Estimates ignore drivers, the graphics API, thermal limits and the operating system, which can matter as much as the chip. Treat them as a rough idea, and run horizon-client --benchmark standard on your own machine for the real figure.

-
-
- The specification table -
{{SPEC_TABLE}}
-
-
- -
-

How we measure

-
-

tools/perf_bench.py starts each game from a fresh world (seed 1234, creative), waits until every chunk around the spawn is loaded and drawn, then for each scene teleports, waits for the chunks, holds for 2 seconds and flies a straight 192-block path in 12 seconds. Every frame is recorded. Vanilla runs as players get it (your own client, the official launcher's Java options, Java 25), driven by a small development-only mod that only calls the game's own code; nothing of Minecraft is shipped. The full method and its caveats are in docs/benchmark.md, and every raw report is in the repository.

-

Measure your own computer with horizon-client --benchmark standard --render-distance 12: it writes a report to the benchmarks folder of the game folder.

-
-
-

Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

-
-
-{{SITE_FOOTER}} - - - diff --git a/website/src/chrome.js b/website/src/chrome.js deleted file mode 100644 index d11eb3370..000000000 --- a/website/src/chrome.js +++ /dev/null @@ -1,90 +0,0 @@ -// What every page with the site's top bar shares: the light and dark switch and the phone menu. -// Used by Home, Releases, Benchmarks and Docs. -const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches; - -// The page follows the system; the toggle picks the other appearance and remembers it. -export function setUpTheme() { - const root = document.documentElement; - const button = document.querySelector(".theme-toggle"); - if (!button) return; - const label = button.querySelector("[data-theme-label]"); - const system = matchMedia("(prefers-color-scheme: dark)"); - const dark = () => (root.dataset.theme ? root.dataset.theme === "dark" : system.matches); - const show = () => (label.textContent = dark() ? "Light" : "Dark"); - button.addEventListener("click", () => { - root.dataset.theme = dark() ? "light" : "dark"; - try { - localStorage.setItem("theme", root.dataset.theme); - } catch {} - show(); - }); - system.addEventListener("change", show); - show(); -} - -// The phone menu: a full-screen sheet; the page behind it is inert while it is open. -export function setUpMenu() { - const bar = document.querySelector(".nav"); - const button = document.querySelector(".menu-button"); - const menu = document.getElementById("menu"); - const content = document.querySelector("[data-menu-content]") || document.getElementById("main"); - if (!bar || !button || !menu) return; - const label = button.querySelector(".menu-label"); - const items = [...menu.querySelectorAll("nav a")]; - items.forEach((a, i) => a.style.setProperty("transition-delay", `${60 + i * 35}ms`)); - let closing; - const setOpen = (open) => { - clearTimeout(closing); - button.setAttribute("aria-expanded", String(open)); - label.textContent = open ? "Close" : "Menu"; - bar.classList.toggle("is-menu", open); - content.inert = open; - document.body.style.overflow = open ? "hidden" : ""; - if (open) { - menu.hidden = false; - requestAnimationFrame(() => requestAnimationFrame(() => menu.classList.add("is-open"))); - items[0].focus({ preventScroll: true }); - } else { - menu.classList.remove("is-open"); - closing = setTimeout(() => (menu.hidden = true), reducedMotion ? 0 : 320); - } - }; - button.addEventListener("click", () => setOpen(button.getAttribute("aria-expanded") !== "true")); - items.forEach((a) => a.addEventListener("click", () => setOpen(false))); - addEventListener("keydown", (e) => { - if (e.key === "Escape" && button.getAttribute("aria-expanded") === "true") { - setOpen(false); - button.focus(); - } - }); - matchMedia("(min-width: 1280px)").addEventListener("change", (e) => e.matches && setOpen(false)); -} - -// GitHub answers, cached for ten minutes in the tab. -export async function cached(key, load) { - try { - const hit = JSON.parse(sessionStorage.getItem(key) || "null"); - if (hit && Date.now() - hit.at < 10 * 60 * 1000) return hit.value; - } catch {} - const value = await load(); - try { - sessionStorage.setItem(key, JSON.stringify({ at: Date.now(), value })); - } catch {} - return value; -} - -export async function get(url, as = "json") { - const res = await fetch(url, { headers: as === "json" ? { Accept: "application/vnd.github+json" } : {} }); - if (!res.ok) throw new Error(`${res.status}`); - return as === "json" ? res.json() : res.text(); -} - -export const slim = (r) => ({ - tag_name: r.tag_name, - name: r.name, - published_at: r.published_at, - html_url: r.html_url, - prerelease: r.prerelease, - body: r.body || "", - assets: (r.assets || []).map((a) => ({ name: a.name, browser_download_url: a.browser_download_url, size: a.size })), -}); diff --git a/website/src/contributors.js b/website/src/contributors.js deleted file mode 100644 index 12bce9457..000000000 --- a/website/src/contributors.js +++ /dev/null @@ -1,39 +0,0 @@ -// The contributors: GitHub's list for the repository, without bots, the owner first. Shared by -// build.mjs (baked into the page) and main.js (refreshed from GitHub). -import { escape } from "./markdown.js"; - -const OWNER = "ludovic111"; -const AVATARS = "https://avatars.githubusercontent.com/"; - -// Reduces GitHub's contributor objects to what the page shows; bots (type Bot, or a login -// ending in [bot]) and anything without a login or a profile address are dropped. -export function contributorsFrom(list) { - if (!Array.isArray(list)) return []; - return list - .filter((c) => c && typeof c.login === "string" && c.login && c.type !== "Bot" && !/\[bot\]$/i.test(c.login)) - .map((c) => ({ - login: c.login, - html_url: typeof c.html_url === "string" ? c.html_url : `https://github.com/${c.login}`, - avatar_url: typeof c.avatar_url === "string" ? c.avatar_url : "", - contributions: Number(c.contributions) || 0, - })) - .sort((a, b) => (b.login === OWNER) - (a.login === OWNER) || b.contributions - a.contributions); -} - -// GitHub serves avatars at any size: 96 px is twice what the page draws, for sharp screens. -export function avatar(url) { - if (!url.startsWith(AVATARS)) return ""; - const u = new URL(url); - u.searchParams.set("s", "96"); - return u.href; -} - -export function contributorsHtml(list) { - return list - .map((c) => { - const src = avatar(c.avatar_url); - const count = `${c.contributions.toLocaleString("en-US")} ${c.contributions === 1 ? "commit" : "commits"}`; - return `
  • ${src ? `` : ``}${escape(c.login)}${count}
  • `; - }) - .join(""); -} diff --git a/website/src/docs-page.js b/website/src/docs-page.js deleted file mode 100644 index 99da35187..000000000 --- a/website/src/docs-page.js +++ /dev/null @@ -1,5 +0,0 @@ -// The Docs pages share the site's theme switch and phone menu. -import { setUpMenu, setUpTheme } from "./chrome.js"; - -setUpTheme(); -setUpMenu(); diff --git a/website/src/docs.html b/website/src/docs.html deleted file mode 100644 index 56ba89c09..000000000 --- a/website/src/docs.html +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - {{DOC_TITLE}} · Horizon docs - - - - - - - - - - - - - - - - - - - - -{{SITE_NAV}} - -
    -
    - Docs menu - -
    - - -
    -

    {{DOC_GROUP}}

    -

    {{DOC_TITLE}}

    -

    {{DOC_LEDE}}

    -{{DOC_TOC}} -
    -{{DOC_BODY}} -
    - -

    Edit this page on GitHub · Spotted something wrong? Open an issue or ask on Discord.

    -

    Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

    -
    -
    - - - diff --git a/website/src/estimate.js b/website/src/estimate.js deleted file mode 100644 index ccd053cc0..000000000 --- a/website/src/estimate.js +++ /dev/null @@ -1,110 +0,0 @@ -// Estimates for hardware nobody has measured yet, from the nearest measured machine and the spec table -// (src/hardware.js). The method, which the Benchmarks page explains: -// -// - GPU factor: the geometric mean of the two GPUs' FP32 throughput ratio and memory bandwidth ratio. -// - CPU factor: the ratio of the two CPUs' single-thread scores (boost clock x generation factor). -// - Frames: when the measured run split each frame into CPU and GPU time, the slower of the two is scaled by its -// own factor; otherwise the frame rate is scaled by the geometric mean of both factors. Whatever the split, the -// true figure lies between the measured one scaled by the smaller and by the larger factor, widened by 15% for -// the roughness of the table: that is the range shown. -// - World and chunk load times are CPU work (generation, lighting, meshing): scaled by the CPU factor. -// - Memory is not scaled: it depends on the world and settings, not on speed. -// - Memory size: players' groups say how their installs split by RAM and by the GPU's own memory (breakdowns). A -// base whose players have neither the picked RAM nor the picked GPU's memory class counts as further away, and -// the estimate says what the base's players had, and when the game's peak memory is a large share of the RAM. -import { findCpu, findGpu, ramClass, singleThread, vramClass } from "./hardware.js"; - -const MARGIN = 0.15; - -export function factors(fromGpu, fromCpu, toGpu, toCpu) { - const gpu = Math.sqrt((toGpu.tflops / fromGpu.tflops) * (toGpu.gbps / fromGpu.gbps)); - const cpu = singleThread(toCpu) / singleThread(fromCpu); - return { gpu, cpu }; -} - -const distance = (f) => Math.abs(Math.log(f.gpu)) + Math.abs(Math.log(f.cpu)); -// Added to the distance per memory class (RAM, VRAM) the base's players don't have: about a 20% speed gap. -const MEMORY_MISMATCH = 0.2; - -// The classes a row's installs have in a breakdown, or null when it has none (our own rows, older summaries). -const classesIn = (row, dim) => (row.breakdowns?.[dim]?.length ? row.breakdowns[dim].map((c) => c.class) : null); - -function mismatch(row, gpu, ramGb) { - let d = 0; - const vram = classesIn(row, "vram"); - if (vram && !vram.includes(vramClass(gpu))) d += MEMORY_MISMATCH; - const ram = classesIn(row, "ram"); - if (ram && ramGb && !ram.includes(ramClass(ramGb))) d += MEMORY_MISMATCH; - return d; -} - -// What to say about memory: the base's players' RAM and VRAM when they differ from the pick, and the game's peak -// memory against the picked RAM. -export function memoryNotes(row, gpu, ramGb) { - const notes = []; - const list = (dim) => row.breakdowns[dim].map((c) => `${c.class} (${c.installs})`).join(", "); - const vram = classesIn(row, "vram"); - if (vram && gpu && !vram.includes(vramClass(gpu))) notes.push(`The measured players' graphics cards have ${list("vram")} of their own memory; this one has ${gpu.vram_gb ? `${gpu.vram_gb} GB` : "none (it shares the system's)"}.`); - const ram = classesIn(row, "ram"); - if (ram && ramGb && !ram.includes(ramClass(ramGb))) notes.push(`The measured players have ${list("ram")} of memory, not ${ramGb} GB.`); - const peak = row.medians?.rss_peak_mb; - if (ramGb && peak && peak / 1024 > ramGb * 0.4) - notes.push(`${row.game === "vanilla" ? "Java" : "Horizon"} used up to ${(peak / 1024).toFixed(1)} GB here: with ${ramGb} GB, close other programs, or the system may swap and stutter.`); - return notes; -} - -// The rows (benchmarks.json groups) usable as a base: a known GPU and CPU. -function known(rows) { - return rows.map((row) => ({ row, gpu: findGpu(row.gpu), cpu: findCpu(row.cpu) })).filter((r) => r.gpu && r.cpu); -} - -// The measured row for exactly this GPU and CPU, players' first when there are some (more installs), or null. -export function measured(rows, gpu, cpu, rd, game) { - const hits = known(rows).filter((r) => r.gpu === gpu && r.cpu === cpu && r.row.render_distance === rd && r.row.game === game); - hits.sort((a, b) => (b.row.installs || 0) - (a.row.installs || 0)); - return hits.map((r) => r.row); -} - -// The nearest measured machine for a target GPU and CPU, for one game and render distance. -export function nearest(rows, gpu, cpu, rd, game, { ramGb } = {}) { - let best = null; - for (const r of known(rows)) { - if (r.row.render_distance !== rd || r.row.game !== game) continue; - const f = factors(r.gpu, r.cpu, gpu, cpu); - const d = distance(f) + mismatch(r.row, gpu, ramGb); - if (!best || d < best.d) best = { ...r, f, d }; - } - return best; -} - -export function estimate(rows, gpu, cpu, rd, game, { ramGb } = {}) { - const base = nearest(rows, gpu, cpu, rd, game, { ramGb }); - if (!base) return null; - const m = base.row.medians; - const { gpu: g, cpu: c } = base.f; - const lo = Math.min(g, c) * (1 - MARGIN); - const hi = Math.max(g, c) * (1 + MARGIN); - let scale = Math.sqrt(g * c); - if (m.cpu_p50_ms && m.gpu_p50_ms) { - const worst = Math.max(m.cpu_p50_ms, m.gpu_p50_ms); - scale = worst / Math.max(m.cpu_p50_ms / c, m.gpu_p50_ms / g); - } - scale = Math.min(hi, Math.max(lo, scale)); - const fps = (x) => (x == null ? null : { value: x * scale, low: x * lo, high: x * hi }); - // A base held to its display's refresh rate gives only a floor for the average. - const avg = fps(m.avg_fps); - if (avg && base.row.capped_fps && m.avg_fps >= base.row.capped_fps * 0.97) Object.assign(avg, { value: null, high: null, atLeast: true }); - const time = (x, f) => (x == null ? null : { value: x / f, low: x / (f * (1 + MARGIN)), high: x / (f * (1 - MARGIN)) }); - return { - base: base.row, - factors: base.f, - avg_fps: avg, - low_1pct_fps: fps(m.low_1pct_fps), - p95_ms: m.p95_ms == null ? null : { value: m.p95_ms / scale, low: m.p95_ms / hi, high: m.p95_ms / lo }, - world_ms: time(m.world_ms, c), - chunk_load_ms: time(m.chunk_load_ms, c), - rss_steady_mb: m.rss_steady_mb == null ? null : { value: m.rss_steady_mb }, - rss_peak_mb: m.rss_peak_mb == null ? null : { value: m.rss_peak_mb }, - notes: memoryNotes(base.row, gpu, ramGb), - }; -} diff --git a/website/src/estimate.test.mjs b/website/src/estimate.test.mjs deleted file mode 100644 index d46f9c4b5..000000000 --- a/website/src/estimate.test.mjs +++ /dev/null @@ -1,101 +0,0 @@ -// node --test website/src/ (npm test in website/) -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { estimate, factors, measured, nearest } from "./estimate.js"; -import { CPUS, GPUS, findCpu, findGpu } from "./hardware.js"; - -const row = (gpu, cpu, medians, extra = {}) => ({ gpu, cpu, render_distance: 12, game: "horizon", source: "us", medians, ...extra }); -const mac = row("Apple M4 Pro", "Apple M4 Pro", { avg_fps: 500, low_1pct_fps: 100, p95_ms: 3, world_ms: 4000, chunk_load_ms: 1000, rss_peak_mb: 1500, rss_steady_mb: 1200 }); -const laptop = row("Mesa Intel HD Graphics 620 (KBL GT2)", "Intel Core i7-7500U CPU @ 2.70GHz", { avg_fps: 100, low_1pct_fps: 20, p95_ms: 15, world_ms: 12000, chunk_load_ms: 5000, rss_peak_mb: 1400, rss_steady_mb: 1100, cpu_p50_ms: 4, gpu_p50_ms: 9 }); - -test("every reported name of our machines is in the table", () => { - assert.equal(findGpu("Apple M4 Pro").name, "Apple M4 Pro (20-core GPU)"); - assert.equal(findGpu("Mesa Intel HD Graphics 620 (KBL GT2)").name, "Intel HD Graphics 620"); - assert.equal(findGpu("NVIDIA GeForce RTX 4080").name, "NVIDIA GeForce RTX 4080"); - assert.equal(findGpu("NVIDIA GeForce RTX 4080 SUPER"), null); - assert.equal(findCpu("13th Gen Intel Core i7-13700KF").name, "Intel Core i7-13700K / KF"); - assert.equal(findCpu("Intel Core i7-7500U CPU @ 2.70GHz").name, "Intel Core i7-7500U"); - for (const g of GPUS) assert.equal(findGpu(g.name), g, g.name); - for (const c of CPUS) assert.equal(findCpu(c.name), c, c.name); -}); - -test("an exact match is a measurement, not an estimate", () => { - assert.deepEqual(measured([mac, laptop], findGpu("Apple M4 Pro"), findCpu("Apple M4 Pro"), 12, "horizon"), [mac]); - assert.deepEqual(measured([mac], findGpu("Apple M4 Pro"), findCpu("Apple M4 Pro"), 32, "horizon"), []); -}); - -test("the nearest machine is the base, and the range holds the estimate", () => { - const gpu = findGpu("Intel Iris Xe Graphics (96 EU)"); - const cpu = findCpu("Intel Core i5-1135G7"); - assert.equal(nearest([mac, laptop], gpu, cpu, 12, "horizon").row, laptop); - const e = estimate([mac, laptop], gpu, cpu, 12, "horizon"); - const f = factors(findGpu(laptop.gpu), findCpu(laptop.cpu), gpu, cpu); - assert.ok(f.gpu > 1 && f.cpu > 1); - for (const key of ["avg_fps", "low_1pct_fps", "p95_ms", "world_ms", "chunk_load_ms"]) { - const { value, low, high } = e[key]; - assert.ok(low <= value && value <= high, key); - } - // GPU-bound frames (9 ms GPU, 4 ms CPU) follow the GPU factor. - assert.ok(Math.abs(e.avg_fps.value - 100 * Math.min(f.gpu, 9 / (4 / f.cpu))) < 1e-9); - assert.ok(Math.abs(e.world_ms.value - 12000 / f.cpu) < 1e-9); - assert.equal(e.rss_steady_mb.value, 1100); -}); - -test("no base, no estimate", () => { - assert.equal(estimate([mac], findGpu("Apple M4"), findCpu("Apple M4"), 32, "horizon"), null); - assert.equal(estimate([mac], findGpu("Apple M4"), findCpu("Apple M4"), 12, "vanilla"), null); -}); - -test("a base held to its display's refresh rate gives only a floor for the average", () => { - const held = { ...mac, capped_fps: 144, medians: { ...mac.medians, avg_fps: 144 } }; - const e = estimate([held], findGpu("NVIDIA GeForce RTX 4060"), findCpu("AMD Ryzen 5 5600X"), 12, "horizon"); - assert.equal(e.avg_fps.atLeast, true); - assert.equal(e.avg_fps.high, null); - assert.ok(e.avg_fps.low > 0); - // The lows sit under the cap: still a range. - assert.ok(e.low_1pct_fps.high > e.low_1pct_fps.low); -}); - -test("a release title of issue numbers falls back to its notes", async () => { - const { parts } = await import("./releases.js"); - const r = { tag_name: "v2026.10.22.07", name: "Horizon 2026.10.22.07: #1255, mob pushes, fix, #1222", body: "### Fixed\n- Fix #1222: single player runs in the frame again (#1257, fixes #1222)\n- Mob pushes: one list per mob (#1205)\n" }; - assert.equal(parts(r).line, "Single player runs in the frame again and 1 more"); - assert.equal(parts({ ...r, name: "Horizon 2026.10.22.05: Hoppers, mob tick, server tick" }).line, "Hoppers, mob tick, server tick"); -}); - -test("players' memory classes steer the base and the notes", async () => { - const { memoryNotes } = await import("./estimate.js"); - const { ramClass, vramClass } = await import("./hardware.js"); - assert.equal(vramClass(findGpu("NVIDIA GeForce RTX 4080")), "16 GB"); - assert.equal(vramClass(findGpu("NVIDIA GeForce RTX 3080")), "12 GB"); - assert.equal(vramClass(findGpu("Apple M4 Pro")), "shared"); - assert.equal(ramClass(16), "16 GB"); - // Two equally near groups: the one whose players have the picked GPU's memory class wins. - const players = (vram, ram, fps) => - row("NVIDIA GeForce RTX 4070", "AMD Ryzen 5 7600X", { avg_fps: fps, rss_peak_mb: 3600 }, { source: "players", installs: 3, breakdowns: { vram: [{ class: vram, installs: 3 }], ram: [{ class: ram, installs: 3 }] } }); - const a = players("8 GB", "16 GB", 400); - const b = { ...players("12 GB", "32 GB", 500), cpu: "AMD Ryzen 7 7800X3D" }; - const gpu = findGpu("NVIDIA GeForce RTX 4070 Ti"); - const cpu = findCpu("AMD Ryzen 5 7600X"); - assert.equal(nearest([a, b], gpu, cpu, 12, "horizon").row, b, "12 GB like the 4070 Ti, though the CPU differs"); - assert.equal(nearest([a, b], gpu, cpu, 12, "horizon", { ramGb: 16 }).row, a, "both classes count"); - assert.deepEqual(memoryNotes(b, gpu, 32), []); - const notes = memoryNotes(a, gpu, 8); - assert.equal(notes.length, 3); - assert.match(notes[0], /8 GB \(3\) of their own memory; this one has 12 GB/); - assert.match(notes[1], /16 GB \(3\) of memory, not 8 GB/); - assert.match(notes[2], /Horizon used up to 3\.5 GB/); - // Our own rows have no breakdowns: only the peak memory note. - assert.deepEqual(memoryNotes(mac, gpu, 32), []); - assert.equal(estimate([a], gpu, cpu, 12, "horizon", { ramGb: 8 }).notes.length, 3); -}); - -test("breakdowns read as words, and the hardware table shows only with data", async () => { - const { breakdownLine, hardwareHtml } = await import("./bench.js"); - assert.equal(breakdownLine({ ram: [{ class: "32 GB", installs: 3 }], storage: [{ class: "nvme", installs: 4 }], gpu_kind: [{ class: "discrete", installs: 3 }] }), "32 GB RAM (3) · NVMe (4) · separate GPU (3)"); - assert.equal(breakdownLine(undefined), ""); - assert.equal(hardwareHtml({ breakdowns: {} }), ""); - const html = hardwareHtml({ breakdowns: { os: [{ class: "linux", installs: 5, sessions: 9, hours: 4.5, p50_ms: 6.2, p99_ms: 14 }] } }); - assert.match(html, /Linux/); - assert.match(html, /6\.2 ms/); -}); diff --git a/website/src/hardware.js b/website/src/hardware.js deleted file mode 100644 index bf4c8bbbd..000000000 --- a/website/src/hardware.js +++ /dev/null @@ -1,88 +0,0 @@ -// The hardware the Benchmarks page can estimate for, from specifications only (our own table, no benchmark -// database): each GPU's FP32 shader throughput in TFLOPS and its memory bandwidth in GB/s as its maker states them, -// its own memory in GB (vram_gb; 0 for a GPU that shares the system's: integrated, Apple silicon), -// and each CPU's single-thread score = its top boost clock (GHz) x our rough per-generation factor (instructions per -// clock, Zen 4 = 1). The factors are round numbers, so estimates are ranges, and the page says so. -// `match` finds a reported name (the GPU and CPU strings in benchmark reports) in this table. - -export const GPUS = [ - { name: "NVIDIA GeForce RTX 4090", tflops: 82.6, gbps: 1008, vram_gb: 24, match: /RTX 4090/i }, - { name: "NVIDIA GeForce RTX 4080", tflops: 48.7, gbps: 717, vram_gb: 16, match: /RTX 4080(?! SUPER)/i }, - { name: "NVIDIA GeForce RTX 4070 Ti", tflops: 40.1, gbps: 504, vram_gb: 12, match: /RTX 4070 Ti/i }, - { name: "NVIDIA GeForce RTX 4070", tflops: 29.1, gbps: 504, vram_gb: 12, match: /RTX 4070(?! Ti)/i }, - { name: "NVIDIA GeForce RTX 4060 Ti", tflops: 22.1, gbps: 288, vram_gb: 8, match: /RTX 4060 Ti/i }, - { name: "NVIDIA GeForce RTX 4060", tflops: 15.1, gbps: 272, vram_gb: 8, match: /RTX 4060(?! Ti)/i }, - { name: "NVIDIA GeForce RTX 3080", tflops: 29.8, gbps: 760, vram_gb: 10, match: /RTX 3080(?! Ti)/i }, - { name: "NVIDIA GeForce RTX 3070", tflops: 20.3, gbps: 448, vram_gb: 8, match: /RTX 3070(?! Ti)/i }, - { name: "NVIDIA GeForce RTX 3060", tflops: 12.7, gbps: 360, vram_gb: 12, match: /RTX 3060(?! Ti)/i }, - { name: "NVIDIA GeForce RTX 3050", tflops: 9.1, gbps: 224, vram_gb: 8, match: /RTX 3050/i }, - { name: "NVIDIA GeForce RTX 2060", tflops: 6.5, gbps: 336, vram_gb: 6, match: /RTX 2060(?! SUPER)/i }, - { name: "NVIDIA GeForce GTX 1660 SUPER", tflops: 5.0, gbps: 336, vram_gb: 6, match: /GTX 1660 SUPER/i }, - { name: "NVIDIA GeForce GTX 1060 6GB", tflops: 4.4, gbps: 192, vram_gb: 6, match: /GTX 1060/i }, - { name: "NVIDIA GeForce GTX 1050 Ti", tflops: 2.1, gbps: 112, vram_gb: 4, match: /GTX 1050 Ti/i }, - { name: "AMD Radeon RX 7900 XTX", tflops: 61.4, gbps: 960, vram_gb: 24, match: /RX 7900 XTX/i }, - { name: "AMD Radeon RX 7800 XT", tflops: 37.3, gbps: 624, vram_gb: 16, match: /RX 7800 XT/i }, - { name: "AMD Radeon RX 7600", tflops: 21.8, gbps: 288, vram_gb: 8, match: /RX 7600(?! XT)/i }, - { name: "AMD Radeon RX 6700 XT", tflops: 13.2, gbps: 384, vram_gb: 12, match: /RX 6700 XT/i }, - { name: "AMD Radeon RX 6600", tflops: 8.9, gbps: 224, vram_gb: 8, match: /RX 6600(?! XT)/i }, - { name: "AMD Radeon RX 580", tflops: 6.2, gbps: 256, vram_gb: 8, match: /RX 580/i }, - { name: "AMD Radeon 780M (integrated)", tflops: 8.6, gbps: 89, vram_gb: 0, match: /780M/i }, - { name: "Steam Deck (AMD Van Gogh)", tflops: 1.6, gbps: 88, vram_gb: 0, match: /VanGogh|Van Gogh|Custom GPU 0405/i }, - { name: "Intel Arc A770", tflops: 19.7, gbps: 560, vram_gb: 16, match: /Arc.*A770/i }, - { name: "Intel Iris Xe Graphics (96 EU)", tflops: 2.1, gbps: 68, vram_gb: 0, match: /Iris\(?R?\)? Xe/i }, - { name: "Intel HD Graphics 620", tflops: 0.4, gbps: 34, vram_gb: 0, match: /\bU?HD Graphics 620\b/i }, - { name: "Apple M1", tflops: 2.6, gbps: 68, vram_gb: 0, match: /^Apple M1$/i }, - { name: "Apple M2", tflops: 3.6, gbps: 100, vram_gb: 0, match: /^Apple M2$/i }, - { name: "Apple M3", tflops: 4.1, gbps: 100, vram_gb: 0, match: /^Apple M3$/i }, - { name: "Apple M4", tflops: 4.3, gbps: 120, vram_gb: 0, match: /^Apple M4$/i }, - { name: "Apple M1 Pro (16-core GPU)", tflops: 5.2, gbps: 200, vram_gb: 0, match: /^Apple M1 Pro$/i }, - { name: "Apple M4 Pro (20-core GPU)", tflops: 8.5, gbps: 273, vram_gb: 0, match: /^Apple M4 Pro$/i }, - { name: "Apple M4 Max (40-core GPU)", tflops: 17.0, gbps: 546, vram_gb: 0, match: /^Apple M4 Max$/i }, -]; - -// ghz: top single-core boost clock; ipc: our per-generation factor (Zen 4 = 1). -export const CPUS = [ - { name: "Intel Core i7-7500U", ghz: 3.5, ipc: 0.62, match: /i7-7500U/i }, - { name: "Intel Core i5-7200U", ghz: 3.1, ipc: 0.62, match: /i5-7200U/i }, - { name: "Intel Core i5-8250U", ghz: 3.4, ipc: 0.62, match: /i5-8250U/i }, - { name: "Intel Core i5-9400F", ghz: 4.1, ipc: 0.62, match: /i5-9400/i }, - { name: "Intel Core i7-9700K", ghz: 4.9, ipc: 0.62, match: /i7-9700K/i }, - { name: "Intel Core i5-10400", ghz: 4.3, ipc: 0.62, match: /i5-10400/i }, - { name: "Intel Core i5-1135G7", ghz: 4.2, ipc: 0.78, match: /i5-1135G7/i }, - { name: "Intel Core i5-12400", ghz: 4.4, ipc: 0.95, match: /i5-12400/i }, - { name: "Intel Core i5-13600K", ghz: 5.1, ipc: 0.95, match: /i5-13600K/i }, - { name: "Intel Core i7-13700K / KF", ghz: 5.4, ipc: 0.95, match: /i7-13700K/i }, - { name: "Intel Core i9-14900K", ghz: 6.0, ipc: 0.95, match: /i9-14900K/i }, - { name: "AMD Ryzen 5 3600", ghz: 4.2, ipc: 0.72, match: /Ryzen 5 3600/i }, - { name: "AMD Ryzen 5 5600X", ghz: 4.6, ipc: 0.88, match: /Ryzen 5 5600X?\b/i }, - { name: "AMD Ryzen 7 5800X3D", ghz: 4.5, ipc: 0.88, match: /5800X3D/i }, - { name: "AMD Ryzen 5 7600X", ghz: 5.3, ipc: 1.0, match: /Ryzen 5 7600/i }, - { name: "AMD Ryzen 7 7800X3D", ghz: 5.0, ipc: 1.0, match: /7800X3D/i }, - { name: "AMD Ryzen 9 7950X", ghz: 5.7, ipc: 1.0, match: /Ryzen 9 7950X(?!3D)/i }, - { name: "AMD Ryzen 7 9700X", ghz: 5.5, ipc: 1.12, match: /Ryzen 7 9700X/i }, - { name: "AMD Ryzen 7 7840U / HS", ghz: 5.1, ipc: 1.0, match: /7840(U|HS)/i }, - { name: "Steam Deck (AMD Zen 2, 4 cores)", ghz: 3.5, ipc: 0.72, match: /AMD Custom APU 0405|Van ?Gogh/i }, - { name: "Apple M1", ghz: 3.2, ipc: 1.25, match: /^Apple M1$/i }, - { name: "Apple M2", ghz: 3.5, ipc: 1.28, match: /^Apple M2$/i }, - { name: "Apple M3", ghz: 4.05, ipc: 1.38, match: /^Apple M3$/i }, - { name: "Apple M4", ghz: 4.4, ipc: 1.5, match: /^Apple M4$/i }, - { name: "Apple M4 Pro", ghz: 4.5, ipc: 1.5, match: /^Apple M4 Pro$/i }, -]; - -export const singleThread = (cpu) => cpu.ghz * cpu.ipc; -export const findGpu = (name) => GPUS.find((g) => g.name === name || g.match.test(name || "")) || null; -export const findCpu = (name) => CPUS.find((c) => c.name === name || c.match.test(name || "")) || null; - -// The telemetry server's hardware classes (crates/horizon-telemetry-server/src/classes.rs), which players' -// results are broken down by: memory and a GPU's own memory in coarse steps. -export function ramClass(gb) { - if (!(gb > 0)) return null; - return gb <= 5 ? "4 GB or less" : gb <= 10 ? "8 GB" : gb <= 20 ? "16 GB" : gb <= 40 ? "32 GB" : "64 GB or more"; -} -export function vramClass(gpu) { - if (!gpu) return null; - if (!gpu.vram_gb) return "shared"; - const mb = gpu.vram_gb * 1024; - for (const [max, name] of [[2560, "2 GB or less"], [4608, "4 GB"], [6656, "6 GB"], [8704, "8 GB"], [12800, "12 GB"], [16896, "16 GB"]]) if (mb <= max) return name; - return "more than 16 GB"; -} diff --git a/website/src/hub-page.js b/website/src/hub-page.js deleted file mode 100644 index 9115c5ca4..000000000 --- a/website/src/hub-page.js +++ /dev/null @@ -1,270 +0,0 @@ -// The hub page (/hub): its tabs (one per #hash, so /hub#roadmap and /hub# can be linked), the -// Simple / Technical switch (remembered in localStorage), the area filter, and the live state of every -// linked issue and pull request, refreshed from GitHub's public API. Without JavaScript, every tab reads -// one after the other with what was baked at build time. -import { cached, get, setUpMenu, setUpTheme } from "./chrome.js"; -import { REPO, boardFilterHtml, boardFrom, boardHtml, journalFrom, journalHtml, overviewHtml, roadmapHtml, slimIssue } from "./hub.js"; - -const root = document.documentElement; -const data = JSON.parse(document.getElementById("hub-data").textContent); -const tabs = [...document.querySelectorAll('.hub-tabs [role="tab"]')]; -const pill = document.querySelector(".hub-tabs .tab-pill"); -let area = "all"; - -// --- Tabs ------------------------------------------------------------------------------------------------------ - -const panelOf = (tab) => document.getElementById(tab.getAttribute("aria-controls")); -const place = (tab) => { - pill.style.width = `${tab.offsetWidth}px`; - pill.style.height = `${tab.offsetHeight}px`; - pill.style.transform = `translate(${tab.offsetLeft}px, ${tab.offsetTop}px)`; -}; -function choose(tab, { focus = false, push = false } = {}) { - for (const t of tabs) { - const on = t === tab; - t.setAttribute("aria-selected", String(on)); - t.tabIndex = on ? 0 : -1; - panelOf(t).classList.toggle("is-active", on); - } - place(tab); - if (focus) tab.focus(); - if (push && location.hash !== `#${panelOf(tab).id}`) history.replaceState(null, "", `#${panelOf(tab).id}`); -} -// "#roadmap" opens its tab; "#" or "#help-wanted" opens the tab holding it and scrolls there. -function follow() { - const target = location.hash && document.getElementById(decodeURIComponent(location.hash.slice(1))); - const tab = tabs.find((t) => target && (panelOf(t) === target || panelOf(t).contains(target))) || tabs[0]; - choose(tab); - if (target && target !== panelOf(tab)) { - if (target.dataset.area && area !== "all" && target.dataset.area !== area) filter("all"); - requestAnimationFrame(() => target.scrollIntoView({ block: "start" })); - } -} -tabs.forEach((tab, i) => { - tab.addEventListener("click", () => choose(tab, { push: true })); - tab.addEventListener("keydown", (e) => { - const step = { ArrowRight: 1, ArrowLeft: -1 }[e.key]; - if (step) choose(tabs[(i + step + tabs.length) % tabs.length], { focus: true, push: true }); - }); -}); -// Links inside the page ("Help wanted", an item of the overview) switch tabs through the hash. -addEventListener("hashchange", follow); -addEventListener("resize", () => place(tabs.find((t) => t.getAttribute("aria-selected") === "true"))); -document.fonts?.ready.then(() => place(tabs.find((t) => t.getAttribute("aria-selected") === "true"))); - -// --- Simple / Technical ---------------------------------------------------------------------------------------- - -const detailButtons = [...document.querySelectorAll("[data-detail]")]; -function detail(mode) { - if (mode === "dev") root.dataset.detail = "dev"; - else delete root.dataset.detail; - detailButtons.forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.detail === mode))); -} -detailButtons.forEach((b) => - b.addEventListener("click", () => { - detail(b.dataset.detail); - try { - localStorage.setItem("hub:detail", b.dataset.detail); - } catch {} - }), -); -detail(root.dataset.detail === "dev" ? "dev" : "plain"); - -// --- Area filter ----------------------------------------------------------------------------------------------- - -const areaButtons = [...document.querySelectorAll("[data-area-filter]")]; -function filter(to) { - area = to; - areaButtons.forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.areaFilter === area))); - for (const section of document.querySelectorAll("[data-roadmap] .hub-section")) { - let shown = 0; - for (const item of section.querySelectorAll(".hub-item")) { - item.hidden = area !== "all" && item.dataset.area !== area; - if (!item.hidden) shown++; - } - section.hidden = shown === 0; - } -} -areaButtons.forEach((b) => b.addEventListener("click", () => filter(b.dataset.areaFilter))); - -// --- The board: a roadmap item's cards, and the long columns' "Show more" ---------------------------------------- - -const boardSelect = document.querySelector("[data-board-item]"); -function showItem() { - const want = boardSelect.value; - for (const card of document.querySelectorAll("[data-board] .hub-card")) { - card.hidden = want === "-" ? !card.dataset.item : want ? card.dataset.item !== want : false; - } - for (const column of document.querySelectorAll("[data-board] .hub-column")) { - column.querySelector("[data-count]").textContent = column.querySelectorAll(".hub-card:not([hidden])").length; - // A filtered column shows all its cards. - column.classList.toggle("is-open", Boolean(want) || column.classList.contains("was-opened")); - } -} -boardSelect?.addEventListener("change", showItem); -document.querySelector("[data-board]")?.addEventListener("click", (e) => { - const button = e.target.closest("[data-more-button]"); - if (!button) return; - button.closest(".hub-column").classList.add("is-open", "was-opened"); - button.remove(); -}); - -// --- Live state from GitHub ------------------------------------------------------------------------------------ - -// The open issues and pull requests, and those closed or merged lately: four requests at most, kept ten minutes. -async function loadLive() { - const list = []; - for (let page = 1; page <= 3; page++) { - const batch = await get(`https://api.github.com/repos/${REPO}/issues?state=open&per_page=100&page=${page}`); - list.push(...batch.map(slimIssue)); - if (batch.length < 100) break; - } - const closed = await get(`https://api.github.com/repos/${REPO}/issues?state=closed&sort=updated&direction=desc&per_page=100`); - return list.concat(closed.map(slimIssue)); -} -const loadReleases = () => get(`https://api.github.com/repos/${REPO}/releases?per_page=40`); - -async function refresh() { - const fresh = await cached("horizon:hub-live", loadLive).catch(() => null); - if (!fresh) return; - // What the build knew about older links stays; GitHub's answer wins for the rest. - const live = new Map([...data.live, ...fresh].map((i) => [i.n, i])); - document.querySelector("[data-overview]").innerHTML = overviewHtml(data.roadmap, live); - document.querySelector("[data-roadmap]").innerHTML = roadmapHtml(data.roadmap, live); - filter(area); - showVotes(); - const board = boardFrom(fresh, data.roadmap); - const chosen = boardSelect.value; - boardSelect.innerHTML = boardFilterHtml(board, data.roadmap); - boardSelect.value = [...boardSelect.options].some((o) => o.value === chosen) ? chosen : ""; - document.querySelector("[data-board]").innerHTML = boardHtml(board, data.roadmap); - showItem(); - const releases = await cached("horizon:hub-releases", loadReleases).catch(() => null); - if (releases) document.querySelector("[data-journal]").innerHTML = journalHtml(journalFrom(releases, fresh, data.roadmap), data.roadmap); - const note = document.querySelector("[data-live-note]"); - if (note) note.textContent = "Pull request and issue states are live from GitHub."; -} - -// --- Votes, bug reports and suggestions: the hub's server (crates/horizon-telemetry-server) -------------------- - -const saved = (key, fallback) => { - try { - return JSON.parse(localStorage.getItem(key)) ?? fallback; - } catch { - return fallback; - } -}; -const save = (key, value) => { - try { - localStorage.setItem(key, JSON.stringify(value)); - } catch {} -}; -const post = (path, body) => fetch(`${data.api}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); - -// This browser's random id (one vote per item per browser) and the items it voted for. Nothing else identifies it. -function voter() { - let id = saved("hub:voter", ""); - if (typeof id !== "string" || id.length < 16) { - id = crypto.randomUUID ? crypto.randomUUID() : [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, "0")).join(""); - save("hub:voter", id); - } - return id; -} -const mine = new Set(saved("hub:voted", [])); -let counts = null; // { item: votes } once the server answered; until then the buttons stay hidden - -function showVotes() { - if (!counts) return; - for (const button of document.querySelectorAll("[data-vote]")) { - const id = button.dataset.vote; - button.hidden = false; - button.setAttribute("aria-pressed", String(mine.has(id))); - button.querySelector(".hub-vote-label").textContent = mine.has(id) ? "Wanted" : "Want it"; - button.querySelector("[data-votes]").textContent = counts[id] ? String(counts[id]) : ""; - } -} - -async function vote(id) { - const up = !mine.has(id); - const apply = (on, step) => { - if (on) mine.add(id); - else mine.delete(id); - counts[id] = Math.max(0, (counts[id] || 0) + step); - save("hub:voted", [...mine]); - showVotes(); - }; - apply(up, up ? 1 : -1); - try { - const res = await post("/hub/vote", { item: id, voter: voter(), up }); - if (!res.ok) throw new Error(res.status); - counts[id] = (await res.json()).votes; - showVotes(); - } catch { - apply(!up, up ? -1 : 1); - } -} -document.addEventListener("click", (e) => { - const button = e.target.closest("[data-vote]"); - if (button && counts) vote(button.dataset.vote); -}); - -const LABELS = { title: "the title", did: "what you did", happened: "what happened", expected: "what you expected", version: "the version", system: "OS, CPU, GPU", text: "your idea", name: "your name" }; -// The server's answer in words: "did: 3 to 2000 characters" becomes "Check what you did: 3 to 2000 characters." -function trouble(code, answer) { - if (code === 429) return "Too many sent from your connection: try again in a few minutes."; - const said = typeof answer.error === "string" ? answer.error : ""; - const field = said.match(/^(\w+): (.+)$/); - if (code === 400 && field) return `Check ${LABELS[field[1]] || field[1]}: ${field[2]}.`; - return said ? `${said[0].toUpperCase()}${said.slice(1)}.` : "That didn't go through: try again in a moment."; -} - -function setUpForm(form, path, thanks) { - const status = form.querySelector("[data-status]"); - form.hidden = false; - form.parentElement.querySelector("[data-closed]").hidden = true; - form.addEventListener("submit", async (e) => { - e.preventDefault(); - if (!form.reportValidity()) return; - const button = form.querySelector('[type="submit"]'); - button.disabled = true; - status.textContent = "Sending…"; - try { - const res = await post(path, Object.fromEntries(new FormData(form))); - const answer = await res.json().catch(() => ({})); - if (res.ok) { - thanks(status, answer); - // A new report starts with the version filled in again; the name stays for the next one. - for (const field of form.querySelectorAll("textarea, input:not([name='version']):not([name='name'])")) field.value = ""; - } else status.textContent = trouble(res.status, answer); - } catch { - status.textContent = "Couldn't reach the server: try again, or use GitHub or Discord."; - } - button.disabled = false; - }); -} - -// The forms and the votes show once the server answers; without it the page points to GitHub and Discord. -async function connect() { - try { - // Revalidated: the server keeps the counts a minute, a browser's copy would miss this browser's own vote. - const res = await fetch(`${data.api}/hub/votes`, { cache: "no-cache" }); - if (!res.ok) return; - counts = (await res.json()).votes || {}; - } catch { - return; - } - showVotes(); - setUpForm(document.querySelector('[data-form="report"]'), "/hub/report", (status, answer) => { - const issue = typeof answer.issue === "string" && answer.issue.match(/^https:\/\/github\.com\/ludovic111\/horizon\/issues\/(\d+)$/); - status.innerHTML = issue ? `Thanks! It's issue #${issue[1]} on GitHub: follow it there.` : "Thanks! It will be on GitHub in a few minutes."; - }); - setUpForm(document.querySelector('[data-form="suggest"]'), "/hub/suggest", (status) => { - status.textContent = "Thanks! The maintainers read every suggestion."; - }); -} - -setUpTheme(); -setUpMenu(); -connect(); -follow(); -refresh().then(() => data.roadmap.items.some((i) => `#${i.id}` === location.hash) && follow()); diff --git a/website/src/hub.html b/website/src/hub.html deleted file mode 100644 index 167ffc15e..000000000 --- a/website/src/hub.html +++ /dev/null @@ -1,170 +0,0 @@ - - - - - - Hub · Horizon - - - - - - - - - - - - - - - - - - - - - -{{SITE_NAV}} -
    -
    -

    HubNow, next and how to help

    -

    Where Horizon is going

    -

    What is being done, what comes next, what shipped and where you can help. No dates: things are Now, Next or Later. Read it in plain words, or switch to the technical picture.

    -
    -
    - - - - - - -
    -
    - - -
    -
    - -
    -{{HUB_OVERVIEW}} -
    - -
    -
    -{{HUB_AREAS}} -
    -
    -{{HUB_ROADMAP}} -
    -

    The roadmap lives in the repository: ROADMAP.md, generated from roadmap/roadmap.toml. Pull requests carry the roadmap:<id> label of their item.

    -
    - -
    -
    -

    Every open issue and pull request, placed by its state on GitHub, as on Kira's work board in Discord.

    - -
    -
    -{{HUB_BOARD}} -
    -
    - -
    -

    Every release with what it changed, grouped by roadmap item in Technical, and a summary of each week. Also as journal.json.

    -
    -{{HUB_JOURNAL}} -
    -
    - -
    -
    -

    Good first tasks

    -

    Each one is a small difference from vanilla, with an issue that says how to see it.

    -

    Each links its issue; the technical text says where in the code and in vanilla to start.

    -
      {{HUB_HELP_WANTED}}
    -
    -
    -

    Ways to help

    -
    -
    -

    Tell us what differs

    -

    Something that doesn't play like vanilla is a bug. Say what you did, what happened and what vanilla does, with your Horizon version and system.

    -

    Report a bugSuggest something

    -
    -
    -

    Take a task

    -

    Pick a good first task or an open issue. On Discord, /claim 1234 tells everyone you are on issue 1234, so nobody starts the same work; /unclaim frees it.

    -

    Open issues

    -
    -
    -

    Bring your AI agent

    -

    On Discord, /agent connect gives your coding agent a personal token for Kira's MCP server: it reads the work board, claims tasks and posts its progress in your name.

    -

    Join the Discord

    -
    -
    -

    Benchmark your computer

    -

    Run the built-in benchmark and share the report: every new machine makes the performance work more accurate. No coding needed.

    -

    How to

    -
    -
    -
    -
    -

    Report a bug

    -

    One bug per report: something that breaks, or doesn't play like vanilla. It becomes an issue on GitHub, public, and you get its link to follow it. Search the open bugs first.

    - -

    Report it on GitHub or in #horizon-bugs on Discord, where Kira turns your post into an issue.

    -
    -
    -

    Suggest something

    -

    An idea for Horizon, or about something on the roadmap. The maintainers read every one, and the good ones become roadmap items. Nothing you send here is published.

    - -

    Post it in #horizon-ideas on Discord, or send it to Kira with /suggest.

    -
    -
    -

    The rules

    -
      -
    1. Vanilla is the specification. Wherever Minecraft 26.3 has the feature, Horizon does exactly what it does: read vanilla's code, then match it.
    2. -
    3. Small pull requests, proven. One change each, under about 500 lines, with the block python3 tools/pr_ready.py prints: formatting, Clippy, tests and the harnesses your change can affect.
    4. -
    5. Say who wrote it. If an AI agent wrote or posts it, the pull request says so, and commits keep its co-author line.
    6. -
    7. Never commit Mojang's files. No game jars, assets, decompiled code or prepared resources, and nothing taken from other mods' code.
    8. -
    -

    The contributing guideCONTRIBUTING.md

    -
    -
    -

    Contributors

    -

    Everyone with commits in Horizon. On Discord, /link-github <your login> credit:True adds your Discord name next to yours.

    -
      {{HUB_CREDIT}}
    -

    All contributors on GitHub

    -
    -
    -

    Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

    -
    -
    -{{SITE_FOOTER}} - - - diff --git a/website/src/hub.js b/website/src/hub.js deleted file mode 100644 index f11668d8c..000000000 --- a/website/src/hub.js +++ /dev/null @@ -1,457 +0,0 @@ -// The hub (/hub): the roadmap from website/data/roadmap.json (generated from roadmap/roadmap.toml by -// tools/roadmap.py), with each item's issues and pull requests in their live GitHub state. Shared by build.mjs -// (baked into the page) and hub-page.js (refreshed from GitHub in the browser). Every item says the same thing -// twice: `plain` (.hub-plain) for players and `dev` (.hub-dev) for contributors; the page's Simple / Technical -// switch shows one of them. -import { escape, inline } from "./markdown.js"; -import { parts, plainItem, sections } from "./releases.js"; -import { isGame, isLauncher } from "./versions.js"; -import { avatar } from "./contributors.js"; - -export const REPO = "ludovic111/horizon"; -const issueUrl = (n) => `https://github.com/${REPO}/issues/${n}`; -const fileUrl = (path) => `https://github.com/${REPO}/blob/main/${path}`; - -// The issues a pull request closes when merged: "Fixes #12", "closes #3, resolves #4" (as Kira's board reads them). -export function fixesIn(text) { - const out = new Set(); - for (const m of String(text ?? "").matchAll(/\b(?:fix(?:e[sd])?|close[sd]?|resolve[sd]?)\s*:?\s+((?:#\d+(?:\s*(?:,|and)\s*)?)+)/gi)) { - for (const n of m[1].matchAll(/#(\d+)/g)) out.add(Number(n[1])); - } - return [...out].sort((a, b) => a - b); -} - -// A GitHub issue or pull request (from /issues, which lists both) reduced to what the hub shows. -export function slimIssue(raw) { - const pr = Boolean(raw.pull_request); - const merged = pr && raw.pull_request.merged_at; - return { - n: raw.number, - title: String(raw.title || ""), - kind: pr ? "pr" : "issue", - state: merged ? "merged" : raw.state === "open" ? "open" : raw.state_reason === "not_planned" ? "dropped" : "closed", - draft: Boolean(raw.draft), - user: raw.user?.login || "", - labels: (raw.labels || []).map((l) => (typeof l === "string" ? l : l.name)).filter(Boolean), - assigned: (raw.assignees || []).length > 0, - fixes: pr ? fixesIn(raw.body) : [], - at: merged || raw.closed_at || raw.updated_at || "", - url: raw.html_url || issueUrl(raw.number), - }; -} - -const number = (link) => Number((String(link).match(/^#(\d+)$/) || [])[1]) || null; - -// "#12 in review", "#13 merged": a link's state, when GitHub told us. -function linkState(issue) { - if (!issue) return null; - if (issue.kind === "pr") return issue.state === "open" ? (issue.draft ? "in progress" : "in review") : issue.state; - return issue.state === "open" ? "open" : "closed"; -} - -function linkHtml(link, live) { - const n = number(link); - if (!n) { - const url = link.startsWith("https://") ? link : fileUrl(link); - return `${escape(link.replace(/^https:\/\//, ""))}`; - } - const issue = live.get(n); - const state = linkState(issue); - const label = issue ? `${issue.kind === "pr" ? "Pull request" : "Issue"} #${n}: ${issue.title}` : `#${n}`; - return `#${n}${state ? ` ${state}` : ""}`; -} - -// The technical text with its #N and the item's own paths as links. -function devHtml(item) { - let text = item.dev.replace(/(^|[^\w[/`])#(\d+)\b/g, (_, before, n) => `${before}[#${n}](${issueUrl(n)})`); - for (const link of item.links || []) { - if (!number(link) && !link.startsWith("https://")) text = text.replace(link, `[${link}](${fileUrl(link)})`); - } - return inline(text); -} - -// "2 pull requests in review · 3 merged · 1 issue open", from the item's links. -export function progress(item, live) { - const known = (item.links || []).map(number).filter(Boolean).map((n) => live.get(n)).filter(Boolean); - const pulls = known.filter((i) => i.kind === "pr"); - const count = (list, word) => (list.length ? `${list.length} ${word}` : ""); - const parts = [ - count(pulls.filter((p) => p.state === "open" && !p.draft), pulls.filter((p) => p.state === "open" && !p.draft).length === 1 ? "pull request in review" : "pull requests in review"), - count(pulls.filter((p) => p.state === "open" && p.draft), "in progress"), - count(pulls.filter((p) => p.state === "merged"), "merged"), - count(known.filter((i) => i.kind === "issue" && i.state === "open"), known.filter((i) => i.kind === "issue" && i.state === "open").length === 1 ? "issue open" : "issues open"), - ].filter(Boolean); - return parts.join(" · "); -} - -const areaName = (roadmap, id) => roadmap.areas.find((a) => a.id === id)?.name || id; - -// An item's vote button: hidden until the page has the counts from the hub's server (hub-page.js). -export function voteHtml(item) { - return ``; -} - -export function itemHtml(item, roadmap, live) { - const done = item.status === "shipped"; - const state = done ? "" : progress(item, live); - return `
    -

    ${escape(areaName(roadmap, item.area))}${done ? `${escape(item.shipped_in)}` : ""}${item.ongoing ? `Ongoing` : ""}${done ? "" : voteHtml(item)}

    -

    ${escape(item.title)}

    -

    ${inline(item.plain)}

    -

    ${devHtml(item)}

    - ${state ? `

    ${escape(state)}

    ` : ""} - -
    `; -} - -const SECTION_LEDE = { - now: "Being worked on, with pull requests open or just merged.", - next: "Decided, and up after what is being done now.", - later: "Decided, further out.", - "help-wanted": "Good first contributions: a clear vanilla behaviour, an issue with the steps, a place to start.", - shipped: "Out in a release. The journal has every change.", -}; - -// The Roadmap tab: one section per status, the items in the file's order (areas by priority). -export function roadmapHtml(roadmap, live = new Map()) { - const order = new Map(roadmap.areas.map((a, i) => [a.id, i])); - return roadmap.statuses - .map(({ id, name }) => { - const items = roadmap.items.filter((i) => i.status === id); - if (!items.length) return ""; - // Shipped stays newest first; the others go by the areas' priority. - if (id !== "shipped") items.sort((a, b) => order.get(a.area) - order.get(b.area)); - return `
    -

    ${escape(name)}

    ${escape(SECTION_LEDE[id] || "")}

    -
    -${items.map((item) => itemHtml(item, roadmap, live)).join("\n")} -
    -
    `; - }) - .join("\n"); -} - -// The area filter's buttons: every area that has an item. -export function areaFilterHtml(roadmap) { - const used = roadmap.areas.filter((a) => roadmap.items.some((i) => i.area === a.id)); - return [``] - .concat(used.map((a) => ``)) - .join("\n"); -} - -// The Overview tab: where Horizon is, the 3 to 5 things in focus, what is next, what shipped last, how to help. -export function overviewHtml(roadmap, live = new Map()) { - const o = roadmap.overview; - const focus = roadmap.items.filter((i) => i.focus); - const next = roadmap.items.filter((i) => i.status === "next"); - const shipped = roadmap.items.filter((i) => i.status === "shipped").slice(0, 3); - const row = (item, i, meta) => `
  • ${String(i + 1).padStart(2, "0")}${escape(item.title)}${inline(item.plain)}${inline(item.dev)}${escape(meta(item))}
  • `; - return `
    -

    ${inline(o.today_plain)}

    -

    ${inline(o.today_dev)}

    -
    -
    -

    Being done now

    -
      ${focus.map((item, i) => row(item, i, (x) => progress(x, live))).join("")}
    -
    -
    -

    Next

    -
      ${next.map((item, i) => row(item, i, (x) => areaName(roadmap, x.area))).join("")}
    -
    -
    -

    Recently shipped

    -
      ${shipped.map((item, i) => row(item, i, (x) => `In ${x.shipped_in}`)).join("")}
    -
    -
    -

    How to help

    -

    ${inline(o.help_plain)}

    -

    ${inline(o.help_dev)}

    -

    ContributeHelp wantedReport a bugSuggest something

    -
    `; -} - -// The Contribute tab's list of good first tasks. -export function helpWantedHtml(roadmap) { - return roadmap.items - .filter((i) => i.status === "help-wanted") - .map((item, i) => { - const first = (item.links || []).map(number).find(Boolean); - const href = first ? issueUrl(first) : `#${item.id}`; - return `
  • ${String(i + 1).padStart(2, "0")}${escape(item.title)}${inline(item.plain)}${inline(item.dev)}${first ? `#${first}` : ""}
  • `; - }) - .join(""); -} - -// --- The work board -------------------------------------------------------------------------------------------- - -export const COLUMNS = [ - { id: "todo", name: "To do", about: "Open and free: pick one, and say so with /claim on Discord." }, - { id: "progress", name: "In progress", about: "Claimed, assigned, or a draft pull request." }, - { id: "review", name: "In review", about: "A pull request is ready for review." }, - { id: "done", name: "Done", about: "Closed or merged in the last seven days." }, -]; -const DONE_DAYS = 7; - -// The roadmap item an issue or pull request moves: its roadmap: label, else the item linking it, else (for a -// pull request) the item linking an issue it fixes. -export function itemOf(issue, roadmap) { - const label = issue.labels.find((l) => l.startsWith("roadmap:")); - const ids = new Set(roadmap.items.map((i) => i.id)); - if (label && ids.has(label.slice(8))) return label.slice(8); - const linking = (n) => roadmap.items.find((i) => (i.links || []).includes(`#${n}`))?.id; - return linking(issue.n) || issue.fixes.map(linking).find(Boolean) || null; -} - -// The board from GitHub's open issues and pull requests and those closed lately, placed as Kira's work board places -// them: an issue goes to review when an open, ready pull request fixes it, to progress when a draft one does or it is -// claimed or assigned; a pull request that fixes no open issue is a card of its own. -export function boardFrom(list, roadmap, now = Date.now()) { - const columns = Object.fromEntries(COLUMNS.map((c) => [c.id, []])); - const open = list.filter((i) => i.state === "open"); - const openIssues = new Set(open.filter((i) => i.kind === "issue").map((i) => i.n)); - const fixing = (n) => open.filter((p) => p.kind === "pr" && p.fixes.includes(n)); - const card = (i, prs = []) => ({ n: i.n, kind: i.kind, title: i.title, user: i.user, url: i.url, item: itemOf(i, roadmap) || prs.map((p) => itemOf(p, roadmap)).find(Boolean) || null, prs: prs.map((p) => p.n) }); - for (const i of open) { - if (i.kind === "issue") { - const prs = fixing(i.n); - const claimed = i.assigned || i.labels.some((l) => /^(in progress|claimed)$/i.test(l)); - const column = prs.some((p) => !p.draft) ? "review" : prs.length || claimed ? "progress" : "todo"; - columns[column].push(card(i, prs)); - } else if (!i.fixes.some((n) => openIssues.has(n))) { - columns[i.draft ? "progress" : "review"].push(card(i)); - } - } - const since = now - DONE_DAYS * 864e5; - const seen = new Set(); - for (const i of list) { - if (seen.has(i.n) || !["merged", "closed"].includes(i.state) || !(Date.parse(i.at) >= since)) continue; - seen.add(i.n); - columns.done.push(card(i)); - } - columns.done.sort((a, b) => b.n - a.n); - return columns; -} - -const SHOWN = 20; // cards per column before "Show more" - -function cardHtml(c, roadmap, more) { - const item = c.item && roadmap.items.find((i) => i.id === c.item); - return `
  • ${c.kind === "pr" ? "PR" : "Issue"} #${c.n}${c.prs.length ? ` · ${c.prs.map((n) => `PR #${n}`).join(", ")}` : ""}${escape(c.title)}${item ? `${escape(item.title)}` : ""}${c.user ? `${escape(c.user)}` : ""}
  • `; -} - -export function boardHtml(columns, roadmap) { - return COLUMNS.map(({ id, name, about }) => { - const cards = columns[id]; - return `
    -

    ${escape(name)}${cards.length}

    -

    ${escape(about)}

    -
      ${cards.map((c, i) => cardHtml(c, roadmap, i >= SHOWN)).join("")}
    - ${cards.length > SHOWN ? `` : ""} -
    `; - }).join("\n"); -} - -// The board's roadmap filter: every item that has a card. -export function boardFilterHtml(columns, roadmap) { - const used = new Set(Object.values(columns).flat().map((c) => c.item).filter(Boolean)); - return [``, ``] - .concat(roadmap.items.filter((i) => used.has(i.id)).map((i) => ``)) - .join(""); -} - -// --- The journal ----------------------------------------------------------------------------------------------- - -export const JOURNAL_URL = "https://playhorizon.dev/hub#journal"; -const ENTRIES = 40; - -// The journal, newest first: each release with its changes grouped by roadmap item, the weekly summaries -// (roadmap/journal/), and what merged since the newest game release. releases: GitHub's release objects; list: the -// hub's issues and pull requests (their roadmap: labels place changes the roadmap doesn't link). -export function journalFrom(releases, list, roadmap) { - const prs = new Map(list.filter((i) => i.kind === "pr").map((i) => [i.n, i])); - const placed = (numbers) => { - for (const n of numbers) { - const known = prs.get(n); - const id = known ? itemOf(known, roadmap) : roadmap.items.find((i) => (i.links || []).includes(`#${n}`))?.id; - if (id) return id; - } - return null; - }; - const ours = releases.filter((r) => !r.draft && (isGame(r.tag_name) || isLauncher(r.tag_name))); - const entries = ours.map((r) => { - const changes = sections(r.body) - .filter((x) => /^(new|what's new|fixed)/i.test(x.title)) - .flatMap((x) => x.items.map((text) => ({ section: /^fixed/i.test(x.title) ? "fixed" : "new", text }))) - .map((c) => { - const numbers = [...c.text.matchAll(/#(\d+)/g)].map((m) => Number(m[1])); - return { ...c, text: plainItem(c.text), prs: numbers, item: placed(numbers) }; - }); - return { - id: r.tag_name, - kind: isLauncher(r.tag_name) ? "launcher" : "release", - date: r.published_at || "", - title: r.name || r.tag_name, - plain: parts(r).line, - url: r.html_url, - changes, - shipped: roadmap.items.filter((i) => i.status === "shipped" && i.shipped_in === r.tag_name).map((i) => i.id), - }; - }); - // Merged but in no release's notes yet: a release is cut from main a while after its last merge, so the newest - // releases' notes, not their dates, say what they hold. Pull requests players don't see (skip-release) never are. - const games = ours.filter((r) => isGame(r.tag_name)).map((r) => r.published_at).sort().reverse(); - const since = games[Math.min(4, games.length - 1)] || ""; - const noted = new Set(entries.flatMap((e) => e.changes.flatMap((c) => c.prs))); - const pending = list - .filter((i) => i.kind === "pr" && i.state === "merged" && i.at > since && !noted.has(i.n) && !i.labels.includes("skip-release")) - .sort((a, b) => b.at.localeCompare(a.at)); - if (pending.length) { - entries.push({ - id: "next-release", - kind: "merged", - date: pending[0].at, - title: "Merged, in the next release", - plain: `${pending.length} change${pending.length === 1 ? "" : "s"} merged since the last release.`, - url: `https://github.com/${REPO}/pulls?q=is%3Apr+is%3Amerged`, - changes: pending.map((p) => ({ section: "merged", text: p.title, prs: [p.n], item: itemOf(p, roadmap) })), - shipped: [], - }); - } - for (const w of roadmap.journal || []) { - // A week's summary sits after its last day's releases. - const end = new Date(Date.parse(w.date) + 7 * 864e5 - 1).toISOString(); - entries.push({ id: `week-${w.week}`, kind: "week", date: end, title: w.title, plain: w.plain, dev: w.dev, url: `${JOURNAL_URL.replace("#journal", "")}#week-${w.week}`, changes: [], shipped: [] }); - } - return entries.sort((a, b) => b.date.localeCompare(a.date)).slice(0, ENTRIES); -} - -const HUB = "https://playhorizon.dev/hub"; -const FEED = 300; - -// /data/journal.json, which Kira reads for #updates and X (kira's src/journal.js): one flat entry per merged pull -// request, release, shipped roadmap item and weekly summary, newest first. An entry's id never changes: Kira posts -// each id once. Shipped items carry `post` (at most 240 characters, tools/roadmap.py checks) and `announce`. -export function journalJson(releases, list, roadmap, generated = new Date().toISOString()) { - const items = new Map(roadmap.items.map((i) => [i.id, i])); - const ours = releases.filter((r) => !r.draft && (isGame(r.tag_name) || isLauncher(r.tag_name))); - const published = new Map(ours.map((r) => [r.tag_name, r.published_at || ""])); - const merges = list - .filter((i) => i.kind === "pr" && i.state === "merged") - .map((pr) => ({ pr, item: itemOf(pr, roadmap) })) - // What players see, and anything that moves a roadmap item. - .filter(({ pr, item }) => item || !pr.labels.includes("skip-release")) - .map(({ pr, item }) => ({ - id: `pr-${pr.n}`, - kind: "merge", - date: pr.at, - title: pr.title, - url: pr.url, - number: pr.n, - ...(item ? { item, item_title: items.get(item)?.title } : {}), - })); - const released = ours.map((r) => ({ - id: `release-${r.tag_name}`, - kind: "release", - date: r.published_at || "", - title: r.name || r.tag_name, - plain: parts(r).line, - url: r.html_url, - tag: r.tag_name, - })); - const shipped = roadmap.items - .filter((i) => i.status === "shipped") - .map((i) => ({ - id: `shipped-${i.id}`, - kind: "shipped", - date: published.get(i.shipped_in) || generated, - title: i.title, - plain: i.plain, - url: `${HUB}#${i.id}`, - item: i.id, - item_title: i.title, - shipped_in: i.shipped_in, - post: i.post || i.plain, - announce: Boolean(i.announce), - })); - // A week's summary is dated at the end of its week, after that week's releases. - const weekly = (roadmap.journal || []).map((w) => ({ - id: `weekly-${w.week}`, - kind: "weekly", - date: new Date(Date.parse(w.date) + 7 * 864e5 - 1000).toISOString(), - title: w.title, - plain: w.plain, - dev: w.dev, - url: `${HUB}#week-${w.week}`, - })); - const entries = [...merges, ...released, ...shipped, ...weekly].sort((a, b) => b.date.localeCompare(a.date) || a.id.localeCompare(b.id)); - return { format: "horizon-journal", version: 2, generated, url: `${HUB}#journal`, entries: entries.slice(0, FEED) }; -} - -const KIND = { release: "Game", launcher: "Launcher", merged: "Merged", week: "This week" }; - -function changesHtml(entry, roadmap) { - if (!entry.changes.length) return ""; - const line = (c) => `
  • ${inline(c.text)}${c.prs.length ? ` ${c.prs.map((n) => `#${n}`).join(" ")}` : ""}
  • `; - // Simple: what is new, then how many fixes. Technical: every change, under the roadmap item it moves. - const added = entry.changes.filter((c) => c.section !== "fixed"); - const fixes = entry.changes.length - added.length; - const simple = `
    ${added.length ? `
      ${added.map((c) => `
    • ${inline(c.text)}
    • `).join("")}
    ` : ""}${fixes ? `

    ${added.length ? "And " : ""}${fixes} fix${fixes === 1 ? "" : "es"}.

    ` : ""}
    `; - const groups = new Map(); - for (const c of entry.changes) groups.set(c.item || "", [...(groups.get(c.item || "") || []), c]); - const order = [...groups.keys()].sort((a, b) => (a === "") - (b === "")); - const dev = `
    ${order - .map((id) => { - const item = roadmap.items.find((i) => i.id === id); - return `

    ${item ? `${escape(item.title)}` : "Other changes"}

      ${groups.get(id).map(line).join("")}
    `; - }) - .join("")}
    `; - return simple + dev; -} - -export function journalHtml(entries, roadmap) { - return entries - .map((e) => { - const shipped = e.shipped.map((id) => roadmap.items.find((i) => i.id === id)).filter(Boolean); - const items = [...new Set(e.changes.map((c) => c.item).filter(Boolean))].map((id) => roadmap.items.find((i) => i.id === id)).filter(Boolean); - return `
    - -

    ${e.url ? `${escape(e.title)}` : escape(e.title)}

    - ${e.kind === "week" ? `

    ${inline(e.plain)}

    ${inline(e.dev.replace(/(^|[^\w[/`])#(\d+)\b/g, (_, b, n) => `${b}[#${n}](${issueUrl(n)})`))}

    ` : ""} - ${shipped.length ? `

    Shipped: ${shipped.map((i) => `${escape(i.title)}`).join(", ")}

    ` : ""} - ${items.length ? `

    ${items.map((i) => `${escape(i.title)}`).join("")}

    ` : ""} - ${changesHtml(e, roadmap)} -
    `; - }) - .join("\n"); -} - -// --- Contribute: the suggestion form's items and the contributors ------------------------------------------------ - -// The suggestion form's "About" choices: the items still to come. -export function suggestItemsHtml(roadmap) { - const open = roadmap.items.filter((i) => i.status !== "shipped"); - return [``] - .concat(open.map((i) => ``)) - .join(""); -} - -// The contributors, from GitHub (contributors.js's list), with the Discord name of those who linked their accounts -// on Kira and agreed to be credited (Kira's /contributors.json: { contributors: [{ github, discord }] }). -export function creditFrom(github, kira) { - const discord = new Map( - (Array.isArray(kira?.contributors) ? kira.contributors : []) - .filter((c) => c && typeof c.github === "string" && typeof c.discord === "string") - .map((c) => [c.github.toLowerCase(), c.discord]), - ); - return github.map((c) => ({ ...c, discord: discord.get(c.login.toLowerCase()) || "" })); -} - -export function creditHtml(list) { - return list - .map((c) => { - const src = avatar(c.avatar_url); - const count = `${c.contributions.toLocaleString("en-US")} ${c.contributions === 1 ? "commit" : "commits"}`; - return `
  • ${src ? `` : ``}${escape(c.login)}${count}${c.discord ? ` · ${escape(c.discord)} on Discord` : ""}
  • `; - }) - .join(""); -} diff --git a/website/src/hub.test.mjs b/website/src/hub.test.mjs deleted file mode 100644 index 4213d8a87..000000000 --- a/website/src/hub.test.mjs +++ /dev/null @@ -1,159 +0,0 @@ -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import { boardFrom, boardHtml, creditFrom, creditHtml, fixesIn, itemOf, journalFrom, journalHtml, journalJson, overviewHtml, progress, roadmapHtml, slimIssue, suggestItemsHtml } from "./hub.js"; - -const roadmap = JSON.parse(readFileSync(new URL("../data/roadmap.json", import.meta.url), "utf8")); - -const pr = (number, extra = {}) => ({ number, title: `PR ${number}`, state: "open", pull_request: { merged_at: null }, user: { login: "a" }, labels: [], assignees: [], body: "", ...extra }); -const issue = (number, extra = {}) => ({ number, title: `Issue ${number}`, state: "open", user: { login: "b" }, labels: [{ name: "bug" }], assignees: [], ...extra }); - -test("pull requests and issues reduce to their hub state", () => { - assert.deepEqual(fixesIn("Fixes #12, #13 and closes #4. Mentions #9."), [4, 12, 13]); - const merged = slimIssue(pr(5, { state: "closed", pull_request: { merged_at: "2030-01-01T00:00:00Z" }, body: "Fixes #3" })); - assert.equal(merged.kind, "pr"); - assert.equal(merged.state, "merged"); - assert.deepEqual(merged.fixes, [3]); - assert.equal(slimIssue(issue(6, { state: "closed", state_reason: "not_planned" })).state, "dropped"); - assert.deepEqual(slimIssue(issue(7)).labels, ["bug"]); -}); - -test("an item's progress counts its pull requests and issues", () => { - const live = new Map([ - [1, slimIssue(pr(1))], - [2, slimIssue(pr(2, { draft: true }))], - [3, slimIssue(pr(3, { state: "closed", pull_request: { merged_at: "2030-01-01T00:00:00Z" } }))], - [4, slimIssue(issue(4))], - ]); - const item = { links: ["#1", "#2", "#3", "#4", "#99", "docs/x.md"] }; - assert.equal(progress(item, live), "1 pull request in review · 1 in progress · 1 merged · 1 issue open"); - assert.equal(progress(item, new Map()), ""); -}); - -test("the roadmap renders every item once, with both texts, in its status's section", () => { - const html = roadmapHtml(roadmap); - for (const item of roadmap.items) { - assert.equal(html.split(`id="${item.id}"`).length, 2, item.id); - } - assert.ok(html.indexOf('id="now"') < html.indexOf('id="next"')); - assert.ok(html.includes('class="hub-plain"') && html.includes('class="hub-dev"')); - // Shipped items say which release had them. - assert.ok(html.includes(`>${roadmap.items.find((i) => i.status === "shipped").shipped_in}<`)); -}); - -test("an item is its own anchor (hub#, as Kira links it) and takes no other id of the page", () => { - const week = { week: "2030-01", date: "2029-12-31", title: "A week", plain: "p", dev: "d" }; - const release = { tag_name: "v0.2.2", name: "0.2.2", published_at: "2030-01-02T00:00:00Z", html_url: "u", body: "" }; - const journal = journalHtml(journalFrom([release], [], { ...roadmap, journal: [week] }), roadmap); - const board = boardHtml(boardFrom([], roadmap), roadmap); - const page = readFileSync(new URL("./hub.html", import.meta.url), "utf8") + roadmapHtml(roadmap) + overviewHtml(roadmap) + board + journal; - const ids = [...page.matchAll(/ id="([^"]+)"/g)].map((m) => m[1]); - assert.deepEqual(ids.filter((id, i) => ids.indexOf(id) !== i), []); - for (const item of roadmap.items) assert.ok(ids.includes(item.id), item.id); -}); - -test("the overview lists the focus items and never nests links", () => { - const html = overviewHtml(roadmap); - for (const item of roadmap.items.filter((i) => i.focus)) assert.ok(html.includes(`href="#${item.id}"`), item.id); - for (const row of html.match(/
  • [\s\S]*?<\/li>/g)) assert.equal(row.split(" { - const now = Date.parse("2030-01-10T00:00:00Z"); - const list = [ - issue(1), - issue(2), - issue(3, { assignees: [{ login: "x" }] }), - pr(10, { body: "Fixes #1" }), - pr(11, { body: "Fixes #2", draft: true }), - pr(12, { labels: [{ name: `roadmap:${roadmap.items[0].id}` }] }), - pr(13, { draft: true }), - pr(14, { state: "closed", pull_request: { merged_at: "2030-01-09T00:00:00Z" } }), - pr(15, { state: "closed", pull_request: { merged_at: "2029-12-01T00:00:00Z" } }), - ].map(slimIssue); - const board = boardFrom(list, roadmap, now); - const ids = (column) => board[column].map((c) => c.n); - assert.deepEqual(ids("todo"), []); - assert.deepEqual(ids("progress"), [2, 3, 13]); - assert.deepEqual(ids("review"), [1, 12]); - assert.deepEqual(ids("done"), [14]); - assert.deepEqual(board.review[0].prs, [10]); - assert.equal(board.review[1].item, roadmap.items[0].id); - assert.equal(itemOf(slimIssue(pr(16, { body: "Fixes #1438" })), roadmap), "end-city-banners"); -}); - -test("the journal groups a release's changes by roadmap item and lists what awaits a release", () => { - const releases = [ - { tag_name: "v0.2.2", name: "Horizon 0.2.2: Rich presence", published_at: "2030-01-02T00:00:00Z", html_url: "u2", body: "### New\n- Discord Rich Presence (#1787)\n\n### Fixed\n- A fix (#5, fixes #4)\n" }, - { tag_name: "launcher@0.2.1", name: "Horizon launcher 0.2.1", published_at: "2030-01-01T00:00:00Z", html_url: "u1", body: "### Fixed\n- Window (#6)\n" }, - ]; - const list = [ - pr(1788, { state: "closed", pull_request: { merged_at: "2030-01-03T00:00:00Z" } }), - pr(7, { state: "closed", pull_request: { merged_at: "2030-01-03T00:00:00Z" }, labels: [{ name: "skip-release" }] }), - ].map(slimIssue); - const entries = journalFrom(releases, list, { ...roadmap, journal: [] }); - assert.deepEqual(entries.map((e) => e.id), ["next-release", "v0.2.2", "launcher@0.2.1"]); - assert.deepEqual(entries[0].changes.map((c) => [c.prs, c.item]), [[[1788], "discord-presence"]]); - assert.deepEqual(entries[1].changes.map((c) => [c.section, c.text, c.item]), [["new", "Discord Rich Presence", "discord-presence"], ["fixed", "A fix", null]]); - const html = journalHtml(entries, roadmap); - assert.ok(html.includes('href="#discord-presence"')); - assert.ok(html.includes("And 1 fix.")); -}); - -test("journal.json is the flat feed Kira reads: merges, releases, shipped items, weeks, ids that never change", () => { - const releases = [ - { tag_name: "v0.2.48", name: "Horizon 0.2.48", published_at: "2030-01-02T00:00:00Z", html_url: "https://github.com/ludovic111/horizon/releases/tag/v0.2.48", body: "### New\n- Packs (#1)\n" }, - { tag_name: "nightly-1", name: "Nightly", published_at: "2030-01-03T00:00:00Z", html_url: "u", body: "" }, - ]; - const list = [ - pr(1788, { state: "closed", pull_request: { merged_at: "2030-01-04T00:00:00Z" }, html_url: "https://github.com/ludovic111/horizon/pull/1788" }), - pr(7, { state: "closed", pull_request: { merged_at: "2030-01-04T00:00:00Z" }, labels: [{ name: "skip-release" }] }), - pr(8, { state: "closed", pull_request: { merged_at: "2030-01-04T00:00:00Z" }, labels: [{ name: "skip-release" }, { name: "roadmap:lean-code" }] }), - pr(9), - ].map(slimIssue); - const week = { week: "2030-01", date: "2029-12-31", title: "A week", plain: "p", dev: "d" }; - const feed = journalJson(releases, list, { ...roadmap, journal: [week] }, "2030-01-05T00:00:00Z"); - const byId = new Map(feed.entries.map((e) => [e.id, e])); - // A merged pull request, with its roadmap item; skip-release ones only when they move an item; open ones never. - assert.deepEqual(byId.get("pr-1788"), { id: "pr-1788", kind: "merge", date: "2030-01-04T00:00:00Z", title: "PR 1788", url: "https://github.com/ludovic111/horizon/pull/1788", number: 1788, item: "discord-presence", item_title: "Discord Rich Presence" }); - assert.ok(!byId.has("pr-7") && byId.get("pr-8").item === "lean-code" && !byId.has("pr-9")); - // Game and launcher releases only. - assert.equal(byId.get("release-v0.2.48").tag, "v0.2.48"); - assert.ok(!byId.has("release-nightly-1")); - // Every shipped item, dated by its release when the feed has it, with its post and the announce flag. - const shipped = roadmap.items.filter((i) => i.status === "shipped"); - for (const item of shipped) { - const e = byId.get(`shipped-${item.id}`); - assert.equal(e.kind, "shipped"); - assert.equal(e.url, `https://playhorizon.dev/hub#${item.id}`); - assert.ok(e.post.length <= 240 && typeof e.announce === "boolean", item.id); - } - assert.equal(byId.get("shipped-server-resource-packs").date, "2030-01-02T00:00:00Z"); - assert.equal(byId.get("weekly-2030-01").date, "2030-01-06T23:59:59.000Z"); - // Newest first; every entry has what Kira needs, and links only where Kira shows them. - assert.deepEqual(feed.entries.map((e) => e.date), feed.entries.map((e) => e.date).sort().reverse()); - for (const e of feed.entries) { - assert.ok(e.id && ["merge", "release", "weekly", "shipped"].includes(e.kind) && e.date && e.title, e.id); - assert.match(e.url, /^https:\/\/(github\.com|playhorizon\.dev)\//, e.id); - } -}); - -test("items still to come take votes and suggestions; shipped ones don't", () => { - const html = roadmapHtml(roadmap); - for (const item of roadmap.items) { - assert.equal(html.includes(`data-vote="${item.id}"`), item.status !== "shipped", item.id); - assert.equal(suggestItemsHtml(roadmap).includes(`value="${item.id}"`), item.status !== "shipped", item.id); - } - // Hidden until the hub's server answers. - assert.ok(html.includes('aria-pressed="false" hidden>')); -}); - -test("the contributors carry the Discord name of those who agreed on Kira", () => { - const github = [{ login: "Alex", html_url: "https://github.com/Alex", avatar_url: "", contributions: 3 }, { login: "sam", html_url: "https://github.com/sam", avatar_url: "", contributions: 1 }]; - const kira = { contributors: [{ github: "alex", discord: "Alex " }, { github: 5 }, null] }; - const credit = creditFrom(github, kira); - assert.deepEqual(credit.map((c) => c.discord), ["Alex ", ""]); - const html = creditHtml(credit); - assert.ok(html.includes("3 commits · Alex <b> on Discord") && html.includes("1 commit")); - assert.deepEqual(creditFrom(github, "not json").map((c) => c.discord), ["", ""]); -}); diff --git a/website/src/index.html b/website/src/index.html deleted file mode 100644 index 3776733c6..000000000 --- a/website/src/index.html +++ /dev/null @@ -1,216 +0,0 @@ - - - - - - Horizon: a Rust rewrite for Minecraft: Java Edition 26.3 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -{{SITE_NAV}} - -
    -
    -
    -

    Minecraft: Java Edition 26.3Rust

    -

    Horizon: The game you know, rebuilt in Rust.

    -

    The Minecraft: Java Edition 26.3 client and its game logic, rewritten in Rust and checked against the vanilla game by {{HARNESSES}} differential harnesses.

    - -

    For Linux x86-64, macOS on Apple Silicon and Windows x64.

    -
    -
    -
    -
      -
    1. 01Matches vanilla{{PERCENT}}
    2. -
    3. 02Differential harnesses{{HARNESSES}}
    4. -
    5. 03Drawn by Horizon5 shots
    6. -
    7. 04Recently addedReleases
    8. - -
    -

    Unofficial. Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

    -
    - -
    -
    -

    01What it is

    -

    Horizon rebuilds Minecraft: Java Edition 26.3 in Rust, one subsystem at a time, and holds every piece to the same inputs as the vanilla game until the outputs are identical.

    -
    -
    - -

    Your own copy

    -

    Install Java Edition with the official launcher and play 26.3 once. Horizon builds its resources from those files on your machine, and never downloads or shares game files.

    -
    -
    - -

    Native on three platforms

    -

    Linux, macOS on Apple Silicon and Windows. Worlds come from a Rust port of the vanilla generators, drawn with vanilla's block models, lighting, sky and fog.

    -
    -
    - -

    Open source

    -

    Horizon's code is MIT. It contains no Minecraft code, assets or data; those belong to Mojang and Microsoft under the Minecraft EULA.

    -
    -
    -
    -
    - -
    -
    -
    -

    02In game

    -

    Drawn by Horizon

    -

    Captured in the Rust client itself, with vanilla assets from the player's own copy and no mods or shaders.

    -
    -
    -
    01A plains village
    -
    02Moonrise
    -
    03A crimson forest in the Nether
    -
    04A coral reef
    -
    05Survival at dusk
    -
    -
    -
    - -
    -
    -

    03Parity

    -
    -
    - -

    {{HARNESSES}} differential harnesses drive the same inputs through Horizon and through the vanilla client and server, and compare what comes out.

    -
    -
    -

    {{PARITY_HEADLINE}}

    -
    {{PARITY_INTRO}}
    -

    Last audited {{AUDITED}}{{PERCENT}} of what the harnesses comparefrom the README on main

    -
    -
    -
      - {{PARITY_CELLS}} -
    -

    Each subsystem scores 0 (absent), 0.25 (started), 0.5 (playable, major features missing), 0.75 (mostly complete) or 1 (complete and verified against vanilla by differential tests).

    -
    -
    - -
    -
    -
    -

    04The launcher

    -

    One small app, then play

    -

    The launcher installs Horizon, prepares it from your copy of the game and keeps both up to date.

    -
      -
    • One-click install

      Pick a release and it installs the build for your platform into its own folder, then prepares the resources from your Java Edition 26.3 install.

    • -
    • Updates on its own

      It looks for a new Horizon release when it starts and every four hours, and updates itself from the launcher's own releases.

    • -
    • Client or server

      Start the client, or host a server from the Servers page: create it, start it, watch players and the console, change its settings and keep backups.

    • -
    • Logs and crash reports

      The Settings page shows where the game's logs and crash reports are, and horizon-launcher logs prints them.

    • -
    • Modpacks and packs

      The Modpacks page reads a Modrinth or CurseForge pack and carries over the mods Horizon can run. The Mods page installs resource packs and modpacks from Modrinth.

    • -
    -
    - Download the launcher -

    {{LAUNCHER_META}}

    -
    -
    - -
    -
    - - - -
    -
    -
    The launcher's Play page: the version, Client and Server, the version picker and Play, the prepared resources and the Minecraft folder as a numbered list
    -
    Vanilla's Video Settings screen with Horizon's own buttons at the top: Horizon Graphics and Advanced Graphics
    -
    -

    The launcher, and Horizon's graphics settings in the game: vanilla's menus, with Horizon's pages added the way mods add theirs.

    -
    -
    -
    - -
    -
    -
    -

    05Releases

    -

    Recently added

    -

    New versions come out many times a day, as changes land, and the launcher installs each one once it has passed its test. The newest, and what they added:

    -
    -
    - {{RECENT}} -
    -
    -
    - -
    -
    -

    06Community

    -

    Built in the open

    - -
    -

    Contributors

    -

    Everyone who has committed to Horizon on GitHub, with how many commits.

    -
      {{CONTRIBUTORS}}
    -
    -
    -
    -
    - -
    -
    - - - -
    - -
    - - -
    - - -
    - - - - diff --git a/website/src/main.js b/website/src/main.js deleted file mode 100644 index 72e8577a5..000000000 --- a/website/src/main.js +++ /dev/null @@ -1,265 +0,0 @@ -// The page's behaviour: the download buttons for this platform, the latest releases, the -// links and contributors, how many play now, the navigation, the menus' tabs, the lightbox -// and the motion. -// Everything degrades to the baked-in content when GitHub can't be reached. -import { escape } from "./markdown.js"; -import { recentHtml } from "./releases.js"; -import { contributorsFrom, contributorsHtml } from "./contributors.js"; -import { isGame, isLauncher as isLauncherTag, launcherVersion, newestFirst } from "./versions.js"; -import { cached, get, setUpMenu, setUpTheme, slim } from "./chrome.js"; - -const REPO = "ludovic111/horizon"; -const RELEASES_PAGE = `https://github.com/${REPO}/releases?q=launcher&expanded=true`; -const baked = JSON.parse(document.getElementById("baked").textContent); -const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches; - -// --- GitHub -------------------------------------------------------------------------- - -const isLauncher = (r) => isLauncherTag(r.tag_name) && !r.prerelease; - -// The newest 100 releases (GitHub's most per page). The newest game release that is not a pre-release (the old -// Alpha channel's, docs/release-flow.md) and the newest launcher release can be older than all of them. The game -// release is then GitHub's "latest" (pre-releases and launcher releases never are); the launcher release is looked up by its -// tag (the newest launcher@ tag with a published release, or launcher-v before 0.2: docs/versioning.md). -async function loadReleases() { - const list = (await get(`https://api.github.com/repos/${REPO}/releases?per_page=100`)).filter((r) => !r.draft).map(slim); - if (!list.some((r) => isGame(r.tag_name) && !r.prerelease)) { - const latest = await get(`https://api.github.com/repos/${REPO}/releases/latest`).catch(() => null); - if (latest && !latest.draft) list.push(slim(latest)); - } - if (list.some(isLauncher)) return list; - let tags = []; - for (const prefix of ["launcher@", "launcher-v"]) { - if (tags.length) break; - const refs = await get(`https://api.github.com/repos/${REPO}/git/matching-refs/tags/${prefix}`).catch(() => []); - tags = refs.map((r) => r.ref.replace("refs/tags/", "")).filter(isLauncherTag).sort(newestFirst); - } - for (const tag of tags.slice(0, 3)) { - const release = await get(`https://api.github.com/repos/${REPO}/releases/tags/${tag}`).catch(() => null); - if (release && !release.draft) return [...list, slim(release)]; - } - return list; -} - -const releases = cached("horizon:releases", loadReleases).catch(() => baked.releases); - -async function setUpContributors() { - let list = baked.contributors || []; - try { - list = contributorsFrom(await cached("horizon:contributors", () => get(`https://api.github.com/repos/${REPO}/contributors?per_page=100`))); - } catch {} - if (list.length) document.getElementById("contributors-list").innerHTML = contributorsHtml(list); - // With nobody to show, the block and its menu entries go, as an empty link's card does. - document.querySelectorAll("[data-contributors]").forEach((el) => (el.hidden = !list.length)); -} - -// --- Download ------------------------------------------------------------------------ - -function platform() { - const ua = navigator.userAgent; - const hint = (navigator.userAgentData && navigator.userAgentData.platform) || navigator.platform || ""; - if (/iPhone|iPad|iPod|Android/i.test(ua) || (navigator.maxTouchPoints > 1 && /Mac/.test(hint))) return null; - if (/Win/i.test(hint) || /Windows/.test(ua)) return { key: "windows-x64", label: "Windows x64" }; - if (/Mac/i.test(hint) || /Mac OS X/.test(ua)) return { key: "macos-arm64", label: "macOS on Apple Silicon" }; - if (/Linux|X11/i.test(hint) || /Linux/.test(ua)) return { key: "linux-x86_64", label: "Linux x86-64" }; - return null; -} - -async function setUpDownload() { - const os = platform(); - const list = await releases; - const launcher = list.filter(isLauncher).sort((a, b) => newestFirst(a.tag_name, b.tag_name))[0]; - if (!launcher) return; - const version = launcherVersion(launcher.tag_name); - const asset = os && launcher.assets.find((a) => a.name.includes(os.key)); - const others = `Other platforms`; - document.querySelectorAll("[data-download]").forEach((a) => (a.href = asset ? asset.browser_download_url : launcher.html_url || RELEASES_PAGE)); - const mb = asset && asset.size ? ` · ${(asset.size / 1e6).toFixed(0)} MB` : ""; - const meta = asset - ? `For ${escape(os.label)} · launcher ${escape(version)}${mb} · ${others}` - : `Launcher ${escape(version)} for Linux x86-64, macOS on Apple Silicon and Windows x64. It runs on a computer, not on phones or tablets.`; - document.querySelectorAll("[data-download-meta]").forEach((p) => (p.innerHTML = meta)); -} - -// --- Recently added and the links from main --------------------------------- - -// "Recently added": the newest game releases. -async function setUpRecent() { - const html = recentHtml((await releases).filter((r) => isGame(r.tag_name))); - if (html) document.getElementById("recent-releases").innerHTML = html; -} - -async function setUpLinks() { - let links = baked.links; - try { - const remote = await cached("horizon:links", () => get(`https://raw.githubusercontent.com/${REPO}/main/launcher/links.json`, "text").then(JSON.parse)); - links = { ...links }; - for (const key of Object.keys(links)) if (typeof remote[key] === "string") links[key] = remote[key].trim(); - } catch {} - document.querySelectorAll("[data-link]").forEach((a) => { - const url = links[a.dataset.link]; - // An empty address hides its card, as the launcher hides its button. - if (!url) a.hidden = true; - else if (/^https:\/\//.test(url)) a.href = url; - }); -} - -// --- Playing now --------------------------------------------------------------------- - -const TELEMETRY = "https://telemetry.playhorizon.dev"; - -// How many play right now, from the games' anonymous "I'm playing" pings (Privacy explains them). The -// server rounds it and makes it again at most every 15 seconds; the row stays hidden while nobody plays -// or the server doesn't answer. -async function setUpLive() { - const row = document.querySelector("[data-live]"); - if (!row) return; - const update = async () => { - try { - const res = await fetch(`${TELEMETRY}/v1/live`, { signal: AbortSignal.timeout(3000) }); - if (!res.ok) throw new Error(String(res.status)); - const { playing } = await res.json(); - if (!Number.isInteger(playing) || playing < 1) throw new Error("nobody"); - row.querySelector("[data-live-count]").textContent = playing.toLocaleString("en"); - row.hidden = false; - // It shows up after the others came in, so it skips their entrance. - row.classList.add("is-visible"); - } catch { - row.hidden = true; - } - }; - await update(); - setInterval(() => document.visibilityState === "visible" && update(), 60_000); -} - -// --- Navigation ---------------------------------------------------------------------- - -function setUpNav() { - // The home sections use the same root-relative links in every page's header. - const links = [...document.querySelectorAll('.nav-links a[href^="/#"]')]; - const sections = links.map((a) => document.querySelector(a.hash)); - - let current = null; - const update = () => { - const line = innerHeight * 0.4; - let index = -1; - sections.forEach((s, i) => { - if (s.getClientRects().length && s.getBoundingClientRect().top <= line) index = i; - }); - if (index !== current) { - current = index; - links.forEach((a, i) => (i === index ? a.setAttribute("aria-current", "true") : a.removeAttribute("aria-current"))); - } - }; - onScroll(update); - update(); -} - -// One rAF-throttled scroll listener for everything that follows the scroll. -const scrollers = []; -function onScroll(fn) { - scrollers.push(fn); -} -let queued = false; -const run = () => ((queued = false), scrollers.forEach((fn) => fn())); -addEventListener("scroll", () => !queued && ((queued = true), requestAnimationFrame(run)), { passive: true }); -addEventListener("resize", () => requestAnimationFrame(run)); - -// --- The menus' tabs ------------------------------------------------------------------ - -function setUpTabs() { - const list = document.querySelector(".tabs"); - const tabs = [...list.querySelectorAll('[role="tab"]')]; - const pill = list.querySelector(".tab-pill"); - const selected = () => tabs.find((t) => t.getAttribute("aria-selected") === "true"); - const place = (tab) => { - pill.style.width = `${tab.offsetWidth}px`; - pill.style.height = `${tab.offsetHeight}px`; - pill.style.transform = `translate(${tab.offsetLeft}px, ${tab.offsetTop}px)`; - }; - const choose = (tab, focus) => { - tabs.forEach((t) => { - const on = t === tab; - t.setAttribute("aria-selected", String(on)); - t.tabIndex = on ? 0 : -1; - const panel = document.getElementById(t.getAttribute("aria-controls")); - panel.classList.toggle("is-active", on); - panel.inert = !on; - panel.setAttribute("aria-hidden", String(!on)); - }); - place(tab); - if (focus) tab.focus(); - }; - tabs.forEach((tab, i) => { - tab.addEventListener("click", () => choose(tab)); - tab.addEventListener("keydown", (e) => { - const step = { ArrowRight: 1, ArrowLeft: -1 }[e.key]; - if (step) choose(tabs[(i + step + tabs.length) % tabs.length], true); - if (e.key === "Home") choose(tabs[0], true); - if (e.key === "End") choose(tabs[tabs.length - 1], true); - }); - }); - choose(selected()); - addEventListener("resize", () => place(selected())); - document.fonts?.ready.then(() => place(selected())); -} - -function setUpLightbox() { - const dialog = document.querySelector(".lightbox"); - const big = dialog.querySelector("img"); - const caption = dialog.querySelector(".lightbox-caption"); - document.querySelectorAll(".zoom").forEach((button) => { - button.addEventListener("click", () => { - const img = button.querySelector("img"); - big.src = img.currentSrc.replace("-800.webp", ".webp"); - big.alt = img.alt; - caption.textContent = img.alt; - dialog.showModal(); - }); - }); - dialog.addEventListener("click", (e) => { - if (e.target === dialog) dialog.close(); - }); -} - -// --- Motion --------------------------------------------------------------------------- - -function setUpReveal() { - // Siblings that enter together come in one after another. - const stagger = (els, step) => els.forEach((el, i) => el.style.setProperty("--d", `${i * step}ms`)); - document.querySelectorAll(".facts, .features, .cards, .mosaic, .hero-index").forEach((group) => stagger([...group.children], 40)); - document.querySelectorAll(".hero .container, .section-head, .parity-count, .parity-copy, .launcher-copy").forEach((group) => stagger([...group.querySelectorAll(":scope > .reveal")], 60)); - stagger([...document.querySelectorAll(".system")], 40); - - const count = document.querySelector("[data-digits]"); - count.innerHTML = [...count.textContent].map((c) => `${escape(c)}`).join(""); - - const items = document.querySelectorAll(".reveal, .reveal-media, .systems"); - if (reducedMotion || !("IntersectionObserver" in window)) { - items.forEach((el) => el.classList.add("is-visible")); - return; - } - const observer = new IntersectionObserver( - (entries) => - entries.forEach((e) => { - if (e.isIntersecting) { - e.target.classList.add("is-visible"); - observer.unobserve(e.target); - } - }), - { rootMargin: "0px 0px -10% 0px" }, - ); - items.forEach((el) => observer.observe(el)); -} - -setUpReveal(); -setUpTheme(); -setUpNav(); -setUpMenu(); -setUpTabs(); -setUpLightbox(); -setUpDownload(); -setUpRecent(); -setUpLinks(); -setUpContributors(); -setUpLive(); diff --git a/website/src/markdown.js b/website/src/markdown.js deleted file mode 100644 index 1735f7304..000000000 --- a/website/src/markdown.js +++ /dev/null @@ -1,203 +0,0 @@ -// A small Markdown renderer for release notes, the README and the docs: headings, paragraphs, -// lists (nested by indentation), fenced code, quotes, rules, tables, and inline code, bold, -// italic and links. Everything is escaped first, so its output never carries raw HTML. -// Shared by build.mjs (Node) and main.js (browser). - -const REPO_BLOB = "https://github.com/ludovic111/horizon/blob/main/"; - -export function escape(text) { - return text.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]); -} - -function href(url, site) { - url = url.trim(); - if (/^(https?:|mailto:)/i.test(url)) return url; - // The docs pages (`site`) link each other and their own headings; the README's anchors have no target here. - if (site && (/^\/(?!\/)/.test(url) || url.startsWith("#"))) return url; - if (url.startsWith("#")) return null; - if (/^[a-z]+:/i.test(url)) return null; // javascript: and the like - return REPO_BLOB + url.replace(/^\.?\//, ""); -} - -export function inline(text, site = false) { - const codes = []; - let out = text.replace(/`([^`]+)`/g, (_, code) => { - codes.push(code); - return `\u0000${codes.length - 1}\u0000`; - }); - const links = []; - out = out.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, label, url) => { - links.push([label, url]); - return `\u0001${links.length - 1}\u0001`; - }); - out = escape(out) - .replace(/\*\*([^*]+)\*\*/g, "$1") - .replace(/(^|[^\w*])\*([^*\s][^*]*)\*/g, "$1$2") - .replace(/(^|[^\w])_([^_\s][^_]*)_(?!\w)/g, "$1$2") - .replace(/<(https?:\/\/[^\s&]+)>/g, (_, u) => `${u}`); - out = out.replace(/\u0001(\d+)\u0001/g, (_, i) => { - const [label, url] = links[i]; - const target = href(url, site); - // The label's code spans are already placeholders: put them back for its own pass. - const body = inline(label.replace(/\u0000(\d+)\u0000/g, (_, c) => `\`${codes[c]}\``), site); - return target ? `${body}` : body; - }); - return out.replace(/\u0000(\d+)\u0000/g, (_, i) => `${escape(codes[i])}`); -} - -// A table: a row of cells, a rule row (`| --- | :-: |`), then body rows, until a line that isn't a row. -const ROW = /^\s*\|.*\|\s*$/; -const RULE = /^\s*\|(\s*:?-+:?\s*\|)+\s*$/; - -/** A row's cells: split on `|` outside code spans; `\|` is a literal bar. */ -function cells(row) { - const s = row.trim().slice(1, -1); - const out = [""]; - let code = false; - for (let i = 0; i < s.length; i++) { - if (s[i] === "\\" && s[i + 1] === "|") out[out.length - 1] += s[++i]; - else if (s[i] === "|" && !code) out.push(""); - else { - if (s[i] === "`") code = !code; - out[out.length - 1] += s[i]; - } - } - return out.map((c) => c.trim()); -} - -function table(lines, start, site) { - const row = (line, tag) => `${cells(line).map((c) => `<${tag}>${inline(c, site)}`).join("")}`; - let i = start + 2; - const body = []; - while (i < lines.length && ROW.test(lines[i])) body.push(row(lines[i++], "td")); - return [`
    ${row(lines[start], "th")}${body.join("")}
    `, i]; -} - -const indentOf = (line) => line.match(/^ */)[0].length; -const ITEM = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/; - -function list(lines, start, site) { - // Collects the items at this list's indentation; deeper lines belong to the item above. - const base = indentOf(lines[start]); - const ordered = /\d/.test(lines[start].match(ITEM)[2]); - const items = []; - let i = start; - while (i < lines.length) { - const line = lines[i]; - if (!line.trim()) { - const next = lines.slice(i + 1).find((l) => l.trim()); - if (next && ITEM.test(next) && indentOf(next) >= base) { - i++; - continue; - } - break; - } - const m = line.match(ITEM); - if (m && indentOf(line) === base) { - items.push({ text: [m[3]], children: [] }); - } else if (m && indentOf(line) > base) { - const [html, end] = list(lines, i, site); - items[items.length - 1].children.push(html); - i = end; - continue; - } else if (indentOf(line) > base && items.length) { - items[items.length - 1].text.push(line.trim()); - } else { - break; - } - i++; - } - const tag = ordered ? "ol" : "ul"; - const body = items.map((it) => `
  • ${inline(it.text.join(" "), site)}${it.children.join("")}
  • `).join(""); - return [`<${tag}>${body}`, i]; -} - -const slug = (text) => - text - .toLowerCase() - .replace(/`/g, "") - .replace(/[^a-z0-9]+/g, "-") - .replace(/^-|-$/g, ""); - -/** - * Renders Markdown; `shift` moves headings down (a `#` becomes `h{1 + shift}`). - * `site` is for the docs pages: links to the site's own pages and anchors stay as they are, `##` and `###` - * headings get an id (and are pushed onto `headings`, for a table of contents), and a line holding only - * `![caption](/media/…)` becomes a figure. - */ -export function markdown(source, { shift = 0, site = false, headings = null } = {}) { - const lines = source.replace(/\r\n?/g, "\n").split("\n"); - const out = []; - let i = 0; - while (i < lines.length) { - const line = lines[i]; - if (!line.trim() || /^\s*<\/?[a-z][^>]*>\s*$/i.test(line)) { - i++; // blank lines and lone HTML tags (the README's layout tables) are skipped - continue; - } - let m; - if ((m = line.match(/^(#{1,6})\s+(.*?)\s*#*$/))) { - const level = Math.min(6, m[1].length + shift); - let id = ""; - if (site && (m[1].length === 2 || m[1].length === 3)) { - const base = slug(m[2]); - id = base; - for (let n = 2; headings && headings.some((h) => h.id === id); n++) id = `${base}-${n}`; - headings?.push({ level: m[1].length, text: m[2].replace(/`/g, ""), id }); - } - out.push(`${inline(m[2], site)}`); - i++; - } else if (site && (m = line.match(/^!\[([^\]]*)\]\((\/media\/[\w./-]+)\)\s*$/))) { - out.push(`
    ${escape(m[1])}
    ${inline(m[1], true)}
    `); - i++; - } else if ((m = line.match(/^\s*(```|~~~)/))) { - const fence = m[1]; - const code = []; - i++; - while (i < lines.length && !lines[i].trim().startsWith(fence)) code.push(lines[i++]); - i++; - out.push(`
    ${escape(code.join("\n"))}
    `); - } else if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) { - out.push("
    "); - i++; - } else if (ROW.test(line) && RULE.test(lines[i + 1] || "")) { - const [html, end] = table(lines, i, site); - out.push(html); - i = end; - } else if (ITEM.test(line)) { - const [html, end] = list(lines, i, site); - out.push(html); - i = end; - } else if (line.startsWith(">")) { - const quote = []; - while (i < lines.length && lines[i].startsWith(">")) quote.push(lines[i++].replace(/^>\s?/, "")); - out.push(`
    ${markdown(quote.join("\n"), { shift, site })}
    `); - } else { - const para = []; - while ( - i < lines.length && - lines[i].trim() && - !/^(#{1,6}\s|>|\s*```|\s*~~~)/.test(lines[i]) && - !ITEM.test(lines[i]) - ) { - para.push(lines[i++].trim()); - } - out.push(`

    ${inline(para.join(" "), site)}

    `); - } - } - return out.join("\n"); -} - -/** The body of the section titled `title` (any heading level), up to the next heading at its level or above. */ -export function section(source, title) { - const lines = source.replace(/\r\n?/g, "\n").split("\n"); - const level = (l) => (l.match(/^(#{1,6})\s/) || [, ""])[1].length; - const start = lines.findIndex((l) => level(l) > 0 && l.replace(/^#+/, "").trim() === title); - if (start < 0) return null; - const depth = level(lines[start]); - const end = lines.findIndex((l, i) => i > start && level(l) > 0 && level(l) <= depth); - return lines - .slice(start + 1, end < 0 ? undefined : end) - .join("\n") - .trim(); -} diff --git a/website/src/markdown.test.mjs b/website/src/markdown.test.mjs deleted file mode 100644 index 171348e45..000000000 --- a/website/src/markdown.test.mjs +++ /dev/null @@ -1,25 +0,0 @@ -// node --test src/: the Markdown the docs pages and release notes are rendered from. -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { markdown } from "./markdown.js"; - -test("a table renders with its header, cells and inline Markdown", () => { - const html = markdown("| Way in | Status |\n| --- | :-: |\n| Rust | `cargo horizon-mod` |\n| Lua | planned \\| soon |\n\nAfter."); - assert.equal( - html, - '
    ' + - "
    Way inStatus
    Rustcargo horizon-mod
    Luaplanned | soon
    \n

    After.

    ", - ); -}); - -test("a bar inside a code span stays in its cell", () => { - assert.match(markdown("| a | b |\n|---|---|\n| `x | y` | z |"), /x \| y<\/code><\/td>z<\/td>/); -}); - -test("rows without a rule line are a paragraph", () => { - assert.equal(markdown("| a | b |\n| c | d |"), "

    | a | b | | c | d |

    "); -}); - -test("a link whose label is code keeps it", () => { - assert.equal(markdown("See [`AGENTS.md`](/docs/agents).", { site: true }), '

    See AGENTS.md.

    '); -}); diff --git a/website/src/mods-page.js b/website/src/mods-page.js deleted file mode 100644 index 121ba8067..000000000 --- a/website/src/mods-page.js +++ /dev/null @@ -1,66 +0,0 @@ -// /mods and /mods/: the registry's list (kind filter, search) and a project's page. The pages are baked from -// the index at build time; this fetches the published index again so a project merged since shows at once. -import { INDEX_URL, KINDS, listHtml, matches, projectHtml, readIndex } from "./mods.js"; -import { cached, setUpMenu, setUpTheme } from "./chrome.js"; - -const root = document.getElementById("mods"); -const baked = readIndex(JSON.parse(document.getElementById("mods-index").textContent || "null")) || []; -let projects = baked; -let kind = "all"; -let text = ""; - -const id = (location.pathname.match(/^\/mods\/([a-z0-9_]+)\/?$/) || [])[1]; - -function showList() { - const list = root.querySelector("#mod-list"); - if (!list) return; - const shown = projects.filter((p) => matches(p, kind, text)); - list.innerHTML = listHtml(shown); - root.querySelector("[data-mod-count]").textContent = `${shown.length} of ${projects.length}`; - root.querySelectorAll("[data-kind-filter]").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.kindFilter === kind))); -} - -function showProject() { - const p = projects.find((x) => x.id === id); - const page = root.querySelector(".mod-page, .mod-missing"); - if (!page) return; - if (p) { - page.outerHTML = projectHtml(p); - document.title = `${p.name} · Horizon`; - } else { - page.outerHTML = `

    Not in the registry

    No project is called ${id} here. It may not be published yet, or it was taken down.

    Every mod
    `; - } -} - -function render() { - if (id) showProject(); - else showList(); -} - -if (!id) { - root.querySelectorAll("[data-kind-filter]").forEach((b) => - b.addEventListener("click", () => { - kind = b.dataset.kindFilter; - showList(); - }), - ); - root.querySelector("#mod-search")?.addEventListener("input", (e) => { - text = e.target.value; - showList(); - }); - const wanted = new URLSearchParams(location.search).get("kind"); - if (KINDS.some(([k]) => k === wanted)) kind = wanted; -} - -setUpTheme(); -setUpMenu(); -render(); -cached("horizon:mod-index", () => fetch(INDEX_URL).then((r) => (r.ok ? r.json() : Promise.reject(new Error(`${r.status}`))))) - .then((index) => { - const fresh = readIndex(index); - if (fresh) { - projects = fresh; - render(); - } - }) - .catch(() => {}); diff --git a/website/src/mods-submit.js b/website/src/mods-submit.js deleted file mode 100644 index c1024495b..000000000 --- a/website/src/mods-submit.js +++ /dev/null @@ -1,80 +0,0 @@ -// /mods/submit: signs in with GitHub through the registry's service, then sends the page and the file. The service -// checks the file and answers with the pull request it opened, or with what to fix. -import { API, entryFrom } from "./mods.js"; -import { setUpMenu, setUpTheme } from "./chrome.js"; -import { escape } from "./markdown.js"; - -const auth = document.getElementById("submit-auth"); -const form = document.getElementById("submit-form"); -const result = document.getElementById("submit-result"); -let csrf = ""; -// The form's own controls by name (form.id and form.name are the form's attributes). -const control = (name) => form.elements.namedItem(name); - -function signedOut(message) { - auth.innerHTML = `

    ${message}

    Sign in with GitHub

    It only reads your public profile: your GitHub name goes on the pull request and in the project's owners.

    `; - form.hidden = true; -} - -async function start() { - let me; - try { - const r = await fetch(`${API}/me`, { credentials: "same-origin" }); - if (r.status === 401) return signedOut("Sign in to submit: reviewers and updates go through your GitHub account."); - if (!r.ok) throw new Error(String(r.status)); - me = await r.json(); - } catch { - auth.innerHTML = `

    The form isn't open right now. You can open a pull request by hand.

    `; - return; - } - csrf = me.csrf; - auth.innerHTML = `

    Signed in as ${escape(me.login)}.

    `; - document.getElementById("sign-out").addEventListener("click", async () => { - await fetch(`${API}/auth/logout`, { method: "POST", credentials: "same-origin" }); - signedOut("Signed out."); - }); - form.hidden = false; -} - -// A file named -. fills in the two fields and the kind. -form.querySelector("#f-file").addEventListener("change", (e) => { - const name = e.target.files[0]?.name || ""; - const m = name.match(/^([a-z0-9_]{1,64})-([A-Za-z0-9][A-Za-z0-9._-]*)\.(hmod|hpack|zip)$/); - const kind = { hmod: "mod", hpack: "modpack", zip: "resourcepack" }[name.split(".").pop()]; - if (kind) control("kind").value = kind; - if (m) { - if (!control("id").value) control("id").value = m[1]; - if (!control("version").value) control("version").value = m[2]; - } -}); - -form.addEventListener("submit", async (e) => { - e.preventDefault(); - const send = form.querySelector("#f-send"); - const values = Object.fromEntries(["id", "kind", "name", "summary", "description", "authors", "license", "source", "icon", "key", "version", "game", "changelog"].map((k) => [k, control(k).value])); - const sig = form.querySelector("#f-signature").files[0]; - values.signature = sig ? await sig.text() : ""; - const body = new FormData(); - body.append("entry", JSON.stringify(entryFrom(values))); - body.append("file", form.querySelector("#f-file").files[0]); - send.disabled = true; - result.innerHTML = `

    Checking the file and opening the pull request…

    `; - try { - const r = await fetch(`${API}/submit`, { method: "POST", body, credentials: "same-origin", headers: { "X-CSRF-Token": csrf } }); - const json = await r.json().catch(() => ({})); - if (r.ok && /^https:\/\/github\.com\//.test(json.pull_request || "")) { - result.innerHTML = `

    Submitted. Follow the review in its pull request: the checks' report is there, and reviewers answer there.

    `; - form.reset(); - } else { - result.innerHTML = `

    ${escape(json.error || `The service answered ${r.status}.`)}

    `; - } - } catch { - result.innerHTML = `

    The service didn't answer. Try again in a minute.

    `; - } finally { - send.disabled = false; - } -}); - -setUpTheme(); -setUpMenu(); -start(); diff --git a/website/src/mods.html b/website/src/mods.html deleted file mode 100644 index 0c0e5eea2..000000000 --- a/website/src/mods.html +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - {{MODS_TITLE}} · Horizon - - - - - - - - - - - - - - - - - - - - -{{SITE_NAV}} -
    -
    -{{MODS_MAIN}} -

    Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

    -
    -
    -{{SITE_FOOTER}} - - - diff --git a/website/src/mods.js b/website/src/mods.js deleted file mode 100644 index 414db7396..000000000 --- a/website/src/mods.js +++ /dev/null @@ -1,189 +0,0 @@ -// Horizon's registry on the site (/mods): the list with its kind filter and search, and a page per project. -// Shared by build.mjs (baked into the pages) and mods-page.js (refreshed from the published index). -// The index's format is docs/api/mod-index.md in the repository. -import { markdown, escape } from "./markdown.js"; - -export const INDEX_URL = "https://ludovic111.github.io/horizon-mods/index.json"; -const REGISTRY = "https://github.com/ludovic111/horizon-mods"; -export const SUBMIT = "/mods/submit"; -// The submission form's service (crates/horizon-mod-registry), behind the site's own address. -export const API = "/api/mods"; -export const SCHEMA = 1; - -// The kinds the site shows, in the filter's order. Kinds a newer index adds are left out until the site knows them. -export const KINDS = [ - ["mod", "Mods"], - ["modpack", "Modpacks"], - ["resourcepack", "Resource packs"], - ["shader", "Shader packs"], -]; -const KIND_NAMES = { mod: "Mod", modpack: "Modpack", resourcepack: "Resource pack", shader: "Shader pack" }; - -// What a capability lets a mod do, as the game and the launcher say it (horizon_mods::Capability::describe). -export const CAPABILITIES = { - "game-read": "see your position, health and the time", - chat: "show you chat messages", - hud: "draw text on your screen", - storage: "save its own settings to disk", - registries: "add blocks and items to your worlds", -}; - -// The index's projects this site can show, or null when it isn't an index it reads. -export function readIndex(index) { - if (!index || typeof index !== "object" || index.schema > SCHEMA || !Array.isArray(index.projects)) return null; - const known = new Set(KINDS.map(([k]) => k)); - return index.projects.filter((p) => known.has(p.kind) && /^[a-z0-9_]{1,64}$/.test(p.id) && p.versions?.length); -} - -const https = (url) => (typeof url === "string" && url.startsWith("https://") ? url : ""); -const size = (bytes) => (bytes >= 1 << 20 ? `${(bytes / (1 << 20)).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`); -const trust = (p) => - p.key ? `Signed` : `Unsigned`; -const initial = (p) => escape((p.name || p.id).trim().charAt(0).toUpperCase()); -const icon = (p) => - https(p.icon) ? `` : ``; - -export function matches(p, kind, text) { - if (kind !== "all" && p.kind !== kind) return false; - const hay = `${p.id} ${p.name} ${p.summary} ${(p.authors || []).join(" ")}`.toLowerCase(); - return text.toLowerCase().split(/\s+/).filter(Boolean).every((w) => hay.includes(w)); -} - -// The list: a row per project, newest version and kind on the right. -export function listHtml(projects) { - if (!projects.length) return `

    Nothing here yet. Submit yours.

    `; - return projects - .map( - (p) => ` - ${icon(p)} - ${escape(p.name)}${escape(p.summary || "")} - ${escape(KIND_NAMES[p.kind] || p.kind)}${escape(p.versions[0].version)} · ${escape((p.authors || []).join(", "))} -`, - ) - .join("\n"); -} - -function installHtml(p, v) { - const file = escape(v.file.name); - const cli = `horizon-launcher mods install --source horizon ${p.id}`; - const where = { - mod: `put it in horizon-mods/ beside options.txt in the game folder, then turn it on in the game: Options > Mods`, - resourcepack: `put it in resourcepacks/ beside options.txt, then turn it on in Options > Resource Packs`, - modpack: `a modpack lists registry mods: install them one by one, or wait for the launcher to install modpacks`, - shader: `Horizon's own shader packs aren't installed yet`, - }[p.kind]; - return `
      -
    1. In the launcher: Mods, pick Horizon beside Modrinth, find ${escape(p.name)} and press Install. It checks the file's checksum${p.key ? " and signature" : ""} first.
    2. -
    3. From a terminal or an agent: ${escape(cli)}
    4. -
    5. By hand: download ${file} (${size(v.file.size)}), check its SHA-256 below, and ${where}.
    6. -
    `; -} - -// GitHub's rule for a login: letters, digits and single dashes, at most 39. -const LOGIN = /^(?!-)(?!.*--)[A-Za-z0-9-]{1,39}(? LOGIN.test(o)); - if (!owners.length) return ""; - const links = owners - .map((o) => `@${o}`) - .join(" "); - return `

    Published by ${links}

    `; -} - -// One project's page. -export function projectHtml(p) { - const v = p.versions[0]; - const caps = v.capabilities || []; - const capsHtml = caps.length - ? `
      ${caps.map((c) => `
    • May ${escape(CAPABILITIES[c] || c)}
    • `).join("")}
    ` - : `

    It asks for nothing beyond writing its own log.

    `; - const requires = (v.requires || []).length - ? `

    Its mods

    ` - : ""; - const versions = p.versions - .map((x) => `
  • ${escape(x.version)} ${escape(x.published || "")} · for ${escape(x.game)}${x.api ? ` · API ${escape(x.api)}` : ""}${x.changelog ? `
    ${markdown(x.changelog)}
    ` : ""}
  • `) - .join(""); - return `
    -
    ${icon(p)}

    ${escape(KIND_NAMES[p.kind] || p.kind)}${escape((p.authors || []).join(", "))}

    ${ownersHtml(p)} -

    ${escape(p.name)}

    ${escape(p.summary || "")}

    -

    ${trust(p)} ${escape(p.license)} ${escape(v.version)}${v.side ? ` ${escape(v.side)}` : ""}

    - ${p.description ? `
    ${markdown(p.description)}
    ` : ""} - ${p.kind === "mod" ? `

    What it may do

    ${capsHtml}

    Mods run in a sandbox with no file, network or clock access. The game refuses a mod whose code uses more than this list.

    ` : ""} - ${requires} -

    Install

    - ${installHtml(p, v)} -

    File

    -
    Name
    ${escape(v.file.name)}
    Size
    ${size(v.file.size)}
    SHA-256
    ${escape(v.file.sha256)}
    ${p.key ? `
    Signing key
    ${escape(p.key)}
    ` : ""}
    -

    Versions

    -
      ${versions}
    - -
    `; -} - -// /mods/submit: the form. Its script (mods-submit.js) signs in, then sends the page and the file to the service, which -// checks the file and opens the pull request the reviewers read. -const field = (name, label, input, hint = "") => - ``; -const text = (name, attrs = "") => ``; - -export function submitHtml() { - return `

    ModsSubmit

    -

    Submit to the registry

    -

    A mod, a modpack of registry mods, or a resource pack made for Horizon. The form checks the file and opens a pull request; a reviewer reads it, its source and the checks' report, and merging publishes it to this site and the launcher.

    -

    First time? Publish a mod walks through building, checking and signing the file, and Make a mod starts from the beginning.

    -
    -

    The form needs JavaScript. You can also open a pull request by hand.

    -
    - `; -} - -// The service's "entry" from the form's values (strings), as it reads it. -export function entryFrom(v) { - const optional = (x) => (x && x.trim() ? x.trim() : undefined); - return { - id: v.id.trim(), - kind: v.kind, - name: v.name.trim(), - summary: v.summary.trim(), - description: v.description || "", - authors: (v.authors || "").split(",").map((a) => a.trim()).filter(Boolean), - license: v.license.trim(), - source: v.source.trim(), - icon: optional(v.icon), - key: optional(v.key), - signature: optional(v.signature), - version: v.version.trim(), - game: v.game.trim(), - changelog: v.changelog || "", - }; -} diff --git a/website/src/mods.test.mjs b/website/src/mods.test.mjs deleted file mode 100644 index c5ff2e783..000000000 --- a/website/src/mods.test.mjs +++ /dev/null @@ -1,63 +0,0 @@ -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { CAPABILITIES, entryFrom, listHtml, matches, projectHtml, readIndex, submitHtml } from "./mods.js"; - -const project = (over = {}) => ({ - id: "coords_hud", kind: "mod", name: "Coordinates HUD", summary: "Where you are.", authors: ["Horizon"], - license: "MIT", source: "https://example.org/src", - versions: [{ version: "0.1.0", api: "0.1", side: "client", capabilities: ["game-read", "hud"], game: "26.3", - file: { name: "coords_hud-0.1.0.hmod", url: "https://github.com/ludovic111/horizon-mods/releases/download/x/coords_hud-0.1.0.hmod", size: 438, sha256: "e".repeat(64) } }], - ...over, -}); - -test("reads schema 1, keeps the kinds it knows and refuses a newer schema", () => { - const index = { schema: 1, projects: [project(), project({ id: "map", kind: "world" }), project({ id: "Bad id" })] }; - assert.deepEqual(readIndex(index).map((p) => p.id), ["coords_hud"]); - assert.equal(readIndex({ schema: 2, projects: [project()] }), null); - assert.equal(readIndex(null), null); -}); - -test("filters by kind and every word", () => { - const p = project(); - assert.ok(matches(p, "all", "coordinates horizon")); - assert.ok(matches(p, "mod", "")); - assert.ok(!matches(p, "modpack", "")); - assert.ok(!matches(p, "all", "zoom")); -}); - -test("escapes what authors wrote and only links https addresses", () => { - const evil = project({ name: "", source: "javascript:alert(1)", summary: '">' }); - const html = listHtml([evil]) + projectHtml(evil); - assert.ok(!html.includes(" - - -
    -
    -

    PrivacyData collection

    -

    Nothing leaves without your yes.

    -

    The Horizon launcher can send a few things that help make the game faster and steadier. It asks first, each kind has its own switch, and every switch is off until you turn it on.

    -
    -

    What can be sent

    -

    Only the kinds you allow, from the launcher's first-run question or Settings → Data collection:

    -
      -
    • Performance statistics, after each play session of a minute or more. These are the frame-time and tick-time percentiles and a 14-bucket histogram (never a recording of each frame), the peak memory, how long the game took to start and to load the world, and the settings that change performance (render and simulation distance, frame limit, VSync, fullscreen, graphics mode).
    • -
    • Crash reports, when the game crashes. They hold the error, where it happened in Horizon's code, your graphics adapter and settings. They hold no log, no world, no server and no resource packs.
    • -
    • Bug reports that you write and send yourself. The end of the game's log goes with one only if you add it after reading it, and lines of chat are removed first.
    • -
    • Benchmark uploads of the benchmarks you run. They are shown publicly on the Benchmarks page, only as medians of groups of at least 3 different installs with the same graphics card, processor and render distance; never one by one, and never with your install ID, the day, your OS version, driver, exact memory or screen.
    • -
    -

    Each one also carries the Horizon version, the day it was made (not the time), and a description of your machine, because that is what explains how fast the game runs on it:

    -
      -
    • the operating system, its version and the processor architecture;
    • -
    • the processor model, its cores and threads, and its base and boost clock where the system gives them;
    • -
    • the memory, rounded to the gigabyte;
    • -
    • the graphics card the game draws with: its model, maker, whether it is built into the processor or separate, its own memory, its driver version and the graphics interface (Vulkan, Metal, DirectX 12);
    • -
    • the kind of drive the game folder is on (NVMe, SSD or hard disk);
    • -
    • the screen the game opened on: its size in pixels, refresh rate and scaling;
    • -
    • whether the computer is a laptop or a desktop, and whether it runs on battery.
    • -
    -

    No serial number, computer name, user name, network address or file path is read. Each item also carries a random install ID. The launcher makes that ID the first time you allow something; it says nothing about you and exists only so that your data can be deleted.

    -

    Never sent: your Microsoft or Minecraft account name or UUID, world names, server or LAN addresses, chat, and your user name or home folder in file paths. Before anything is kept, those are replaced with placeholders, along with e-mail and IP addresses. The server does not store the IP address requests come from.

    -

    The launcher shows exactly what would be sent: Settings → Data collection → View what would be sent, or horizon-launcher data show. Every field is listed in docs/telemetry.md.

    - -

    The "I'm playing" ping

    -

    The game sends an anonymous "I'm playing" ping, so the launcher can show how many people play Horizon right now. It is sent once a minute while you play, whatever the switches say.

    -

    It holds: a random number made when the game starts and forgotten when it closes, the Horizon version, your operating system (Linux, macOS or Windows), and whether you have a world open to LAN or to friends. It does not hold: your account, your install ID, world or server names, your hardware or settings, or anything you do in the game. The random number changes every time you start the game, so two of your sessions can't be linked to each other or to you.

    -

    The server keeps the pings in memory only, never on disk, and not with the address they came from (that is used only to stop abuse, as below). A session counts while it pinged in the last two minutes and is then forgotten. What it shows is the number playing now, per version and with a world open, rounded.

    - -

    Why

    -

    To find what is slow or crashes on which machines, and fix it. The ping shows players, and Horizon, how many people play right now. Benchmark uploads also show other players how Horizon runs on hardware like theirs. Nothing is sold, shared for advertising, or used to identify you.

    - -

    On what basis

    -

    For the switches: your consent (Article 6(1)(a) of the EU's General Data Protection Regulation). It is given kind by kind, recorded on your computer with the version of the question you answered and when, and withdrawn at any time with the same switches. Withdrawing deletes what was waiting to be sent. When what is collected changes, the launcher asks again, and nothing new is sent until you answer. The ping holds nothing that identifies you; the address it comes from is used only to limit how often one address may send, kept in memory for an hour at most and never stored.

    - -

    Where and how long

    -

    Items wait on your computer (telemetry/ in the game folder) and are sent compressed when the launcher starts or closes, to Horizon's own server, telemetry.playhorizon.dev, hosted by Railway in the European Union (Amsterdam, the Netherlands). The server keeps them for 180 days, then deletes them. What stays after that are anonymous totals per day, Horizon version, operating system, GPU maker and render distance (for example "120 sessions on macOS with Apple GPUs at render distance 12"). They hold no install ID, and groups too small to be anonymous are never shown. Published results also show how players split by memory size (in steps: 8, 16, 32 GB…), graphics memory, drive type, operating system and built-in or separate graphics, each class only once it holds at least 3 different installs; the exact values, the driver, the clocks and the screen are never published.

    - -

    Deleting your data

    -

    Settings → Data collection → Delete my data, or horizon-launcher data delete. The server deletes everything sent under your install ID, your share of the totals is recomputed, anything waiting on your computer is removed, and you get a new install ID. You can also turn everything off, or delete the telemetry/ folder.

    - -

    Your rights and contact

    -

    Horizon is made by Ludovic Marie, who is responsible for this data. To ask for a copy of what was sent under your install ID, have it corrected or deleted, or ask anything about it, write through lu4ovic.com (give your install ID, shown in Settings → Data collection). You can also complain to the data protection authority where you live.

    -

    This website itself sets no cookies and has no analytics; its footer says what it loads from GitHub.

    -
    - -

    Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

    -
    -
    - - - diff --git a/website/src/releases-page.js b/website/src/releases-page.js deleted file mode 100644 index ace84f63d..000000000 --- a/website/src/releases-page.js +++ /dev/null @@ -1,78 +0,0 @@ -// The Releases page: the list baked at build time, refreshed from GitHub when a newer release is out, and the -// channel filter. Without JavaScript the baked list reads as it is. -import { releasesPageHtml } from "./releases.js"; -import { isGame, isLauncher, newestFirst } from "./versions.js"; -import { cached, get, setUpMenu, setUpTheme, slim } from "./chrome.js"; - -const REPO = "ludovic111/horizon"; -const list = document.getElementById("release-list"); -const counter = document.querySelector("[data-release-count]"); -const buttons = [...document.querySelectorAll("[data-filter]")]; -let filter = "all"; - -const ours = (r) => !r.draft && (isGame(r.tag_name) || isLauncher(r.tag_name)); - -// Every release, a page of 100 at a time (GitHub's most), up to 500. -async function loadAll() { - const all = []; - for (let page = 1; page <= 5; page++) { - const batch = await get(`https://api.github.com/repos/${REPO}/releases?per_page=100&page=${page}`); - all.push(...batch.filter(ours).map(slim)); - if (batch.length < 100) break; - } - return all; -} - -function apply() { - const entries = [...list.querySelectorAll(".release-entry")]; - let shown = 0; - for (const el of entries) { - const on = filter === "all" || el.dataset.channel === filter; - el.hidden = !on; - if (on) shown++; - } - counter.textContent = `${shown} release${shown === 1 ? "" : "s"}`; - buttons.forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.filter === filter))); -} - -async function refresh() { - // One small request first: the full list only when GitHub has something newer than the page. - const newest = await cached("horizon:releases-newest", () => get(`https://api.github.com/repos/${REPO}/releases?per_page=5`)).catch(() => null); - if (!newest) return; - const top = newest.filter(ours).map((r) => r.tag_name).sort(newestFirst)[0]; - if (!top || top === list.dataset.newest) return; - const all = await cached("horizon:releases-all", loadAll).catch(() => null); - if (!all || !all.length) return; - const open = new Set([...list.querySelectorAll(".release-entry[open]")].map((el) => el.id)); - list.innerHTML = releasesPageHtml(all); - list.dataset.newest = top; - // Keep what the reader opened open. - open.forEach((id) => document.getElementById(id)?.setAttribute("open", "")); - apply(); -} - -// A link to one release (/releases#release-v0.2.1) opens it. -function openTarget() { - const el = location.hash && document.getElementById(location.hash.slice(1)); - if (el && el.classList.contains("release-entry")) { - if (el.hidden) { - filter = "all"; - apply(); - } - el.open = true; - el.scrollIntoView(); - } -} - -buttons.forEach((b) => - b.addEventListener("click", () => { - filter = b.dataset.filter; - apply(); - }), -); -addEventListener("hashchange", openTarget); -setUpTheme(); -setUpMenu(); -apply(); -openTarget(); -refresh().then(openTarget); diff --git a/website/src/releases.html b/website/src/releases.html deleted file mode 100644 index 989164653..000000000 --- a/website/src/releases.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - Releases · Horizon - - - - - - - - - - - - - - - - - - - - - -{{SITE_NAV}} -
    -
    -

    ReleasesEvery version, newest first

    -

    What's new in Horizon

    -

    Each release lists what it adds and fixes, then its full notes and its downloads. New versions come out many times a day as changes land, and the launcher installs each one once it has passed its test. The launcher has its own releases.

    -
    - - - -
    -

    {{RELEASE_COUNT}}

    -
    -{{RELEASE_LIST}} -
    -

    The releases on GitHub

    -

    Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

    -
    -
    -{{SITE_FOOTER}} - - diff --git a/website/src/releases.js b/website/src/releases.js deleted file mode 100644 index d4932e7f7..000000000 --- a/website/src/releases.js +++ /dev/null @@ -1,156 +0,0 @@ -// The release notes on the site: the home page's "Recently added" block and the Releases page (every release, -// newest first). Shared by build.mjs (baked into the pages) and the pages' scripts (refreshed from GitHub). -// Tags: the game's vX.Y.Z and the launcher's launcher@X.Y.Z from 0.2, vYYYY.MM.DD[.N] and launcher-vX.Y.Z before -// (src/versions.js). One channel (docs/release-flow.md, "One channel"): a release is the game's or the launcher's. -import { markdown, inline, escape } from "./markdown.js"; -import { isLauncher, launcherVersion, newestFirst } from "./versions.js"; - -const REPO = "ludovic111/horizon"; - -export const channel = (r) => (isLauncher(r.tag_name) ? "Launcher" : "Game"); -const anchor = (r) => `release-${r.tag_name.replace(/[^\w.-]/g, "-")}`; - -// "Horizon 0.2.3: Cave culling, weather" (before 0.2, "Horizon 2026.10.13: …") reads as the version and its line. -export function parts(r) { - const version = launcherVersion(r.tag_name) ?? r.tag_name.replace(/^v/, ""); - const name = (r.name || "").trim(); - let line = name.includes(": ") ? name.slice(name.indexOf(": ") + 2) : name.replace(/^Horizon( launcher)?\s*/i, "").replace(version, "").trim(); - if (junk(line)) line = fromNotes(r.body) || line; - return { version, line: line.charAt(0).toUpperCase() + line.slice(1), date: (r.published_at || "").slice(0, 10) }; -} - -// A title made of issue numbers and "fix" ("#1255, mob pushes, fix, #1222") says nothing. -const junk = (line) => { - const bits = line.split(",").map((b) => b.trim()).filter(Boolean); - return bits.length > 1 && bits.filter((b) => /^(#\d+|fix(es)?|fixed)$/i.test(b)).length * 2 >= bits.length; -}; - -// The first item that isn't a bare "Fix #123:" prefix, as the line: "Mob pushes: one list per mob… and 3 more fixes". -function fromNotes(body) { - const s = sections(body); - const items = [...s.filter((x) => /^new|what's new/i.test(x.title)), ...s.filter((x) => /^fixed/i.test(x.title))].flatMap((x) => x.items).map(plainItem); - const clean = items.map((i) => i.replace(/^(fix|fixes)\s+#\d+:\s*/i, "").replace(/^\w+\([^)]*\):\s*/, "")).filter(Boolean); - if (!clean.length) return ""; - const first = clean[0].replace(/[.]$/, ""); - return clean.length > 1 ? `${first} and ${clean.length - 1} more` : first; -} - -// The notes' "### Heading" sections and their top-level items, in order. -export function sections(body) { - const out = []; - let current = null; - for (const raw of (body || "").replace(/\r\n?/g, "\n").split("\n")) { - const heading = raw.match(/^#{2,3}\s+(.+?)\s*$/); - if (heading) out.push((current = { title: heading[1], items: [] })); - else if (current && /^[-*]\s+/.test(raw)) current.items.push(raw.replace(/^[-*]\s+/, "").trim()); - } - return out; -} - -// An item without its pull request references: "Riptide (#123, fixes #45)" -> "Riptide". -export const plainItem = (item) => item.replace(/\s*\((?:#\d+|fixes #\d+|[^()]*#\d+[^()]*)\)\s*/g, " ").replace(/\s+/g, " ").trim(); - -// A game release's notes open with an HTML block sending people to the launcher (PLAYERS in tools/release_train.py): -// GitHub's latest release is the game's. This site has its own download button, so it leaves the block out. -export const notesText = (body) => (body || "").replace(/^

    Want to play\?[^\n]*(?:\r?\n)*/, ""); - -// The notes' first sentence, for a release with no title line and no sections ("Rebuilt from the latest main."). -const firstLine = (body) => (notesText(body).split(/\r?\n/).find((l) => l.trim() && !/^#/.test(l)) || "").trim().replace(/[.:]$/, ""); - -const count = (n, one, many) => `${n} ${n === 1 ? one : many}`; - -// What a release changes, in a line: "12 new, 30 fixed, 2 known issues". -export function overview(r) { - const s = sections(r.body); - const by = (re) => s.filter((x) => re.test(x.title)).reduce((n, x) => n + x.items.length, 0); - const added = by(/^new|what's new/i); - const fixed = by(/^fixed/i); - const known = by(/^known/i); - const bits = []; - if (added) bits.push(count(added, "new feature", "new features")); - if (fixed) bits.push(count(fixed, "fix", "fixes")); - if (known) bits.push(count(known, "known issue", "known issues")); - return { added, fixed, known, text: bits.join(", ") }; -} - -export function highlights(r, n = 3) { - const added = sections(r.body).filter((x) => /^new|what's new/i.test(x.title)).flatMap((x) => x.items); - return added.slice(0, n).map(plainItem); -} - -const byTag = (a, b) => newestFirst(a.tag_name, b.tag_name); -const badge = (r) => `${channel(r)}`; - -// The home page: the newest releases on a line each, and what the newest ones added. -export function recentHtml(list, { rows = 5, picks = 3 } = {}) { - const sorted = [...list].sort(byTag); - const game = sorted.filter((r) => !isLauncher(r.tag_name)); - if (!game.length) return ""; - const lines = game - .slice(0, rows) - .map((r) => { - const p = parts(r); - return `
  • ${escape(p.version)}${escape(p.line || overview(r).text || firstLine(r.body) || "Release notes")}${badge(r)}
  • `; - }) - .join(""); - // What landed last: the "New" items of the newest releases with the highest pull request numbers (a release's - // notes list everything since the release before it, oldest first). - const pr = (item) => Math.max(0, ...[...item.matchAll(/#(\d+)/g)].map((m) => Number(m[1]))); - const seen = new Set(); - const picked = game - .slice(0, rows) - .flatMap((r) => sections(r.body).filter((x) => /^new|what's new/i.test(x.title)).flatMap((x) => x.items).map((raw) => ({ raw, item: plainItem(raw), r }))) - .filter(({ item }) => !seen.has(item) && seen.add(item)) - .sort((a, b) => pr(b.raw) - pr(a.raw)) - .slice(0, picks); - const picks_ = picked - .map(({ item, r }) => `
  • ${inline(item)}

    ${escape(parts(r).version)}
  • `) - .join(""); - return `
      ${lines}
    - ${picks_ ? `

    New lately

      ${picks_}
    ` : ""} -

    Every release, with its full notes

    `; -} - -const ASSET_LABELS = [ - [/linux-x86_64/, "Linux x86-64"], - [/macos-arm64/, "macOS, Apple Silicon"], - [/macos-x86_64/, "macOS, Intel"], - [/windows-x64/, "Windows x64"], -]; -function assetLabel(name) { - if (/^SHA256SUMS/.test(name)) return name.endsWith(".sig") ? "Checksums signature" : "Checksums"; - const os = ASSET_LABELS.find(([re]) => re.test(name)); - const what = /server/.test(name) ? "Server" : /launcher/.test(name) ? "Launcher" : /smoke-test/.test(name) ? "Smoke test" : "Game"; - return os ? `${what}, ${os[1]}` : name; -} -const size = (bytes) => (bytes >= 1e6 ? `${(bytes / 1e6).toFixed(0)} MB` : bytes >= 1e3 ? `${(bytes / 1e3).toFixed(0)} kB` : `${bytes} B`); - -function releaseHtml(r, open) { - const p = parts(r); - const o = overview(r); - const top = highlights(r, 4); - const downloads = (r.assets || []) - .map((a) => `
  • ${escape(assetLabel(a.name))}${escape(a.name)} · ${size(a.size || 0)}
  • `) - .join(""); - return `
    - ${escape(p.version)}${badge(r)}${escape(p.line)} -
    - ${o.text || top.length ? `
    - ${o.text ? `

    ${escape(o.text)}

    ` : ""} - ${top.length ? `
      ${top.map((t) => `
    • ${inline(t)}
    • `).join("")}
    ` : ""} -
    ` : ""} -
    ${markdown(notesText(r.body)) || "

    No notes for this release.

    "}
    - ${downloads ? `

    Downloads

      ${downloads}
    ` : ""} -

    This release on GitHub

    -
    -
    `; -} - -// The Releases page: every release, newest first; the newest few open. -export function releasesPageHtml(list, { open = 3 } = {}) { - const sorted = [...list].sort(byTag); - if (!sorted.length) return ""; - return sorted.map((r, i) => releaseHtml(r, i < open)).join("\n"); -} - -export const releasesUrl = `https://github.com/${REPO}/releases`; diff --git a/website/src/releases.test.mjs b/website/src/releases.test.mjs deleted file mode 100644 index acd1a0965..000000000 --- a/website/src/releases.test.mjs +++ /dev/null @@ -1,13 +0,0 @@ -// node --test src/: the release notes as the site shows them. -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { notesText } from "./releases.js"; - -const players = '

    Want to play? Download the Horizon launcher, not the files below

    It installs this version.

    '; - -test("the block sending people to the launcher is left out, the notes stay", () => { - assert.equal(notesText(`${players}\n\n### Fixed\n- A fix (#1)\n`), "### Fixed\n- A fix (#1)\n"); - assert.equal(notesText(`${players}\r\n\r\nRebuilt from the latest main.\r\n`), "Rebuilt from the latest main.\r\n"); - assert.equal(notesText("

    Other HTML

    \n\n### New\n- A thing (#2)\n"), "

    Other HTML

    \n\n### New\n- A thing (#2)\n"); - assert.equal(notesText(undefined), ""); -}); diff --git a/website/src/style.css b/website/src/style.css deleted file mode 100644 index 1de2a3d3d..000000000 --- a/website/src/style.css +++ /dev/null @@ -1,918 +0,0 @@ -/* Horizon's design language (docs/design-system.md), set as a page. The tokens come from - crates/horizon-theme through src/tokens.css, which build.mjs puts before this file: the - launcher's Blocks palettes, type, spacing and motion. The base below lays out the page; the - "Blocks" section at the end gives it the launcher's blocky, Minecraft-like look. */ - -@font-face { font-family: "Geist"; src: url("/fonts/Geist-Regular.woff2") format("woff2"); font-weight: 400; font-display: swap; } -@font-face { font-family: "Geist"; src: url("/fonts/Geist-Medium.woff2") format("woff2"); font-weight: 500; font-display: swap; } -@font-face { font-family: "Geist"; src: url("/fonts/Geist-SemiBold.woff2") format("woff2"); font-weight: 600; font-display: swap; } -@font-face { font-family: "Geist Mono"; src: url("/fonts/GeistMono-Regular.woff2") format("woff2"); font-weight: 400; font-display: swap; } - -:root { - --g: clamp(var(--gutter-narrow), 4.5vw, var(--gutter)); - --max: 1440px; - --nav: 72px; -} - -*, *::before, *::after { box-sizing: border-box; } - -html { - background: var(--page); - color: var(--ink); - font: 400 var(--text-body) / var(--text-body-line) var(--font); - font-synthesis: none; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; - text-rendering: optimizeLegibility; - scroll-behavior: smooth; - scroll-padding-top: calc(var(--nav) + 16px); - transition: background-color var(--move) var(--ease-move), color var(--move) var(--ease-move); -} -body { margin: 0; min-height: 100vh; overflow-x: clip; } -img { display: block; max-width: 100%; height: auto; } -h1, h2, h3 { margin: 0; font-weight: var(--text-heading-weight); } -p { margin: 0; } -ol, ul { margin: 0; padding: 0; list-style: none; } -::selection { background: var(--accent); color: var(--on-accent); } - -a { color: var(--accent); text-decoration: none; transition: color var(--quick) var(--ease-quick); } -a:hover { color: var(--ink); } -[hidden] { display: none !important; } -/* Links inside running text are underlined, so they don't rely on colour alone. */ -p a:not(.button):not(.link-arrow), li > p a, .prose a { - color: inherit; text-decoration: underline; text-decoration-color: var(--rule); - text-decoration-thickness: 1px; text-underline-offset: 3px; - transition: text-decoration-color var(--quick) var(--ease-quick); -} -p a:not(.button):not(.link-arrow):hover, li > p a:hover, .prose a:hover { text-decoration-color: currentColor; } -:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; border-radius: var(--radius); } - -code { - font: 0.86em/1.5 var(--mono); - background: var(--plate-soft); - border-radius: 4px; - padding: 1px 5px; - overflow-wrap: anywhere; -} - -.sr-only { - position: absolute; width: 1px; height: 1px; overflow: hidden; - clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; -} -.skip { - position: fixed; left: var(--g); top: 12px; z-index: 50; padding: 8px 14px; - background: var(--ink); color: var(--page); border-radius: var(--radius-pill); - transform: translateY(-200%); -} -.skip:focus { transform: none; } - -.container { width: 100%; max-width: var(--max); margin: 0 auto; padding: 0 var(--g); } - -/* --- Type ----------------------------------------------------------------------------- */ - -.display { - font-size: var(--text-display); line-height: var(--text-display-line); - letter-spacing: var(--text-display-tracking); font-weight: var(--text-display-weight); - text-wrap: balance; -} -.title { - font-size: var(--text-title); line-height: var(--text-title-line); - letter-spacing: var(--text-title-tracking); font-weight: var(--text-title-weight); - text-wrap: balance; -} -.lede { max-width: var(--measure); color: var(--muted); text-wrap: pretty; } -.kicker, .meta, .download-meta, .eyebrow, .row-index, .row-meta, .disclaimer { - font: var(--text-micro-weight) var(--text-micro) / var(--text-micro-line) var(--mono); - letter-spacing: var(--text-micro-tracking); - color: var(--muted); -} -.kicker { display: flex; gap: 16px; text-transform: uppercase; margin-bottom: 24px; } -.kicker span { color: var(--ink); } -.meta { margin-top: 16px; } -.download-meta { margin-top: 12px; } -.download-meta a { color: inherit; } - -/* --- Buttons --------------------------------------------------------------------------- */ - -.button { - display: inline-flex; align-items: center; justify-content: center; gap: 8px; - height: var(--control); padding: 0 16px; border: 0; border-radius: var(--radius-pill); - font: 500 var(--text-label) / 1 var(--font); cursor: pointer; white-space: nowrap; - transition: background-color var(--quick) var(--ease-quick), color var(--quick) var(--ease-quick), opacity var(--quick) var(--ease-quick); -} -.button.large { height: var(--control-large); padding: 0 22px; font-size: var(--text-ui); } -.button.small { height: 30px; padding: 0 14px; } -.button.primary { background: var(--accent); color: var(--on-accent); } -.button.primary:hover { color: var(--on-accent); opacity: 0.88; } -.button.secondary { background: var(--plate-soft); color: var(--ink); } -.button.secondary:hover { background: var(--plate); color: var(--ink); } -.button.ghost { background: transparent; color: var(--muted); } -.button.ghost:hover { background: var(--plate-soft); color: var(--ink); } -.button:active { opacity: 0.85; } - -.link-arrow { display: inline-flex; gap: 8px; color: var(--accent); font-weight: 500; } -.link-arrow span { transition: transform var(--quick) var(--ease-quick); } -.link-arrow:hover span { transform: translateX(3px); } - -/* --- Navigation ------------------------------------------------------------------------- */ - -.nav { - position: fixed; inset: 0 0 auto; z-index: 20; height: var(--nav); max-width: 100vw; - background: color-mix(in srgb, var(--page) 88%, transparent); - -webkit-backdrop-filter: blur(16px) saturate(1.2); backdrop-filter: blur(16px) saturate(1.2); - box-shadow: 0 1px 0 var(--rule); - transition: background-color var(--move) var(--ease-move), box-shadow var(--move) var(--ease-move); -} -.nav-inner { display: flex; align-items: center; gap: 24px; height: 100%; max-width: var(--max); margin: 0 auto; padding: 0 var(--g); } -.nav-mark { display: inline-flex; align-items: center; gap: 10px; color: var(--ink); font-weight: 500; font-size: var(--text-label); } -.nav-mark:hover { color: var(--ink); } -.mark { width: 18px; height: 18px; } -.mark-stem { fill: var(--ink); } -.mark-low { fill: var(--ink); opacity: 0.36; } -.mark-line { fill: var(--accent); } -.nav-links { display: flex; gap: 2px; margin-left: auto; white-space: nowrap; } -.nav-links a, .nav-github, .theme-toggle { - display: inline-flex; align-items: center; height: 32px; padding: 0 12px; - border-radius: var(--radius-pill); color: var(--muted); font-size: var(--text-label); - transition: background-color var(--quick) var(--ease-quick), color var(--quick) var(--ease-quick); -} -.nav-links a:hover, .nav-github:hover, .theme-toggle:hover { color: var(--ink); background: var(--plate-soft); } -.nav-links a[aria-current] { color: var(--ink); background: var(--plate-soft); } -.nav-end { display: flex; align-items: center; gap: 2px; } -.theme-toggle { - border: 0; background: none; cursor: pointer; - font: var(--text-micro) / 1 var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; -} -.nav-end .button { margin-left: 8px; } -.menu-button { - display: none; align-items: center; gap: 10px; height: 44px; padding: 0 4px 0 14px; margin-left: 4px; - border: 0; background: none; color: var(--ink); font: 500 var(--text-label) / 1 var(--font); cursor: pointer; -} -.menu-icon { position: relative; width: 18px; height: 10px; } -.menu-icon::before, .menu-icon::after { - content: ""; position: absolute; left: 0; right: 0; height: 1.5px; border-radius: 1px; background: currentColor; - transition: transform var(--move) var(--ease-move), top var(--move) var(--ease-move); -} -.menu-icon::before { top: 0; } -.menu-icon::after { top: 8px; } -.is-menu .menu-icon::before { top: 4px; transform: rotate(45deg); } -.is-menu .menu-icon::after { top: 4px; transform: rotate(-45deg); } - -.menu { - position: fixed; inset: var(--nav) 0 0; z-index: 19; display: flex; flex-direction: column; max-width: 100vw; - justify-content: space-between; gap: 24px; overflow-y: auto; padding: 24px var(--g) 32px; background: var(--page); - opacity: 0; transition: opacity var(--move) var(--ease-move); -} -.menu.is-open { opacity: 1; } -.menu nav { display: flex; flex-direction: column; flex-shrink: 0; } -.menu nav a { - display: flex; align-items: baseline; gap: 16px; padding: 12px 0; border-bottom: 1px solid var(--rule); - color: var(--ink); font-size: var(--text-title); line-height: var(--text-title-line); - letter-spacing: var(--text-title-tracking); font-weight: 500; - opacity: 0; transform: translateY(var(--rise)); - transition: opacity var(--enter) var(--ease-enter), transform var(--enter) var(--ease-enter); -} -.menu.is-open nav a { opacity: 1; transform: none; } -.menu-foot { display: flex; flex-direction: column; gap: 16px; flex-shrink: 0; } -.menu-foot p { font-size: var(--text-caption); color: var(--muted); } - -@media (max-width: 1279px) { - .nav-links, .nav-github { display: none; } - .menu-button { display: inline-flex; } - .nav-end { margin-left: auto; } -} -@media (max-width: 520px) { - .nav-end .button { display: none; } -} - -/* --- Index lists: the signature component ------------------------------------------------ */ - -.index { border-top: 1px solid var(--rule); } -.row { position: relative; border-bottom: 1px solid var(--rule); } -.row > a, .row.card { - position: relative; display: grid; grid-template-columns: var(--index) 1fr auto; align-items: baseline; - column-gap: 16px; padding: 18px 0; color: var(--ink); -} -.row-index { transition: color var(--quick) var(--ease-quick); } -.row-name { font-size: var(--text-title); line-height: var(--text-title-line); letter-spacing: var(--text-title-tracking); font-weight: 500; } -.row-meta { text-align: right; } -/* Hover: a soft plate fades in behind the row and reaches past it; the index turns to ink. */ -.row > a::before, .row.card::before { - content: ""; position: absolute; inset: 0 calc(-1 * var(--plate-bleed)); z-index: -1; - border-radius: var(--radius-plate); background: var(--plate-soft); opacity: 0; - transition: opacity var(--quick) var(--ease-quick); -} -.row > a, .row.card { z-index: 0; } -.row > a:hover::before, .row.card:hover::before { opacity: 1; } -.row > a:hover .row-index, .row.card:hover .row-index { color: var(--ink); } -.row > a:hover, .row.card:hover { color: var(--ink); } - -/* --- Hero -------------------------------------------------------------------------------- */ - -.hero { padding: calc(var(--nav) + clamp(48px, 9vw, 120px)) 0 clamp(64px, 8vw, 112px); } -.hero-title { max-width: 14ch; margin-bottom: 20px; } -.hero .lede { font-size: var(--text-body); } -.hero-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 32px; } -.hero-index { margin-top: clamp(48px, 7vw, 88px); } -.hero .disclaimer { margin-top: 24px; } - -/* --- Sections ------------------------------------------------------------------------------- */ - -.section { padding: clamp(72px, 10vw, 144px) 0; } -.section-head { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 16px 48px; align-items: end; margin-bottom: 48px; } -.section-head .kicker { grid-column: 1 / -1; margin-bottom: 0; } -.section .title { font-size: var(--text-display); line-height: var(--text-display-line); letter-spacing: var(--text-display-tracking); } - -.statement { - max-width: 28ch; font-size: var(--text-title); line-height: 1.15; - letter-spacing: var(--text-title-tracking); font-weight: 500; text-wrap: balance; -} -.facts { margin-top: 56px; } -.fact, .features li { - display: grid; grid-template-columns: var(--index) minmax(0, 18rem) minmax(0, 1fr); column-gap: 16px; - align-items: baseline; padding: 20px 0; -} -.fact h3, .features h3 { font-size: var(--text-heading); line-height: var(--text-heading-line); letter-spacing: var(--text-heading-tracking); } -.fact p, .features p { max-width: var(--measure); color: var(--muted); } - -/* Screenshots: no frames, the images themselves. */ -.mosaic { display: grid; grid-template-columns: repeat(6, 1fr); gap: 12px; } -.tile { margin: 0; grid-column: span 2; } -.tile-wide { grid-column: span 4; } -.tile-tall { grid-column: span 2; } -.tile-wide, .tile-tall { grid-row: span 1; } -.zoom { display: block; width: 100%; padding: 0; border: 0; background: var(--plate-soft); border-radius: var(--radius-plate); overflow: hidden; cursor: zoom-in; } -.zoom img { width: 100%; aspect-ratio: 16 / 9; object-fit: cover; transition: transform var(--enter) var(--ease-enter); } -.zoom:hover img { transform: scale(1.02); } -figcaption { display: flex; gap: 12px; margin-top: 10px; font-size: var(--text-caption); color: var(--muted); } -figcaption span { font-family: var(--mono); font-size: var(--text-micro); letter-spacing: var(--text-micro-tracking); padding-top: 1px; } - -/* Parity: the count, then every subsystem as an index row. */ -.parity-hero { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 48px; align-items: end; margin-bottom: 64px; } -.count { font-size: clamp(96px, 16vw, 220px); line-height: 0.85; letter-spacing: -0.05em; font-weight: 500; } -.count .digits span { display: inline-block; } -.count-label { margin-top: 20px; max-width: 32ch; color: var(--muted); } -.parity-copy .title { margin-bottom: 16px; } -.prose { color: var(--ink-soft); max-width: var(--measure); } -.prose > * + * { margin-top: 12px; } -.systems { border-top: 1px solid var(--rule); } -.system { - display: grid; grid-template-columns: var(--index) minmax(0, 1fr) auto; column-gap: 16px; row-gap: 6px; - padding: 20px 0; border-bottom: 1px solid var(--rule); position: relative; -} -.system-head { display: contents; } -.system-index { grid-column: 1; grid-row: 1; font: var(--text-micro) / var(--text-micro-line) var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); padding-top: 0.6em; } -.system h3 { grid-column: 2; grid-row: 1; font-size: var(--text-heading); line-height: var(--text-heading-line); letter-spacing: var(--text-heading-tracking); } -.system-state { - grid-column: 3; grid-row: 1; display: inline-flex; align-items: center; gap: 6px; padding-top: 0.5em; - font: var(--text-micro) / var(--text-micro-line) var(--mono); letter-spacing: var(--text-micro-tracking); - text-transform: uppercase; color: var(--muted); -} -.system.is-full .system-state { color: var(--success); } -.check { width: 12px; height: 12px; fill: none; stroke: currentColor; stroke-width: 1.6; } -.system-detail { grid-column: 2 / 4; max-width: 72ch; font-size: var(--text-caption); line-height: 1.6; color: var(--muted); } -.gap { color: var(--ink); font-weight: 500; } -.legend { max-width: 80ch; } - -/* The launcher: copy and features on the left, the menus on the right. */ -.launcher-grid { display: grid; grid-template-columns: minmax(0, 5fr) minmax(0, 7fr); gap: clamp(32px, 5vw, 80px); align-items: start; } -.launcher-copy .title { margin-bottom: 16px; } -.launcher-copy .features { margin-top: 40px; } -.features li { grid-template-columns: var(--index) minmax(0, 1fr); row-gap: 4px; } -.features li p { grid-column: 2; font-size: var(--text-ui); } -.launcher-actions { margin-top: 32px; } -.screens { position: sticky; top: calc(var(--nav) + 24px); } -.tabs { position: relative; display: inline-flex; padding: 2px; gap: 2px; margin-bottom: 16px; border-radius: var(--radius-pill); background: var(--plate-soft); } -.tabs button { - position: relative; z-index: 1; height: var(--segment); padding: 0 14px; border: 0; background: none; - border-radius: var(--radius-pill); color: var(--muted); font: 500 var(--text-label) / 1 var(--font); cursor: pointer; - transition: color var(--quick) var(--ease-quick); -} -.tabs button:hover { color: var(--ink); } -.tabs button[aria-selected="true"] { color: var(--page); } -.tab-pill { position: absolute; top: 0; left: 0; border-radius: var(--radius-pill); background: var(--ink); transition: transform var(--move) var(--ease-move), width var(--move) var(--ease-move); } -.screen { position: relative; aspect-ratio: 16 / 10; border-radius: var(--radius-plate); overflow: hidden; background: var(--plate-soft); } -.screen-panel { position: absolute; inset: 0; opacity: 0; transition: opacity var(--move) var(--ease-move); } -.screen-panel.is-active { opacity: 1; } -.screen-panel img { width: 100%; height: 100%; object-fit: cover; } -.screen-caption { margin-top: 12px; font-size: var(--text-caption); color: var(--muted); } - -/* Patch notes. */ -.eyebrow { text-transform: uppercase; } -.prose h2, .prose h3, .prose h4 { font-size: var(--text-heading); line-height: var(--text-heading-line); color: var(--ink); margin-top: 28px; } -.prose ul, .prose ol { padding-left: 18px; list-style: disc; } -.prose li + li { margin-top: 6px; } -.prose li::marker { color: var(--muted); } -.prose strong { color: var(--ink); font-weight: 500; } -.prose pre { padding: 16px; border-radius: var(--radius-plate); background: var(--plate-soft); overflow-x: auto; } -.prose pre code { background: none; padding: 0; } -.release { border-top: 1px solid var(--rule); } -.release:last-of-type { border-bottom: 1px solid var(--rule); } -.release summary { - display: grid; grid-template-columns: minmax(0, 12rem) minmax(0, 1fr) auto; gap: 16px; align-items: baseline; - padding: 18px 0; cursor: pointer; list-style: none; -} -.release summary::-webkit-details-marker { display: none; } -.release-tag { font-size: var(--text-heading); font-weight: 500; letter-spacing: var(--text-heading-tracking); } -.release-sub { color: var(--muted); font-size: var(--text-ui); } -.release time { font: var(--text-micro) / 1 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); } -.release[open] summary .release-tag { color: var(--accent); } -.release .prose { padding: 0 0 24px 12rem; margin-left: 16px; font-size: var(--text-ui); } -.release-more { margin-top: 24px; } - -/* Community. */ -.cards { margin-top: 48px; } -.row.card { grid-template-columns: var(--index) minmax(0, 1fr) minmax(0, 1.4fr) auto; } -.card-title { font-size: var(--text-title); line-height: var(--text-title-line); letter-spacing: var(--text-title-tracking); font-weight: 500; } -.card-text { color: var(--muted); } -.card-arrow { color: var(--muted); transition: transform var(--quick) var(--ease-quick), color var(--quick) var(--ease-quick); } -.card:hover .card-arrow { color: var(--accent); transform: translateX(4px); } -.contributors { margin-top: 96px; } -.contributors-title { font-size: var(--text-heading); line-height: var(--text-heading-line); } -.contributors-text { margin-top: 8px; color: var(--muted); } -.contributors-list { margin-top: 24px; display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 0 24px; border-top: 1px solid var(--rule); } -.contributor { display: grid; grid-template-columns: 32px 1fr; column-gap: 12px; align-items: center; padding: 14px 0; border-bottom: 1px solid var(--rule); color: var(--ink); } -.contributor-avatar { grid-row: span 2; width: 32px; height: 32px; border-radius: 50%; background: var(--plate); } -.contributor-name { font-weight: 500; } -.contributor-count { font: var(--text-micro) / 1.4 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); } -.contributor:hover .contributor-name { color: var(--accent); } - -/* --- Footer: small print, then the giant faint wordmark --------------------------------- */ - -.footer { padding: clamp(72px, 9vw, 120px) 0 0; overflow: hidden; } -.footer-disclaimer { max-width: 24ch; font-size: var(--text-heading); line-height: var(--text-heading-line); letter-spacing: var(--text-heading-tracking); font-weight: 500; } -.footer-cols { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 32px; margin-top: 40px; } -.footer-cols p { font-size: var(--text-caption); line-height: 1.7; color: var(--muted); } -.footer-bar { display: flex; justify-content: space-between; align-items: center; gap: 24px; margin-top: 56px; font-size: var(--text-caption); color: var(--muted); } -.footer-links { display: flex; flex-wrap: wrap; gap: 20px; } -.footer-links a { color: var(--muted); } -.footer-links a:hover { color: var(--ink); } -.footer-word { - box-sizing: border-box; width: 100%; margin: 24px auto 0; padding: 0 var(--g); max-width: var(--max); - font-size: var(--text-wordmark); line-height: var(--text-wordmark-line); letter-spacing: var(--text-wordmark-tracking); - font-weight: var(--text-wordmark-weight); color: var(--plate); white-space: nowrap; user-select: none; - translate: -0.05em 0.12em; -} -:root[data-theme="dark"] .footer-word { color: var(--plate-soft); } -@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .footer-word { color: var(--plate-soft); } } - -/* --- Lightbox ---------------------------------------------------------------------------- */ - -.lightbox { width: min(1400px, 94vw); max-height: 92vh; padding: 0; border: 0; border-radius: var(--radius-plate); background: var(--surface); color: var(--ink); } -.lightbox::backdrop { background: color-mix(in srgb, var(--page) 86%, transparent); -webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px); } -.lightbox img { width: 100%; } -.lightbox form { position: absolute; top: 12px; right: 12px; } -.lightbox-caption { padding: 14px 16px; font-size: var(--text-caption); color: var(--muted); } - -/* --- 404 --------------------------------------------------------------------------------- */ - -.lost { min-height: 100vh; display: flex; flex-direction: column; justify-content: space-between; } -.lost .hero { padding-top: clamp(96px, 16vh, 200px); } - -/* --- Motion: content arrives with a fade and a short rise, a few tens of ms apart --------- */ - -.js .reveal, .js .reveal-media { - opacity: 0; transform: translateY(var(--rise)); filter: blur(4px); - transition: opacity var(--enter) var(--ease-enter) var(--d, 0ms), transform var(--enter) var(--ease-enter) var(--d, 0ms), filter var(--enter) var(--ease-enter) var(--d, 0ms); -} -.js .reveal.is-visible, .js .reveal-media.is-visible { opacity: 1; transform: none; filter: none; } -.js .systems .system { opacity: 0; transform: translateY(var(--rise)); transition: opacity var(--enter) var(--ease-enter) var(--d, 0ms), transform var(--enter) var(--ease-enter) var(--d, 0ms); } -.js .systems.is-visible .system { opacity: 1; transform: none; } -@media (prefers-reduced-motion: reduce) { - html { scroll-behavior: auto; } - .js .reveal, .js .reveal-media, .js .systems .system { transform: none; filter: none; transition: opacity 200ms linear; } - .menu nav a { transform: none; } -} - -/* --- Touch: every target at least 44 px high ------------------------------------------- */ - -@media (pointer: coarse) { - .button, .button.large, .button.small, .tabs button { height: 44px; } - .nav-mark, .theme-toggle, .nav-github { min-height: 44px; } - .link-arrow, .footer-links a { display: inline-flex; align-items: center; min-height: 44px; } -} - -/* --- Narrow screens ------------------------------------------------------------------------ */ - -@media (max-width: 900px) { - .section-head, .parity-hero, .launcher-grid { grid-template-columns: minmax(0, 1fr); } - .section-head { gap: 16px; } - .screens { position: static; } - .fact { grid-template-columns: var(--index) minmax(0, 1fr); row-gap: 6px; } - .fact p { grid-column: 2; } - .mosaic { grid-template-columns: minmax(0, 1fr); } - .tile, .tile-wide, .tile-tall { grid-column: auto; } - .row.card { grid-template-columns: var(--index) minmax(0, 1fr) auto; row-gap: 4px; } - .card-text { grid-column: 2; grid-row: 2; font-size: var(--text-ui); } - .card-arrow { grid-row: 1; grid-column: 3; } - .release summary { grid-template-columns: minmax(0, 1fr) auto; } - .release-sub { grid-column: 1 / -1; grid-row: 2; } - .release .prose { padding-left: 0; margin-left: 0; } - .footer-cols { grid-template-columns: minmax(0, 1fr); } - .footer-bar { flex-direction: column; align-items: flex-start; } - .system { grid-template-columns: var(--index) minmax(0, 1fr); } - .system-state { grid-column: 2; grid-row: 2; padding-top: 0; } - .system-detail { grid-column: 2; } - .row > a { grid-template-columns: 28px 1fr auto; padding: 16px 0; } - :root { --index: 28px; } -} - -/* The privacy page: one long read under the hero type. */ -.privacy h1 { margin-bottom: 16px; } -.privacy .prose { margin: 40px 0; } -.privacy .disclaimer { margin-top: 32px; } - -/* --- Documentation (/docs): a left navigation and one page at a time --------------------- */ - -.docs { - display: grid; grid-template-columns: 248px minmax(0, 1fr); gap: clamp(32px, 6vw, 96px); - max-width: var(--max); margin: 0 auto; padding: calc(var(--nav) + 48px) var(--g) 0; align-items: start; -} -.docs-nav-wrap { position: sticky; top: calc(var(--nav) + 24px); max-height: calc(100vh - var(--nav) - 48px); overflow-y: auto; padding-bottom: 24px; } -.docs-nav-wrap summary { display: none; } -.docs-nav-group { margin: 28px 0 8px; font: var(--text-micro) / var(--text-micro-line) var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); } -.docs-nav-group:first-child { margin-top: 0; } -.docs-nav li a { display: block; padding: 6px 12px; margin-left: -12px; border-radius: var(--radius); color: var(--ink-soft); font-size: var(--text-ui); } -.docs-nav li a:hover { background: var(--plate-soft); color: var(--ink); } -.docs-nav li a[aria-current] { background: var(--plate-soft); color: var(--ink); font-weight: 500; } -.docs-main { min-width: 0; padding-bottom: 48px; } -.docs-main .title { margin-bottom: 16px; } -.docs-main .lede { max-width: 64ch; font-size: var(--text-heading); line-height: 1.45; } -.docs-toc { margin-top: 28px; max-width: 72ch; } -.docs-toc p { font: var(--text-micro) / var(--text-micro-line) var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); margin-bottom: 8px; } -.docs-toc ul { display: flex; flex-wrap: wrap; gap: 6px; } -.docs-toc a { display: block; padding: 4px 12px; border-radius: var(--radius-pill); background: var(--plate-soft); color: var(--ink-soft); font-size: var(--text-label); } -.docs-toc a:hover { background: var(--plate); color: var(--ink); } -.docs-prose { max-width: 72ch; margin-top: 40px; font-size: var(--text-body); } -.docs-prose > * + * { margin-top: 14px; } -.docs-prose h2 { margin-top: 56px; padding-top: 24px; border-top: 1px solid var(--rule); font-size: clamp(24px, 2.4vw, 30px); line-height: 1.2; letter-spacing: var(--text-title-tracking); scroll-margin-top: 80px; } -.docs-prose h2:first-child { margin-top: 0; padding-top: 0; border-top: 0; } -.docs-prose h3 { margin-top: 32px; scroll-margin-top: 80px; } -.docs-prose ol { list-style: decimal; } -.docs-prose pre { font: 0.86em/1.6 var(--mono); } -.docs-prose blockquote { padding: 2px 0 2px 16px; border-left: 2px solid var(--accent); color: var(--ink-soft); } -.docs-prose blockquote > * + * { margin-top: 8px; } -.docs-prose figure { margin: 28px 0; } -.docs-prose figure img { width: 100%; border-radius: var(--radius-plate); box-shadow: 0 0 0 1px var(--rule); } -.docs-prose figcaption { margin-top: 10px; font-size: var(--text-caption); color: var(--muted); } -.docs-pager { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; max-width: 72ch; margin-top: 56px; } -.docs-pager a { display: flex; flex-direction: column; gap: 2px; padding: 14px 16px; border-radius: var(--radius-plate); box-shadow: 0 0 0 1px var(--rule); color: var(--ink); font-weight: 500; } -.docs-pager a:hover { background: var(--plate-soft); color: var(--ink); } -.docs-pager a span { font: var(--text-micro) / var(--text-micro-line) var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); font-weight: 400; } -.docs-pager-next { grid-column: 2; text-align: right; } -.docs-edit { margin-top: 32px; font-size: var(--text-caption); color: var(--muted); } -.docs-edit a { color: inherit; text-decoration: underline; text-decoration-color: var(--rule); text-underline-offset: 3px; } -.docs-main .disclaimer { margin-top: 24px; } - -@media (max-width: 900px) { - .docs { grid-template-columns: minmax(0, 1fr); gap: 0; padding-top: calc(var(--nav) + 12px); } - .docs-nav-wrap { position: static; max-height: none; overflow: visible; margin-bottom: 24px; border-bottom: 1px solid var(--rule); } - .docs-nav-wrap summary { display: flex; align-items: center; min-height: 44px; cursor: pointer; font-weight: 500; list-style: none; } - .docs-nav-wrap summary::-webkit-details-marker { display: none; } - .docs-nav-wrap summary::after { content: "+"; margin-left: auto; color: var(--muted); } - .docs-nav-wrap[open] summary::after { content: "\2212"; } - .docs-pager { grid-template-columns: minmax(0, 1fr); } - .docs-pager-next { grid-column: 1; } -} -@media (pointer: coarse) { - .docs-nav li a, .docs-toc a { display: flex; align-items: center; min-height: 44px; } -} - -/* --- Blocks: the launcher's look on the page (docs/design-system.md, "Blocks") ------------- - Pixel type for headings and controls, square panels with a dark outline, a light bevel on top - and a darker lip below, the violet face for the main action, sunk wells, a stone texture - behind the page and Horizon's pixel landscape behind the hero. The art is drawn in code - (scripts/art.mjs, like launcher/src/art.rs); nothing in it comes from Minecraft. */ - -@font-face { font-family: "Pixelify Sans"; src: url("/fonts/PixelifySans-Medium.woff2") format("woff2"); font-weight: 500; font-display: swap; } -@font-face { font-family: "Pixelify Sans"; src: url("/fonts/PixelifySans-SemiBold.woff2") format("woff2"); font-weight: 600; font-display: swap; } -@font-face { font-family: "Pixelify Sans"; src: url("/fonts/PixelifySans-Bold.woff2") format("woff2"); font-weight: 700; font-display: swap; } - -:root { - --stone: url("/media/stone-light.png"); - --scene: url("/media/scene-light.png"); - --sky: #8d7fd8; - --panel-edges: inset 0 var(--block-bevel) 0 var(--bevel), inset 0 calc(-1 * var(--block-bevel)) 0 var(--lip); - --radius: 0px; --radius-plate: 0px; --radius-pill: 0px; -} -:root[data-theme="dark"] { --stone: url("/media/stone-dark.png"); --scene: url("/media/scene-dark.png"); --sky: #0a0f2c; } -@media (prefers-color-scheme: dark) { - :root:not([data-theme="light"]) { --stone: url("/media/stone-dark.png"); --scene: url("/media/scene-dark.png"); --sky: #0a0f2c; } -} - -/* The stone: 64 texels of the page colour in close shades, each texel 4 px. */ -body { position: relative; isolation: isolate; } -body::before { - content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none; - background: var(--stone) 0 0 / 256px 256px repeat; image-rendering: pixelated; -} - -/* Pixel type for what names and what you act on; paragraphs stay in Geist. */ -.display, .title, .statement, .row-name, .card-title, .release-tag, .count, -.fact h3, .features h3, .system h3, .contributors-title, .footer-disclaimer, .footer-word, -.nav-mark, .docs-prose h2, .docs-prose h3, .prose h2, .prose h3, .prose h4, .menu nav a { - font-family: var(--pixel); font-weight: 600; letter-spacing: 0; -} -.display, .count, .footer-word { font-weight: 700; } -.nav-mark { font-size: 18px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em; } -code { border-radius: 0; background: var(--well); box-shadow: 0 0 0 1px var(--outline); } - -/* Buttons: blocks with an outline, a bevel and a lip; they sink a pixel when pressed. */ -.button { - border: var(--block-outline) solid var(--outline); border-radius: 0; - font: 500 var(--text-ui) / 1 var(--pixel); - box-shadow: inset 0 var(--block-bevel) 0 var(--button-bevel), inset 0 calc(-1 * var(--block-lip)) 0 var(--lip); - padding-bottom: 2px; -} -.button.large { font-size: 18px; } -.button.primary { background: var(--face); color: var(--on-face); box-shadow: inset 0 var(--block-bevel) 0 var(--face-bevel), inset 0 calc(-1 * var(--block-lip)) 0 var(--face-lip); } -.button.primary:hover { opacity: 1; filter: brightness(1.08); } -.button.secondary { background: var(--button); } -.button.secondary:hover { background: var(--button); filter: brightness(1.06); } -.button.ghost { border-color: transparent; box-shadow: none; } -.button:active { opacity: 1; transform: translateY(1px); box-shadow: inset 0 var(--block-bevel) 0 var(--lip); } -:focus-visible { border-radius: 0; } - -/* The top bar: the sidebar colour with an outline under it, tabs with an accent underline. */ -.nav { background: var(--side); -webkit-backdrop-filter: none; backdrop-filter: none; box-shadow: 0 var(--block-outline) 0 var(--outline); } -.nav-links a, .nav-github, .theme-toggle { border-radius: 0; font-family: var(--pixel); font-weight: 500; font-size: 15px; } -.nav-links a:hover, .nav-github:hover, .theme-toggle:hover { background: var(--raised); } -.nav-links a[aria-current] { background: var(--raised); box-shadow: inset 0 -3px 0 var(--accent); } -.theme-toggle { text-transform: none; letter-spacing: 0; } -.menu { background: var(--side); } -.menu nav a { border-bottom: 0; } - -/* Lists become stacks of panels. */ -.index, .systems, .contributors-list { border-top: 0; display: grid; gap: 8px; } -.row, .system, .release, .release:last-of-type, .contributor { border-bottom: 0; border-top: 0; } -.row > a, .row.card, .fact.row, .features li, .system, .release, .contributor, .docs-pager a { - background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); - border-radius: 0; -} -.row > a, .row.card, .fact.row, .features li, .system { padding-left: 20px; padding-right: 20px; } -.row > a::before, .row.card::before { display: none; } -.row > a:hover, .row.card:hover, .contributor:hover, .docs-pager a:hover { background: var(--raised); } -.row > a:hover .row-index { color: var(--accent); } -.row-name { font-size: clamp(20px, 2.2vw, 28px); } -.release { padding: 0 20px; } -.release + .release { margin-top: 8px; } -.release .prose { padding-left: 12rem; } -.contributor { padding: 12px 14px; } -.contributors-list { grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 8px; } -.contributor-avatar { border-radius: 0; box-shadow: 0 0 0 2px var(--outline); image-rendering: pixelated; } -.system.is-full .system-state { color: var(--success); } - -/* Screenshots and the launcher's screens: square, outlined. */ -.zoom, .screen, .lightbox, .prose pre, .docs-prose figure img { border-radius: 0; box-shadow: 0 0 0 var(--block-outline) var(--outline); } -.tabs { border-radius: 0; background: var(--well); box-shadow: 0 0 0 var(--block-outline) var(--outline); } -.tabs button { border-radius: 0; font-family: var(--pixel); font-weight: 500; font-size: 15px; } -.tabs button[aria-selected="true"] { color: var(--on-face); } -.tab-pill { border-radius: 0; background: var(--face); box-shadow: inset 0 var(--block-bevel) 0 var(--face-bevel), inset 0 calc(-1 * var(--block-bevel)) 0 var(--face-lip); } - -/* The hero: Horizon's landscape under a veil of the page colour, the words on the left. */ -.hero { - position: relative; isolation: isolate; overflow: hidden; - background: var(--scene) 70% 100% / clamp(1200px, 135vw, 2400px) auto no-repeat, var(--sky); image-rendering: pixelated; - border-bottom: var(--block-outline) solid var(--outline); -} -.hero::before { - content: ""; position: absolute; inset: 0; z-index: -1; - background: - linear-gradient(90deg, color-mix(in srgb, var(--page) 92%, transparent) 0%, color-mix(in srgb, var(--page) 78%, transparent) 45%, color-mix(in srgb, var(--page) 0%, transparent) 78%), - linear-gradient(180deg, color-mix(in srgb, var(--page) 0%, transparent) 55%, color-mix(in srgb, var(--page) 70%, transparent) 100%); -} -.hero .kicker span, .hero .kicker { color: var(--ink-soft); } -.hero .lede { color: var(--ink-soft); } -.hero { padding-bottom: clamp(160px, 18vw, 280px); } -.hero-after { padding-top: 40px; } -.hero-after .hero-index { margin-top: 0; max-width: 860px; } -.hero-after .disclaimer { margin-top: 24px; } -@media (max-width: 900px) { - .hero::before { background: color-mix(in srgb, var(--page) 84%, transparent); } -} - -/* Documentation. */ -.docs-nav li a { border-radius: 0; } -.docs-nav li a[aria-current] { background: var(--raised); box-shadow: inset 4px 0 0 var(--accent); } -.docs-toc a { border-radius: 0; background: var(--button); box-shadow: 0 0 0 var(--block-outline) var(--outline); } -.docs-pager a { box-shadow: var(--panel-edges); } -.docs-prose h2 { border-top: var(--block-outline) solid var(--outline); } -.docs-prose blockquote { border-left: 4px solid var(--accent); background: var(--panel); padding: 10px 16px; box-shadow: 0 0 0 var(--block-outline) var(--outline); } - -/* The footer: the giant wordmark in pixels. */ -.footer { background: var(--side); border-top: var(--block-outline) solid var(--outline); margin-top: 48px; } -.footer-word { color: var(--raised); letter-spacing: 0.02em; } -:root[data-theme="dark"] .footer-word { color: var(--panel); } -@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .footer-word { color: var(--panel); } } - -/* --- Releases and Benchmarks pages, and the home page's "Recently added" ------------------ */ - -/* Pixelify Sans' "fi" ligature draws as "A" ("8 Axes"): no common ligatures anywhere. */ -:root { font-variant-ligatures: no-common-ligatures; } - -.page-main { padding-top: calc(var(--nav) + clamp(40px, 6vw, 80px)); } -.page-title { max-width: 18ch; margin-bottom: 20px; } -.page-main > .container > .lede { font-size: var(--text-body); } -.page-main .disclaimer { margin-top: 48px; } - -/* Release and source badges: small square tags. */ -.badge { - display: inline-flex; align-items: center; height: 22px; padding: 0 8px; margin-right: 10px; vertical-align: 2px; - font: 500 12px / 1 var(--pixel); letter-spacing: 0.02em; text-transform: uppercase; white-space: nowrap; - border: var(--block-outline) solid var(--outline); background: var(--well); color: var(--ink-soft); -} -.badge-game { background: color-mix(in srgb, var(--success) 22%, var(--panel)); color: var(--ink); } -.badge-launcher { background: color-mix(in srgb, var(--accent) 20%, var(--panel)); color: var(--ink); } -.badge-us { background: color-mix(in srgb, var(--accent) 20%, var(--panel)); color: var(--ink); } -.badge-players { background: color-mix(in srgb, var(--success) 22%, var(--panel)); color: var(--ink); } -.badge-estimate { background: color-mix(in srgb, var(--warn) 24%, var(--panel)); color: var(--ink); } - -/* Home: the newest releases on a line each, then what they added. */ -.recent-list .row > a { grid-template-columns: 8.5rem minmax(0, 13rem) minmax(0, 1fr) auto; align-items: baseline; } -.recent-line { color: var(--muted); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.recent-list .row-name { font-size: clamp(18px, 1.8vw, 22px); } -.recent-list .badge { margin-right: 0; } -.recent-picks { margin-top: 32px; } -.recent-picks .eyebrow { margin-bottom: 12px; } -.highlights { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; } -.highlight { - display: flex; flex-direction: column; justify-content: space-between; gap: 16px; padding: 18px 20px; - background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); -} -.highlight p { color: var(--ink); } -.highlight-from { font: var(--text-micro) / 1 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); } -.highlight-from:hover { color: var(--accent); } - -/* Releases: a filter, then every release as a panel that opens. */ -.release-filter { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 32px; } -.release-filter .button[aria-pressed="true"], .hub-detail .button[aria-pressed="true"], .button.hub-vote[aria-pressed="true"] { background: var(--face); color: var(--on-face); box-shadow: inset 0 var(--block-bevel) 0 var(--face-bevel), inset 0 calc(-1 * var(--block-lip)) 0 var(--face-lip); } -.release-count { margin: 16px 0 12px; } -.release-list { display: grid; gap: 8px; } -.release-list .release + .release { margin-top: 0; } -.release-entry summary { grid-template-columns: minmax(0, 11rem) minmax(0, 1fr) auto; } -.release-entry .release-sub { display: flex; align-items: baseline; flex-wrap: wrap; row-gap: 4px; } -.release-detail { padding: 0 0 24px 11rem; margin-left: 16px; display: grid; gap: 20px; max-width: calc(11rem + 16px + var(--measure) + 120px); } -.release-detail .prose { padding: 0; margin: 0; font-size: var(--text-ui); max-width: none; } -.release-overview { padding: 16px 18px; background: var(--well); box-shadow: 0 0 0 var(--block-outline) var(--outline); } -.release-counts { font-family: var(--pixel); font-weight: 600; color: var(--ink); margin-bottom: 8px; } -.release-overview ul { list-style: square; padding-left: 18px; color: var(--ink-soft); font-size: var(--text-ui); } -.release-overview li + li { margin-top: 4px; } -.release-downloads ul { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 8px; margin-top: 8px; } -.release-downloads li { display: flex; flex-direction: column; gap: 2px; padding: 10px 12px; background: var(--button); box-shadow: 0 0 0 var(--block-outline) var(--outline); } -.release-downloads li a { font-weight: 500; } -.release-downloads li span { font: var(--text-micro) / 1.4 var(--mono); color: var(--muted); overflow-wrap: anywhere; } -.release-github { font-size: var(--text-caption); } -.release-entry:target { box-shadow: var(--panel-edges), 0 0 0 3px var(--accent); } - -/* Benchmarks. */ -.bench-section { margin-top: clamp(64px, 8vw, 112px); } -.bench-section > .title { margin-bottom: 16px; } -.bench-section > .lede { margin-bottom: 32px; } -.machines { display: grid; grid-template-columns: minmax(0, 1fr); gap: 24px; } -.machine { min-width: 0; padding: 24px; background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); } -.machine-head { display: grid; gap: 10px; margin-bottom: 20px; } -.machine-name { font-family: var(--pixel); font-weight: 600; font-size: var(--text-title); line-height: var(--text-title-line); } -.machine-facts { display: flex; flex-wrap: wrap; gap: 6px 28px; margin: 0; } -.machine-facts div { display: flex; gap: 8px; min-width: 0; } -.machine-facts dt { font: var(--text-micro) / 1.6 var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); } -.machine-facts dd { margin: 0; min-width: 0; overflow-wrap: anywhere; font-size: var(--text-caption); color: var(--ink-soft); } -.machine-note { font-size: var(--text-caption); color: var(--muted); max-width: 90ch; } -/* relative: the screen-reader-only labels inside are absolute and would escape the scroll box otherwise. */ -.table-wrap { position: relative; overflow-x: auto; } -.bench-table { width: 100%; border-collapse: collapse; font-size: var(--text-ui); } -.bench-table th, .bench-table td { padding: 9px 12px; text-align: left; border-bottom: 1px solid var(--rule); vertical-align: baseline; } -.bench-table thead th { font: var(--text-micro) / 1.4 var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); font-weight: 400; } -.bench-table thead tr:first-child th { color: var(--ink); } -.bench-table tbody th { font-weight: 500; color: var(--ink); } -.bench-table td.num { font-variant-numeric: tabular-nums; white-space: nowrap; } -.bench-table td.wins { color: var(--ink); font-weight: 600; } -.bench-table td.vs { font-size: var(--text-caption); white-space: nowrap; } -.md-table { width: 100%; border-collapse: collapse; font-size: var(--text-ui); } -.md-table th, .md-table td { padding: 8px 12px 8px 0; text-align: left; border-bottom: 1px solid var(--rule); vertical-align: baseline; } -.md-table th { font-weight: 500; color: var(--ink); } -.md-table td code, .md-table th code { overflow-wrap: anywhere; } -.vs-horizon { color: var(--success); } -.vs-java { color: var(--danger); } -.vs-tie, .vs-none { color: var(--muted); } -.capped { font: var(--text-micro) / 1 var(--mono); color: var(--warn); cursor: help; } -.metric-hint { display: block; font: var(--text-micro) / 1.4 var(--mono); color: var(--muted); font-weight: 400; } -.java-wins { margin-top: 16px; font-size: var(--text-caption); color: var(--ink-soft); } -.picker { display: flex; flex-wrap: wrap; gap: 16px 24px; align-items: end; padding: 20px; background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); } -.picker label { display: grid; gap: 6px; } -.picker label > span, .picker legend { font: var(--text-micro) / 1.4 var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); } -.picker select { - min-width: min(320px, 80vw); height: var(--control); padding: 0 10px; font: inherit; font-size: var(--text-ui); color: var(--ink); - background: var(--well); border: var(--block-outline) solid var(--outline); border-radius: 0; -} -.picker-rd { display: flex; gap: 16px; align-items: center; border: 0; padding: 0; margin: 0; } -.picker-rd legend { margin-bottom: 6px; } -.picker-rd label { display: inline-flex; align-items: center; gap: 6px; font-family: var(--pixel); font-weight: 500; height: var(--control); } -.picker-rd input { accent-color: var(--accent); width: 18px; height: 18px; } -.pick-result { margin-top: 16px; padding: 20px; background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); } -.pick-head { margin-bottom: 12px; font-size: var(--text-caption); color: var(--ink-soft); line-height: 1.8; } -.pick-result .meta { margin-top: 12px; } -.pick-notes { margin: 12px 0 0; padding-left: 20px; font-size: var(--text-caption); color: var(--ink-soft); line-height: 1.6; } -.players-hardware th[scope="rowgroup"] { vertical-align: top; } -.empty { color: var(--muted); } -.prose-section .prose { max-width: 80ch; } -.spec-table { margin-top: 24px; } -.spec-table summary { cursor: pointer; font-family: var(--pixel); font-weight: 600; } -.spec-table .bench-table { margin-top: 16px; max-width: 760px; } - -@media (max-width: 900px) { - .recent-list .row > a { grid-template-columns: minmax(0, 1fr) auto; row-gap: 4px; } - .recent-list .row-index { grid-column: 1; grid-row: 1; } - .recent-list .row-name { grid-column: 1; grid-row: 2; } - .recent-line { grid-column: 1 / -1; grid-row: 3; white-space: normal; } - .recent-list .row-meta { grid-column: 2; grid-row: 1; } - .highlights { grid-template-columns: minmax(0, 1fr); } - .release-entry summary { grid-template-columns: minmax(0, 1fr) auto; } - .release-detail { padding-left: 0; margin-left: 0; } - .machine { padding: 16px; } -} - -/* --- The hub (/hub): tabs, the Simple / Technical switch, roadmap items as panels ------------------- */ - -.hub-bar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 16px; margin-top: 32px; } -.hub-tabs { margin-bottom: 0; } -.hub-detail { display: flex; gap: 8px; } -/* A link to a tab (/hub#roadmap) lands with the tabs in view under the top bar. */ -.hub-panel { margin-top: 40px; scroll-margin-top: calc(var(--nav) + 120px); } -.js .hub-panel:not(.is-active) { display: none; } -/* Simple shows `plain`, Technical shows `dev`; without the switch (no JavaScript) Simple reads. */ -.hub .hub-dev { display: none; } -:root[data-detail="dev"] .hub .hub-dev { display: block; } -:root[data-detail="dev"] .hub .hub-plain { display: none; } -.hub-lead { max-width: 60ch; font-size: var(--text-heading); line-height: var(--text-heading-line); color: var(--ink); } -.hub-block { margin-top: 56px; } -.hub-block > .title { margin-bottom: 16px; } -.hub-intro { margin-bottom: 16px; color: var(--ink-soft); max-width: var(--measure); } -.hub-rows .row > a { grid-template-columns: var(--index) minmax(0, 1fr) auto; align-items: baseline; } -.hub-row-body { display: grid; gap: 4px; min-width: 0; } -.hub-row-title { font-size: clamp(18px, 1.8vw, 22px); font-weight: 500; color: var(--ink); } -.hub-row-body .hub-plain, .hub-row-body .hub-dev { color: var(--ink-soft); font-size: var(--text-ui); max-width: 80ch; } -.hub-rows .row-meta { max-width: 16rem; } -.hub-section { margin-top: 48px; } -.hub-section-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 8px 20px; } -.hub-items { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 340px), 1fr)); gap: 8px; margin-top: 16px; } -.hub-item { - display: flex; flex-direction: column; gap: 10px; padding: 18px 20px; scroll-margin-top: calc(var(--nav) + 24px); - background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); -} -.hub-item:target { box-shadow: var(--panel-edges), 0 0 0 3px var(--accent); } -.hub-item-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } -.hub-item-meta .badge { margin-right: 0; } -.hub-ongoing { font: var(--text-micro) / 1 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); } -.hub-item-title { font-size: var(--text-heading); line-height: var(--text-heading-line); } -.hub-item .hub-plain, .hub-item .hub-dev { font-size: var(--text-ui); color: var(--ink-soft); } -.hub-progress { font: var(--text-micro) / 1.4 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--ink); } -.hub-links { display: flex; flex-wrap: wrap; gap: 6px; margin-top: auto; padding-top: 4px; } -.hub-link { - display: inline-flex; gap: 6px; align-items: baseline; padding: 3px 7px; font: var(--text-micro) / 1.3 var(--mono); - color: var(--ink-soft); background: var(--well); box-shadow: 0 0 0 var(--block-outline) var(--outline); -} -.hub-link span { color: var(--muted); } -.hub-link:hover { color: var(--accent); } -.hub-link.is-merged { background: color-mix(in srgb, var(--success) 18%, var(--well)); } -.hub-link.is-in-review { background: color-mix(in srgb, var(--accent) 18%, var(--well)); } -.hub-link.is-in-progress { background: color-mix(in srgb, var(--warn) 22%, var(--well)); } -.hub-link.is-merged span, .hub-link.is-in-review span, .hub-link.is-in-progress span { color: var(--ink); } -.hub-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 260px), 1fr)); gap: 8px; } -.hub-cards .highlight { justify-content: flex-start; } -.hub-cards h3 { font-size: var(--text-heading); line-height: var(--text-heading-line); } -.hub-cards p { color: var(--ink-soft); font-size: var(--text-ui); } -.hub-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 16px; } -.hub-cards .hub-actions { margin-top: auto; } -.hub-rules { list-style: decimal; padding-left: 20px; max-width: var(--measure); } -.hub-rules li + li { margin-top: 10px; } -.hub-rules li::marker { color: var(--muted); font-family: var(--mono); } -.hub-source { margin-top: 40px; max-width: var(--measure); } -.hub-board-head { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px 24px; } -.hub-board-head .hub-intro { margin-bottom: 0; } -.hub-select { display: inline-flex; align-items: center; gap: 10px; } -.hub-select select { - height: 32px; max-width: 22rem; padding: 0 10px; font: var(--text-label) / 1 var(--font); color: var(--ink); - background: var(--well); border: 0; box-shadow: 0 0 0 var(--block-outline) var(--outline); -} -.hub-board { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; margin-top: 24px; align-items: start; } -.hub-column { padding: 14px; background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); } -.hub-column h3 { display: flex; justify-content: space-between; align-items: baseline; font-size: var(--text-heading); } -.hub-count { font: var(--text-micro) / 1 var(--mono); color: var(--muted); } -.hub-column > .meta { margin: 6px 0 12px; } -.hub-cards-list { display: grid; gap: 6px; } -.js .hub-column:not(.is-open) .hub-card[data-more] { display: none; } -.hub-card a { display: grid; gap: 4px; padding: 10px 12px; background: var(--well); box-shadow: 0 0 0 var(--block-outline) var(--outline); color: var(--ink); } -.hub-card a:hover { box-shadow: 0 0 0 var(--block-outline) var(--accent); } -.hub-card-ref, .hub-card-meta { font: var(--text-micro) / 1.4 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); } -.hub-card-title { font-size: var(--text-label); line-height: 1.4; overflow-wrap: anywhere; } -.hub-card-meta { display: flex; flex-wrap: wrap; gap: 4px 10px; } -.hub-card-item { color: var(--accent); } -.hub-more { margin-top: 10px; width: 100%; justify-content: center; } -.hub-journal { display: grid; gap: 8px; margin-top: 24px; max-width: 56rem; } -.hub-entry { display: grid; gap: 10px; padding: 18px 20px; background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); scroll-margin-top: calc(var(--nav) + 24px); } -.hub-entry-week { background: color-mix(in srgb, var(--accent) 8%, var(--panel)); } -.hub-entry-meta { display: flex; align-items: center; gap: 10px; font: var(--text-micro) / 1 var(--mono); color: var(--muted); } -.hub-entry-meta .badge { margin-right: 0; } -.hub-entry-title { font-size: var(--text-heading); line-height: var(--text-heading-line); } -.hub-entry-title a { color: var(--ink); } -.hub-entry-title a:hover { color: var(--accent); } -.hub-entry .hub-plain, .hub-entry .hub-dev { font-size: var(--text-ui); color: var(--ink-soft); } -.hub-entry-items { display: flex; flex-wrap: wrap; gap: 6px; } -.hub-shipped { font-size: var(--text-ui); color: var(--ink); } -.hub-changes { list-style: square; padding-left: 18px; font-size: var(--text-ui); color: var(--ink-soft); } -.hub-changes li + li { margin-top: 4px; } -.hub-ref { font: var(--text-micro) / 1 var(--mono); } -.hub-group { margin-top: 8px; font: 500 var(--text-label) / 1.4 var(--font); } -.hub-group:first-child { margin-top: 0; } -@media (max-width: 1100px) { .hub-board { grid-template-columns: repeat(2, minmax(0, 1fr)); } } -@media (max-width: 720px) { - .hub-board { grid-template-columns: minmax(0, 1fr); } - .hub-rows .row > a { grid-template-columns: var(--index) minmax(0, 1fr); } - .hub-rows .row-meta { grid-column: 2; text-align: left; } -} - -/* --- Hub: votes, the report and suggestion forms, the contributors ---------------------- */ -.hub-vote { margin-left: auto; } -.hub-vote-count { margin-left: -2px; } -.hub-vote-count:empty { display: none; } -.hub-form { display: grid; gap: 16px; max-width: 46rem; margin-top: 8px; } -.hub-form-pair { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; } -.hub-field { display: grid; gap: 6px; font-size: var(--text-label); color: var(--ink-soft); } -.hub-field input, .hub-field textarea, .hub-field select { - width: 100%; min-height: 36px; padding: 8px 10px; font: var(--text-ui) / 1.4 var(--font); color: var(--ink); - background: var(--well); border: 0; box-shadow: 0 0 0 var(--block-outline) var(--outline); -} -.hub-field textarea { resize: vertical; } -.hub-field input:focus-visible, .hub-field textarea:focus-visible, .hub-field select:focus-visible { outline: 1px solid var(--accent); outline-offset: 2px; } -.hub-field input::placeholder, .hub-field textarea::placeholder { color: var(--muted); } -.hub-trap { position: absolute; left: -10000px; width: 1px; height: 1px; overflow: hidden; } -.hub-form-foot { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; } -.hub-form-foot [data-status] { color: var(--ink); } -.hub-form-foot .button:disabled { opacity: 0.4; cursor: default; } -.hub-form-closed { color: var(--ink-soft); } -@media (max-width: 720px) { - .hub-form-pair { grid-template-columns: minmax(0, 1fr); } -} - -/* The registry (/mods): a search and the kind filter, rows as panels, then a page per project. */ -.mod-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 24px; } -.mod-tools { display: flex; flex-wrap: wrap; align-items: center; gap: 16px; margin-top: 32px; } -.mod-tools .release-filter { margin-top: 0; } -.mod-search { - height: 36px; min-width: min(320px, 100%); padding: 0 12px; font: var(--text-ui) / 1 var(--sans); color: var(--ink); - background: var(--well); border: var(--block-outline) solid var(--outline); border-radius: 0; -} -.mod-search:focus-visible { outline: 2px solid var(--accent); outline-offset: 0; } -.mod-list { display: grid; gap: 8px; } -.mod-row { - display: grid; grid-template-columns: 48px minmax(0, 1fr) auto; align-items: center; gap: 16px; padding: 14px 20px; - background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); color: var(--ink); text-decoration: none; -} -.mod-row:hover { background: var(--raised); } -.mod-row:hover .mod-name { color: var(--accent); } -.mod-icon { - display: grid; place-items: center; width: 48px; height: 48px; flex: none; image-rendering: pixelated; - font: 600 22px / 1 var(--pixel); color: var(--ink); background: var(--well); box-shadow: 0 0 0 var(--block-outline) var(--outline); -} -.mod-text { display: grid; gap: 4px; min-width: 0; } -.mod-name { font: 500 var(--text-heading) / 1.2 var(--pixel); } -.mod-summary { color: var(--muted); font-size: var(--text-ui); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.mod-side { display: grid; justify-items: end; gap: 6px; } -.mod-side .badge { margin-right: 0; } -.mod-version { font: var(--text-micro) / 1.4 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); } -.mod-empty a { color: var(--accent); } -.badge-signed { background: color-mix(in srgb, var(--success) 22%, var(--panel)); color: var(--ink); } -.badge-unsigned { background: color-mix(in srgb, var(--warn) 24%, var(--panel)); color: var(--ink); } -.mod-page { display: grid; gap: 16px; max-width: calc(var(--measure) + 240px); } -.mod-page .heading { margin-top: 24px; } -.mod-head { display: grid; grid-template-columns: 96px minmax(0, 1fr); gap: 24px; align-items: start; } -.mod-owners { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 4px 0 0; } -.mod-owner { display: inline-flex; align-items: center; gap: 6px; } -.mod-owner img { border-radius: 50%; } -.mod-head .mod-icon { width: 96px; height: 96px; font-size: 44px; } -.mod-head .page-title { margin-top: 0; } -.mod-badges { margin-top: 16px; } -.mod-caps, .mod-steps, .mod-versions { display: grid; gap: 8px; padding-left: 20px; font-size: var(--text-ui); } -.mod-caps li::marker, .mod-steps li::marker { color: var(--accent); } -.mod-file { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 8px 16px; font-size: var(--text-ui); } -.mod-file dt { color: var(--muted); } -.mod-file code, .mod-steps code { font-family: var(--mono); font-size: 13px; overflow-wrap: anywhere; } -.mod-links { display: flex; flex-wrap: wrap; gap: 24px; margin-top: 24px; } -/* /mods/submit */ -.mod-form { display: grid; gap: 24px; max-width: var(--measure); margin-top: 32px; } -.mod-form fieldset { display: grid; gap: 16px; margin: 0; padding: 0; border: 0; } -.mod-form legend { padding: 0; margin-bottom: 8px; } -.mod-field { display: grid; gap: 6px; } -.mod-label { font-size: var(--text-ui); font-weight: 500; } -.mod-form .mod-search { width: 100%; } -.mod-form textarea.mod-search { height: auto; padding: 10px 12px; line-height: 1.5; resize: vertical; } -.mod-check { display: flex; gap: 10px; align-items: flex-start; font-size: var(--text-ui); } -.mod-auth { margin-top: 24px; } -.mod-error { color: var(--danger); font-size: var(--text-ui); } -.js .no-script { display: none; } -@media (max-width: 640px) { - .mod-row { grid-template-columns: 40px minmax(0, 1fr); } - .mod-side { grid-column: 2; justify-items: start; } - .mod-icon { width: 40px; height: 40px; } - .mod-head { grid-template-columns: 1fr; } -} diff --git a/website/src/versions.js b/website/src/versions.js deleted file mode 100644 index b2483b4ed..000000000 --- a/website/src/versions.js +++ /dev/null @@ -1,59 +0,0 @@ -// Horizon's release tags (docs/versioning.md). From 0.2 the game is vX.Y.Z and the launcher launcher@X.Y.Z; -// before, vYYYY.MM.DD[.N] and launcher-vX.Y.Z. Every 0.2 tag is newer than every tag from before. Shared by -// build.mjs and main.js, and the same order as the launcher's and tools/release_train.py's. - -const SEMVER = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/; -// Semver's majors stay below this; a date tag's first number is a year. -const FIRST_YEAR = 1000; - -const semver = (version) => { - const m = SEMVER.exec(version); - return m && Number(m[1]) < FIRST_YEAR ? m : null; -}; - -export const isGame = (tag) => /^v\d{4}\.\d{1,2}\.\d{1,2}(\.\d+)?$/.test(tag) || (tag.startsWith("v") && !!semver(tag.slice(1))); - -// The version in a launcher tag (launcher@0.2.0, launcher-v0.16.0), or null. -export function launcherVersion(tag) { - if (tag.startsWith("launcher@") && semver(tag.slice(9))) return tag.slice(9); - const old = /^launcher-v(\d+\.\d+\.\d+)$/.exec(tag); - return old ? old[1] : null; -} - -export const isLauncher = (tag) => launcherVersion(tag) !== null; - -// [line, numbers, pre-release]: tags from before 0.2 by their numbers, then 0.2 tags in semver's order. -function key(tag) { - const version = tag.startsWith("launcher@") ? tag.slice(9) : tag.startsWith("v") ? tag.slice(1) : null; - const m = version !== null && semver(version); - if (!m) return [0, (tag.match(/\d+/g) || []).map(Number), []]; - const pre = m[4] ? m[4].split(".").map((id) => (/^\d+$/.test(id) ? [0, Number(id)] : [1, id])) : null; - return [1, [m[1], m[2], m[3]].map(Number), pre]; -} - -const cmpList = (a, b, cmp) => { - for (let i = 0; i < Math.min(a.length, b.length); i++) { - const d = cmp(a[i], b[i]); - if (d) return d; - } - return a.length - b.length; -}; -const cmpNumbers = (a, b) => { - const strip = (l) => { const c = [...l]; while (c.length && c[c.length - 1] === 0) c.pop(); return c; }; - return cmpList(strip(a), strip(b), (x, y) => x - y); -}; -const cmpId = ([ka, va], [kb, vb]) => ka - kb || (ka ? (va < vb ? -1 : va > vb ? 1 : 0) : va - vb); - -// Negative when tag a is older than tag b. -export function compareTags(a, b) { - const [la, na, pa] = key(a); - const [lb, nb, pb] = key(b); - if (la !== lb) return la - lb; - const d = cmpNumbers(na, nb); - if (d || !la) return d; - // A release follows its pre-releases. - if (!pa || !pb) return (pa ? -1 : 0) - (pb ? -1 : 0); - return cmpList(pa, pb, cmpId); -} - -export const newestFirst = (a, b) => compareTags(b, a); diff --git a/website/src/versions.test.mjs b/website/src/versions.test.mjs deleted file mode 100644 index eed334429..000000000 --- a/website/src/versions.test.mjs +++ /dev/null @@ -1,21 +0,0 @@ -// node --test website/src/ (npm test in website/) -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { compareTags, isGame, isLauncher, launcherVersion, newestFirst } from "./versions.js"; - -test("0.2 tags follow every tag from before", () => { - const order = ["v2026.10.19.15", "v2026.10.21", "v0.2.0-beta.1", "v0.2.0", "v0.2.1-beta", "v0.2.1-beta.2", - "v0.2.1-beta.11", "v0.2.1-rc.1", "v0.2.1", "v0.2.9", "v0.2.10", "v0.3.0-1", "v0.3.0-alpha", "v0.3.0", "v1.0.0"]; - assert.deepEqual([...order].reverse().sort(compareTags), order); - assert.deepEqual(["launcher-v0.16.0", "launcher@0.2.0", "launcher-v0.17.0", "launcher@0.2.1"].sort(newestFirst), - ["launcher@0.2.1", "launcher@0.2.0", "launcher-v0.17.0", "launcher-v0.16.0"]); - assert.equal(compareTags("v2026.10.19", "v2026.10.19.0"), 0); -}); - -test("game and launcher tags never mix", () => { - for (const tag of ["v0.2.0", "v0.3.0-rc.1", "v2026.10.21", "v2026.10.19.15"]) assert.ok(isGame(tag), tag); - for (const tag of ["launcher@0.2.0", "launcher-v0.16.0", "v0.2", "vnext", "v2026.10.21-x"]) assert.ok(!isGame(tag), tag); - assert.equal(launcherVersion("launcher@0.2.0"), "0.2.0"); - assert.equal(launcherVersion("launcher-v0.16.0"), "0.16.0"); - assert.ok(!isLauncher("v0.2.0") && !isLauncher("launcher-vnext")); -}); diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 2682b1f82..b71910da4 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -10,7 +10,7 @@ //! (`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 +//! `tokens`: writes `crates/horizon-theme/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). //! //! `icons`: renders the icon masters in `docs/media/brand` (with `rsvg-convert`, from librsvg) @@ -79,9 +79,9 @@ fn git(repo: &Path, args: &[&str]) -> Result, String> { } fn tokens() -> Result<(), String> { - let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../website/src/tokens.css"); + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../crates/horizon-theme/tokens.css"); fs::write(&path, horizon_theme::css()).map_err(|e| format!("{}: {e}", path.display()))?; - println!("wrote website/src/tokens.css"); + println!("wrote crates/horizon-theme/tokens.css"); Ok(()) } @@ -195,7 +195,7 @@ fn icons() -> Result<(), String> { &repo.join("crates/horizon-theme/icons/horizon-64.png"), &render(&square, (64, 64))?, )?; - // Avatars and the website's icons. + // Avatars, and the website's icons (horizon-site copies docs/media/brand/web/ into its public/). let avatar = brand.join("avatar.svg"); for (svg, size, out) in [ ( @@ -203,15 +203,15 @@ fn icons() -> Result<(), String> { 500, "docs/media/brand/social/github-avatar-500.png", ), - (&avatar, 180, "website/public/apple-touch-icon.png"), - (&square, 32, "website/public/favicon-32.png"), + (&avatar, 180, "docs/media/brand/web/apple-touch-icon.png"), + (&square, 32, "docs/media/brand/web/favicon-32.png"), (&square, 1024, "docs/media/brand/icon-1024.png"), (&macos, 1024, "docs/media/brand/icon-macos-1024.png"), ] { write(&repo.join(out), &render(svg, (size, size))?)?; } write( - &repo.join("website/public/favicon.svg"), + &repo.join("docs/media/brand/web/favicon.svg"), &fs::read(&square).map_err(|e| format!("{}: {e}", square.display()))?, )?; println!("wrote packaging/icons, the window icon, the avatars and the website's icons");