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..227d810d6 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -72,7 +72,46 @@ jobs:
if: steps.rust.outputs.required != 'false'
run: |
cargo +stable test --workspace --lib --bins --tests --features horizon-client/mods,horizon-mods/pack
+ # The full content-root tests (#[ignore]d: minutes each on a laptop). The same build as above; they need the
+ # prepared vanilla data, so without it they pass at once.
+ cargo +stable test --workspace --lib --features horizon-client/mods,horizon-mods/pack mod_content::tests:: -- --ignored
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 +147,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..3804ebae8 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`, `HORIZON_LAUNCHER_CLIPBOARD` and `HORIZON_LAUNCHER_DESKTOP` 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
@@ -62,6 +66,7 @@ unittest discover -s tests`), `mods/horizon/src/test/java/dev/horizonlab/parity/
python3 tools/pr_ready.py # the self-check: fmt, clippy -D warnings, touched crates' tests, harnesses; paste its block in the PR
python3 tools/pr_ready.py --quick # same without harnesses
cargo test -p horizon-client --lib --bins --tests # skips the 104 examples (pr_ready does this); `--doc` separately
+cargo test -p horizon-client --features horizon-client/mods --lib mod_content::tests:: -- --ignored # the 5 slow content-root tests, #[ignore]d; pr_ready runs them when mod content, assets, blocks or items change
cargo build --profile fast -p horizon-client # optimized, quick to link: use it to play or run lan_e2e
python3 tools/parity.py --changed origin/main # the harnesses your branch can affect (CI's parity job)
python3 tools/parity.py --changed-files paths.txt --list # which harnesses cover these files, without running them
@@ -117,16 +122,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..e65b25dab 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"
@@ -923,6 +930,13 @@ version = "3.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7"
+[[package]]
+name = "far-view"
+version = "1.0.0"
+dependencies = [
+ "horizon-mod-sdk",
+]
+
[[package]]
name = "fdeflate"
version = "0.3.7"
@@ -1365,9 +1379,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",
@@ -1388,6 +1405,7 @@ dependencies = [
"sha1",
"sha2",
"symphonia",
+ "unicode-bidi",
"ureq",
"wgpu",
"winit",
@@ -1395,6 +1413,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 +1461,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 +3005,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"
@@ -3725,6 +3775,12 @@ version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+[[package]]
+name = "unicode-bidi"
+version = "0.3.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
+
[[package]]
name = "unicode-ident"
version = "1.0.26"
diff --git a/Cargo.toml b/Cargo.toml
index e4628f962..8f3153c62 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,46 @@
[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/far-view",
+ "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 90%
rename from crates/horizon-client/src/lang.rs
rename to crates/horizon-client-core/src/lang.rs
index cb96cc373..ad9f1a358 100644
--- a/crates/horizon-client/src/lang.rs
+++ b/crates/horizon-client-core/src/lang.rs
@@ -4,7 +4,10 @@
//! language used by every screen.
use std::{
collections::{BTreeMap, HashMap},
- sync::{Arc, RwLock},
+ sync::{
+ Arc, RwLock,
+ atomic::{AtomicBool, Ordering},
+ },
};
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -23,11 +26,16 @@ impl LanguageInfo {
#[derive(Default)]
pub struct Language {
pub code: String,
+ /// `LanguageInfo.bidirectional`: text without a strong character reads
+ /// right to left (`ClientLanguage.defaultRightToLeft`).
+ bidirectional: bool,
map: HashMap,
}
pub const DEFAULT: &str = "en_us";
static CURRENT: RwLock>> = RwLock::new(None);
+/// The current language's `bidirectional`, read for every drawn string.
+static BIDIRECTIONAL: AtomicBool = AtomicBool::new(false);
/// A source of resource files: the prepared root plus packs, highest priority last.
pub trait ResourceSource {
@@ -42,8 +50,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())
@@ -130,8 +142,12 @@ impl Language {
{
apply_deprecated(&mut map, &bytes);
}
+ let bidirectional = available(sources)
+ .iter()
+ .any(|info| info.code == code && info.bidirectional);
Self {
code: code.to_owned(),
+ bidirectional,
map,
}
}
@@ -193,11 +209,16 @@ pub fn available(sources: &[&dyn ResourceSource]) -> Vec {
}
pub fn set(language: Language) {
+ BIDIRECTIONAL.store(language.bidirectional, Ordering::Relaxed);
*CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(language));
}
pub fn current() -> Option> {
CURRENT.read().unwrap_or_else(|e| e.into_inner()).clone()
}
+/// `ClientLanguage.defaultRightToLeft` of the current language.
+pub fn bidirectional() -> bool {
+ BIDIRECTIONAL.load(Ordering::Relaxed)
+}
pub fn code() -> String {
current().map_or_else(|| DEFAULT.to_owned(), |l| l.code.clone())
}
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..150433918 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.
@@ -59,6 +62,7 @@ gilrs = { version = "0.11", optional = true }
horizon-dualsense = { path = "../horizon-dualsense", optional = true }
# HTTPS to the Minecraft services (online-mode session join).
ureq = { version = "2", default-features = false, features = ["tls"] }
+unicode-bidi = "0.3.18"
[target.'cfg(unix)'.dependencies]
# The server thread's CPU time per tick (`HORIZON_SPIKES`, spans.rs).
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/finalize_spawn_fixture.rs b/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs
index b1b25e723..067d545a8 100644
--- a/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs
+++ b/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs
@@ -154,11 +154,11 @@ const MEMORIES: [&str; 7] = [
fn variant(m: &Mob, regs: &SpawnRegistries, v: &mut Vec) {
use Species as S;
let s = m.species();
- let named = |reg: &finalize::VariantRegistry, i: u8| {
- format!(
- "minecraft:{}",
+ let named = |reg: &finalize::VariantRegistry, i: Option| {
+ let name = i.map_or("classic", |i| {
reg.names.get(i as usize).map_or("?", |n| n.as_str())
- )
+ });
+ format!("minecraft:{name}")
};
let var = format!("minecraft:{}", finalize::variant_name(s, m.extra.variant));
match s {
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/recipe_book_fixture.rs b/crates/horizon-client/examples/probe/recipe_book_fixture.rs
index ce2afe624..2dda3b109 100644
--- a/crates/horizon-client/examples/probe/recipe_book_fixture.rs
+++ b/crates/horizon-client/examples/probe/recipe_book_fixture.rs
@@ -5,6 +5,10 @@
//!
//! usage: recipe_book_fixture RESOURCES CASES OUTPUT
use horizon_client::recipe_book::{BookType, RecipeIndex, Settings};
+use horizon_protocol::{
+ buf::{Codec, Reader, Writer},
+ packets::recipes::RecipeBookChangeSettings,
+};
use horizon_world::nbt::Tag;
use serde_json::Value;
use std::{collections::BTreeSet, fs, path::Path};
@@ -93,8 +97,23 @@ pub fn main() -> horizon_client::Result<()> {
_ => BookType::Smoker,
}
.index();
- book.open[i] = op["open"].as_bool().unwrap_or(false);
- book.filtering[i] = op["filtering"].as_bool().unwrap_or(false);
+ let packet = RecipeBookChangeSettings {
+ book_type: i as i32,
+ open: op["open"].as_bool().unwrap_or(false),
+ filtering: op["filtering"].as_bool().unwrap_or(false),
+ };
+ let mut wire = Writer::new();
+ RecipeBookChangeSettings::write(&packet, &mut wire);
+ extra = format!(
+ " packet={}",
+ wire.data
+ .iter()
+ .map(|b| format!("{b:02x}"))
+ .collect::()
+ );
+ let decoded = RecipeBookChangeSettings::read(&mut Reader::new(&wire.data))?;
+ book.open[decoded.book_type as usize] = decoded.open;
+ book.filtering[decoded.book_type as usize] = decoded.filtering;
}
"save" => {
let tag = book.write();
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 ad160d787..3d473d7e7 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.
@@ -83,6 +89,8 @@ enum Animate {
EndGateway,
/// A lightning rod, by the axis it points along (0, 1, 2 for X, Y, Z).
LightningRod(usize),
+ /// `WetSpongeBlock.animateTick`.
+ WetSponge,
}
fn step(facing: &str) -> [i32; 3] {
match facing {
@@ -118,10 +126,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()),
@@ -133,6 +148,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);
@@ -157,7 +180,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"),
},
@@ -194,6 +218,10 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate {
2
})
}
+ "wet_sponge" => Animate::WetSponge,
+ // BrushableBlock has no dust colour of its own, so the dust is the map colour.
+ "suspicious_sand" => Animate::Falling(0xF7E9A3),
+ "suspicious_gravel" => Animate::Falling(0x707070),
"sculk_sensor" | "calibrated_sculk_sensor"
if prop("sculk_sensor_phase").as_deref() == Some("active") =>
{
@@ -206,6 +234,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;
@@ -239,6 +288,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>,
/// Per state: 1 for a pointed dripstone, 2 for one whose tip points down.
@@ -271,6 +322,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!(
@@ -316,6 +382,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,
})
}
@@ -561,6 +628,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,
@@ -742,7 +856,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
@@ -762,7 +876,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 {
@@ -934,6 +1048,36 @@ fn block_animate_tick(
}
}
}
+ Animate::WetSponge => {
+ // Direction.getRandom: DOWN, UP, NORTH, SOUTH, WEST, EAST.
+ const DIRECTIONS: [[i32; 3]; 6] = [
+ [0, -1, 0],
+ [0, 1, 0],
+ [0, 0, -1],
+ [0, 0, 1],
+ [-1, 0, 0],
+ [1, 0, 0],
+ ];
+ let d = DIRECTIONS[next_int(engine.random(), 6) as usize];
+ // The sponge occludes, so only a sturdy neighbour face hides the drip.
+ if d != [0, 1, 0] && !ctx.sturdy([pos[0] + d[0], pos[1] + d[1], pos[2] + d[2]]) {
+ let r = engine.random();
+ let p = match d {
+ [0, -1, 0] => [fx + r.next_double(), fy - 0.05, fz + r.next_double()],
+ [dx, _, 0] => {
+ let y = fy + r.next_double() * 0.8;
+ let z = fz + r.next_double();
+ [fx + if dx > 0 { 1.1 } else { 0.05 }, y, z]
+ }
+ [_, _, dz] => {
+ let y = fy + r.next_double() * 0.8;
+ let x = fx + r.next_double();
+ [x, y, fz + if dz > 0 { 1.1 } else { 0.05 }]
+ }
+ };
+ add(engine, T::DrippingWater, p, [0.0; 3]);
+ }
+ }
Animate::Mycelium => {
let r = engine.random();
if next_int(r, 10) == 0 {
@@ -1127,6 +1271,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],
@@ -1275,7 +1426,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);
@@ -1287,6 +1438,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]);
+ }
+ }
}
}
}
@@ -1372,32 +1572,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;
@@ -1411,6 +1650,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/audio.rs b/crates/horizon-client/src/audio.rs
index be6628ece..e45362e19 100644
--- a/crates/horizon-client/src/audio.rs
+++ b/crates/horizon-client/src/audio.rs
@@ -719,11 +719,6 @@ impl Audio {
self.play(event, at, volume, pitch);
self.capture = capture;
}
- /// `LivingEntity.handleDamageEvent`'s pitch, `(r - r) * 0.2 + 1`, drawn on the
- /// client (the entity's own random there, never the server's world random).
- pub fn hurt_pitch(&mut self) -> f32 {
- (self.random.next_float() - self.random.next_float()) * 0.2 + 1.0
- }
/// `AbstractWidget.playButtonClickSound`: an unseeded, relative UI sound.
pub fn play_button_click(&mut self) {
self.play_instance(
diff --git a/crates/horizon-client/src/benchmark.rs b/crates/horizon-client/src/benchmark.rs
index bcb94589c..bd2e97be0 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,61 @@ 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);
+ }
+ /// The status a fake control answers with: the player is where it should
+ /// be, nothing is queued, and the world holds `chunks` resident chunks.
+ fn status(chunks: u64) -> String {
+ serde_json::json!({
+ "player": {"position": [0.0, 64.0, 0.0]},
+ "pending_chunks": 0,
+ "screen": "playing",
+ "render_distance": 12,
+ "chunks": chunks,
+ "generated_chunks": chunks,
+ "meshed_sections": 0,
+ "streaming": {},
+ })
+ .to_string()
+ }
+
+ #[test]
+ fn the_load_waits_for_the_chunks_a_teleport_starts() {
+ // Right after a teleport the game reports steady counts and nothing
+ // queued for over a second, before the integrated server has sent the
+ // first chunk: the quiet rule alone would call that loaded, and the
+ // scene would be measured over an empty view (#1749).
+ const LATE: usize = 30;
+ let (tx, rx) = mpsc::channel::();
+ let polls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let counted = std::sync::Arc::clone(&polls);
+ let server = thread::spawn(move || {
+ let mut seen = 0;
+ while let Ok(request) = rx.recv() {
+ if request.line == "status" {
+ let chunks = if seen < LATE { 0 } else { 400 };
+ seen += 1;
+ counted.store(seen, std::sync::atomic::Ordering::SeqCst);
+ let _ = request.reply.send(status(chunks));
+ } else {
+ let _ = request.reply.send("{}".to_owned());
+ }
+ }
+ });
+ let control = Control(tx);
+ wait_loaded(&control, |_| true).expect("the scene loads");
+ assert!(
+ polls.load(std::sync::atomic::Ordering::SeqCst) > LATE,
+ "the load finished before the chunks arrived"
+ );
+ drop(control);
+ let _ = server.join();
+ }
+
#[test]
fn yaw_matches_vanilla() {
// South (+Z) is 0, west (-X) 90, east (+X) -90.
diff --git a/crates/horizon-client/src/bidi.rs b/crates/horizon-client/src/bidi.rs
new file mode 100644
index 000000000..c9c6caac7
--- /dev/null
+++ b/crates/horizon-client/src/bidi.rs
@@ -0,0 +1,302 @@
+//! Right-to-left text (`FormattedBidiReorder.reorder`, behind
+//! `Language.getVisualOrder`): the logical text a player types becomes the
+//! glyphs a font draws left to right. Arabic letters are shaped into their
+//! joined presentation forms (ICU's `ArabicShaping` with `LETTERS_SHAPE`), the
+//! text is reordered by the Unicode bidirectional algorithm, and characters in
+//! right-to-left runs are mirrored. Left-to-right text comes back unchanged.
+use crate::text::{Span, Text};
+use std::borrow::Cow;
+use unicode_bidi::{
+ BidiClass, Direction, Level, ParagraphBidiInfo, bidi_class, get_base_direction,
+};
+
+/// How a letter joins its neighbours, as ICU's shaper sees it: `Right` joins
+/// the letter before it only, `Dual` both neighbours, `Mark` is skipped over
+/// (diacritics) and `None` never joins.
+#[derive(Clone, Copy, PartialEq)]
+enum Join {
+ None,
+ Right,
+ Dual,
+ Mark,
+}
+use Join::{Dual, Mark, Right};
+
+/// ICU's joining table (`araLink`): code point ranges and their class, with the
+/// lam-alef ligatures at the end. Anything else is `Join::None`.
+const JOINS: &[(u32, u32, Join)] = &[
+ (0x0622, 0x0625, Right),
+ (0x0626, 0x0626, Dual),
+ (0x0627, 0x0627, Right),
+ (0x0628, 0x0628, Dual),
+ (0x0629, 0x0629, Right),
+ (0x062A, 0x062E, Dual),
+ (0x062F, 0x0632, Right),
+ (0x0633, 0x063A, Dual),
+ (0x0640, 0x0647, Dual),
+ (0x0648, 0x0649, Right),
+ (0x064A, 0x064A, Dual),
+ (0x064B, 0x0656, Mark),
+ (0x0670, 0x0670, Mark),
+ (0x0671, 0x0673, Right),
+ (0x0675, 0x0677, Right),
+ (0x0678, 0x0687, Dual),
+ (0x0688, 0x0699, Right),
+ (0x069A, 0x06B9, Dual),
+ (0x06BA, 0x06BA, Right),
+ (0x06BB, 0x06BF, Dual),
+ (0x06C0, 0x06C0, Right),
+ (0x06C1, 0x06C1, Dual),
+ (0x06C2, 0x06CB, Right),
+ (0x06CC, 0x06CC, Dual),
+ (0x06CD, 0x06CD, Right),
+ (0x06CE, 0x06D1, Dual),
+ (0x06D2, 0x06D3, Right),
+ (0x200D, 0x200D, Dual),
+ (0x206D, 0x206F, Mark),
+ (0xFEF5, 0xFEFC, Right),
+];
+
+/// Letters that have joined forms and the code point of the isolated one; the
+/// final, initial and medial forms follow it (a right-joining letter has the
+/// isolated and final only). The lam-alef ligatures are their own letters.
+/// ICU leaves the extended letters (پ چ ژ ک گ ی and the rest of U+0679 to
+/// U+06D3) unchanged, so they are in `JOINS` but not here.
+#[rustfmt::skip]
+const FORMS: &[(u32, u32)] = &[
+ (0x0622, 0xFE81), (0x0623, 0xFE83), (0x0624, 0xFE85), (0x0625, 0xFE87), (0x0626, 0xFE89),
+ (0x0627, 0xFE8D), (0x0628, 0xFE8F), (0x0629, 0xFE93), (0x062A, 0xFE95), (0x062B, 0xFE99),
+ (0x062C, 0xFE9D), (0x062D, 0xFEA1), (0x062E, 0xFEA5), (0x062F, 0xFEA9), (0x0630, 0xFEAB),
+ (0x0631, 0xFEAD), (0x0632, 0xFEAF), (0x0633, 0xFEB1), (0x0634, 0xFEB5), (0x0635, 0xFEB9),
+ (0x0636, 0xFEBD), (0x0637, 0xFEC1), (0x0638, 0xFEC5), (0x0639, 0xFEC9), (0x063A, 0xFECD),
+ (0x0641, 0xFED1), (0x0642, 0xFED5), (0x0643, 0xFED9), (0x0644, 0xFEDD), (0x0645, 0xFEE1),
+ (0x0646, 0xFEE5), (0x0647, 0xFEE9), (0x0648, 0xFEED), (0x0649, 0xFEEF), (0x064A, 0xFEF1),
+ (0xFEF5, 0xFEF5), (0xFEF7, 0xFEF7), (0xFEF9, 0xFEF9), (0xFEFB, 0xFEFB),
+];
+
+/// `Bidi_Mirroring_Glyph` (`UCharacter.getMirror`): each pair is two
+/// neighbouring characters that mirror each other.
+const MIRRORED: &str = "\
+ ()<>[]{}«»༺༻༼༽᚛᚜‹›⁅⁆⁽⁾₍₎∈∋∉∌∊∍∕⧵∟⯾∠⦣∡⦛∢⦠∤⫮∼∽≃⋍≅≌≒≓\
+ ≔≕≤≥≦≧≨≩≪≫≮≯≰≱≲≳≴≵≶≷≸≹≺≻≼≽≾≿⊀⊁⊂⊃⊄⊅⊆⊇⊈⊉⊊⊋⊏⊐⊑⊒⊘⦸⊢⊣⊦⫞\
+ ⊨⫤⊩⫣⊫⫥⊰⊱⊲⊳⊴⊵⊶⊷⊸⟜⋉⋊⋋⋌⋐⋑⋖⋗⋘⋙⋚⋛⋜⋝⋞⋟⋠⋡⋢⋣⋤⋥⋦⋧⋨⋩⋪⋫⋬⋭⋰⋱⋲⋺\
+ ⋳⋻⋴⋼⋶⋽⋷⋾⌈⌉⌊⌋〈〉❨❩❪❫❬❭❮❯❰❱❲❳❴❵⟃⟄⟅⟆⟈⟉⟋⟍⟕⟖⟝⟞⟢⟣⟤⟥⟦⟧⟨⟩⟪⟫\
+ ⟬⟭⟮⟯⦃⦄⦅⦆⦇⦈⦉⦊⦋⦌⦍⦐⦎⦏⦑⦒⦓⦔⦕⦖⦗⦘⦤⦥⦨⦩⦪⦫⦬⦭⦮⦯⧀⧁⧄⧅⧏⧐⧑⧒⧔⧕⧘⧙⧚⧛\
+ ⧨⧩⧸⧹⧼⧽⨫⨬⨭⨮⨴⨵⨼⨽⩤⩥⩹⩺⩻⩼⩽⩾⩿⪀⪁⪂⪃⪄⪅⪆⪇⪈⪉⪊⪋⪌⪍⪎⪏⪐⪑⪒⪓⪔⪕⪖⪗⪘⪙⪚\
+ ⪛⪜⪝⪞⪟⪠⪡⪢⪦⪧⪨⪩⪪⪫⪬⪭⪯⪰⪱⪲⪳⪴⪵⪶⪷⪸⪹⪺⪻⪼⪽⪾⪿⫀⫁⫂⫃⫄⫅⫆⫇⫈⫉⫊⫋⫌⫍⫎⫏⫐\
+ ⫑⫒⫓⫔⫕⫖⫬⫭⫷⫸⫹⫺⸂⸃⸄⸅⸉⸊⸌⸍⸜⸝⸠⸡⸢⸣⸤⸥⸦⸧⸨⸩⹕⹖⹗⹘⹙⹚⹛⹜〈〉《》「」『』【】\
+ 〔〕〖〗〘〙〚〛﹙﹚﹛﹜﹝﹞﹤﹥()<>[]{}⦅⦆「」";
+
+fn join(c: char) -> Join {
+ let c = c as u32;
+ JOINS
+ .iter()
+ .find(|&&(from, to, _)| (from..=to).contains(&c))
+ .map_or(Join::None, |&(_, _, join)| join)
+}
+
+/// The letter whose joined form `c` is (ICU shapes the forms again), or `c`.
+fn letter_of(c: char) -> char {
+ let c32 = c as u32;
+ if !matches!(c32, 0xFE70..=0xFEFC) {
+ return c;
+ }
+ if (0xFE70..0xFE80).contains(&c32) {
+ // The diacritics' forms pair up from fathatan on.
+ return char::from_u32(0x064B + (c32 - 0xFE70) / 2).unwrap_or(c);
+ }
+ FORMS
+ .iter()
+ .find(|&&(letter, iso)| {
+ let forms = if join(char::from_u32(letter).unwrap_or(c)) == Dual {
+ 4
+ } else {
+ 2
+ };
+ (iso..iso + forms).contains(&c32)
+ })
+ .and_then(|&(letter, _)| char::from_u32(letter))
+ .unwrap_or(c)
+}
+
+/// `ArabicShaping(LETTERS_SHAPE).shape`: lam followed by an alef (diacritics
+/// may sit between) becomes one ligature, then every letter takes the isolated,
+/// final, initial or medial form its neighbours call for. Diacritics take the
+/// tatweel form between two joined letters. The text can only get shorter.
+fn shape(text: &[char]) -> Vec {
+ let letters: Vec = text.iter().map(|&c| letter_of(c)).collect();
+ let mut chars = Vec::with_capacity(letters.len());
+ let mut i = 0;
+ while i < letters.len() {
+ if letters[i] == '\u{644}' {
+ let mut at = i + 1;
+ while letters.get(at).is_some_and(|&c| join(c) == Mark) {
+ at += 1;
+ }
+ let alef = letters.get(at).and_then(|&c| {
+ ['\u{622}', '\u{623}', '\u{625}', '\u{627}']
+ .iter()
+ .position(|&a| a == c)
+ });
+ if let Some(alef) = alef {
+ chars.push(char::from_u32(0xFEF5 + 2 * alef as u32).unwrap_or('\u{644}'));
+ chars.extend_from_slice(&letters[i + 1..at]);
+ i = at + 1;
+ continue;
+ }
+ }
+ chars.push(letters[i]);
+ i += 1;
+ }
+ // Whether the nearest letter before joins the next one, and the joins of
+ // the nearest letter after.
+ let mut joins_next = false;
+ let mut out = Vec::with_capacity(chars.len());
+ for (i, &c) in chars.iter().enumerate() {
+ let next_joins = chars[i + 1..]
+ .iter()
+ .map(|&n| join(n))
+ .find(|&j| j != Mark)
+ .is_some_and(|j| j != Join::None);
+ let kind = join(c);
+ let shaped = match kind {
+ Join::None => {
+ joins_next = false;
+ c
+ }
+ Mark => match c as u32 {
+ m @ 0x064B..=0x0652 => {
+ let iso = 0xFE70 + 2 * (m - 0x064B);
+ let tatweel = joins_next && next_joins && !matches!(m, 0x064C | 0x064D);
+ char::from_u32(iso + u32::from(tatweel)).unwrap_or(c)
+ }
+ _ => c,
+ },
+ Right | Dual => {
+ let to_next = kind == Dual && next_joins;
+ let form = match (joins_next, to_next) {
+ (false, false) => 0,
+ (true, false) => 1,
+ (false, true) => 2,
+ (true, true) => 3,
+ };
+ joins_next = kind == Dual;
+ FORMS
+ .binary_search_by_key(&(c as u32), |&(letter, _)| letter)
+ .ok()
+ .and_then(|at| char::from_u32(FORMS[at].1 + form))
+ .unwrap_or(c)
+ }
+ };
+ out.push(shaped);
+ }
+ out
+}
+
+/// `UCharacter.getMirror`.
+fn mirror(c: char) -> char {
+ if bidi_class(c) != BidiClass::ON {
+ return c;
+ }
+ let mut pairs = MIRRORED.chars();
+ while let (Some(a), Some(b)) = (pairs.next(), pairs.next()) {
+ if c == a {
+ return b;
+ }
+ if c == b {
+ return a;
+ }
+ }
+ c
+}
+
+/// Whether a character can change anything: right-to-left letters and numbers,
+/// the explicit direction controls and the diacritics that shaping turns into
+/// letters. Without any, left-to-right text keeps its order.
+fn directional(c: char) -> bool {
+ c as u32 >= 0x0590
+ && (matches!(c as u32, 0x064B..=0x0652)
+ || matches!(
+ bidi_class(c),
+ BidiClass::R
+ | BidiClass::AL
+ | BidiClass::AN
+ | BidiClass::LRE
+ | BidiClass::RLE
+ | BidiClass::LRO
+ | BidiClass::RLO
+ | BidiClass::PDF
+ | BidiClass::LRI
+ | BidiClass::RLI
+ | BidiClass::FSI
+ | BidiClass::PDI
+ ))
+}
+
+/// Whether `chars` keep their order and shapes: left-to-right text without
+/// anything directional, in a language that reads left to right by default.
+fn unchanged(mut chars: impl Iterator- , default_rtl: bool) -> bool {
+ !default_rtl && !chars.any(directional)
+}
+
+/// `FormattedBidiReorder.reorder`: `chars` shaped, in visual order, with each
+/// character's position in the shaped text. A character's style is the one at
+/// its position in the shaped text, as `SubStringSource` takes it (the text
+/// shrinks at a lam-alef ligature).
+fn reorder(chars: &[char], default_rtl: bool) -> Vec<(char, usize)> {
+ let shaped = shape(chars);
+ let plain: String = shaped.iter().collect();
+ // DEFAULT_RTL only changes text without a strong character.
+ let level =
+ (default_rtl && get_base_direction(plain.as_str()) == Direction::Mixed).then(Level::rtl);
+ let info = ParagraphBidiInfo::new(&plain, level);
+ let levels = info.reordered_levels_per_char(0..plain.len());
+ ParagraphBidiInfo::reorder_visual(&levels)
+ .into_iter()
+ .map(|i| {
+ let c = if levels[i].is_rtl() {
+ mirror(shaped[i])
+ } else {
+ shaped[i]
+ };
+ (c, i)
+ })
+ .collect()
+}
+
+/// `Language.getVisualOrder` of a text (its `§` codes already resolved), for
+/// the current language's direction.
+pub fn visual(text: &Text) -> Cow<'_, Text> {
+ let default_rtl = crate::lang::bidirectional();
+ if unchanged(text.chars().map(|(c, _)| c), default_rtl) {
+ return Cow::Borrowed(text);
+ }
+ let chars: Vec
= text.chars().map(|(c, _)| c).collect();
+ let styles: Vec<_> = text.chars().map(|(_, style)| style).collect();
+ let mut out = Text::default();
+ for (c, at) in reorder(&chars, default_rtl) {
+ match out.spans.last_mut() {
+ Some(span) if span.style == *styles[at] => span.text.push(c),
+ _ => out.spans.push(Span {
+ text: c.to_string(),
+ style: styles[at].clone(),
+ }),
+ }
+ }
+ Cow::Owned(out)
+}
+
+/// The same for a plain string.
+pub fn visual_str(s: &str) -> Cow<'_, str> {
+ let default_rtl = crate::lang::bidirectional();
+ if unchanged(s.chars(), default_rtl) {
+ return Cow::Borrowed(s);
+ }
+ let chars: Vec = s.chars().collect();
+ Cow::Owned(
+ reorder(&chars, default_rtl)
+ .into_iter()
+ .map(|(c, _)| c)
+ .collect(),
+ )
+}
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 b8146a63f..57cf406c4 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()
@@ -609,7 +610,9 @@ fn sign_text_calls(
.iter()
.enumerate()
.map(|(i, line)| {
+ // The line that fits, in the order it is drawn (getVisualOrder).
let shown = first_line(line, data.max_line_width(), &advance);
+ let shown = crate::bidi::visual_str(&shown).into_owned();
TextCall {
matrix: m,
x: -((width(&shown) as i32) / 2) as f32,
@@ -2108,4 +2111,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/brewing.rs b/crates/horizon-client/src/brewing.rs
index f29bfc08b..cdd988a7a 100644
--- a/crates/horizon-client/src/brewing.rs
+++ b/crates/horizon-client/src/brewing.rs
@@ -7,7 +7,12 @@ use crate::{
items::{ItemStack, Items},
};
use serde_json::Value;
-use std::{collections::HashSet, fs, path::Path, sync::Arc};
+use std::{
+ collections::{HashMap, HashSet},
+ fs,
+ path::Path,
+ sync::{Arc, OnceLock},
+};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Category {
@@ -94,6 +99,24 @@ pub fn effect(id: &str) -> Option<&'static EffectDef> {
let id = id.trim_start_matches("minecraft:");
EFFECTS.iter().find(|e| e.id == id)
}
+/// Namespaced effect ids for mob effect storage.
+pub fn namespaced(id: &'static str) -> &'static str {
+ static IDS: OnceLock> = OnceLock::new();
+ IDS.get_or_init(|| {
+ EFFECTS
+ .iter()
+ .map(|e| {
+ (
+ e.id,
+ &*Box::leak(format!("minecraft:{}", e.id).into_boxed_str()),
+ )
+ })
+ .collect()
+ })
+ .get(id)
+ .copied()
+ .unwrap_or(id)
+}
/// A `Potion`: id, name suffix (`item.minecraft.potion.effect.`) and
/// effects as (effect, duration ticks, amplifier).
#[derive(Clone, Copy, Debug)]
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/chunk_map.rs b/crates/horizon-client/src/chunk_map.rs
index ed25491c5..fddded9e1 100644
--- a/crates/horizon-client/src/chunk_map.rs
+++ b/crates/horizon-client/src/chunk_map.rs
@@ -76,14 +76,11 @@ impl<'a> IntoIterator for &'a ChunkMap {
}
}
impl crate::light::LightWorld for ChunkMap {
- fn state(&self, x: i32, y: i32, z: i32) -> Option {
- self.columns.state(x, y, z)
+ fn section(&self, cx: i32, s: usize, cz: i32) -> Option<&Arc> {
+ self.columns.section(cx, s, cz)
}
- fn light(&self, x: i32, y: i32, z: i32) -> Option {
- self.columns.light(x, y, z)
- }
- fn set_light(&mut self, x: i32, y: i32, z: i32, packed: u8) {
- self.columns.set_light(x, y, z, packed);
+ fn set_section_light(&mut self, cx: i32, s: usize, cz: i32, light: crate::chunk::Light) {
+ self.columns.set_section_light(cx, s, cz, light);
}
}
@@ -106,7 +103,13 @@ mod tests {
for column in map.values_mut() {
Arc::make_mut(column).light_loaded = true;
}
- crate::light::LightWorld::set_light(&mut map, 0, 0, 0, 0);
+ crate::light::LightWorld::set_section_light(
+ &mut map,
+ 0,
+ 0,
+ 0,
+ crate::chunk::Light::Uniform(0),
+ );
assert_eq!(inserted, map.membership_revision());
map.remove(&(0, 0));
map.insert((1, 0), chunk);
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/command_block.rs b/crates/horizon-client/src/command_block.rs
index 942e11ab6..47f808932 100644
--- a/crates/horizon-client/src/command_block.rs
+++ b/crates/horizon-client/src/command_block.rs
@@ -35,6 +35,23 @@ impl Mode {
Self::Redstone => "minecraft:command_block",
}
}
+ /// `Enum.ordinal`, which `ServerboundSetCommandBlockPacket` writes.
+ pub fn ordinal(self) -> i32 {
+ match self {
+ Self::Sequence => 0,
+ Self::Auto => 1,
+ Self::Redstone => 2,
+ }
+ }
+ /// The mode of a packet's ordinal; `handleSetCommandBlock` treats any
+ /// other value as a plain command block (its `default` branch).
+ pub fn from_ordinal(ordinal: i32) -> Self {
+ match ordinal {
+ 0 => Self::Sequence,
+ 1 => Self::Auto,
+ _ => Self::Redstone,
+ }
+ }
/// `CycleButton`: the next value, wrapping round.
pub fn next(self) -> Self {
match self {
diff --git a/crates/horizon-client/src/container_screen.rs b/crates/horizon-client/src/container_screen.rs
index 2c490861a..a7b1794c5 100644
--- a/crates/horizon-client/src/container_screen.rs
+++ b/crates/horizon-client/src/container_screen.rs
@@ -124,6 +124,18 @@ impl Clicks {
self.skip_next_release = true;
}
+ /// The screen that takes the pointer over starts with its own state:
+ /// `AbstractContainerScreen` holds `isQuickCrafting` and the drag it
+ /// belongs to on the screen, so a screen that opens (or closes) drops
+ /// them. A press whose release never arrived -- the pointer left the
+ /// window -- would otherwise keep the drag running, and `press` answers
+ /// `None` for every later press, so the quick move and the clicks go
+ /// dead on every screen after it.
+ pub fn cancel_drag(&mut self) {
+ self.quick_crafting = None;
+ self.skip_next_release = false;
+ }
+
/// `mouseClicked` (no double click): the `slotClicked` input it sends on
/// `target`, if any. A press holding a stack starts a quick craft drag
/// instead. `cloning` is `keyPickItem` with infinite materials.
@@ -275,4 +287,61 @@ 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)
+ );
+ }
+
+ /// #1737: a press whose release never arrives (the pointer left the
+ /// window) leaves `isQuickCrafting` set, and `press` answers `None` for
+ /// every later press, so the Shift quick move and the clicks on the
+ /// inventory go dead. The drag belongs to the screen that has it
+ /// (`AbstractContainerScreen` holds `isQuickCrafting`), so the screen
+ /// that takes the pointer over drops it and the quick move works again.
+ #[test]
+ fn a_lost_release_does_not_wedge_the_quick_move() {
+ let mut clicks = Clicks::default();
+ let slot = Target::::Slot(3);
+ // Pressed with a stack carried: a quick craft drag starts, and its
+ // release never arrives.
+ assert_eq!(clicks.press(&slot, Button::Left, false, false, false), None);
+ assert!(clicks.quick_crafting().is_some());
+ // The stuck drag swallows the next press: the Shift quick move stops
+ // working and the inventory stops answering.
+ assert_eq!(clicks.press(&slot, Button::Right, true, true, false), None);
+ // The screen that takes the pointer over starts with its own state.
+ clicks.cancel_drag();
+ assert!(clicks.quick_crafting().is_none());
+ // The quick move works again.
+ assert_eq!(
+ clicks.press(&slot, Button::Right, true, true, false),
+ Some(Input::QuickMove)
+ );
+ 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/effects.rs b/crates/horizon-client/src/effects.rs
index 17dce93ab..16a7a273a 100644
--- a/crates/horizon-client/src/effects.rs
+++ b/crates/horizon-client/src/effects.rs
@@ -179,13 +179,14 @@ impl PlayerEffects {
self.list.clear();
}
/// The effects of a saved player (`Player.active_effects`: id,
- /// duration, amplifier, ambient, visible).
+ /// duration, amplifier, ambient, particles visible).
pub fn from_saved(saved: &[(String, i32, i32, bool, bool)]) -> Self {
let mut effects = Self::default();
- for (id, duration, amplifier, ambient, _) in saved {
+ for (id, duration, amplifier, ambient, particles) in saved {
if let Some(def) = brewing::effect(id) {
let mut e = EffectInstance::new(def.id, *duration, *amplifier);
e.ambient = *ambient;
+ e.visible = *particles;
effects.add(e);
}
}
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..14cd946c2 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 {
@@ -525,17 +582,21 @@ impl Experience {
7 + level * 2
}
}
- /// Returns true when a level was gained.
- pub fn give(&mut self, points: i32) -> bool {
- let start = self.level;
+ /// Returns the first multiple of 5 the player reached, where each level
+ /// gained would play the level-up sound (`Player.giveExperienceLevels`).
+ pub fn give(&mut self, points: i32) -> Option {
+ let mut sound_level = None;
self.progress += points as f32 / Self::needed(self.level) as f32;
self.total = self.total.saturating_add(points).max(0);
while self.progress >= 1.0 {
self.progress = (self.progress - 1.0) * Self::needed(self.level) as f32;
self.level += 1;
+ if self.level % 5 == 0 {
+ sound_level.get_or_insert(self.level);
+ }
self.progress /= Self::needed(self.level) as f32;
}
- self.level > start
+ sound_level
}
}
/// A painting (`Painting`, a `HangingEntity`): the block it hangs in, the
@@ -591,6 +652,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..2541a4b35 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 {
@@ -192,7 +203,7 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
// lit texture, then the lightmap, then the glint and fog.
color = vec4(mix(in.overlay_color.rgb, color.rgb, in.overlay_color.a), color.a);
color *= in.light_color;
- if in.overlay == 7u || in.overlay == 8u {
+ if in.overlay == 7u || in.overlay == 8u || in.overlay == 33u {
// Enchantment glint (overlay 7, 8 with the hurt tint): the purple
// enchanted_glint sheen drifting diagonally over the item's shape.
let px = in.uv * vec2(textureDimensions(atlas));
@@ -208,9 +219,22 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a);
}
+fn celestial_color(in: Out) -> vec4 {
+ return textureSample(atlas, atlas_sampler, in.uv) * in.color * in.light_color;
+}
@fragment fn fs_celestial(in: Out) -> @location(0) vec4 {
- let color = textureSample(atlas, atlas_sampler, in.uv) * in.color * in.light_color;
- return color;
+ return celestial_color(in);
+}
+
+// The sky's celestial pass (sun, moon, the End sky): fs_celestial's light,
+// premultiplied for an additive (one, one) blend, and as alpha how much of it
+// the texel adds, which the blend takes off the frame's alpha. HDR output
+// (hdr.wgsl) lifts only where that left it low: the sun's and moon's discs, not
+// the dark rest of their quads or the dim End sky.
+@fragment fn fs_sky_celestial(in: Out) -> @location(0) vec4 {
+ let color = celestial_color(in);
+ let added = color.rgb * color.a;
+ return vec4(added, smoothstep(0.1, 0.3, max(added.r, max(added.g, added.b))));
}
// RenderPipelines.WATER_MASK: depth only (the pipeline masks the colour off).
diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs
index 00576ea02..c65f35f5b 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,51 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
map.remove(&horizon_world::nbt::JavaString::from(key));
}
}
+ // LivingEntity.addAdditionalSaveData: `active_effects` only when there are
+ // any (MobEffectInstance.CODEC; a mob's effects are never ambient, and one
+ // given with `hideParticles` shows neither particles nor its icon).
+ if m.extra.effects.is_empty() {
+ map.remove(&horizon_world::nbt::JavaString::from("active_effects"));
+ } else {
+ let effects = m
+ .extra
+ .effects
+ .iter()
+ .map(|&(effect, duration, amplifier)| {
+ let shown = !m.extra.hidden_effects.contains(&effect);
+ let mut e = vec![
+ ("id", string(crate::brewing::namespaced(effect))),
+ ("amplifier", Tag::Byte(amplifier.clamp(0, 255) as u8 as i8)),
+ ("duration", Tag::Int(duration)),
+ ];
+ if !shown {
+ e.push(("show_particles", Tag::Byte(0)));
+ }
+ e.push(("show_icon", Tag::Byte(i8::from(shown))));
+ Tag::compound(e)
+ });
+ map.insert("active_effects".into(), Tag::List(effects.collect()));
+ }
+ 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 +241,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 +253,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));
@@ -225,7 +269,51 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
if is_animal(id) {
map.insert("InLove".into(), Tag::Int(m.extra.in_love.max(0)));
}
+ let species = m.species();
+ if let Some((_, variant)) =
+ crate::mobs::finalize::species_variant_component(species, m.extra.variant)
+ {
+ map.insert("variant".into(), string(&variant));
+ }
+ if species == crate::mobs::Species::Chicken {
+ map.insert("EggLayTime".into(), Tag::Int(m.extra.egg_time));
+ }
+ let sounds = crate::mobs::finalize::sound_variants(species);
+ if !sounds.is_empty() {
+ let sound = m.extra.sound_variant.and_then(|i| sounds.get(i as usize));
+ let sound = sound.copied().unwrap_or("classic");
+ map.insert(
+ "sound_variant".into(),
+ string(&format!("minecraft:{sound}")),
+ );
+ }
match id {
+ // Fox.addAdditionalSaveData; Horizon models only the type.
+ "minecraft:fox" => {
+ let kind = if m.extra.variant == 1 { "snow" } else { "red" };
+ map.insert("Type".into(), string(kind));
+ for (key, value) in [
+ ("Trusted", Tag::List(Vec::new())),
+ ("Sleeping", Tag::Byte(0)),
+ ("Sitting", Tag::Byte(0)),
+ ("Crouching", Tag::Byte(0)),
+ ] {
+ map.entry(key.into()).or_insert(value);
+ }
+ }
+ "minecraft:rabbit" => {
+ map.insert("RabbitType".into(), Tag::Int(i32::from(m.extra.variant)));
+ map.entry("MoreCarrotTicks".into()).or_insert(Tag::Int(0));
+ }
+ "minecraft:goat" => {
+ map.insert(
+ "IsScreamingGoat".into(),
+ Tag::Byte(i8::from(m.extra.screaming)),
+ );
+ let [left, right] = m.extra.lost_horns;
+ map.insert("HasLeftHorn".into(), Tag::Byte(i8::from(!left)));
+ map.insert("HasRightHorn".into(), Tag::Byte(i8::from(!right)));
+ }
"minecraft:creeper" => {
for (key, value) in [("Fuse", Tag::Short(30)), ("ExplosionRadius", Tag::Byte(3))] {
map.entry(key.into()).or_insert(value);
@@ -241,10 +329,6 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
}
map.insert("Sitting".into(), Tag::Byte(i8::from(m.extra.sitting)));
map.insert("CollarColor".into(), Tag::Byte(m.extra.color as i8));
- let variant = crate::mobs::tame::CAT_VARIANTS[(m.extra.variant as usize).min(10)];
- map.insert("variant".into(), string(&format!("minecraft:{variant}")));
- map.entry("sound_variant".into())
- .or_insert_with(|| string("minecraft:classic"));
}
"minecraft:wolf" => {
if let Some(owner) = m.extra.owner {
@@ -254,17 +338,30 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
}
map.insert("Sitting".into(), Tag::Byte(i8::from(m.extra.sitting)));
map.insert("CollarColor".into(), Tag::Byte(m.extra.color as i8));
- let variant = crate::mobs::tame::WOLF_VARIANTS[(m.extra.variant as usize).min(8)].0;
- map.insert("variant".into(), string(&format!("minecraft:{variant}")));
- map.entry("sound_variant".into())
- .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"
@@ -275,6 +372,10 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
| "minecraft:trader_llama" => {
map.insert("Tame".into(), Tag::Byte(i8::from(m.extra.tame)));
map.insert("Temper".into(), Tag::Int(i32::from(m.extra.variant3)));
+ // AbstractHorse.addAdditionalSaveData; Horizon models neither.
+ for key in ["EatingHaystack", "Bred"] {
+ map.entry(key.into()).or_insert(Tag::Byte(0));
+ }
if let Some(owner) = m.extra.owner {
map.insert("Owner".into(), Tag::IntArray(owner.to_vec()));
}
@@ -357,6 +458,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 {
@@ -384,7 +491,36 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
crate::mobs::villager::write_nbt(m, map);
}
"minecraft:wandering_trader" => put_offers(map, m),
- "minecraft:axolotl" => write_axolotl_memories(m, map),
+ "minecraft:axolotl" => {
+ write_axolotl_memories(m, map);
+ map.insert(
+ "Variant".into(),
+ Tag::Int(i32::from(m.extra.variant.min(4))),
+ );
+ }
+ // Rabbit.addAdditionalSaveData (the legacy id; 99 is the killer bunny).
+ "minecraft:rabbit" => {
+ map.insert("RabbitType".into(), Tag::Int(i32::from(m.extra.variant)));
+ }
+ "minecraft:parrot" => {
+ map.insert(
+ "Variant".into(),
+ Tag::Int(i32::from(m.extra.variant.min(4))),
+ );
+ }
+ "minecraft:salmon" => {
+ let size = SALMON_SIZES[usize::from(m.extra.variant).min(2)];
+ map.insert("type".into(), string(size));
+ }
+ // TropicalFish.addAdditionalSaveData: the packed variant.
+ "minecraft:tropical_fish" => {
+ let pattern = m.extra.variant.min(11);
+ let packed = i32::from(pattern >= 6)
+ | i32::from(pattern % 6) << 8
+ | i32::from(m.extra.variant2 & 15) << 16
+ | i32::from(m.extra.variant3 & 15) << 24;
+ map.insert("Variant".into(), Tag::Int(packed));
+ }
"minecraft:allay" => {
// InventoryCarrier: the fetched stack; the liked player memory.
let mut inv = Vec::new();
@@ -479,10 +615,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 +641,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 +745,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 +847,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,7 +888,18 @@ 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);
+ // LivingEntity.setHealth clamps to the max health: a horse or llama is made
+ // with the type's and saved before it drops to the one it rolled. (Only
+ // the base is read here, so the clamp would cut a leader zombie's bonus.)
+ if crate::mobs::equine::is_equine(m.species()) {
+ m.health = m.health.min(m.attrs.max_health);
+ }
m.hurt_time = number(tag.get("HurtTime")).unwrap_or(0) as i32;
// What it holds (equipment.mainhand / offhand), when saved.
if let Some(eq) = tag.get("equipment") {
@@ -674,7 +940,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");
@@ -687,6 +954,25 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) -
m.no_gravity = flag(tag, "NoGravity");
m.glowing = flag(tag, "Glowing");
m.ticks_frozen = number(tag.get("TicksFrozen")).unwrap_or(0) as i32;
+ // LivingEntity.readAdditionalSaveData: the saved `active_effects`, the last
+ // entry of an effect winning.
+ if let Some(Tag::List(effects)) = tag.get("active_effects") {
+ for e in effects {
+ let Some(def) = text(e.get("id")).and_then(|id| crate::brewing::effect(&id)) else {
+ continue;
+ };
+ let effect = crate::brewing::namespaced(def.id);
+ let duration = number(e.get("duration")).unwrap_or(0) as i32;
+ let amplifier = number(e.get("amplifier")).unwrap_or(0) as i32;
+ m.extra.effects.retain(|x| x.0 != effect);
+ m.extra.effects.push((effect, duration, amplifier));
+ // Details.CODEC: `show_particles` defaults to true.
+ m.extra.hidden_effects.retain(|h| *h != effect);
+ if number(e.get("show_particles")) == Some(0) {
+ m.extra.hidden_effects.push(effect);
+ }
+ }
+ }
m.silent = flag(tag, "Silent");
m.invulnerable_flag = flag(tag, "Invulnerable");
if m.species() == crate::mobs::Species::Bat {
@@ -706,6 +992,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(),
@@ -758,20 +1054,45 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) -
m.extra.vector[0] = 0.7;
}
}
+ if crate::mobs::finalize::species_variant_component(m.species(), 0).is_some()
+ && let Some(v) = text(tag.get("variant"))
+ {
+ m.extra.variant = crate::mobs::finalize::variant_index(m.species(), &v);
+ }
+ if m.species() == crate::mobs::Species::Chicken
+ && let Some(t) = number(tag.get("EggLayTime"))
+ {
+ m.extra.egg_time = t as i32;
+ }
+ if let Some(v) = text(tag.get("sound_variant")) {
+ let v = v.trim_start_matches("minecraft:");
+ let sounds = crate::mobs::finalize::sound_variants(m.species());
+ m.extra.sound_variant = sounds.iter().position(|n| *n == v).map(|i| i as u8);
+ }
+ match m.species() {
+ crate::mobs::Species::Fox => {
+ m.extra.variant = u8::from(text(tag.get("Type")).as_deref() == Some("snow"));
+ }
+ crate::mobs::Species::Rabbit => {
+ // Rabbit.Variant.byId: an unknown id is brown.
+ m.extra.variant = match number(tag.get("RabbitType")).unwrap_or(0) {
+ v @ (0..=5 | 99) => v as u8,
+ _ => 0,
+ };
+ }
+ crate::mobs::Species::Goat => {
+ m.extra.screaming = flag(tag, "IsScreamingGoat");
+ let horn = |key| number(tag.get(key)).is_some_and(|v| v == 0);
+ m.extra.lost_horns = [horn("HasLeftHorn"), horn("HasRightHorn")];
+ }
+ _ => {}
+ }
if m.species() == crate::mobs::Species::Cat {
m.extra.owner = crate::save::uuid_from_tag(tag.get("Owner"));
m.extra.tame = m.extra.owner.is_some();
m.extra.sitting = flag(tag, "Sitting");
m.extra.color =
number(tag.get("CollarColor")).map_or(crate::mobs::tame::RED, |c| (c as u8) & 15);
- if let Some(Tag::String(v)) = tag.get("variant") {
- let v = v.to_string().unwrap_or_default();
- let v = v.trim_start_matches("minecraft:");
- m.extra.variant = crate::mobs::tame::CAT_VARIANTS
- .iter()
- .position(|n| *n == v)
- .unwrap_or(0) as u8;
- }
}
if m.species() == crate::mobs::Species::Wolf {
let health = m.health;
@@ -782,14 +1103,6 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) -
m.extra.sitting = flag(tag, "Sitting");
m.extra.color =
number(tag.get("CollarColor")).map_or(crate::mobs::tame::RED, |c| (c as u8) & 15);
- if let Some(Tag::String(v)) = tag.get("variant") {
- let v = v.to_string().unwrap_or_default();
- let v = v.trim_start_matches("minecraft:");
- m.extra.variant = crate::mobs::tame::WOLF_VARIANTS
- .iter()
- .position(|(n, _)| *n == v)
- .unwrap_or(0) as u8;
- }
}
if matches!(
m.species(),
@@ -808,6 +1121,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) -
if m.species() == crate::mobs::Species::Axolotl {
restore_axolotl_memories(&mut m, tag);
}
+ read_variant(&mut m, tag);
m.fire_ticks = number(tag.get("Fire")).unwrap_or(0) as i32;
m.air = number(tag.get("Air")).unwrap_or(300) as i32;
if m.species() == crate::mobs::Species::Allay {
@@ -847,6 +1161,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 +1251,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 +1373,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 +1393,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 +1645,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 +2245,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 +2254,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);
}
}
@@ -1896,6 +2303,41 @@ fn write_axolotl_memories(m: &Mob, map: &mut Compound) {
}
}
}
+/// The variant tags `Axolotl`, `Rabbit`, `Parrot`, `Salmon` and
+/// `TropicalFish` read; a missing tag is the default variant (a medium
+/// salmon, otherwise index 0).
+fn read_variant(m: &mut Mob, tag: &Tag) {
+ use crate::mobs::Species as S;
+ let int = |key| number(tag.get(key)).unwrap_or(0) as i32;
+ match m.species() {
+ S::Axolotl | S::Parrot => m.extra.variant = int("Variant").clamp(0, 4) as u8,
+ // Rabbit.Variant.LEGACY_CODEC: an unknown id is brown.
+ S::Rabbit => {
+ m.extra.variant = match int("RabbitType") {
+ v @ (0..=5 | 99) => v as u8,
+ _ => 0,
+ }
+ }
+ S::Salmon => {
+ m.extra.variant = text(tag.get("type"))
+ .and_then(|t| SALMON_SIZES.iter().position(|v| *v == t))
+ .unwrap_or(1) as u8;
+ }
+ S::TropicalFish => {
+ let packed = int("Variant");
+ let (size, index) = (packed & 0xFF, (packed >> 8) & 0xFF);
+ // TropicalFish.Pattern.byId: an unknown id is a kob.
+ m.extra.variant = if size <= 1 && index < 6 {
+ (size * 6 + index) as u8
+ } else {
+ 0
+ };
+ m.extra.variant2 = ((packed >> 16) & 15) as u8;
+ m.extra.variant3 = ((packed >> 24) & 15) as u8;
+ }
+ _ => {}
+ }
+}
fn restore_axolotl_memories(m: &mut Mob, tag: &Tag) {
let memories = tag.get("Brain").and_then(|b| b.get("memories"));
let ttl = memories
@@ -1919,12 +2361,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 +2423,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 +2496,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)]
@@ -2214,6 +2739,123 @@ mod sheep_nbt_tests {
let back = mob_from_nbt(&tag, &types, 2).unwrap();
assert_eq!((back.extra.color, back.extra.sheared), (14, true));
}
+
+ #[test]
+ fn farm_animals_keep_their_variant_and_sound_variant() {
+ let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("../../.local/horizon-client")
+ .join(horizon_core::VANILLA_VERSION);
+ if !root.join("items.json").exists() {
+ return;
+ }
+ let data = crate::mobs::MobTypes::load(&root).unwrap();
+ let types: HashMap> = data
+ .types
+ .iter()
+ .map(|(k, v)| (k.clone(), Arc::new(v.clone())))
+ .collect();
+ let mut m = Mob::new(
+ 1,
+ types["minecraft:pig"].clone(),
+ Vec3::new(0.0, 4.0, 0.0),
+ 0.0,
+ );
+ let tag = mob_to_nbt(&m, [1, 2, 3, 4], None);
+ assert_eq!(
+ text(tag.get("variant")).as_deref(),
+ Some("minecraft:temperate")
+ );
+ assert_eq!(
+ text(tag.get("sound_variant")).as_deref(),
+ Some("minecraft:classic")
+ );
+ // Spawned in a warm biome with the mini sounds.
+ (m.extra.variant, m.extra.sound_variant) = (1, Some(2));
+ let tag = mob_to_nbt(&m, [1, 2, 3, 4], None);
+ assert_eq!(text(tag.get("variant")).as_deref(), Some("minecraft:warm"));
+ assert_eq!(
+ text(tag.get("sound_variant")).as_deref(),
+ Some("minecraft:mini")
+ );
+ let back = mob_from_nbt(&tag, &types, 2).unwrap();
+ assert_eq!((back.extra.variant, back.extra.sound_variant), (1, Some(2)));
+ let mut hen = Mob::new(
+ 3,
+ types["minecraft:chicken"].clone(),
+ Vec3::new(0.0, 4.0, 0.0),
+ 0.0,
+ );
+ (hen.extra.variant, hen.extra.egg_time) = (2, 7795);
+ let tag = mob_to_nbt(&hen, [1, 2, 3, 4], None);
+ assert_eq!(text(tag.get("variant")).as_deref(), Some("minecraft:cold"));
+ let back = mob_from_nbt(&tag, &types, 4).unwrap();
+ assert_eq!((back.extra.variant, back.extra.egg_time), (2, 7795));
+ // The sound variants are indices into the registries finalizeSpawn draws from.
+ use crate::mobs::{Species, finalize};
+ let registries = finalize::SpawnRegistries::load(&root);
+ for (species, registry) in [
+ (Species::Pig, ®istries.pig_sound),
+ (Species::Cow, ®istries.cow_sound),
+ (Species::Chicken, ®istries.chicken_sound),
+ (Species::Cat, ®istries.cat_sound),
+ (Species::Wolf, ®istries.wolf_sound),
+ ] {
+ assert_eq!(
+ finalize::sound_variants(species),
+ registry.names,
+ "{species:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn foxes_rabbits_and_goats_keep_their_kind() {
+ let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("../../.local/horizon-client")
+ .join(horizon_core::VANILLA_VERSION);
+ if !root.join("items.json").exists() {
+ return;
+ }
+ let data = crate::mobs::MobTypes::load(&root).unwrap();
+ let types: HashMap> = data
+ .types
+ .iter()
+ .map(|(k, v)| (k.clone(), Arc::new(v.clone())))
+ .collect();
+ let new = |kind: &str| Mob::new(1, types[kind].clone(), Vec3::new(0.0, 4.0, 0.0), 0.0);
+ let round_trip = |m: &Mob| {
+ let tag = mob_to_nbt(m, [1, 2, 3, 4], None);
+ (mob_from_nbt(&tag, &types, 2).unwrap(), tag)
+ };
+ let mut fox = new("minecraft:fox");
+ fox.extra.variant = 1;
+ let (back, tag) = round_trip(&fox);
+ assert_eq!(text(tag.get("Type")).as_deref(), Some("snow"));
+ assert_eq!(number(tag.get("Sleeping")), Some(0));
+ assert_eq!(back.extra.variant, 1);
+ let mut rabbit = new("minecraft:rabbit");
+ rabbit.extra.variant = 4;
+ let (back, tag) = round_trip(&rabbit);
+ assert_eq!(number(tag.get("RabbitType")), Some(4));
+ assert_eq!(back.extra.variant, 4);
+ let mut goat = new("minecraft:goat");
+ (goat.extra.screaming, goat.extra.lost_horns) = (true, [false, true]);
+ let (back, tag) = round_trip(&goat);
+ assert_eq!(number(tag.get("HasRightHorn")), Some(0));
+ assert_eq!(
+ (back.extra.screaming, back.extra.lost_horns),
+ (true, [false, true])
+ );
+ // A goat saved without horn flags has both, as vanilla reads it.
+ let bare = Tag::compound([
+ ("id", string("minecraft:goat")),
+ ("Pos", doubles(&[0.5, 64.0, 0.5])),
+ ]);
+ assert_eq!(
+ mob_from_nbt(&bare, &types, 3).unwrap().extra.lost_horns,
+ [false; 2]
+ );
+ }
}
#[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..2bb712612 100644
--- a/crates/horizon-client/src/font.rs
+++ b/crates/horizon-client/src/font.rs
@@ -889,12 +889,17 @@ impl Font {
if s.contains('§') {
return self.width_text(&Text::legacy(s));
}
- s.chars().map(|c| self.glyph(c).advance).sum::().ceil()
+ crate::bidi::visual_str(s)
+ .chars()
+ .map(|c| self.glyph(c).advance)
+ .sum::()
+ .ceil()
}
/// Font.width of a component: `§` codes in the spans are formatting,
- /// not glyphs.
+ /// not glyphs. Right-to-left text is measured as it is drawn, shaped.
pub fn width_text(&self, t: &Text) -> f32 {
- t.resolved()
+ let t = t.resolved();
+ crate::bidi::visual(&t)
.chars()
.map(|(c, s)| self.advance(c, s))
.sum::()
@@ -1201,6 +1206,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 cdbd72d7b..bf2434965 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;
@@ -59,7 +63,6 @@ mod frames;
mod friends;
mod functions;
mod game_mode;
-mod game_rules_screen;
mod gamemode_switcher;
mod ghasts;
mod golems;
@@ -80,6 +83,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 +102,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 +156,8 @@ mod scoreboard;
mod screens;
mod sculk;
mod sculk_fixture;
+mod server_links;
+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()),
@@ -486,6 +508,12 @@ enum Screen {
Friends,
/// CommandBlockEditScreen (game/command_blocks.rs).
CommandBlock,
+ /// ServerLinksDialogScreen: a server's links (game/server_links.rs).
+ ServerLinks,
+ /// ConfirmLinkScreen for a server link (game/server_links.rs).
+ ConfirmLink,
+ /// DialogScreen.WarningScreen: the note about custom screens.
+ DialogWarning,
/// WinScreen: the end poem and the credits (game/win.rs).
Win,
/// A `ui` mod's own screen, or its settings page from Options > Mods
@@ -532,6 +560,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 +570,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 +584,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 +598,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 +690,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 +758,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 +830,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 +903,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 +914,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 +924,7 @@ impl LevelAccess for GameLevel<'_> {
};
match query {
EntityQuery::Minecart => carts(),
+ EntityQuery::Arrows => arrows(),
EntityQuery::Mobs => players(),
EntityQuery::Everything => players() + carts(),
}
@@ -853,7 +932,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 +1282,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 +1356,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 +1451,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 +1530,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 +1547,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>,
@@ -1576,10 +1681,13 @@ struct Game<'a> {
guest_use: Option,
/// Level events of this tick for the guests, and the guest acting now.
lan_events: Vec<(i32, [i32; 3], i32, Option)>,
+ lan_cushion_breaks: Vec<(horizon_world::registry::BlockStateId, [f64; 3])>,
/// Block events (position, b0, b1, state) and entity events (id, event,
/// 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)
@@ -1597,6 +1705,9 @@ struct Game<'a> {
/// The acting guest's cooldowns, as (item, ticks): their packet needs the
/// hub's item registry, which the guest's turn does not hold.
guest_cooldowns: Vec<(Arc, i32)>,
+ /// The acting guest's own entity events (`ServerPlayer.connection.send`),
+ /// sent with their entity id, which the guest's turn does not hold.
+ guest_entity_events: Vec,
/// `broadcastToAdmins` lines a guest's command queued, sent once it
/// returns: the line, whether operators get it and whether the console
/// logs it.
@@ -1631,6 +1742,8 @@ struct Game<'a> {
restore_player_state: bool,
stats_ui: stats_screen::StatsUi,
adv_ui: advancements_screen::AdvUi,
+ /// The Server Links screens' state (game/server_links.rs).
+ links_ui: server_links::LinksUi,
camera_type: perspective::CameraType,
fangs: fangs::FangState,
/// The local player as a model (third person, the inventory).
@@ -1727,9 +1840,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
@@ -1899,9 +2049,11 @@ impl Game<'_> {
/// item in use (LocalPlayer.modifyInput), the helmet's Respiration
/// (decreaseAirSupply), the wings, leather boots on powder snow
/// (PowderSnowBlock.canEntityWalkOnPowderSnow), freeze-immune wear
- /// (LivingEntity.canFreeze) and the dimension's FAST_LAVA.
+ /// (LivingEntity.canFreeze), the dimension's FAST_LAVA and the sleeping
+ /// pose.
pub(crate) fn sync_player_body(&mut self) {
let glider = self.glider_worn();
+ let sleeping = self.sleeping.is_some();
let item_use_speed = self
.using
.and_then(|(slot, _)| {
@@ -1929,6 +2081,7 @@ impl Game<'_> {
player.item_use_speed = item_use_speed;
player.respiration = respiration;
player.glider = glider;
+ let _ = player.set_sleeping(sleeping);
player.leather_boots = leather_boots;
player.freeze_immune = freeze_immune;
player.fluids.fast_lava = self.dim == Dim::Nether;
@@ -2024,6 +2177,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 +2339,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 +2355,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 +2401,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 +2421,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 +2635,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 +2654,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 +2677,7 @@ impl Game<'_> {
};
let mut level = GameLevel {
cart_boxes,
+ arrow_boxes,
blockers,
world: &mut self.world,
facts: self.res.facts(),
@@ -2469,6 +2685,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 +2703,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 +2773,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 +2816,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 +2850,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).
@@ -2761,6 +3005,16 @@ impl Game<'_> {
data,
} => self.sculk_charge_event(pos, data),
LevelEvent::LevelEvent { id: 3007, pos, .. } => self.shriek_event(pos),
+ // LevelEventHandler 2019 and 2020: the crack on a face of the
+ // block being mined, with its hit sound for 2020.
+ LevelEvent::LevelEvent {
+ id: id @ (2019 | 2020),
+ pos,
+ data,
+ } => {
+ let face = horizon_core::geometry::Direction::ALL[data.clamp(0, 5) as usize];
+ self.breaking_block_effects([pos.x, pos.y, pos.z], face.normal(), id == 2020);
+ }
LevelEvent::LevelEvent { id: 2004, pos, .. } => {
self.spawner_burst([pos.x, pos.y, pos.z])
}
@@ -2780,16 +3034,35 @@ impl Game<'_> {
pos,
data,
} => self.dragon_egg_particles([pos.x, pos.y, pos.z], data),
+ LevelEvent::LevelEvent {
+ id: 2016,
+ pos,
+ data,
+ } => self.shulker_teleport_particles([pos.x, pos.y, pos.z], data),
LevelEvent::LevelEvent {
id: 2017,
pos,
data,
} => self.consume_teleport_particles([pos.x, pos.y, pos.z], data),
+ LevelEvent::LevelEvent { id: 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,
@@ -2815,6 +3088,9 @@ impl Game<'_> {
1501 => Some(("minecraft:block.lava.extinguish", 0.5)),
1009 => Some(("minecraft:block.fire.extinguish", 0.5)),
1502 => Some(("minecraft:block.redstone_torch.burnout", 0.5)),
+ // 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)),
@@ -2822,6 +3098,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 {
@@ -2831,12 +3109,17 @@ impl Game<'_> {
- self.world.random.next_float())
* 0.8
}
- 1029 | 1030 | 1042 | 1043 | 1044 => {
+ 1029 | 1030 | 1042 | 1043 | 1044 | 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);
@@ -2885,11 +3168,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,
});
}
@@ -2966,6 +3247,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",
@@ -2987,6 +3273,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 { .. } => {}
@@ -3003,6 +3314,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;
@@ -3333,9 +3648,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.
@@ -3350,7 +3673,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,
@@ -3367,6 +3690,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);
@@ -3475,6 +3801,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()?
@@ -3536,6 +3863,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();
@@ -3661,6 +3992,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);
@@ -3709,6 +4041,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);
@@ -3899,6 +4232,7 @@ impl Game<'_> {
if &*stack.item == "minecraft:spyglass" {
// SpyglassItem.USE_DURATION, then finishUsingItem.
if ticks + 1 >= 1200 {
+ self.send_use_item_complete();
self.stop_spyglass();
self.using = None;
} else {
@@ -3920,6 +4254,7 @@ impl Game<'_> {
}
if ticks >= duration {
self.using = None;
+ self.send_use_item_complete();
// ItemStack.finishUsingItem's applyAfterUseComponentSideEffects.
self.apply_use_cooldown(&stack);
self.finish_consuming(&info, consumable, &stack);
@@ -3938,6 +4273,17 @@ impl Game<'_> {
_ => {}
}
}
+ /// `ServerPlayerGameMode.tick` while a player digs: level event 2020 every
+ /// fourth tick since the START (the hit sound), else 2019 (the crack only),
+ /// for everyone around, the digger included (`levelEvent(null, ...)`).
+ fn destroy_progress_event(&mut self, pos: [i32; 3], face: [i32; 3], ticks: u32) {
+ let id = if ticks.is_multiple_of(4) { 2020 } else { 2019 };
+ let direction = horizon_core::geometry::Direction::ALL
+ .iter()
+ .position(|d| d.normal() == face)
+ .unwrap_or(1);
+ self.level_event_at(id, pos, direction as i32);
+ }
fn tick_mining(&mut self) -> Result<()> {
if self.destroy_delay > 0 {
self.destroy_delay -= 1;
@@ -3951,7 +4297,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(());
}
@@ -3976,6 +4327,11 @@ impl Game<'_> {
let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
let facts = self.res.facts().get(state);
if facts.hardness < 0.0 {
+ // The server still counts its destroy ticks on an unbreakable block.
+ let m = self.mining.as_mut().ok_or("mining")?;
+ m.ticks += 1;
+ let (pos, ticks) = (m.pos, m.ticks);
+ self.destroy_progress_event(pos, hit.face, ticks);
return Ok(());
}
// Player.getDestroySpeed / BlockBehaviour.getDestroyProgress.
@@ -4006,26 +4362,15 @@ impl Game<'_> {
} else {
speed / facts.hardness / if harvest { 30.0 } else { 100.0 }
};
- let hit_sound = facts.sounds.clone();
self.swing_arm();
let m = self.mining.as_mut().ok_or("mining")?;
m.progress += progress;
m.ticks += 1;
- let crack = (m.pos, hit.face);
- if m.ticks % 4 == 1 {
- let c = [
- f64::from(m.pos[0]) + 0.5,
- f64::from(m.pos[1]) + 0.5,
- f64::from(m.pos[2]) + 0.5,
- ];
- self.audio.play(
- &hit_sound.hit,
- Some(c),
- (hit_sound.volume + 1.0) / 8.0,
- hit_sound.pitch * 0.5,
- );
+ // An instant break at START sends no destroy events.
+ if m.progress < 1.0 || m.ticks > 1 {
+ let (pos, ticks) = (m.pos, m.ticks);
+ self.destroy_progress_event(pos, hit.face, ticks);
}
- self.crack_particle(crack.0, crack.1, state);
let m = self.mining.as_mut().ok_or("mining")?;
// ServerPlayerGameMode breaks a player's block at once only when it is instant (START's
// insta-mine); otherwise it waits for the client's STOP_DESTROY_BLOCK
@@ -4127,6 +4472,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
@@ -4225,11 +4576,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 {
@@ -4242,6 +4598,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() {
@@ -4324,12 +4681,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;
@@ -4339,19 +4690,47 @@ impl Game<'_> {
player.dimensions.eye_height
};
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),
MotionEvent::Emission {
state, in_water, ..
- } if !crouching => {
+ } => {
let sounds = self.res.facts().get(state).sounds.clone();
// Entity.playStepSound: the block's step sound at 0.15 volume,
- // muffled under the swim sound in water.
+ // muffled under the swim sound in water. Whether it plays is
+ // Player.getMovementEmission's call (shift on the ground),
+ // not the pose: a forced crouch still steps.
let (volume, pitch) = if in_water {
(sounds.volume * 0.05, sounds.pitch * 0.8)
} else {
@@ -4363,26 +4742,21 @@ impl Game<'_> {
self.audio
.play("minecraft:entity.player.swim", Some(feet), volume, pitch);
}
+ MotionEvent::Chime { volume, pitch } => {
+ self.audio.play(
+ "minecraft:block.amethyst_block.chime",
+ Some(feet),
+ volume,
+ pitch,
+ );
+ }
MotionEvent::Drown => {
- // LivingEntity.makeDrownParticles: eight bubbles moving
- // with the player.
- use horizon_client::particles::{ParticleOptions, ParticleType};
- for _ in 0..8 {
- let mut triangle = || {
- let r = self.particles.random();
- r.next_double() - r.next_double()
- };
- let p = [
- feet[0] + triangle(),
- feet[1] + triangle(),
- feet[2] + triangle(),
- ];
- self.particles.add(
- &ParticleOptions::simple(ParticleType::Bubble),
- p,
- player_velocity,
- );
+ // The guests see the entity event 67 too.
+ if let Some(host) = &self.lan {
+ host.hub
+ .entity_event(host.host_entity, combat::DROWN_EVENT, feet);
}
+ self.drown_particles(feet, player_velocity);
}
MotionEvent::BubbleColumnParticle { bubble, position } => {
// ServerLevel.sendParticles: SPLASH (speed 1) or BUBBLE
@@ -4418,9 +4792,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(),
@@ -4462,6 +4859,7 @@ impl Game<'_> {
}
}
self.powder_snow_fire()?;
+ self.rain_extinguish_in_frame();
self.tick_totem();
let Some(player) = self.player.as_mut() else {
return Ok(());
@@ -4515,7 +4913,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)
@@ -4523,6 +4921,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
@@ -4530,6 +4929,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
@@ -4544,6 +4944,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());
@@ -4731,6 +5132,9 @@ impl Game<'_> {
| Screen::Advancements
| Screen::WorldOptions
| Screen::Friends
+ | Screen::ServerLinks
+ | Screen::ConfirmLink
+ | Screen::DialogWarning
| Screen::CommandBlock
) || self.book.is_some()
|| self.win_screen_pauses())
@@ -4752,6 +5156,12 @@ impl Game<'_> {
if capture && !self.focused {
return;
}
+ // The container screen's press state belongs to the screen: a screen
+ // that takes the pointer over starts with its own state, as
+ // `AbstractContainerScreen` does, so a press whose release never
+ // arrived (the pointer left the window) cannot wedge the next
+ // screen's quick move and clicks.
+ self.reset_inventory_clicks();
if !capture {
self.stop_mining();
}
@@ -4831,7 +5241,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);
@@ -4921,7 +5331,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,
@@ -5048,12 +5458,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);
}
}
}
@@ -5211,9 +5621,13 @@ impl Game<'_> {
Screen::Advancements => self.draw_advancements(&mut batch),
Screen::WorldOptions => self.draw_world_options(&mut batch),
Screen::Friends => self.draw_friends_screen(&mut batch),
+ Screen::ServerLinks => self.draw_server_links(&mut batch),
+ Screen::ConfirmLink => self.draw_confirm_link(&mut batch),
+ Screen::DialogWarning => self.draw_dialog_warning(&mut batch),
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);
@@ -5222,6 +5636,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);
@@ -5278,7 +5693,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));
@@ -5548,7 +5965,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 => {
@@ -5591,7 +6010,21 @@ impl Game<'_> {
self.draw_inventory_effects(batch, (ox, oy), 176);
}
}
+ /// `AbstractContainerScreen` keeps `isQuickCrafting` and the drag it
+ /// belongs to on the screen. Horizon keeps both on `Game` (`inv_clicks`,
+ /// `inv_drag`, `last_inv_click`), so they are dropped when the pointer
+ /// changes hands: a screen that opens or closes starts with its own
+ /// state, and a press whose release never reached 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.cancel_drag();
+ 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();
@@ -5604,7 +6037,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;
@@ -5687,8 +6121,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);
@@ -5704,6 +6139,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);
@@ -6316,6 +6757,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;
}
@@ -6330,6 +6774,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 {
@@ -6492,24 +6943,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 {
@@ -6523,6 +6958,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`).
@@ -6683,7 +7138,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) {
@@ -6895,6 +7350,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 {
@@ -6991,6 +7449,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).
@@ -7009,7 +7470,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;
@@ -7120,7 +7586,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()
@@ -7233,6 +7699,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");
@@ -7263,7 +7730,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();
@@ -7311,6 +7778,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),
@@ -7336,11 +7817,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()
@@ -7396,7 +7874,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);
@@ -7424,8 +7902,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 {
@@ -7465,6 +7944,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.
@@ -7518,6 +8060,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()
@@ -7548,15 +8091,10 @@ 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;
- if let Some(p) = self.player.as_mut()
- && !self.creative
- {
- p.cause_food_exhaustion(0.1);
- }
let player = self.player.as_ref();
let from = player.map(|p| [p.position.x, p.position.y, p.position.z]);
if knockback_attack {
@@ -7605,13 +8143,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 {
@@ -7638,6 +8187,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);
}
@@ -7648,24 +8198,37 @@ 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);
+ // Player.attack: causeFoodExhaustion(0.1F) only when the hit hurt
+ // (inside `if (wasHurt)`), after damageStatsAndHearts.
+ if let Some(p) = self.player.as_mut()
+ && !self.creative
+ {
+ p.cause_food_exhaustion(0.1);
+ }
} else {
self.audio
.play("minecraft:entity.player.attack.nodamage", from, 1.0, 1.0);
}
}
/// 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>(
@@ -7767,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),
@@ -7832,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();
@@ -7970,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
@@ -7990,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)));
@@ -8207,6 +8774,10 @@ impl Game<'_> {
}
self.lan_close(false);
self.save_game()?;
+ if let Some(mut remote) = self.remote.take() {
+ // Minecraft.disconnect closes the connection, so the host sees a clean leave.
+ remote.session.disconnect();
+ }
self.saved_for_exit = true;
Ok(())
}
@@ -8263,6 +8834,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();
@@ -8317,15 +8889,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) {
@@ -8422,7 +9033,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);
}
}
}
@@ -8660,6 +9272,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,
@@ -8681,6 +9311,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(_)))
@@ -8740,7 +9377,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 });
@@ -8890,8 +9528,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
@@ -8913,6 +9572,8 @@ impl Game<'_> {
value,
age: 0,
on_ground: false,
+ count: 1,
+ ticks: 0,
});
}
fn can_place_used_fire(&mut self, target: [i32; 3]) -> bool {
@@ -8989,18 +9650,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)
@@ -9012,12 +9686,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]
@@ -9025,11 +9709,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
});
@@ -9075,16 +9761,13 @@ impl Game<'_> {
/// sound every fifth level (at most every 100 ticks).
pub(super) fn give_orb_points(&mut self, gained: u32) {
let at = self.eye_position();
- if self.experience.give(gained as i32)
- && self.experience.level % 5 == 0
+ // Player.giveExperienceLevels runs per level, so the first multiple of 5
+ // crossed plays the sound (and starts the cooldown for the rest).
+ if let Some(level) = self.experience.give(gained as i32)
&& self.ticks > self.last_level_up + 100
{
self.last_level_up = self.ticks;
- let volume = if self.experience.level > 30 {
- 1.0
- } else {
- self.experience.level as f32 / 30.0
- };
+ let volume = if level > 30 { 1.0 } else { level as f32 / 30.0 };
self.audio
.play("minecraft:entity.player.levelup", at, volume * 0.75, 1.0);
}
@@ -9105,7 +9788,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,
@@ -9119,9 +9805,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,
@@ -9149,7 +9832,7 @@ impl Game<'_> {
velocity,
on_ground,
);
- self.creatures.projectiles.push(arrow);
+ self.add_projectile(arrow);
self.player_projectile_shot();
let pitch = 1.0 / (self.world.random.next_float() * 0.4 + 1.2) + power * 0.5;
self.audio
@@ -9454,6 +10137,14 @@ impl Game<'_> {
};
Some(t < 0.15)
}
+ /// `Level.isRainingAt`: it rains, the sky light is 15, nothing that stops
+ /// motion is above, and the biome's precipitation there is rain.
+ fn raining_at(&self, p: BlockPos) -> bool {
+ self.world.weather.levels(1.0).0 > 0.2
+ && self.world.light(p.x, p.y, p.z) >> 4 == 15
+ && self.rain_height(p.x, p.z) <= p.y
+ && self.precipitation(p.x, p.y, p.z) == Some(false)
+ }
/// `getHeight(Heightmap.Types.MOTION_BLOCKING, x, z)`: one above the
/// highest block in `blocks_motion_in_heightmap` or holding a fluid.
fn rain_height(&self, x: i32, z: i32) -> i32 {
@@ -9490,12 +10181,15 @@ impl Game<'_> {
} else {
("minecraft:weather.rain", 0.2, 1.0)
};
- self.audio.play(
- name,
- Some([f64::from(x) + 0.5, f64::from(top), f64::from(z) + 0.5]),
- volume,
- pitch,
- );
+ // The Horizon Weather option off silences the rain too.
+ if self.settings.horizon.weather {
+ self.audio.play(
+ name,
+ Some([f64::from(x) + 0.5, f64::from(top), f64::from(z) + 0.5]),
+ volume,
+ pitch,
+ );
+ }
}
}
}
@@ -9579,8 +10273,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;
@@ -9595,22 +10290,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
@@ -9640,13 +10353,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(),
@@ -9696,14 +10411,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();
}
@@ -9731,8 +10452,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_{}_{}_{}",
@@ -9798,20 +10520,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 {
@@ -9919,8 +10637,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);
}
@@ -9973,6 +10690,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
@@ -9985,6 +10705,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.
@@ -9994,6 +10732,9 @@ impl Game<'_> {
let level = &mut self.level;
level.creative = self.creative;
level.game_mode = mode;
+ // PrimaryLevelData.setDifficulty: /difficulty and the options button change it.
+ level.difficulty =
+ horizon_client::title::DIFFICULTIES[usize::from(self.ui.difficulty) & 3].into();
level.time = self.world.game_time;
level.weather = self.world.weather;
level.day_time = self.world.day_time;
@@ -10104,6 +10845,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)));
@@ -10268,7 +11010,11 @@ impl Game<'_> {
let debug_crosshair = horizon_client::gizmos::camera_relative(&crosshair.on_top, at, view);
// LevelExtractor.extractBlockOutline: model translucency controls draw order.
let mut outline_after_terrain = false;
- let outline = if self.screen == Screen::Playing && !self.spectator() {
+ // GameRenderer.shouldRenderBlockOutline: not with the HUD hidden (F1), and only for a
+ // player who may build. Adventure players only get one with a CAN_BREAK or
+ // CAN_PLACE_ON item and spectators with a menu block; Horizon reads neither the
+ // components nor opens menus for spectators, so those never show it.
+ let outline = if self.screen == Screen::Playing && !self.ui.hide_gui && self.may_build() {
self.pick()
.map(|h| {
let state = self.world.block(h.pos[0], h.pos[1], h.pos[2]);
@@ -10293,6 +11039,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]))
@@ -10303,8 +11060,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);
@@ -10406,6 +11161,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,
@@ -10451,6 +11210,7 @@ impl Game<'_> {
dark_disc: self.dark_disc(camera),
outline,
outline_after_terrain,
+ outline_high_contrast: self.settings.file.bool("highContrastBlockOutline"),
debug_lines: &debug_lines,
debug_lines_on_top: &debug_lines_on_top,
debug_crosshair: &debug_crosshair,
@@ -10510,7 +11270,7 @@ impl Game<'_> {
}),
ticks: self.ticks,
darkness: self.darkness_lighting(alpha as f32),
- night_vision: self.night_vision_intensity(),
+ night_vision: self.night_vision_intensity(alpha as f32),
block_flicker: self.fog.block_light_flicker,
boss_darken: self
.boss_overlay
@@ -10682,6 +11442,10 @@ impl Game<'_> {
Screen::GameModeSwitcher => self.close_gamemode_switcher(false),
Screen::Dead => {}
Screen::Stats | Screen::Friends => self.screen = Screen::Paused,
+ Screen::ServerLinks => self.screen = Screen::Paused,
+ // ConfirmScreen.keyPressed: Escape answers no; both return to
+ // the Server Links screen they came from.
+ Screen::ConfirmLink | Screen::DialogWarning => self.screen = Screen::ServerLinks,
Screen::Advancements => self.close_advancements(),
Screen::WorldOptions => self.world_options_escape(),
Screen::CommandBlock => self.close_command_block(),
@@ -10750,8 +11514,10 @@ impl Game<'_> {
// key.swapOffhand: on a server, ServerboundPlayerActionPacket SWAP_ITEM_WITH_OFFHAND
// (the server swaps the hands and sends both slots back; spectators can't).
KeyCode::KeyF if self.screen == Screen::Playing && self.remote.is_some() => {
- if !self.spectator() {
- self.remote_swap_hands();
+ if !self.spectator()
+ && let Some(r) = self.remote.as_mut()
+ {
+ r.pending_keys.push(key);
}
}
KeyCode::KeyF if self.screen == Screen::Playing => {
@@ -10848,11 +11614,28 @@ impl Game<'_> {
}
Ok(())
}
- /// LOD Distance as far terrain uses it (`Graphics::lod_distance_on`).
+ /// LOD Distance and Far Detail Reduced as chosen: the player's LOD
+ /// Distance when it is on, else a mod's far terrain
+ /// (`render.set-far-terrain`).
+ fn far_terrain_choice(&self) -> (u32, bool) {
+ let g = &self.settings.horizon;
+ let reduced = g.far_detail == horizon_client::graphics::FarDetail::Reduced;
+ if g.lod_distance > 0 {
+ return (g.lod_distance, reduced);
+ }
+ match self.mod_far_terrain() {
+ Some(f) => (f.distance, reduced || f.reduced),
+ None => (0, reduced),
+ }
+ }
+ /// LOD Distance as far terrain uses it (`graphics::lod_distance_capped`).
fn lod_distance(&self) -> u32 {
+ let (distance, _) = self.far_terrain_choice();
match &self.renderer {
- Some(renderer) => self.settings.horizon.lod_distance_on(&renderer.info),
- None => self.settings.horizon.lod_distance.min(1024),
+ Some(renderer) => {
+ horizon_client::graphics::lod_distance_capped(distance, &renderer.info)
+ }
+ None => distance.min(1024),
}
}
/// Only enabled LOD worlds extend the renderer's range, never simulation.
@@ -10873,7 +11656,7 @@ impl Game<'_> {
}
}
fn prepare_lod(&mut self) {
- let enabled = self.settings.horizon.lod_distance > 0
+ let enabled = self.far_terrain_choice().0 > 0
&& self.renderer.is_some()
&& self.player.is_some()
&& self.title.is_none()
@@ -10970,6 +11753,7 @@ impl Game<'_> {
{
log::warn!("Horizon: failed to save unloaded chunks: {e}");
}
+ let (far_distance, far_reduced) = self.far_terrain_choice();
if let Some(renderer) = self.renderer.as_mut() {
let g = &self.settings.horizon;
let budgeted = g.chunk_updates > 0 || g.upload_budget_kib > 0;
@@ -11021,18 +11805,12 @@ 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);
+ let lod_distance =
+ horizon_client::graphics::lod_distance_capped(far_distance, &renderer.info);
lod.set_near_loading(self.streaming.busy());
- lod.set_reduced_detail(
- self.settings.horizon.far_detail
- == horizon_client::graphics::FarDetail::Reduced,
- );
+ lod.set_reduced_detail(far_reduced);
// The covered columns change only with the complete ones and
// the render area: rebuilt then, not every frame.
let at = (
@@ -11355,6 +12133,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);
@@ -11365,6 +12144,9 @@ impl ApplicationHandler for Game<'_> {
if self.screen == Screen::WorldOptions && d != 0.0 {
self.world_options_scroll(d);
}
+ if self.screen == Screen::ServerLinks && d != 0.0 {
+ self.server_links_scroll(d);
+ }
if self.screen == Screen::Advancements {
self.advancements_scroll(scaled(raw_x) as f32, d);
}
@@ -11418,7 +12200,8 @@ impl ApplicationHandler for Game<'_> {
let (action, sound) = self.title.as_mut().map_or((Action::None, false), |t| {
let clicked = t.click(self.cursor.0, self.cursor.1, (b.width, b.height));
t.press_field(atlas, self.cursor, (b.width, b.height), shift);
- clicked
+ let rules = t.press_rules(atlas, self.cursor, (b.width, b.height));
+ (clicked.0, clicked.1 || rules)
});
self.save_title_options();
if sound {
@@ -11496,16 +12279,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
@@ -11555,6 +12339,15 @@ impl ApplicationHandler for Game<'_> {
Screen::WorldOptions if pressed && button == MouseButton::Left => {
self.world_options_click()
}
+ Screen::ServerLinks if pressed && button == MouseButton::Left => {
+ self.server_links_click()?
+ }
+ Screen::ConfirmLink if pressed && button == MouseButton::Left => {
+ self.confirm_link_click()
+ }
+ Screen::DialogWarning if pressed && button == MouseButton::Left => {
+ self.dialog_warning_click()?
+ }
Screen::WorldOptions if button == MouseButton::Left => {
self.world_options_release()
}
@@ -11632,8 +12425,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());
}
@@ -11646,6 +12448,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
@@ -11654,6 +12464,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);
@@ -11741,18 +12554,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();
@@ -11960,6 +12779,16 @@ impl ApplicationHandler for Game<'_> {
}
}
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
+ if horizon_threads::stop_requests() > 0
+ && self.pending_save.as_ref().is_none_or(|save| !save.quit)
+ {
+ // SIGTERM, SIGINT or SIGHUP: the shutdown hook's server halt, as a window close.
+ if let Err(error) = self.begin_closing_save(true) {
+ self.error = Some(error);
+ event_loop.exit();
+ return;
+ }
+ }
if self.pending_save.is_some() {
match self.poll_closing_save() {
Ok(true) => event_loop.exit(),
@@ -12117,6 +12946,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,
@@ -12166,6 +12996,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,
@@ -12177,7 +13008,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(),
@@ -12221,6 +13059,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(),
@@ -12270,6 +13110,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,
@@ -12279,6 +13120,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(),
@@ -12363,13 +13205,16 @@ impl<'a> Game<'a> {
forced_hit: None,
guest_use: None,
lan_events: Vec::new(),
+ lan_cushion_breaks: 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,
guest_packets: Vec::new(),
guest_cooldowns: Vec::new(),
+ guest_entity_events: Vec::new(),
lan_acting_name: None,
lan_acting_uuid: None,
chat_capture: None,
@@ -12396,6 +13241,7 @@ impl<'a> Game<'a> {
restore_player_state: true,
stats_ui: Default::default(),
adv_ui: Default::default(),
+ links_ui: Default::default(),
camera_type: Default::default(),
fangs: Default::default(),
player_model: None,
@@ -12416,6 +13262,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,
@@ -12436,6 +13283,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"),
@@ -12539,6 +13387,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();
}
@@ -12995,6 +13854,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,
@@ -13041,6 +13908,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,
@@ -13093,6 +13966,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> {
dark_disc: false,
outline: Vec::new(),
outline_after_terrain: false,
+ outline_high_contrast: false,
debug_lines: &[],
debug_lines_on_top: &[],
debug_crosshair: &[],
@@ -13405,6 +14279,11 @@ impl Loading {
}
}
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
+ if horizon_threads::stop_requests() > 0 {
+ // No world is open yet: nothing to save.
+ event_loop.exit();
+ return;
+ }
if let Err(error) = self.poll_menu_resources() {
self.error = Some(error);
event_loop.exit();
@@ -13682,6 +14561,9 @@ pub fn run() -> Result<()> {
{
horizon_client::heartbeat::start();
}
+ if options.execution_role.is_client() {
+ horizon_threads::catch_stop_signals();
+ }
let started = Instant::now();
horizon_client::spans::enable(options.spikes.is_some());
let vanilla_root = options.resources.clone();
@@ -13777,7 +14659,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();
@@ -13797,6 +14679,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/agent.rs b/crates/horizon-client/src/game/agent.rs
index fa9dbf3c6..d99f32f24 100644
--- a/crates/horizon-client/src/game/agent.rs
+++ b/crates/horizon-client/src/game/agent.rs
@@ -419,6 +419,9 @@ impl Game<'_> {
Screen::Advancements => "advancements",
Screen::WorldOptions => "world-options",
Screen::Friends => "friends",
+ Screen::ServerLinks => "server-links",
+ Screen::ConfirmLink => "confirm-link",
+ Screen::DialogWarning => "dialog-warning",
Screen::CommandBlock => "command-block",
Screen::Win => "win",
Screen::Mod => "mod",
@@ -707,9 +710,12 @@ impl Game<'_> {
// the recipe buttons of the page, page arrows, filter and tabs.
let book = self.recipe_book_targets();
if !book.is_empty() {
+ let (open, filtering) = self.recipe_book_flags().unwrap_or_default();
v["recipe_book"] = json!({
"targets": book.iter().map(|t| t.rect).collect::>(),
"known": self.recipe_book_known(),
+ "open": open,
+ "filtering": filtering,
});
}
v["slot_ids"] = json!(
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..7790a48f3 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.
+ pub(super) 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..7e80f6f58 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(());
@@ -859,7 +862,7 @@ impl Game<'_> {
let a = alpha as f32;
let range = super::entity_culling::default_range(
glam::DVec3::new(WIDTH, HEIGHT, WIDTH),
- self.settings.entity_distance,
+ self.view_scale(),
);
for b in &self.boats {
let entity_start = out.len();
diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs
index 9af1da70c..b09803e49 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 {
@@ -842,9 +1009,12 @@ impl Game<'_> {
}
};
let indicator = |batch: &mut HudBatch, page: usize, count: usize| {
- let text = tr("book.pageIndicator", "Page %s of %s")
- .replacen("%s", &(page + 1).to_string(), 1)
- .replacen("%s", &count.max(1).to_string(), 1);
+ // BookViewScreen.getPageNumberMessage: 26.3's en_us template is
+ // positional ("Page %1$s of %2$s").
+ let text = horizon_protocol::text::format_java(
+ &tr("book.pageIndicator", "Page %1$s of %2$s"),
+ &[(page + 1).to_string(), count.max(1).to_string()],
+ );
let tw = HudBatch::text_width(atlas, &text);
batch.text(atlas, &text, left + 148.0 - tw, top + 16.0, BLACK, false);
};
@@ -865,7 +1035,7 @@ impl Game<'_> {
BookScreen::Edit {
signing: true,
title,
- opened,
+ title_edit,
..
} => {
let edit = tr("book.editTitle", "Enter Book Title:");
@@ -881,19 +1051,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 +1127,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 +1143,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..94f7661b7 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).
@@ -775,7 +801,11 @@ impl Game<'_> {
pub(super) fn load_world_state(&mut self) {
self.ui.rules = GameRules::load(&self.world_root);
self.ui.clock = WorldClock::default();
- self.ui.difficulty = read_difficulty(&self.world_root).unwrap_or(2);
+ // PrimaryLevelData: the difficulty comes back from level.dat's difficulty_settings.
+ self.ui.difficulty = horizon_client::title::DIFFICULTIES
+ .iter()
+ .position(|d| *d == self.level.difficulty)
+ .map_or(2, |i| i as u8);
if let Ok(bytes) = std::fs::read(self.world_root.join("data/minecraft/world_clocks.dat"))
&& let Ok(raw) = horizon_world::compression::Compression::Gzip.decode(&bytes, 1 << 20)
&& let Ok((root, _)) =
@@ -800,9 +830,9 @@ impl Game<'_> {
self.build_registries();
self.sync_rules();
}
- /// Save the clock and the difficulty beside level.dat (Level.write saves
- /// the game rules: a second writer of game_rules.dat could leave it with
- /// the rules loaded when the world opened).
+ /// Save the clock beside level.dat (Level.write saves the game rules: a
+ /// second writer of game_rules.dat could leave it with the rules loaded
+ /// when the world opened).
pub(super) fn save_world_state(&mut self) {
if self.world_root.as_os_str().is_empty() {
return;
@@ -850,9 +880,6 @@ impl Game<'_> {
if let Err(e) = horizon_client::save::write_dat(&path, root) {
log::warn!("the world clocks were not written: {e}");
}
- if let Err(e) = write_difficulty(&self.world_root, self.ui.difficulty) {
- log::warn!("the difficulty was not written: {e}");
- }
}
/// Death message in chat (CombatTracker.getDeathMessage, as far as the
/// cause is known to the client).
@@ -962,34 +989,6 @@ pub fn screenshot_name(dir: &std::path::Path) -> String {
n += 1;
}
}
-fn read_difficulty(world: &std::path::Path) -> Option {
- let bytes = std::fs::read(world.join("level.dat")).ok()?;
- let raw = horizon_world::compression::Compression::Gzip
- .decode(&bytes, 64 << 20)
- .ok()?;
- let (root, _) =
- horizon_world::nbt::read_named(&raw, horizon_world::nbt::Limits::default()).ok()?;
- match root.tag.get("Data")?.get("Difficulty")? {
- horizon_world::nbt::Tag::Byte(b) => Some((*b).clamp(0, 3) as u8),
- _ => None,
- }
-}
-/// Patch `Data.Difficulty` in level.dat (Level::write stores the default).
-fn write_difficulty(world: &std::path::Path, difficulty: u8) -> horizon_client::Result<()> {
- use horizon_world::{compression::Compression, nbt};
- let path = world.join("level.dat");
- let bytes = std::fs::read(&path)?;
- let raw = Compression::Gzip.decode(&bytes, 64 << 20)?;
- let (mut root, _) = nbt::read_named(&raw, nbt::Limits::default()).map_err(|e| e.to_string())?;
- if let Some(data) = root.tag.get_mut("Data")
- && let Some(d) = data.get_mut("Difficulty")
- {
- *d = nbt::Tag::Byte(difficulty as i8);
- }
- let out = nbt::write_named(&root, nbt::Limits::default()).map_err(|e| e.to_string())?;
- std::fs::write(&path, Compression::Gzip.encode(&out)?)?;
- Ok(())
-}
/// `IntegratedServer.getProfilePermissions` for the owner: `OWNER` (4) when
/// commands are allowed, else `ALL` (0).
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..f69f1b695 100644
--- a/crates/horizon-client/src/game/combat.rs
+++ b/crates/horizon-client/src/game/combat.rs
@@ -1,7 +1,16 @@
//! The player's `CombatTracker`: the damage taken lately, who dealt it and
//! where the player fell from, turned into the vanilla death message.
use super::{Game, chat::PLAYER_NAME};
-use horizon_client::{health::HealthEvent, motion::MotionEvent, text::Text};
+use horizon_client::{
+ health::HealthEvent,
+ motion::MotionEvent,
+ particles::{ParticleOptions, ParticleType},
+ text::Text,
+};
+use horizon_core::random::RandomSource;
+
+/// `EntityEvent.DROWN_PARTICLES`: broadcast with the drowning damage.
+pub(super) const DROWN_EVENT: i8 = 67;
struct Entry {
damage_type: String,
@@ -10,6 +19,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 +31,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,11 +45,47 @@ 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,
}
impl Game<'_> {
+ /// `LivingEntity.makeDrownParticles`: eight bubbles around the entity,
+ /// moving with it.
+ pub(super) fn drown_particles(&mut self, at: [f64; 3], velocity: [f64; 3]) {
+ let bubble = ParticleOptions::simple(ParticleType::Bubble);
+ for _ in 0..8 {
+ let mut triangle = || {
+ let r = self.particles.random();
+ r.next_double() - r.next_double()
+ };
+ let p = [at[0] + triangle(), at[1] + triangle(), at[2] + triangle()];
+ self.particles.add(&bubble, p, velocity);
+ }
+ }
+ /// Entity event 67 from a server, for this client's own player or an
+ /// entity it draws.
+ pub(super) fn remote_drown(&mut self, id: i32) {
+ let own = self.remote.as_ref().is_some_and(|r| r.entity_id == id);
+ let body = if own {
+ self.player.as_ref().map(|p| {
+ let (at, v) = (p.position, p.velocity);
+ ([at.x, at.y, at.z], [v.x, v.y, v.z])
+ })
+ } else {
+ self.mobs.iter().find(|m| m.id == id as u32).map(|m| {
+ let (at, v) = (m.position, m.velocity);
+ ([at.x, at.y, at.z], [v.x, v.y, v.z])
+ })
+ };
+ if let Some((at, v)) = body {
+ self.drown_particles(at, v);
+ }
+ }
/// The display name of a mob: its custom name or its type's name.
pub(super) fn mob_display_name(&self, id: u32) -> Option {
let m = self.mobs.iter().find(|m| m.id == id)?;
@@ -52,16 +102,29 @@ 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]) {
- let pitch = self.audio.hurt_pitch();
- self.audio.play(sound, Some(at), 1.0, pitch);
+ // Player.getVoicePitch: always 1.0.
+ self.audio.play(sound, Some(at), 1.0, 1.0);
}
/// `CombatTracker.recordDamage` for the motion events of this tick.
pub(super) fn record_combat(&mut self, events: &[MotionEvent]) {
@@ -85,6 +148,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 +174,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 +289,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 +314,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/command_blocks.rs b/crates/horizon-client/src/game/command_blocks.rs
index 76fc6d48c..868346452 100644
--- a/crates/horizon-client/src/game/command_blocks.rs
+++ b/crates/horizon-client/src/game/command_blocks.rs
@@ -2,7 +2,7 @@
//! tick (`execute`, `executeChain`), `BaseCommandBlock.performCommand`
//! through the command system with the block's output, and
//! `CommandBlockEditScreen` with what `handleSetCommandBlock` does with it.
-use super::{Game, Screen, commands::execute::Source};
+use super::{Game, Screen, commands::execute::Source, lan::LanHost};
use horizon_client::{
command_block::{self, CommandBlock, Mode},
containers::BlockEntity,
@@ -12,6 +12,7 @@ use horizon_client::{
world::World,
};
use horizon_core::position::BlockPos;
+use horizon_protocol::packets::play::{self, Serverbound as S};
use horizon_world::{
chunk::BlockState,
level::flags,
@@ -35,6 +36,16 @@ pub(super) struct CommandBlockScreen {
auto: bool,
}
+/// What `ServerboundSetCommandBlockPacket` carries.
+struct CommandBlockEdit {
+ pos: Pos,
+ command: String,
+ track_output: bool,
+ mode: Mode,
+ conditional: bool,
+ auto: bool,
+}
+
#[derive(Clone, Copy, PartialEq)]
enum Button {
Output,
@@ -186,6 +197,18 @@ impl Game<'_> {
pub(super) fn can_use_game_master_blocks(&self) -> bool {
self.creative && self.ui.registries.permission >= 2
}
+ /// `CommandBlock.useWithoutItem` on a server's client, which opens the
+ /// screen itself (`Player.openCommandBlock`) while the server only
+ /// answers the click: the block at `pos`, when it is a command block the
+ /// player may edit.
+ pub(super) fn open_command_block_if_editable(&mut self, pos: Pos) {
+ let is_command_block = self
+ .block_state_at(pos)
+ .is_some_and(|state| Mode::of_block(&state.name).is_some());
+ if is_command_block && self.can_use_game_master_blocks() {
+ self.open_command_block(pos);
+ }
+ }
fn command_block(&self, pos: Pos) -> Option<&CommandBlock> {
match self.world.block_entities.get(&pos)? {
BlockEntity::CommandBlock(c) => Some(c),
@@ -572,12 +595,66 @@ impl Game<'_> {
s.command.insert_text(&allowed);
}
}
- /// `ServerGamePacketListenerImpl.handleSetCommandBlock`.
+ /// The edit screen's Done: a server's client sends the packet, the
+ /// window's own world applies it (`handleSetCommandBlock`).
fn set_command_block(&mut self, s: &CommandBlockScreen) {
if !self.can_use_game_master_blocks() {
self.system_message(Text::translate("advMode.notAllowed", &[]));
return;
}
+ let edit = CommandBlockEdit {
+ pos: s.pos,
+ command: s.command.value.clone(),
+ track_output: s.track_output,
+ mode: s.mode,
+ conditional: s.conditional,
+ auto: s.auto,
+ };
+ if self.remote.is_some() {
+ self.send(S::SetCommandBlock(play::SetCommandBlock {
+ pos: [edit.pos.0, edit.pos.1, edit.pos.2],
+ command: edit.command,
+ mode: edit.mode.ordinal(),
+ flags: i8::from(edit.track_output)
+ | (i8::from(edit.conditional) << 1)
+ | (i8::from(edit.auto) << 2),
+ }));
+ } else {
+ self.apply_command_block(&edit);
+ }
+ }
+ /// `ServerGamePacketListenerImpl.handleSetCommandBlock` for a guest: the
+ /// block is edited only by a creative player with game master commands.
+ pub(super) fn lan_set_command_block(
+ &mut self,
+ host: &mut LanHost,
+ conn: u32,
+ p: play::SetCommandBlock,
+ ) {
+ let Some(g) = host.hub.guest(conn) else {
+ return;
+ };
+ let allowed = g.creative() && g.permission >= 2;
+ let edit = CommandBlockEdit {
+ pos: (p.pos[0], p.pos[1], p.pos[2]),
+ command: p.command,
+ track_output: p.flags & 1 != 0,
+ mode: Mode::from_ordinal(p.mode),
+ conditional: p.flags & 2 != 0,
+ auto: p.flags & 4 != 0,
+ };
+ self.as_guest(host, conn, |game| {
+ if allowed {
+ game.apply_command_block(&edit);
+ // BaseCommandBlock.onUpdated: the clients get the new command.
+ game.mark_block_entity_updated(edit.pos);
+ } else {
+ game.system_message(Text::translate("advMode.notAllowed", &[]));
+ }
+ });
+ }
+ /// What `handleSetCommandBlock` does once the player may edit the block.
+ fn apply_command_block(&mut self, s: &CommandBlockEdit) {
let pos = s.pos;
let registry = self.pack.assets.registry;
let Some(current) = self.block_state_at(pos) else {
@@ -609,7 +686,7 @@ impl Game<'_> {
}
let _ = self.process_level_events();
}
- let command = s.command.value.clone();
+ let command = s.command.clone();
let Some(c) = command_block_mut(&mut self.world, pos) else {
return;
};
diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs
index f3afdcab6..d3c40c3eb 100644
--- a/crates/horizon-client/src/game/commands.rs
+++ b/crates/horizon-client/src/game/commands.rs
@@ -42,9 +42,10 @@ pub(super) enum Target {
Guest(u32),
Mob(u32),
Item(u32),
- Orb(usize),
- /// By index in `creatures.projectiles`.
- Projectile(usize),
+ /// An experience orb, by its entity id.
+ Orb(u32),
+ /// A projectile, by its entity id.
+ Projectile(u32),
Stand(u32),
Frame(u32),
Painting(u32),
@@ -53,6 +54,10 @@ pub(super) enum Target {
/// An entity of a type Horizon does not simulate (markers, displays,
/// interactions...): kept as its saved data at a position.
Other(u32),
+ /// An End crystal, by its entity id (`minecraft:end_crystal`).
+ Crystal(u32),
+ /// The Ender Dragon, by its entity id (`minecraft:ender_dragon`).
+ Dragon(u32),
}
/// An entity of a type Horizon does not simulate: its compound lives in the
/// entity memory (`persist.raw`), its position and rotation here.
@@ -85,16 +90,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 +108,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 +120,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());
@@ -325,14 +345,16 @@ impl Game<'_> {
.iter()
.find(|i| i.id == id)
.map(|i| [i.position.x, i.position.y, i.position.z]),
- Target::Orb(i) => self
+ Target::Orb(id) => self
.orbs
- .get(i)
+ .iter()
+ .find(|o| o.id == id)
.map(|o| [o.position.x, o.position.y, o.position.z]),
- Target::Projectile(i) => self
+ Target::Projectile(id) => self
.creatures
.projectiles
- .get(i)
+ .iter()
+ .find(|a| a.id == id)
.map(|a| [a.position.x, a.position.y, a.position.z]),
Target::Stand(id) => self
.armor_stands
@@ -370,6 +392,16 @@ impl Game<'_> {
.iter()
.find(|o| o.id == id)
.map(|o| [o.position.x, o.position.y, o.position.z]),
+ Target::Crystal(id) => self
+ .crystals
+ .iter()
+ .find(|c| c.id == id)
+ .map(|c| [c.position.x, c.position.y, c.position.z]),
+ Target::Dragon(id) => self
+ .dragon
+ .as_ref()
+ .filter(|d| d.id == id)
+ .map(|d| [d.position.x, d.position.y, d.position.z]),
}
}
pub(super) fn target_type(&self, t: Target) -> String {
@@ -384,10 +416,11 @@ impl Game<'_> {
}),
Target::Item(_) => "minecraft:item".into(),
Target::Orb(_) => "minecraft:experience_orb".into(),
- Target::Projectile(i) => self
+ Target::Projectile(id) => self
.creatures
.projectiles
- .get(i)
+ .iter()
+ .find(|p| p.id == id)
.map_or_else(String::new, |p| p.kind.id().into()),
Target::Stand(_) => "minecraft:armor_stand".into(),
Target::Frame(id) => {
@@ -413,6 +446,8 @@ impl Game<'_> {
.iter()
.find(|o| o.id == id)
.map_or_else(String::new, |o| o.kind.clone()),
+ Target::Crystal(_) => "minecraft:end_crystal".into(),
+ Target::Dragon(_) => "minecraft:ender_dragon".into(),
}
}
/// The name of the player the game acts for: a guest's own while their
@@ -497,51 +532,72 @@ impl Game<'_> {
s.pos[2].unwrap_or(p[2]),
]
};
- let mut candidates: Vec = Vec::new();
+ let mut source_candidates: Vec = Vec::new();
match (s.kind, self.command_source) {
// @s: the executing entity (none for a server source).
- ('s', Some(source)) => candidates.extend(source.entity),
- ('s', None) => candidates.extend(self.source_entity()),
+ ('s', Some(source)) => source_candidates.extend(source.entity),
+ ('s', None) => source_candidates.extend(self.source_entity()),
// A guest in place is among the players, in join order.
_ if self.player.is_some() && self.lan_acting.is_none() => {
- candidates.push(Target::Player);
+ source_candidates.push(Target::Player);
}
_ => {}
}
if s.kind != 's' {
- use horizon_client::projectiles::ProjectileKind as K;
- candidates.extend(self.player_candidates(s));
- candidates.extend(
- self.mobs
- .iter()
- .filter(|m| m.death_time == 0)
- .map(|m| Target::Mob(m.id)),
- );
- candidates.extend(self.dropped.iter().map(|i| Target::Item(i.id)));
- candidates.extend((0..self.orbs.len()).map(Target::Orb));
- candidates.extend(
- self.creatures
- .projectiles
- .iter()
- .enumerate()
- // The kinds /data can write (entity_nbt).
- .filter(|(_, p)| {
- p.arrow.is_some()
- || matches!(p.kind, K::LargeFireball { .. } | K::SmallFireball)
- })
- .map(|(i, _)| Target::Projectile(i)),
- );
- candidates.extend(self.armor_stands.iter().map(|a| Target::Stand(a.id)));
- candidates.extend(self.item_frames.iter().map(|f| Target::Frame(f.id)));
- candidates.extend(self.paintings.iter().map(|p| Target::Painting(p.id)));
- candidates.extend(self.boats.iter().map(|b| Target::Boat(b.id)));
- candidates.extend(self.carts.iter().map(|c| Target::Cart(c.id)));
- candidates.extend(self.others.iter().map(|o| Target::Other(o.id)));
+ source_candidates.extend(self.player_candidates(s));
}
+ let source_dim = self.dim;
+ // A selector with a spatial constraint reaches the level the command
+ // runs in only; an unbounded one reaches every loaded level
+ // (EntitySelector.findEntities).
+ let dims = if s.world_limited() {
+ vec![source_dim]
+ } else {
+ self.loaded_dims()
+ };
+ let mut out: Vec<(Target, f64)> = Vec::new();
+ for dim in dims {
+ let back = self.enter_command_level(dim);
+ let mut candidates = Vec::new();
+ if dim == source_dim {
+ candidates.append(&mut source_candidates);
+ }
+ if s.kind != 's' {
+ candidates.extend(self.level_candidates());
+ }
+ out.extend(self.select_in_level(candidates, s, origin));
+ if let Some(back) = back {
+ self.enter_command_level(back);
+ }
+ }
+ match s.sort {
+ Sort::Nearest => out.sort_by(|a, b| a.1.total_cmp(&b.1)),
+ Sort::Furthest => out.sort_by(|a, b| b.1.total_cmp(&a.1)),
+ Sort::Random => {
+ for i in (1..out.len()).rev() {
+ let j = self.world.random.next_int_bound(i as i32 + 1).unwrap_or(0) as usize;
+ out.swap(i, j);
+ }
+ }
+ Sort::Arbitrary => {}
+ }
+ out.into_iter()
+ .take(s.limit.max(1))
+ .map(|(t, _)| t)
+ .collect()
+ }
+ /// The candidates of the level in place that pass the selector
+ /// (EntitySelector.getPredicate).
+ fn select_in_level(
+ &mut self,
+ candidates: Vec,
+ s: &Selector,
+ origin: [f64; 3],
+ ) -> Vec<(Target, f64)> {
let level = self.experience.level;
let creative = self.creative;
let passing = self.selector_extra_filter(&candidates, s);
- let mut out: Vec<(Target, f64)> = candidates
+ candidates
.into_iter()
.filter_map(|t| {
let p = self.target_position(t)?;
@@ -613,23 +669,102 @@ impl Game<'_> {
}
Some((t, d2))
})
- .collect();
- match s.sort {
- Sort::Nearest => out.sort_by(|a, b| a.1.total_cmp(&b.1)),
- Sort::Furthest => out.sort_by(|a, b| b.1.total_cmp(&a.1)),
- Sort::Random => {
- for i in (1..out.len()).rev() {
- let j = self.world.random.next_int_bound(i as i32 + 1).unwrap_or(0) as usize;
- out.swap(i, j);
- }
- }
- Sort::Arbitrary => {}
- }
- out.into_iter()
- .take(s.limit.max(1))
- .map(|(t, _)| t)
.collect()
}
+ /// The entities of the level in place a selector can find.
+ fn level_candidates(&self) -> Vec {
+ use horizon_client::projectiles::ProjectileKind as K;
+ let mut candidates = Vec::new();
+ candidates.extend(
+ self.mobs
+ .iter()
+ .filter(|m| m.death_time == 0)
+ .map(|m| Target::Mob(m.id)),
+ );
+ candidates.extend(self.dropped.iter().map(|i| Target::Item(i.id)));
+ candidates.extend(self.orbs.iter().map(|o| Target::Orb(o.id)));
+ candidates.extend(
+ self.creatures
+ .projectiles
+ .iter()
+ // The kinds /data can write (entity_nbt).
+ .filter(|p| {
+ p.is_arrow() || matches!(p.kind, K::LargeFireball { .. } | K::SmallFireball)
+ })
+ .map(|p| Target::Projectile(p.id)),
+ );
+ candidates.extend(self.armor_stands.iter().map(|a| Target::Stand(a.id)));
+ candidates.extend(self.item_frames.iter().map(|f| Target::Frame(f.id)));
+ candidates.extend(self.paintings.iter().map(|p| Target::Painting(p.id)));
+ candidates.extend(self.boats.iter().map(|b| Target::Boat(b.id)));
+ candidates.extend(self.carts.iter().map(|c| Target::Cart(c.id)));
+ candidates.extend(self.others.iter().map(|o| Target::Other(o.id)));
+ // The End crystals and the dragon (EndCrystal and EnderDragon
+ // are entities of their own).
+ candidates.extend(self.crystals.iter().map(|c| Target::Crystal(c.id)));
+ if let Some(d) = &self.dragon {
+ candidates.push(Target::Dragon(d.id));
+ }
+ candidates
+ }
+ /// The loaded levels, in the order the server holds them: the
+ /// overworld, the nether, the end (MinecraftServer.getAllLevels).
+ fn loaded_dims(&self) -> Vec {
+ let mut dims = vec![self.dim];
+ dims.extend(self.levels.parked_dims());
+ dims.sort_by_key(|d| match d {
+ Dim::Overworld => 0,
+ Dim::Nether => 1,
+ Dim::End => 2,
+ });
+ dims
+ }
+ /// Whether the level in place holds the entity a target names.
+ fn level_holds(&self, t: Target) -> bool {
+ match t {
+ // A player is in no level of its own.
+ Target::Player | Target::Guest(_) => true,
+ Target::Mob(id) => self.mobs.iter().any(|m| m.id == id),
+ Target::Item(id) => self.dropped.iter().any(|i| i.id == id),
+ Target::Orb(id) => self.orbs.iter().any(|o| o.id == id),
+ Target::Projectile(id) => self.creatures.projectiles.iter().any(|p| p.id == id),
+ Target::Stand(id) => self.armor_stands.iter().any(|a| a.id == id),
+ Target::Frame(id) => self.item_frames.iter().any(|f| f.id == id),
+ Target::Painting(id) => self.paintings.iter().any(|p| p.id == id),
+ Target::Boat(id) => self.boats.iter().any(|b| b.id == id),
+ Target::Cart(id) => self.carts.iter().any(|c| c.id == id),
+ Target::Other(id) => self.others.iter().any(|o| o.id == id),
+ Target::Crystal(id) => self.crystals.iter().any(|c| c.id == id),
+ Target::Dragon(id) => self.dragon.as_ref().is_some_and(|d| d.id == id),
+ }
+ }
+ /// Run `f` with the level that holds the entity a target names in place
+ /// (the entity ids are unique across the loaded levels) and put the
+ /// level back afterwards. `f` does not run when no level holds the
+ /// entity.
+ pub(in crate::game) fn in_target_level(
+ &mut self,
+ t: Target,
+ f: impl FnOnce(&mut Self) -> R,
+ ) -> Option {
+ if self.level_holds(t) {
+ return Some(f(self));
+ }
+ for dim in self.levels.parked_dims() {
+ let back = self.enter_command_level(dim);
+ if self.level_holds(t) {
+ let r = f(self);
+ if let Some(back) = back {
+ self.enter_command_level(back);
+ }
+ return Some(r);
+ }
+ if let Some(back) = back {
+ self.enter_command_level(back);
+ }
+ }
+ None
+ }
fn entity_tag_matches(&self, tag: &str, ty: &str) -> bool {
let path = self.options.resources.join(format!(
"data/minecraft/tags/entity_type/{}.json",
@@ -1089,6 +1224,10 @@ impl Game<'_> {
Ok(targets.len() as i32)
}
fn teleport_to(&mut self, t: Target, pos: [f64; 3], rotation: Option<[f32; 2]>) {
+ // An entity in another level is teleported in the level that holds it.
+ let _ = self.in_target_level(t, |g| g.teleport_to_in_level(t, pos, rotation));
+ }
+ fn teleport_to_in_level(&mut self, t: Target, pos: [f64; 3], rotation: Option<[f32; 2]>) {
let v = Vec3::new(pos[0], pos[1], pos[2]);
match t {
Target::Guest(_) => {
@@ -1137,14 +1276,14 @@ impl Game<'_> {
i.previous = v;
}
}
- Target::Orb(i) => {
- if let Some(o) = self.orbs.get_mut(i) {
+ Target::Orb(id) => {
+ if let Some(o) = self.orbs.iter_mut().find(|o| o.id == id) {
o.position = v;
o.previous = v;
}
}
- Target::Projectile(i) => {
- if let Some(a) = self.creatures.projectiles.get_mut(i) {
+ Target::Projectile(id) => {
+ if let Some(a) = self.creatures.projectiles.iter_mut().find(|a| a.id == id) {
a.position = v;
a.previous = v;
}
@@ -1184,6 +1323,17 @@ impl Game<'_> {
}
}
}
+ Target::Crystal(id) => {
+ if let Some(c) = self.crystals.iter_mut().find(|c| c.id == id) {
+ c.position = v;
+ }
+ }
+ Target::Dragon(id) => {
+ if let Some(d) = self.dragon.as_mut().filter(|d| d.id == id) {
+ d.position = v;
+ d.previous = v;
+ }
+ }
// Wall-mounted entities do not move.
Target::Frame(_) | Target::Painting(_) => {}
}
@@ -1543,6 +1693,10 @@ impl Game<'_> {
Ok(duration.unwrap_or(-1))
}
fn kill_target(&mut self, t: Target) {
+ // An entity in another level is killed in the level that holds it.
+ let _ = self.in_target_level(t, |g| g.kill_target_in_level(t));
+ }
+ fn kill_target_in_level(&mut self, t: Target) {
match t {
Target::Guest(_) => {
self.for_player(t, |g| g.kill_target(Target::Player));
@@ -1562,16 +1716,13 @@ impl Game<'_> {
}
}
Target::Item(id) => self.dropped.retain(|i| i.id != id),
- Target::Orb(i) => {
- if i < self.orbs.len() {
- self.orbs[i].age = u32::MAX / 2;
+ Target::Orb(id) => {
+ if let Some(o) = self.orbs.iter_mut().find(|o| o.id == id) {
+ o.age = u32::MAX / 2;
}
}
- // cmd_kill goes from the highest index down.
- Target::Projectile(i) => {
- if i < self.creatures.projectiles.len() {
- self.creatures.projectiles.remove(i);
- }
+ Target::Projectile(id) => {
+ self.creatures.projectiles.retain(|p| p.id != id);
}
Target::Stand(id) => self.armor_stands.retain(|a| a.id != id),
Target::Frame(id) => self.item_frames.retain(|f| f.id != id),
@@ -1579,7 +1730,11 @@ impl Game<'_> {
Target::Boat(id) => self.boats.retain(|b| b.id != id),
Target::Cart(id) => self.carts.retain(|c| c.id != id),
Target::Other(id) => self.others.retain(|o| o.id != id),
+ Target::Crystal(id) => self.kill_crystal(id),
+ Target::Dragon(id) => self.kill_dragon(id),
}
+ // The orbs marked for removal are gone (Entity.kill removes them).
+ self.orbs.retain(|o| o.age < u32::MAX / 2);
}
fn cmd_kill(&mut self, ctx: &Context) -> R {
let targets = if ctx.get("targets").is_some() {
@@ -1587,19 +1742,18 @@ impl Game<'_> {
} else {
vec![self.implied_player()]
};
- let names: Vec = targets.iter().map(|&t| self.target_name(t)).collect();
- // Remove indexed entities from the back so earlier indices stay valid.
- let mut ordered = targets.clone();
- ordered.sort_by_key(|t| {
- std::cmp::Reverse(match t {
- Target::Orb(i) | Target::Projectile(i) => *i,
- _ => 0,
- })
- });
- for t in ordered {
+ let mut names: Vec = Vec::new();
+ for &t in &targets {
+ // The name of an entity in another level is read there.
+ let name = match self.in_target_level(t, |g| g.target_name(t)) {
+ Some(name) => name,
+ None => self.target_name(t),
+ };
+ names.push(name);
+ }
+ for &t in &targets {
self.kill_target(t);
}
- self.orbs.retain(|o| o.age < u32::MAX / 2);
let message = if targets.len() == 1 {
Text::translate("commands.kill.success.single", &[names[0].clone()])
} else {
@@ -1682,6 +1836,8 @@ impl Game<'_> {
value: 0,
age: 0,
on_ground: false,
+ count: 1,
+ ticks: 0,
});
name = Text::translate("entity.minecraft.experience_orb", &[]);
}
@@ -1689,6 +1845,20 @@ impl Game<'_> {
self.spawn_bolt(pos, false);
name = Text::translate("entity.minecraft.lightning_bolt", &[]);
}
+ "end_crystal" => {
+ // EndCrystal's constructor takes an id from the entity
+ // counter, and the crystal is shown with its base.
+ self.next_entity += 1;
+ self.crystals.push(super::dragon::Crystal {
+ id: self.next_entity,
+ position: Vec3::new(pos[0], pos[1], pos[2]),
+ show_bottom: true,
+ time: self.world.random.next_int_bound(100_000).unwrap_or(0),
+ beam: None,
+ invulnerable: false,
+ });
+ name = Text::translate("entity.minecraft.end_crystal", &[]);
+ }
k if super::minecarts::CartKind::from_id(&kind).is_some() => {
let cart_kind = super::minecarts::CartKind::from_id(&kind)
.unwrap_or(super::minecarts::CartKind::Rideable);
@@ -1870,11 +2040,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 +2053,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 +2822,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..61bf3abe9 100644
--- a/crates/horizon-client/src/game/commands/data.rs
+++ b/crates/horizon-client/src/game/commands/data.rs
@@ -31,8 +31,13 @@ fn set_key(tag: &mut Tag, key: &str, value: Tag) {
impl Game<'_> {
// ---- entity data ---------------------------------------------------
- /// `NbtPredicate.getEntityTagToCompare`: the entity as saved.
+ /// `NbtPredicate.getEntityTagToCompare`: the entity as saved. An entity
+ /// in another level is read in the level that holds it.
pub(in crate::game) fn entity_nbt(&mut self, t: Target) -> Option {
+ self.in_target_level(t, |g| g.entity_nbt_in_level(t))
+ .flatten()
+ }
+ fn entity_nbt_in_level(&mut self, t: Target) -> Option {
let player_uuid = self.level.player_uuid;
Some(match t {
Target::Guest(_) => {
@@ -113,9 +118,11 @@ impl Game<'_> {
let o = self.others.iter().find(|o| o.id == id)?.clone();
self.other_to_nbt(&o, uuid)
}
- Target::Orb(i) => entity_nbt::orb_to_nbt(self.orbs.get(i)?, random_uuid()),
- Target::Projectile(i) => {
- let p = self.creatures.projectiles.get(i)?;
+ Target::Orb(id) => {
+ entity_nbt::orb_to_nbt(self.orbs.iter().find(|o| o.id == id)?, random_uuid())
+ }
+ Target::Projectile(id) => {
+ let p = self.creatures.projectiles.iter().find(|p| p.id == id)?;
let owner = if p.owner == Some(horizon_client::mobs::Who::Player) {
player_uuid
} else {
@@ -129,6 +136,16 @@ impl Game<'_> {
entity_nbt::arrow_to_nbt(p, random_uuid(), owner, in_block, None)
.or_else(|| entity_nbt::fireball_to_nbt(p, random_uuid(), owner, None))?
}
+ Target::Crystal(id) => {
+ let c = self.crystals.iter().find(|c| c.id == id)?;
+ let (uuid, raw) = self.persist_anon("minecraft:end_crystal", c.position);
+ c.to_nbt(uuid.unwrap_or_else(random_uuid), raw)
+ }
+ Target::Dragon(id) => {
+ let d = self.dragon.as_ref().filter(|d| d.id == id)?;
+ let (uuid, raw) = self.persist_anon("minecraft:ender_dragon", d.position);
+ d.to_nbt(uuid.unwrap_or_else(random_uuid), raw)
+ }
})
}
/// `Entity.load` of new data (`EntityDataAccessor.setData`): the entity is
@@ -286,6 +303,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 +314,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).
@@ -395,6 +414,19 @@ impl Game<'_> {
}
pub(super) fn cmd_data(&mut self, id: &str, ctx: &Context) -> R {
let target = self.data_ref(ctx, 0)?;
+ // An entity in another level is read and written in the level that
+ // holds it.
+ if let DataRef::Entity(t) = &target {
+ let t = *t;
+ let target = target.clone();
+ return match self.in_target_level(t, |g| g.cmd_data_in(id, ctx, target)) {
+ Some(r) => r,
+ None => Err(err("argument.entity.notfound.entity", &[])),
+ };
+ }
+ self.cmd_data_in(id, ctx, target)
+ }
+ fn cmd_data_in(&mut self, id: &str, ctx: &Context, target: DataRef) -> R {
match id {
"data.merge" => {
let Some(Arg::Str(nbt)) = ctx.get("nbt") else {
diff --git a/crates/horizon-client/src/game/commands/effects.rs b/crates/horizon-client/src/game/commands/effects.rs
index 65d6592f7..3a26f6c0d 100644
--- a/crates/horizon-client/src/game/commands/effects.rs
+++ b/crates/horizon-client/src/game/commands/effects.rs
@@ -1,11 +1,10 @@
//! `/effect` (EffectCommands) and `/enchant` (EnchantCommand).
use super::{Arg, Context, Game, R, Target, err, texts};
use horizon_client::{
- brewing,
+ brewing::{self, namespaced},
effects::EffectInstance,
text::{self, Style, Text},
};
-use std::{collections::HashMap, sync::OnceLock};
/// `CommandResponseTracker` over targets: elements with a non-zero result.
#[derive(Default)]
@@ -21,24 +20,6 @@ impl Tracker {
}
}
}
-/// Namespaced effect ids for mob effect storage.
-fn namespaced(id: &'static str) -> &'static str {
- static IDS: OnceLock> = OnceLock::new();
- IDS.get_or_init(|| {
- brewing::EFFECTS
- .iter()
- .map(|e| {
- (
- e.id,
- &*Box::leak(format!("minecraft:{}", e.id).into_boxed_str()),
- )
- })
- .collect()
- })
- .get(id)
- .copied()
- .unwrap_or(id)
-}
fn effect_name(id: &str) -> Text {
Text::translate(&format!("effect.minecraft.{id}"), &[])
}
@@ -91,7 +72,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 +140,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..12aedc59a 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,73 @@ 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(id) => self
+ .creatures
+ .projectiles
+ .iter()
+ .find(|p| p.id == id)
+ .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()) => {
@@ -807,10 +908,12 @@ impl Game<'_> {
.coords(c, "pos")
.map(|co| co.block(self.source_position(), self.source_rotation()));
let dimension = self.command_source.map_or(self.dim, |s| s.dimension);
- return Ok(flag(
- dimension == self.dim
- && p.is_some_and(|p| self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4))),
- ));
+ // ExecuteCommand.isChunkLoaded: ENTITY_TICKING, which is past lit.
+ let loaded = |p: [i32; 3]| {
+ let key = (p[0] >> 4, p[2] >> 4);
+ self.world.chunks.contains_key(&key) && self.streaming.is_lit(key.0, key.1)
+ };
+ return Ok(flag(dimension == self.dim && p.is_some_and(loaded)));
}
if c.has("dimension") {
let dimension = self.command_source.map_or(self.dim, |s| s.dimension);
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