diff --git a/.dockerignore b/.dockerignore
index 417a1867c..458330c93 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -2,7 +2,6 @@
target/
.local/
**/node_modules/
-website/
benchmarks/
packs/
mods/
diff --git a/.gitattributes b/.gitattributes
index 358aeae7a..f9e1922d7 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -2,5 +2,5 @@
# where Git for Windows' core.autocrlf would check them out with CRLF.
docs/launcher-commands.md text eol=lf
docs/horizon-ctl-commands.md text eol=lf
-website/src/tokens.css text eol=lf
+crates/horizon-theme/tokens.css text eol=lf
docs/api/*-reference.md text eol=lf
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index eff82fa99..b2fd9fa48 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -73,6 +73,42 @@ jobs:
run: |
cargo +stable test --workspace --lib --bins --tests --features horizon-client/mods,horizon-mods/pack
cargo +stable test --workspace --doc --features horizon-client/mods,horizon-mods/pack
+ # The launcher is its own workspace (launcher/Cargo.toml), so verify's cargo runs never build it. A pull request that
+ # changes it or a crate it builds is checked here, and so is every push to main: two pull requests can each pass
+ # alone and break it together (#2059 and the registry ratings did, 2026-10-26).
+ launcher:
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ - name: Does this pull request change the launcher or a crate it builds?
+ if: github.event_name == 'pull_request'
+ id: launcher
+ env:
+ BASE_SHA: ${{ github.event.pull_request.base.sha }}
+ HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ run: python3 tools/ci/rust_changes.py --launcher "$BASE_SHA" "$HEAD_SHA" >> "$GITHUB_OUTPUT"
+ - name: Install Rust and the headers GPUI links against
+ if: steps.launcher.outputs.required != 'false'
+ run: |
+ sudo apt-get update && sudo apt-get install -y --no-install-recommends libxkbcommon-x11-dev libwayland-dev \
+ libx11-xcb-dev libfontconfig-dev libvulkan-dev libasound2-dev libudev-dev
+ rustup toolchain install stable --profile minimal --component rustfmt --component clippy
+ - uses: Swatinem/rust-cache@v2
+ if: steps.launcher.outputs.required != 'false'
+ with:
+ workspaces: launcher
+ shared-key: launcher
+ save-if: ${{ github.ref == 'refs/heads/main' }}
+ - name: Check the launcher's formatting, lint and tests
+ if: steps.launcher.outputs.required != 'false'
+ working-directory: launcher
+ run: |
+ cargo +stable fmt --check
+ cargo +stable clippy --all-targets --locked -- -D warnings
+ cargo +stable test --locked --lib
# Most pull requests leave the harnesses to parity-main, which runs them on main a batch of merges at a time
# (.github/workflows/parity-main.yml; releases wait for it). A pull request still runs them itself when it changes
# a harness, an oracle, a probe or the runner, or carries the run-parity label (run-parity.yml, when it is added).
@@ -108,6 +144,7 @@ jobs:
with:
base: ${{ github.event.pull_request.base.sha }}
head: ${{ github.event.pull_request.head.sha }}
+ full: ${{ contains(github.event.pull_request.labels.*.name, 'full-parity') }}
# Horizon never downloads the game. These jobs need a self-hosted Linux runner
# (label horizon-game) holding the maintainer's own copy: the official launcher's
# game directory in HORIZON_MINECRAFT_DIR and the pinned server jar in
diff --git a/.github/workflows/parity-main.yml b/.github/workflows/parity-main.yml
index c47005ab0..4840b98be 100644
--- a/.github/workflows/parity-main.yml
+++ b/.github/workflows/parity-main.yml
@@ -25,8 +25,8 @@ jobs:
parity-main:
# A Mac mini runner of its own (ludovics-mac-mini-2 holds only this label since 2026-10-26): behind PR parity jobs
# this run waited 2 h while every merge replaced the pending one, and on the release runner a release then waited
- # behind the next run. PR parity jobs have ludovics-mac-mini and the desktop. Not the desktop: a job slowed down
- # because the maintainer came back could time out, and a failure here bisects and comments on merges.
+ # behind the next run. PR parity jobs have ludovics-mac-mini and playhorizon. Not playhorizon: its 4 CPUs
+ # make a core-crate run several times longer, and a failure here bisects and comments on merges.
runs-on: [self-hosted, macOS, horizon-parity-main]
timeout-minutes: 240 # a core-crate batch reruns ~300 harnesses (~60-90 min), a bisect a few rounds of the failures
steps:
@@ -48,6 +48,9 @@ jobs:
GH_TOKEN: ${{ github.token }}
run: echo "sha=$(python3 tools/parity_main.py base)" >> "$GITHUB_OUTPUT"
- name: The harnesses the merges since then can affect
+ id: harnesses
+ # A failure here is judged by the next step: the run passes when every failed harness passes again at HEAD.
+ continue-on-error: true
env:
PARITY_HOSTS: ''
BASE_SHA: ${{ steps.base.outputs.sha }}
@@ -55,8 +58,8 @@ jobs:
echo "Merges since ${BASE_SHA}:"
git log --first-parent --format=' %h %s' "$BASE_SHA..HEAD"
python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400
- - name: The merge that broke them
- if: failure()
+ - name: A flake, or the merge that broke them
+ if: steps.harnesses.outcome == 'failure'
env:
GH_TOKEN: ${{ github.token }}
PARITY_HOSTS: ''
@@ -65,7 +68,7 @@ jobs:
rm -rf .local/parity-main-logs && cp -R .local/parity-runner/logs .local/parity-main-logs 2>/dev/null || true
python3 tools/parity_main.py bisect "$BASE_SHA" --comment
- name: Logs of the failed harnesses
- if: failure()
+ if: steps.harnesses.outcome == 'failure'
uses: actions/upload-artifact@v4
with:
name: parity-main-logs
diff --git a/.github/workflows/parity.yml b/.github/workflows/parity.yml
index 1fc31d8cb..c850c17aa 100644
--- a/.github/workflows/parity.yml
+++ b/.github/workflows/parity.yml
@@ -1,6 +1,6 @@
name: parity
-# The vanilla harnesses a pull request's changes can affect, on the Mac mini's runner, which holds the maintainer's
-# own Minecraft files (Horizon never downloads the game). Called by ci.yml for pull requests from this repository
+# The vanilla harnesses a pull request's changes can affect, on the Mac mini's runner or playhorizon's, which hold the
+# maintainer's own Minecraft files (Horizon never downloads the game). Called by ci.yml for pull requests from this repository
# and by run-parity.yml when a maintainer labels a fork's pull request run-parity. See docs/release-flow.md.
on:
workflow_call:
@@ -13,6 +13,13 @@ on:
description: The commit to check out and test
type: string
required: true
+ full:
+ description: >-
+ The pull request carries the full-parity label (a change every harness reaches, such as a crate split): it
+ runs on playhorizon's runner only, so the Mac mini's runners stay free for the others. While that runner is
+ busy the job waits for it.
+ type: boolean
+ default: false
permissions:
contents: read
env:
@@ -21,40 +28,53 @@ env:
jobs:
parity:
- runs-on: [self-hosted, horizon-game]
- timeout-minutes: 120 # a change to core crates reruns ~300 harnesses: ~60-90 min on the Mac mini
+ runs-on: ${{ inputs.full && fromJSON('["self-hosted", "horizon-game", "playhorizon"]') || fromJSON('["self-hosted", "horizon-game"]') }}
+ # A change to core crates reruns ~350 harnesses: ~60-90 min on the Mac mini; on playhorizon (4 of its 8 vCPUs, 4
+ # harnesses at a time) up to a few hours, and any pull request's job may land there.
+ timeout-minutes: ${{ inputs.full && 360 || 180 }}
steps:
- uses: actions/checkout@v4
with:
- # The commit the event names: a fork's later pushes need another run-parity label.
+ # The commit the event names: a fork's later pushes need another run-parity label. The next step merges
+ # main into it.
ref: ${{ inputs.head }}
fetch-depth: 0
persist-credentials: false
# Keeps .local/ (parity state, probe builds, oracle results) and target/ between runs.
clean: false
+ - name: The head merged into main (what merging it would land)
+ id: merge
+ env:
+ BASE_SHA: ${{ inputs.base }}
+ HEAD_SHA: ${{ inputs.head }}
+ run: |
+ # Harness fixes and game fixes that reached main since the branch was made then apply here too: a head
+ # tested alone failed harnesses already fixed on main (server_knockback before #2114, mob_ai's heap before
+ # #2270, save_roundtrip before #2212). Selection then compares with this main, so it sees only the pull
+ # request's own changes. A head that conflicts with main is tested alone.
+ set -euo pipefail
+ git merge --abort 2>/dev/null || true
+ git fetch -q --no-tags origin +refs/heads/main:refs/remotes/origin/main
+ main=$(git rev-parse origin/main)
+ if git -c user.name=parity -c user.email=parity@localhost merge -q --no-edit --no-ff "$main" >/dev/null 2>&1; then
+ echo "base=$main" >> "$GITHUB_OUTPUT"
+ echo "Tested: head ${HEAD_SHA:0:9} merged into main ${main:0:9}" | tee -a "$GITHUB_STEP_SUMMARY"
+ else
+ git merge --abort
+ echo "base=$BASE_SHA" >> "$GITHUB_OUTPUT"
+ echo "::warning::head ${HEAD_SHA:0:9} conflicts with main ${main:0:9}: tested alone, without main's fixes"
+ echo "Tested: head ${HEAD_SHA:0:9} alone (it conflicts with main ${main:0:9})" | tee -a "$GITHUB_STEP_SUMMARY"
+ fi
- uses: dtolnay/rust-toolchain@stable
- name: Tools from the runner
run: bash tools/ci/runner-env.sh
- name: Vanilla data, and resources prepared by this preparer
- env:
- BASE_SHA: ${{ inputs.base }}
- run: |
- # main's script: one written before a fix to it left a real .local/horizon-client without sounds.json on
- # the runner, and every later job there failed `subtitle`. A branch that changes the script runs its own.
- set -euo pipefail
- if git rev-parse --verify -q origin/main >/dev/null \
- && git diff --quiet "$(git merge-base "$BASE_SHA" HEAD)" HEAD -- tools/ci/vanilla-data.sh; then
- git show origin/main:tools/ci/vanilla-data.sh > "$RUNNER_TEMP/vanilla-data.sh"
- bash "$RUNNER_TEMP/vanilla-data.sh"
- else
- bash tools/ci/vanilla-data.sh
- fi
+ run: bash tools/ci/vanilla-data.sh
- name: The prepared output is the one the preparer's OUTPUT_VERSION says
env:
- BASE_SHA: ${{ inputs.base }}
+ BASE_SHA: ${{ steps.merge.outputs.base }}
run: |
- # The job runs main's workflow on the head's files: a head made before OUTPUT_VERSION (#1947) has neither
- # the tool nor the number, so there is nothing to check.
+ # A head made before OUTPUT_VERSION (#1947) that conflicts with main has neither the tool nor the number.
if [ ! -f tools/prepare_output.py ] || ! grep -q OUTPUT_VERSION crates/horizon-prepare/src/lib.rs; then
echo "This head's preparer has no OUTPUT_VERSION: nothing to check"
exit 0
@@ -65,47 +85,8 @@ jobs:
- name: The harnesses this change can affect
env:
PARITY_HOSTS: ''
- BASE_SHA: ${{ inputs.base }}
- run: |
- # main's selection (tools/parity.py --changed --list with main's parity.py and parity_reach.py), so a
- # branch made before a better selection landed gets it too; the head's own runner then runs those
- # harnesses. A branch that changes the selection itself selects with its own code.
- set -euo pipefail
- own() { python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400; } # world_spawn takes ~1480 s on a busy runner
- fork_point=$(git merge-base "$BASE_SHA" HEAD)
- if ! git rev-parse --verify -q origin/main >/dev/null || ! git diff --quiet "$fork_point" HEAD -- tools/parity.py tools/parity_reach.py; then
- own
- exit
- fi
- had_reach=$(git ls-files tools/parity_reach.py)
- git show origin/main:tools/parity.py > tools/parity.py
- git show origin/main:tools/parity_reach.py > tools/parity_reach.py
- status=0
- python3 tools/parity.py --changed "$BASE_SHA" --list > .local/parity-selection.txt || status=$?
- git checkout -- tools/parity.py
- if [ -n "$had_reach" ]; then git checkout -- tools/parity_reach.py; else rm -f tools/parity_reach.py; fi
- cat .local/parity-selection.txt
- if [ "$status" != 0 ]; then
- echo "main's selection failed: the head's own selection runs"
- own
- exit
- fi
- names=$(sed '$d' .local/parity-selection.txt | grep -E '^[A-Za-z0-9_#]+$' || true)
- # The summary line says how many would run: a count that doesn't match the names read (a format change)
- # must not let the job pass untested.
- expected=$(tail -1 .local/parity-selection.txt | sed -nE 's/^([0-9]+) of [0-9]+ harnesses would run$/\1/p')
- count=$(printf '%s' "$names" | grep -c . || true)
- if [ -z "$expected" ] || [ "$expected" != "$count" ]; then
- echo "main's selection listed $count names, its summary says '${expected:-?}': the head's own selection runs"
- own
- exit
- fi
- if [ "$count" = 0 ]; then
- echo "Nothing to run."
- exit 0
- fi
- # shellcheck disable=SC2086
- python3 tools/parity.py $names --timeout 2400
+ BASE_SHA: ${{ steps.merge.outputs.base }}
+ run: python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400 # world_spawn takes ~1480 s on a busy runner
- name: Logs of the failed harnesses
if: failure()
uses: actions/upload-artifact@v4
diff --git a/.github/workflows/run-parity.yml b/.github/workflows/run-parity.yml
index a2b8e3291..9089a9a09 100644
--- a/.github/workflows/run-parity.yml
+++ b/.github/workflows/run-parity.yml
@@ -22,3 +22,4 @@ jobs:
with:
base: ${{ github.event.pull_request.base.sha }}
head: ${{ github.event.pull_request.head.sha }}
+ full: ${{ contains(github.event.pull_request.labels.*.name, 'full-parity') }}
diff --git a/AGENTS.md b/AGENTS.md
index dcd4ca595..489a1466b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -10,7 +10,8 @@ Feature → files → harness for the most-changed areas: [docs/architecture.md]
`tools/check_public_tree.py` rejects them; `git config core.hooksPath .githooks` runs it on commit.
- **Keep your runs away from real player data.** Any game or launcher you start gets fresh `mktemp -d`
folders in `HORIZON_HOME` (the game's data), `HORIZON_LAUNCHER_HOME`, `XDG_DATA_HOME` and
- `XDG_CONFIG_HOME`, plus `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` and `HORIZON_NO_AUDIO=1`. Never write to
+ `XDG_CONFIG_HOME`, plus `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` and `HORIZON_NO_AUDIO=1`, and, for the
+ launcher, `HORIZON_LAUNCHER_TRASH` and `HORIZON_LAUNCHER_CLIPBOARD` pointing into the scratch home. Never write to
`~/.local/share/{applications,horizon,horizon-launcher}` or `~/.local/bin`.
- **Mark what an agent posts.** A PR body starts with a line naming whose agent opened it and with what.
Ludovic's agents write `> 🤖 Opened by Ludovic's AI agent (Claude), not by Ludovic himself.`, and a
@@ -34,7 +35,9 @@ Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-se
| Crate | Owns |
|---|---|
-| `horizon-client` | The game: a lib (`src/lib.rs`, ~190 flat modules) and the bin (`src/main.rs` → `game.rs` + `game/`), plus `horizon-ctl` (`src/bin/horizon-ctl/`). Also the dedicated server (`--dedicated`) |
+| `horizon-client` | The game: a lib (`src/lib.rs`, ~180 flat modules) and the bin (`src/main.rs` → `game.rs` + `game/`), plus `horizon-ctl` (`src/bin/horizon-ctl/`). Also the dedicated server (`--dedicated`) |
+| `horizon-command` | Command parsing (Brigadier): the vanilla tree, argument types, selectors, suggestions, the tree's network form. Re-exported as `horizon_client::command` |
+| `horizon-client-core` | The client lib's bottom layer: `text.rs`, `lang.rs`, `snbt.rs`, `nbt_path.rs`, `component.rs`, `scoreboard.rs`, `bossbar.rs`, `gamerules.rs`, `block_entity_nbt.rs`, registry/particle/sound tables. Re-exported under the old paths (`horizon_client::text`...) |
| `horizon-world` | Vanilla world data with no gameplay loop: NBT, regions, chunks, `datafix/`, `worldgen/`, `level/` (server-side block behaviour, ticks, redstone), entity physics, items, effects, food, damage |
| `horizon-core` | Simulation primitives: Java `Random`s, `jmath` (HotSpot-exact `Math`), positions, noise, density, paletted storage, `version.rs` (the pinned version) |
| `horizon-protocol` | Network protocol 777: codecs, framing, encryption, `packets/{handshake,status,login,configuration,play}.rs`, `entity_data.rs` |
@@ -54,7 +57,8 @@ Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-se
Other top-level folders: `tools/` (harnesses and dev scripts), `tests/` (Python unit tests: `python3 -m
unittest discover -s tests`), `mods/horizon/src/test/java/dev/horizonlab/parity/` (Java oracles),
-`website/` (playhorizon.dev; its paths are relative to `website/`), `docs/`, `.github/workflows/`.
+`docs/`, `.github/workflows/`. The website (playhorizon.dev) is the private ludovic111/horizon-site: its build
+reads `README.md`, `launcher/links.json`, `docs/api/`, `roadmap/roadmap.json` and `crates/horizon-theme/tokens.css` from main.
## Build and test fast
@@ -117,16 +121,16 @@ python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end
| Other entities | L: `entities.rs`, `projectiles.rs`, `arrows.rs`; G: `boats.rs`, `minecarts.rs`, `mounts.rs`, `armor_stands.rs`, `paintings.rs`, `frames.rs`, `fireworks.rs`, `tnt.rs`, `explosion.rs` |
| Player actions | game.rs (`fn use_hand`, `fn use_item`, `fn attack`, `fn tick_mining`, `fn break_block`); G: `hand.rs`, `combat.rs`, `consume.rs`, `potions.rs`, `shield.rs`, `crossbow.rs`, `trident.rs`, `fishing.rs`; L: `motion.rs` + `motion/` (movement), `collisions.rs`, `items.rs`, `item_data.rs` |
| Inventory and containers | L: `menu.rs` (`AbstractContainerMenu.clicked`), `container_screen.rs`, `containers.rs`, `creative.rs`, `crafting.rs`, `recipe_book*.rs`, `stations.rs`, `merchant.rs`; game.rs `fn menu_ops`, `fn click_inventory`; G: `stations.rs`, `trading.rs`, `recipe_book.rs`, `machines.rs` |
-| Commands | parse: L: `command/` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`); run: G: `commands.rs` (dispatch) + `commands/*.rs` (`admin`, `execute`, `items`, `players`, `world_cmds`...); L: `scoreboard_cmd.rs`, `data_cmd.rs`, `nbt_path.rs`; G: `functions.rs`, `command_blocks.rs` |
+| Commands | parse: crate `horizon-command` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`); run: G: `commands.rs` (dispatch) + `commands/*.rs` (`admin`, `execute`, `items`, `players`, `world_cmds`...); L: `scoreboard_cmd.rs`, `data_cmd.rs`; `horizon-client-core`: `nbt_path.rs`, `scoreboard.rs`; G: `functions.rs`, `command_blocks.rs` |
| UI screens | `Screen` enum in game.rs; L: `title.rs` + `title/`, `options_ui.rs`, `multiplayer.rs`, `pack_screen.rs`, `graphics_ui.rs`, `screen_draw.rs`, `ui.rs` (widgets), `hud.rs`, `hud_layout.rs`, `hud_overlays.rs`, `chat.rs`, `tab_list.rs`; G: `startup_menu.rs`, `screens.rs` (pause, death), `options.rs`, `lan_screen.rs`, `chat.rs`, `sign_edit.rs`, `books.rs` |
| Multiplayer client | L: `net.rs` (network thread); G: `remote.rs` (`fn handle_packet`, `fn tick_remote`), `remote_*.rs` (mob data, objects, projectiles, vehicles, stations) |
| LAN host / server side | L: `lan/` (`conn.rs` handshake + login threads, `hub.rs` + `hub/` play state, `chunks.rs`, `entity.rs`, `tracking.rs`, `guest.rs`, `playerdata.rs`); G: `lan.rs` (`LanHost`), `lan_actions.rs` (`fn as_guest`, `fn tick_guests`), `lan_*.rs` per feature, `lan_entities.rs` (tracked entities) |
| Integrated server | G: `integrated.rs` (the server thread), `levels.rs` (one level per dimension, `fn tick_server`), `server_travel.rs` |
| Dedicated server | G: `dedicated.rs`, `dedicated/status.rs`; crates `horizon-server-files`, `horizon-server` |
-| Save and load | L: `save.rs` (level.dat, regions, playerdata), `entity_nbt.rs`, `block_entity_nbt.rs`, `options_file.rs`; G: `saving.rs`, `persist.rs` (entities); `crates/horizon-world/src/{region.rs,nbt.rs,datafix/}` |
+| Save and load | L: `save.rs` (level.dat, regions, playerdata), `entity_nbt.rs`, `options_file.rs`; `horizon-client-core/src/block_entity_nbt.rs`; G: `saving.rs`, `persist.rs` (entities); `crates/horizon-world/src/{region.rs,nbt.rs,datafix/}` |
| Input | game.rs `fn window_event`, `fn key_pressed`, `fn play_mouse`; L: `keybinds.rs`, `keymapping.rs`, `key_names.rs`, `mouse.rs`, `input.rs`, `interaction_input.rs`, `gamepad.rs`, `osk.rs`, `clipboard.rs`; G: `pad.rs`, `pad_menu.rs` |
| Audio | L: `audio.rs` (mixer), `sound_engine.rs`, `sound_events.rs`, `music.rs`, `ambience.rs`; G: `music.rs`, `subtitle_hud.rs` |
-| Resource packs | L: `packs.rs` + `packs/`, `pack_screen.rs`, `atlas_sources.rs`, `sprites.rs`, `mipmap.rs`, `model_library.rs`, `font.rs`, `lang.rs`; crate `horizon-assets`; G: `packs.rs` |
+| Resource packs | L: `packs.rs` + `packs/`, `pack_screen.rs`, `atlas_sources.rs`, `sprites.rs`, `mipmap.rs`, `model_library.rs`, `font.rs`; `horizon-client-core/src/lang.rs`; crate `horizon-assets`; G: `packs.rs` |
| Agent control | L: `control.rs` (socket), `bin/horizon-ctl/`; G: `control.rs`, `agent.rs`, `events.rs`, `ui_control.rs` ([docs/agent-control.md](docs/agent-control.md)) |
| Mods | crate `horizon-mods`; G: `mods.rs`; L: `mod_content.rs`, `mod_list.rs` |
| Horizon extras, settings | L: `extras.rs`, `graphics.rs`, `settings.rs`, `minimap.rs`; G: `extras.rs`, `tweaks.rs`, `options.rs` |
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 21951c083..03f3bd97b 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -4,8 +4,8 @@ Thanks for helping. Horizon is Minecraft: Java Edition 26.3 rewritten in Rust, a
everything is that **it plays exactly like vanilla**. This page is the short version of how we work; questions are
welcome on [Discord](https://discord.gg/HcTeMZxe5E).
-This repository holds the game, the launcher and the website, plus the tools, tests and docs that build, check and
-release them. Anything else (videos, Discord and other community material) lives elsewhere.
+This repository holds the game and the launcher, plus the tools, tests and docs that build, check and release them.
+The website (playhorizon.dev) is built in a separate repository from this one's README, `docs/api/` and roadmap. Anything else (videos, Discord and other community material) lives elsewhere.
**Where to start: [playhorizon.dev/hub](https://playhorizon.dev/hub).** It shows what is being done now and next
([ROADMAP.md](ROADMAP.md) in the repository), the work board, good first tasks, and the forms to report a bug or
diff --git a/Cargo.lock b/Cargo.lock
index 0e93bba0e..0e0a39038 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -216,6 +216,13 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+[[package]]
+name = "beacons"
+version = "0.1.0"
+dependencies = [
+ "horizon-mod-sdk",
+]
+
[[package]]
name = "bit-set"
version = "0.10.0"
@@ -1365,9 +1372,12 @@ dependencies = [
"glam",
"horizon-assets",
"horizon-bench",
+ "horizon-client-core",
+ "horizon-command",
"horizon-core",
"horizon-dualsense",
"horizon-friends",
+ "horizon-hdr",
"horizon-mods",
"horizon-protocol",
"horizon-server-files",
@@ -1395,6 +1405,23 @@ dependencies = [
"zip",
]
+[[package]]
+name = "horizon-client-core"
+version = "0.1.0"
+dependencies = [
+ "horizon-world",
+ "serde_json",
+]
+
+[[package]]
+name = "horizon-command"
+version = "0.1.0"
+dependencies = [
+ "horizon-client-core",
+ "horizon-protocol",
+ "horizon-world",
+]
+
[[package]]
name = "horizon-core"
version = "0.1.0"
@@ -1426,6 +1453,14 @@ dependencies = [
"spake2",
]
+[[package]]
+name = "horizon-hdr"
+version = "0.1.0"
+dependencies = [
+ "ash",
+ "wgpu",
+]
+
[[package]]
name = "horizon-mod-sdk"
version = "0.1.0"
@@ -2962,6 +2997,13 @@ dependencies = [
"objc2-quartz-core 0.3.2",
]
+[[package]]
+name = "recipes"
+version = "1.0.0"
+dependencies = [
+ "horizon-mod-sdk",
+]
+
[[package]]
name = "redox_syscall"
version = "0.4.1"
diff --git a/Cargo.toml b/Cargo.toml
index e4628f962..933901dce 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,45 @@
[workspace]
exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"]
-members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask"]
+members = [
+ "crates/horizon-core",
+ "crates/horizon-dualsense",
+ "crates/horizon-threads",
+ "crates/horizon-hdr",
+ "crates/horizon-world",
+ "crates/horizon-client",
+ "crates/horizon-client-core",
+ "crates/horizon-command",
+ "crates/horizon-server-files",
+ "crates/horizon-server",
+ "crates/horizon-bots",
+ "crates/horizon-assets",
+ "crates/horizon-protocol",
+ "crates/horizon-theme",
+ "crates/horizon-prepare",
+ "crates/horizon-telemetry",
+ "crates/horizon-bench",
+ "crates/horizon-friends",
+ "crates/horizon-relay",
+ "crates/horizon-mod-sdk",
+ "crates/horizon-mods",
+ "crates/horizon-mods/tests/guest",
+ "crates/horizon-mods/tests/ui_guest",
+ "crates/cargo-horizon-mod",
+ "crates/horizon-port-pack",
+ "crates/horizon-shaders",
+ "crates/horizon-shader-api",
+ "crates/horizon-release-sign",
+ "crates/horizon-mod-sdk/examples/coords-hud",
+ "crates/horizon-mod-sdk/examples/predator-missile",
+ "crates/horizon-mod-sdk/examples/welcome",
+ "crates/horizon-mod-sdk/examples/beacons",
+ "mods/official/fps-overlay",
+ "mods/official/keystrokes",
+ "mods/official/minimap",
+ "mods/official/zoom",
+ "xtask",
+ "mods/official/recipes",
+]
resolver = "2"
[workspace.package]
diff --git a/ROADMAP.md b/ROADMAP.md
index a04eca2ce..9b82f4fac 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -134,7 +134,7 @@ Better tools for mod makers: a test runner that needs no game window, templates
`cargo horizon-mod test` runs a mod's test scripts against a fake game snapshot ([#1816](https://github.com/ludovic111/horizon/issues/1816)) and, for server mods, scripted server events ([#1837](https://github.com/ludovic111/horizon/issues/1837)); the content template and the guides are merged ([#1859](https://github.com/ludovic111/horizon/issues/1859), [#1810](https://github.com/ludovic111/horizon/issues/1810), [docs/api/stability.md](docs/api/stability.md)). Left: templates for hud, server and machine mods, typed wrappers in the SDK, a frozen 0.1 compatibility mod that every runtime must load, a CI check that fails when a stable reference entry is removed without a new major version, and the SDK on crates.io once the API is stable.
-More: [website/docs/test-a-mod.md](website/docs/test-a-mod.md)
+More: [https://playhorizon.dev/docs/test-a-mod](https://playhorizon.dev/docs/test-a-mod)
@@ -160,6 +160,66 @@ Translatable components resolved through the selected language for items, contai
+#### Cooldowns drawn on items
+
+After you throw an ender pearl, its slot should show the cooldown sweeping away, as in vanilla.
+
+Technical
+
+Vanilla draws `ItemCooldowns`' percent as a white overlay over the slot (`GuiGraphicsExtractor.itemDecorations` and `itemCooldown`) in the hotbar and in inventories. Issue [#1763](https://github.com/ludovic111/horizon/issues/1763).
+
+More: [#1933](https://github.com/ludovic111/horizon/issues/1933)
+
+
+
+#### Chat settings and team prefixes
+
+The Hidden and Commands Only chat settings should hide chat, and team prefixes should appear before names in chat.
+
+Technical
+
+Vanilla checks `ChatVisiblity` before it delivers chat and system messages ([#1376](https://github.com/ludovic111/horizon/issues/1376)), and chat uses the team-formatted display name ([#1378](https://github.com/ludovic111/horizon/issues/1378)). Both issues have exact steps to reproduce.
+
+More: [#1932](https://github.com/ludovic111/horizon/issues/1932) · [#1841](https://github.com/ludovic111/horizon/issues/1841)
+
+
+
+#### A pointing hand over buttons
+
+The mouse pointer should turn into a pointing hand over menu buttons, as in vanilla 26.3.
+
+Technical
+
+26.3's `AbstractWidget` asks for a cursor from `CursorTypes` when it is hovered; winit's `CursorIcon::Pointer` gives the same shape. Issue [#1347](https://github.com/ludovic111/horizon/issues/1347).
+
+More: [#1897](https://github.com/ludovic111/horizon/issues/1897)
+
+
+
+#### Ctrl+Backspace and scroll bars in menus
+
+Ctrl+Backspace should delete a whole word in the creative search, and every list's scroll bar should be draggable.
+
+Technical
+
+`EditBox` deletes by word with Ctrl ([#1764](https://github.com/ludovic111/horizon/issues/1764)); the Game Rules and Statistics lists' scroll bars can't be dragged ([#1782](https://github.com/ludovic111/horizon/issues/1782), after [#978](https://github.com/ludovic111/horizon/issues/978)).
+
+More: [#1884](https://github.com/ludovic111/horizon/issues/1884) · [#1931](https://github.com/ludovic111/horizon/issues/1931)
+
+
+
+#### Chickens flap while they fall
+
+Chickens should flap their wings while they fall, not stand still in the air.
+
+Technical
+
+Vanilla's `Chicken.aiStep` updates `flap` and `flapSpeed` when the chicken isn't on the ground, and the model's wings follow them. Issue [#1706](https://github.com/ludovic111/horizon/issues/1706).
+
+More: [#1892](https://github.com/ludovic111/horizon/issues/1892)
+
+
+
### Rendering
#### Shader packs, written again from scratch
@@ -250,7 +310,7 @@ Horizon should run well on small machines: integrated graphics, the Steam Deck,
Partly done: an opt-in 60 FPS cap with fewer workers on battery, Far Detail Reduced for integrated GPUs and animated textures on the GPU (both shipped). Left: measured targets and fixes per class of machine (memory use, worker counts, startup) on a Steam Deck, old Intel and Apple Silicon Macs and 8 GB computers, reported on the Benchmarks page.
-More: [docs/benchmark.md](docs/benchmark.md) · [website/docs/performance.md](website/docs/performance.md)
+More: [docs/benchmark.md](docs/benchmark.md) · [https://playhorizon.dev/docs/performance](https://playhorizon.dev/docs/performance)
@@ -540,7 +600,9 @@ You can port a mod to Horizon with your own AI agent on your own computer. Horiz
Technical
-A player runs their own agent locally with `horizon-ctl` and the MCP servers ([docs/agent-control.md](docs/agent-control.md)), `cargo horizon-mod`, `horizon-port-pack` and the parity harnesses as the check. Horizon writes the guide ([website/docs/agents.md](website/docs/agents.md), [docs/modpacks.md](docs/modpacks.md)) and runs no agents, accounts or keys for players. The No AI switch turns all of it off.
+A player runs their own agent locally with `horizon-ctl` and the MCP servers ([docs/agent-control.md](docs/agent-control.md)), `cargo horizon-mod`, `horizon-port-pack` and the parity harnesses as the check. Horizon writes the guide (playhorizon.dev/docs/agents, [docs/modpacks.md](docs/modpacks.md)) and runs no agents, accounts or keys for players. The No AI switch turns all of it off.
+
+More: [https://playhorizon.dev/docs/agents](https://playhorizon.dev/docs/agents)
@@ -876,7 +938,9 @@ Run Horizon's built-in benchmark and share the report: every new computer makes
Technical
-`horizon-launcher play --arg=--benchmark --arg=standard` writes a JSON report; `horizon-launcher data benchmark ` shows what would be sent and uploads it ([website/docs/performance.md](website/docs/performance.md)). Results from three installs with the same hardware appear on the Benchmarks page. Example: [#1711](https://github.com/ludovic111/horizon/issues/1711).
+`horizon-launcher play --arg=--benchmark --arg=standard` writes a JSON report; `horizon-launcher data benchmark ` shows what would be sent and uploads it (playhorizon.dev/docs/performance). Results from three installs with the same hardware appear on the Benchmarks page. Example: [#1711](https://github.com/ludovic111/horizon/issues/1711).
+
+More: [https://playhorizon.dev/docs/performance](https://playhorizon.dev/docs/performance)
@@ -902,56 +966,6 @@ Armour and tools in End city chests should come enchanted, as in vanilla.
-#### Cooldowns drawn on items
-
-After you throw an ender pearl, its slot should show the cooldown sweeping away, as in vanilla.
-
-Technical
-
-Vanilla draws `ItemCooldowns`' percent as a white overlay over the slot (`GuiGraphicsExtractor.itemDecorations` and `itemCooldown`) in the hotbar and in inventories. Issue [#1763](https://github.com/ludovic111/horizon/issues/1763).
-
-
-
-#### Chat settings and team prefixes
-
-The Hidden and Commands Only chat settings should hide chat, and team prefixes should appear before names in chat.
-
-Technical
-
-Vanilla checks `ChatVisiblity` before it delivers chat and system messages ([#1376](https://github.com/ludovic111/horizon/issues/1376)), and chat uses the team-formatted display name ([#1378](https://github.com/ludovic111/horizon/issues/1378)). Both issues have exact steps to reproduce.
-
-
-
-#### A pointing hand over buttons
-
-The mouse pointer should turn into a pointing hand over menu buttons, as in vanilla 26.3.
-
-Technical
-
-26.3's `AbstractWidget` asks for a cursor from `CursorTypes` when it is hovered; winit's `CursorIcon::Pointer` gives the same shape. Issue [#1347](https://github.com/ludovic111/horizon/issues/1347).
-
-
-
-#### Ctrl+Backspace and scroll bars in menus
-
-Ctrl+Backspace should delete a whole word in the creative search, and every list's scroll bar should be draggable.
-
-Technical
-
-`EditBox` deletes by word with Ctrl ([#1764](https://github.com/ludovic111/horizon/issues/1764)); the Game Rules and Statistics lists' scroll bars can't be dragged ([#1782](https://github.com/ludovic111/horizon/issues/1782), after [#978](https://github.com/ludovic111/horizon/issues/978)).
-
-
-
-#### Chickens flap while they fall
-
-Chickens should flap their wings while they fall, not stand still in the air.
-
-Technical
-
-Vanilla's `Chicken.aiStep` updates `flap` and `flapSpeed` when the chicken isn't on the ground, and the model's wings follow them. Issue [#1706](https://github.com/ludovic111/horizon/issues/1706).
-
-
-
## Recently shipped
- **OpenGL for old computers** (v0.2.63): Horizon now starts on old PCs whose graphics card has no Vulkan or DirectX 12 driver: it switches to OpenGL by itself, and Options > Graphics can pick OpenGL by hand. [#1917](https://github.com/ludovic111/horizon/issues/1917) · [#1920](https://github.com/ludovic111/horizon/issues/1920) · [#1936](https://github.com/ludovic111/horizon/issues/1936)
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 63a1f7da3..e83ccd840 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -17,4 +17,5 @@ by The Pixelify Sans Project Authors, licensed under the SIL Open Font License 1
`crates/horizon-theme/icons/pixel/*.svg` are icons from
[Pixelarticons](https://github.com/halfmage/pixelarticons) by Gerrit Halfmann, under the MIT
-license (`crates/horizon-theme/icons/pixel/LICENSE-pixelarticons.txt`).
+license (`crates/horizon-theme/icons/pixel/LICENSE-pixelarticons.txt`). `star.svg` is Horizon's own, drawn on
+the same grid.
diff --git a/crates/cargo-horizon-mod/src/check.rs b/crates/cargo-horizon-mod/src/check.rs
index f42674da8..988ba826d 100644
--- a/crates/cargo-horizon-mod/src/check.rs
+++ b/crates/cargo-horizon-mod/src/check.rs
@@ -200,7 +200,7 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> {
return Err(format!("it didn't start: {reason}"));
}
let client: Vec = mods.commands().map(str::to_owned).collect();
- let server: Vec = mods.server_commands().map(str::to_owned).collect();
+ let server: Vec = mods.server_commands().map(|c| c.name.clone()).collect();
report.commands = [client.clone(), server.clone()].concat();
// A server mod plays with one player on, who joins, chats and leaves.
let steve = ServerPlayer {
@@ -262,9 +262,21 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> {
format!("{}: {text}", if error { "error" } else { "feedback" })
}
Output::Command { line } => format!("command: /{line}"),
+ Output::QuietCommands { lines, .. } => {
+ format!("{} quiet command(s)", lines.len())
+ }
Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")),
+ Output::SetBlocks {
+ dimension, blocks, ..
+ } => {
+ format!("set {} block(s) in {dimension}", blocks.len())
+ }
Output::OpenScreen { .. } => "opened a screen".to_string(),
Output::CloseScreen { .. } => "closed its screen".to_string(),
+ Output::PlaceRecipe { book_id, all } => {
+ format!("placed recipe {book_id}{}", if all { " (all)" } else { "" })
+ }
+ Output::Give { item, count, .. } => format!("gave {count} {item}"),
Output::Shake { strength, seconds } => {
format!("shook the camera: {strength:.2} for {seconds:.1} s")
}
diff --git a/crates/horizon-assets/src/item_model.rs b/crates/horizon-assets/src/item_model.rs
index 5999805eb..d567bc6ac 100644
--- a/crates/horizon-assets/src/item_model.rs
+++ b/crates/horizon-assets/src/item_model.rs
@@ -1031,19 +1031,22 @@ pub struct ItemModels {
}
impl ItemModels {
- pub fn components(&self, stack: &StackView) -> Components {
- let mut out = self
- .prototypes
- .get(&stack.item)
- .cloned()
- .unwrap_or_default();
+ /// The stack's components: its item's defaults with the stack's patch on top. A stack
+ /// with no patch (most stacks a screen draws) borrows the defaults instead of copying them.
+ pub fn components(&self, stack: &StackView) -> std::borrow::Cow<'_, Components> {
+ static NONE: Components = BTreeMap::new();
+ let prototype = self.prototypes.get(&stack.item).unwrap_or(&NONE);
+ if stack.patch.is_empty() {
+ return std::borrow::Cow::Borrowed(prototype);
+ }
+ let mut out = prototype.clone();
for (key, value) in &stack.patch {
match value {
Some(v) => out.insert(key.clone(), v.clone()),
None => out.remove(key),
};
}
- out
+ std::borrow::Cow::Owned(out)
}
/// `ItemModelResolver.updateForTopItem`.
pub fn resolve(&self, stack: &StackView, ctx: &Context, env: &dyn ItemEnv) -> ResolvedItem {
diff --git a/crates/horizon-client-core/Cargo.toml b/crates/horizon-client-core/Cargo.toml
new file mode 100644
index 000000000..8809a5216
--- /dev/null
+++ b/crates/horizon-client-core/Cargo.toml
@@ -0,0 +1,14 @@
+[package]
+name = "horizon-client-core"
+version = "0.1.0"
+edition.workspace = true
+license.workspace = true
+rust-version = "1.90"
+description = "The client's lowest layer: chat text and translations, SNBT and NBT paths, the scoreboard, boss bars, game rules and the registry and particle tables commands name"
+
+[dependencies]
+horizon-world = { path = "../horizon-world" }
+serde_json = { version = "1.0.151", features = ["raw_value"] }
+
+[lints]
+workspace = true
diff --git a/crates/horizon-client/src/block_entity_nbt.rs b/crates/horizon-client-core/src/block_entity_nbt.rs
similarity index 97%
rename from crates/horizon-client/src/block_entity_nbt.rs
rename to crates/horizon-client-core/src/block_entity_nbt.rs
index 54d230eb4..6e214fd61 100644
--- a/crates/horizon-client/src/block_entity_nbt.rs
+++ b/crates/horizon-client-core/src/block_entity_nbt.rs
@@ -259,7 +259,7 @@ fn is_pos(tag: &Tag) -> bool {
matches!(tag, Tag::IntArray(v) if v.len() == 3)
}
/// The loaded `SignText` of one side, or the empty text.
-pub(crate) fn sign_side(tag: Option<&Tag>) -> Tag {
+pub fn sign_side(tag: Option<&Tag>) -> Tag {
let empty = || string("");
let mut messages: Vec = match tag.and_then(|t| t.get("messages")) {
Some(Tag::List(list)) => list.iter().filter_map(component).collect(),
@@ -664,7 +664,9 @@ pub fn canonical(tag: &Tag) -> Option {
}
"minecraft:trial_spawner" => {
// `TrialSpawnerStateData.Packed` and `FullConfig`: every key is optional
- // and defaulted by vanilla; they are kept as loaded.
+ // and defaulted by vanilla; they are kept as loaded. No `spawn_data` is
+ // added: an absent one loads as Optional.empty and is not stored, and
+ // an empty entity would keep the spawner from ever picking a mob.
if let Tag::Compound(c) = tag {
for (k, v) in c {
let key = k.to_string_lossy();
@@ -676,12 +678,6 @@ pub fn canonical(tag: &Tag) -> Option {
}
}
}
- if !f.out.contains_key(&"spawn_data".into()) {
- f.put(
- "spawn_data",
- Tag::compound([("entity", Tag::Compound(Compound::new()))]),
- );
- }
}
"minecraft:vault" => {
// `VaultConfig.DEFAULT` (when the config is absent): the trial key and the
@@ -827,6 +823,21 @@ mod tests {
canonical(&snbt(s)).expect("known type")
}
+ #[test]
+ fn a_trial_spawner_without_spawn_data_saves_none() {
+ let fresh = canon(
+ r#"{id:"minecraft:trial_spawner",x:1,y:2,z:3,normal_config:"minecraft:trial_chamber/ranged/skeleton/normal"}"#,
+ );
+ assert_eq!(fresh.get("spawn_data"), None);
+ let picked = canon(
+ r#"{id:"minecraft:trial_spawner",x:1,y:2,z:3,spawn_data:{entity:{id:"minecraft:skeleton"}}}"#,
+ );
+ assert_eq!(
+ picked.get("spawn_data"),
+ Some(&snbt(r#"{entity:{id:"minecraft:skeleton"}}"#))
+ );
+ }
+
#[test]
fn every_type_has_defaults() {
for id in TYPES.iter().chain(NEWEST.iter()) {
diff --git a/crates/horizon-client/src/bossbar.rs b/crates/horizon-client-core/src/bossbar.rs
similarity index 100%
rename from crates/horizon-client/src/bossbar.rs
rename to crates/horizon-client-core/src/bossbar.rs
diff --git a/crates/horizon-client/src/component.rs b/crates/horizon-client-core/src/component.rs
similarity index 99%
rename from crates/horizon-client/src/component.rs
rename to crates/horizon-client-core/src/component.rs
index fced49898..5b828b305 100644
--- a/crates/horizon-client/src/component.rs
+++ b/crates/horizon-client-core/src/component.rs
@@ -252,7 +252,7 @@ pub fn to_text_with(
} else if let Some(sel) = o.get("selector").and_then(Value::as_str) {
resolve(sel)
} else if let Some(key) = o.get("keybind").and_then(Value::as_str) {
- crate::keybinds::display_name(key)
+ crate::key_display::display_name(key)
} else {
Text::empty()
};
diff --git a/crates/horizon-client/src/fastutil_order.rs b/crates/horizon-client-core/src/fastutil_order.rs
similarity index 100%
rename from crates/horizon-client/src/fastutil_order.rs
rename to crates/horizon-client-core/src/fastutil_order.rs
diff --git a/crates/horizon-client/src/gamerules.rs b/crates/horizon-client-core/src/gamerules.rs
similarity index 90%
rename from crates/horizon-client/src/gamerules.rs
rename to crates/horizon-client-core/src/gamerules.rs
index 7198fd202..6715e01ec 100644
--- a/crates/horizon-client/src/gamerules.rs
+++ b/crates/horizon-client-core/src/gamerules.rs
@@ -292,27 +292,4 @@ mod tests {
assert_eq!(GameRules::load(&dir), rules);
let _ = fs::remove_dir_all(dir);
}
- /// The world's save (Level.write) writes the rules as they are now, and a
- /// world opened again reads them back (#74).
- #[test]
- fn level_save_keeps_changed_rules() {
- let dir =
- std::env::temp_dir().join(format!("horizon-gamerules-level-{}", std::process::id()));
- let _ = fs::remove_dir_all(&dir);
- let mut level = crate::save::Level::default();
- level.write(&dir).unwrap();
- // Rules changed while playing, then saved and loaded again.
- let mut rules = GameRules::load(&dir);
- assert_eq!(rules, GameRules::default());
- assert!(rules.set("advance_time", Value::Bool(false)));
- assert!(rules.set("advance_weather", Value::Bool(false)));
- assert!(rules.set("random_tick_speed", Value::Int(0)));
- level.game_rules = rules.by_name();
- level.write(&dir).unwrap();
- assert_eq!(GameRules::load(&dir), rules);
- let read = crate::save::Level::read(&dir).unwrap();
- assert_eq!(read.game_rules, rules.by_name());
- assert_eq!(read.game_rule("advance_time"), 0);
- let _ = fs::remove_dir_all(dir);
- }
}
diff --git a/crates/horizon-client-core/src/identifier.rs b/crates/horizon-client-core/src/identifier.rs
new file mode 100644
index 000000000..1e76f7731
--- /dev/null
+++ b/crates/horizon-client-core/src/identifier.rs
@@ -0,0 +1,18 @@
+//! Resource identifiers (`Identifier`).
+
+/// Identifier.parse: `ns:path` or `path`, validated.
+pub fn parse_identifier(raw: &str) -> Option {
+ let (ns, path) = match raw.split_once(':') {
+ Some(("", path)) => ("minecraft", path),
+ Some((ns, path)) => (ns, path),
+ None => ("minecraft", raw),
+ };
+ let ns_ok = ns != ".."
+ && ns
+ .chars()
+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-'));
+ let path_ok = path.chars().all(|c| {
+ c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/')
+ });
+ (ns_ok && path_ok).then(|| format!("{ns}:{path}"))
+}
diff --git a/crates/horizon-client-core/src/key_display.rs b/crates/horizon-client-core/src/key_display.rs
new file mode 100644
index 000000000..fc57c97bd
--- /dev/null
+++ b/crates/horizon-client-core/src/key_display.rs
@@ -0,0 +1,38 @@
+//! Key display names (`InputConstants.Key.getDisplayName`), shared by key
+//! mappings and `keybind` text components.
+use crate::text::Text;
+
+/// InputConstants.Key.getDisplayName: one-character keys as the upper-case
+/// character, others by translation.
+pub fn display_name(key: &str) -> Text {
+ if let Some(rest) = key.strip_prefix("key.keyboard.")
+ && rest.chars().count() == 1
+ {
+ let c = rest.to_uppercase();
+ return Text::literal(c);
+ }
+ let symbol = match key {
+ "key.keyboard.minus" => Some("-"),
+ "key.keyboard.equal" => Some("="),
+ "key.keyboard.left.bracket" => Some("["),
+ "key.keyboard.right.bracket" => Some("]"),
+ "key.keyboard.backslash" => Some("\\"),
+ "key.keyboard.semicolon" => Some(";"),
+ "key.keyboard.apostrophe" => Some("'"),
+ "key.keyboard.grave.accent" => Some("`"),
+ "key.keyboard.comma" => Some(","),
+ "key.keyboard.period" => Some("."),
+ "key.keyboard.slash" => Some("/"),
+ _ => None,
+ };
+ if let Some(s) = symbol {
+ return Text::literal(s);
+ }
+ if let Some(n) = key.strip_prefix("key.mouse.")
+ && n.parse::().is_ok()
+ && !crate::lang::has(key)
+ {
+ return Text::translate("key.mouse", &[Text::literal(n)]);
+ }
+ Text::translate(key, &[])
+}
diff --git a/crates/horizon-client/src/lang.rs b/crates/horizon-client-core/src/lang.rs
similarity index 96%
rename from crates/horizon-client/src/lang.rs
rename to crates/horizon-client-core/src/lang.rs
index cb96cc373..6213cedc8 100644
--- a/crates/horizon-client/src/lang.rs
+++ b/crates/horizon-client-core/src/lang.rs
@@ -42,8 +42,12 @@ struct Bundled;
impl ResourceSource for Bundled {
fn read(&self, path: &str) -> Option> {
let body = match path {
- "assets/horizon/lang/en_us.json" => include_str!("../assets/horizon/lang/en_us.json"),
- "assets/horizon/lang/ru_ru.json" => include_str!("../assets/horizon/lang/ru_ru.json"),
+ "assets/horizon/lang/en_us.json" => {
+ include_str!("../../horizon-client/assets/horizon/lang/en_us.json")
+ }
+ "assets/horizon/lang/ru_ru.json" => {
+ include_str!("../../horizon-client/assets/horizon/lang/ru_ru.json")
+ }
_ => return None,
};
Some(body.as_bytes().to_vec())
diff --git a/crates/horizon-client-core/src/lib.rs b/crates/horizon-client-core/src/lib.rs
new file mode 100644
index 000000000..ca40141d1
--- /dev/null
+++ b/crates/horizon-client-core/src/lib.rs
@@ -0,0 +1,23 @@
+//! The client's lowest layer, below commands and gameplay: chat text and
+//! translations, SNBT and NBT paths, text components, the scoreboard, boss
+//! bars, game rules, block entity NBT tables, and the registry, particle and
+//! sound source tables commands name. horizon-client re-exports each module
+//! under its old path (`horizon_client::text`, ...).
+#![forbid(unsafe_code)]
+pub mod block_entity_nbt;
+pub mod bossbar;
+pub mod component;
+pub mod fastutil_order;
+pub mod gamerules;
+pub mod identifier;
+pub mod key_display;
+pub mod lang;
+pub mod nbt_path;
+pub mod particle_type;
+pub mod registries;
+pub mod scoreboard;
+pub mod snbt;
+pub mod sound_source;
+pub mod text;
+pub mod uuid;
+pub type Result = std::result::Result>;
diff --git a/crates/horizon-client/src/nbt_path.rs b/crates/horizon-client-core/src/nbt_path.rs
similarity index 100%
rename from crates/horizon-client/src/nbt_path.rs
rename to crates/horizon-client-core/src/nbt_path.rs
diff --git a/crates/horizon-client-core/src/particle_type.rs b/crates/horizon-client-core/src/particle_type.rs
new file mode 100644
index 000000000..98de2380b
--- /dev/null
+++ b/crates/horizon-client-core/src/particle_type.rs
@@ -0,0 +1,209 @@
+//! Particle types (`ParticleTypes`): the vanilla particle types with a client
+//! implementation, by registry name, and their per-type flags.
+
+macro_rules! particle_types {
+ ($($variant:ident = $name:literal),* $(,)?) => {
+ /// Vanilla particle types with a client implementation here.
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+ pub enum ParticleType { $($variant),* }
+ impl ParticleType {
+ pub const ALL: &'static [ParticleType] = &[$(ParticleType::$variant),*];
+ /// Registry path (`minecraft:`), also the sprite-set file name.
+ pub fn name(self) -> &'static str {
+ match self { $(ParticleType::$variant => $name),* }
+ }
+ pub fn from_name(name: &str) -> Option {
+ let name = name.strip_prefix("minecraft:").unwrap_or(name);
+ match name { $($name => Some(ParticleType::$variant),)* _ => None }
+ }
+ }
+ };
+}
+particle_types! {
+ Block = "block",
+ BlockCrumble = "block_crumble",
+ Trail = "trail",
+ DustPillar = "dust_pillar",
+ FallingDust = "falling_dust",
+ Smoke = "smoke",
+ LargeSmoke = "large_smoke",
+ WhiteSmoke = "white_smoke",
+ Flame = "flame",
+ SoulFireFlame = "soul_fire_flame",
+ CopperFireFlame = "copper_fire_flame",
+ SmallFlame = "small_flame",
+ Lava = "lava",
+ DrippingWater = "dripping_water",
+ FallingWater = "falling_water",
+ DrippingLava = "dripping_lava",
+ FallingLava = "falling_lava",
+ LandingLava = "landing_lava",
+ DrippingHoney = "dripping_honey",
+ FallingHoney = "falling_honey",
+ LandingHoney = "landing_honey",
+ FallingNectar = "falling_nectar",
+ FallingSporeBlossom = "falling_spore_blossom",
+ SporeBlossomAir = "spore_blossom_air",
+ DrippingObsidianTear = "dripping_obsidian_tear",
+ FallingObsidianTear = "falling_obsidian_tear",
+ LandingObsidianTear = "landing_obsidian_tear",
+ DrippingDripstoneWater = "dripping_dripstone_water",
+ FallingDripstoneWater = "falling_dripstone_water",
+ DrippingDripstoneLava = "dripping_dripstone_lava",
+ FallingDripstoneLava = "falling_dripstone_lava",
+ Splash = "splash",
+ Rain = "rain",
+ Bubble = "bubble",
+ SulfurBubbles = "sulfur_bubbles",
+ BubblePop = "bubble_pop",
+ BubbleColumnUp = "bubble_column_up",
+ CurrentDown = "current_down",
+ Underwater = "underwater",
+ Portal = "portal",
+ ReversePortal = "reverse_portal",
+ Enchant = "enchant",
+ Nautilus = "nautilus",
+ VaultConnection = "vault_connection",
+ Crit = "crit",
+ EnchantedHit = "enchanted_hit",
+ DamageIndicator = "damage_indicator",
+ Heart = "heart",
+ AngryVillager = "angry_villager",
+ HappyVillager = "happy_villager",
+ Composter = "composter",
+ Mycelium = "mycelium",
+ Dolphin = "dolphin",
+ EggCrack = "egg_crack",
+ Poof = "poof",
+ Explosion = "explosion",
+ ExplosionEmitter = "explosion_emitter",
+ CampfireCosySmoke = "campfire_cosy_smoke",
+ CampfireSignalSmoke = "campfire_signal_smoke",
+ Note = "note",
+ Dust = "dust",
+ TotemOfUndying = "totem_of_undying",
+ Firework = "firework",
+ EndRod = "end_rod",
+ Ash = "ash",
+ WhiteAsh = "white_ash",
+ CrimsonSpore = "crimson_spore",
+ WarpedSpore = "warped_spore",
+ CherryLeaves = "cherry_leaves",
+ PaleOakLeaves = "pale_oak_leaves",
+ TintedLeaves = "tinted_leaves",
+ Effect = "effect",
+ InstantEffect = "instant_effect",
+ EntityEffect = "entity_effect",
+ Witch = "witch",
+ Infested = "infested",
+ Cloud = "cloud",
+ Sneeze = "sneeze",
+ Snowflake = "snowflake",
+ Soul = "soul",
+ SculkSoul = "sculk_soul",
+ DragonBreath = "dragon_breath",
+ Gust = "gust",
+ SmallGust = "small_gust",
+ GustEmitterLarge = "gust_emitter_large",
+ GustEmitterSmall = "gust_emitter_small",
+ DustColorTransition = "dust_color_transition",
+ SculkCharge = "sculk_charge",
+ SculkChargePop = "sculk_charge_pop",
+ Shriek = "shriek",
+ SonicBoom = "sonic_boom",
+ Vibration = "vibration",
+ SweepAttack = "sweep_attack",
+ Glow = "glow",
+ WaxOn = "wax_on",
+ WaxOff = "wax_off",
+ ElectricSpark = "electric_spark",
+ Scrape = "scrape",
+ SquidInk = "squid_ink",
+ GlowSquidInk = "glow_squid_ink",
+ Item = "item",
+ ItemSlime = "item_slime",
+ ItemSnowball = "item_snowball",
+ ItemCobweb = "item_cobweb",
+ SulfurCubeGoo = "sulfur_cube_goo",
+ Flash = "flash",
+ Firefly = "firefly",
+ TrialSpawnerDetection = "trial_spawner_detection",
+ TrialSpawnerDetectionOminous = "trial_spawner_detection_ominous",
+ TrialOmen = "trial_omen",
+ RaidOmen = "raid_omen",
+ OminousSpawning = "ominous_spawning",
+ Spit = "spit",
+ Fishing = "fishing",
+ DustPlume = "dust_plume",
+ RedPoplarLeaves = "red_poplar_leaves",
+ OrangePoplarLeaves = "orange_poplar_leaves",
+ YellowPoplarLeaves = "yellow_poplar_leaves",
+ PauseMobGrowth = "pause_mob_growth",
+ ResetMobGrowth = "reset_mob_growth",
+ BlockMarker = "block_marker",
+}
+impl ParticleType {
+ /// `ParticleType.getOverrideLimiter` (`ParticleTypes.register(name, true)`):
+ /// spawned regardless of distance.
+ pub fn override_limiter(self) -> bool {
+ matches!(
+ self,
+ Self::BlockMarker
+ | Self::DamageIndicator
+ | Self::ExplosionEmitter
+ | Self::Explosion
+ | Self::Gust
+ | Self::GustEmitterLarge
+ | Self::GustEmitterSmall
+ | Self::SonicBoom
+ | Self::SculkCharge
+ | Self::SculkChargePop
+ | Self::Vibration
+ | Self::Poof
+ | Self::Spit
+ | Self::SquidInk
+ | Self::SweepAttack
+ | Self::CampfireCosySmoke
+ | Self::CampfireSignalSmoke
+ | Self::GlowSquidInk
+ | Self::Glow
+ | Self::WaxOn
+ | Self::WaxOff
+ | Self::ElectricSpark
+ | Self::Scrape
+ | Self::TrialSpawnerDetection
+ | Self::TrialSpawnerDetectionOminous
+ | Self::VaultConnection
+ | Self::OminousSpawning
+ )
+ }
+ /// `SingleQuadParticle.Layer.translucent`: types whose vanilla particle class
+ /// hardcodes the translucent layer, drawn after translucent terrain.
+ /// `TerrainParticle`, `BreakingItemParticle` and `BlockMarker` resolve their
+ /// layer from the sprite instead (`Layer.bySprite`); see the `translucent`
+ /// sprite set on the engine.
+ pub fn translucent_layer(self) -> bool {
+ match self {
+ // CampfireSmokeParticle.
+ Self::CampfireCosySmoke | Self::CampfireSignalSmoke
+ // PlayerCloudParticle.
+ | Self::Cloud | Self::Sneeze
+ // SpellParticle.
+ | Self::Effect | Self::InstantEffect | Self::EntityEffect
+ | Self::Witch | Self::Infested | Self::TrialOmen | Self::RaidOmen
+ // EmissiveRisingParticle.
+ | Self::Soul | Self::SculkSoul
+ // SculkChargeParticle, SculkChargePopParticle, ShriekParticle,
+ // VibrationSignalParticle, FireflyParticle, OverlayParticle.
+ | Self::SculkCharge | Self::SculkChargePop | Self::Shriek
+ | Self::Vibration | Self::Firefly | Self::Flash
+ // SimpleAnimatedParticle and its subclasses: EndRodParticle,
+ // SparkParticle (firework), SquidInkParticle, TotemParticle.
+ | Self::EndRod | Self::Firework | Self::SquidInk | Self::GlowSquidInk
+ | Self::TotemOfUndying
+ // FlyTowardsPositionParticle: its LifetimeAlpha(0, 0.6, 0.25, 1) is not opaque.
+ | Self::VaultConnection => true,
+ _ => false,
+ }
+ }
+}
diff --git a/crates/horizon-client-core/src/registries.rs b/crates/horizon-client-core/src/registries.rs
new file mode 100644
index 000000000..310115cf8
--- /dev/null
+++ b/crates/horizon-client-core/src/registries.rs
@@ -0,0 +1,188 @@
+//! Registry contents and source state that commands validate and complete
+//! arguments against (what the server's registry access holds).
+use std::collections::BTreeMap;
+
+/// Registry contents and source state used to validate and complete arguments.
+#[derive(Clone, Debug, Default)]
+pub struct Registries {
+ /// Permission level of the command source.
+ pub permission: u8,
+ pub items: Vec,
+ pub item_tags: Vec,
+ /// Block id -> (property, allowed values).
+ pub blocks: BTreeMap)>>,
+ pub block_tags: Vec,
+ /// Entity types that `summon` can create.
+ pub summonable: Vec,
+ /// Every entity type (selector `type=`).
+ pub entity_types: Vec,
+ pub effects: Vec,
+ pub enchantments: Vec,
+ pub structures: Vec,
+ pub biomes: Vec,
+ pub dimensions: Vec,
+ pub clocks: Vec,
+ pub timelines: Vec,
+ pub time_markers: Vec,
+ pub advancements: Vec,
+ /// Game rule name -> integer-valued.
+ pub game_rules: Vec<(String, bool)>,
+ pub players: Vec,
+ /// Scoreboard objective names, team names and tracked score holders.
+ pub objectives: Vec,
+ pub teams: Vec,
+ pub tracked: Vec,
+ /// Loaded datapack functions (`ns:path`) and function tags (`ns:path`).
+ pub functions: Vec,
+ /// `/data ... storage` ids.
+ pub storages: Vec,
+ /// Boss bar ids and datapack predicate ids.
+ pub bossbars: Vec,
+ pub predicates: Vec,
+ pub item_modifiers: Vec,
+ pub schedules: Vec,
+ pub stopwatches: Vec,
+ pub recipes: Vec,
+ pub sounds: Vec,
+ pub damage_types: Vec,
+ pub attributes: Vec,
+ pub loot_tables: Vec,
+ pub templates: Vec,
+ pub random_sequences: Vec,
+ pub datapacks_enabled: Vec,
+ pub datapacks_disabled: Vec,
+ pub function_tags: Vec,
+ /// The block the source is looking at (relevant coordinates).
+ pub target_block: Option<[i32; 3]>,
+ /// Every registry's element and tag ids (`minecraft:item` -> ...), as
+ /// the server's registry access and reloadable registries hold them.
+ pub by_registry: BTreeMap,
+ /// Blocks whose default state has a block entity.
+ pub block_entities: std::collections::BTreeSet,
+ /// Block tag -> member blocks.
+ pub block_tag_members: BTreeMap>,
+ /// Data component types with a codec (not transient).
+ pub persistent_components: Vec,
+ /// Recipes `/recipe` can give (not special).
+ pub learnable_recipes: Vec,
+ /// Advancement id -> criterion names.
+ pub advancement_criteria: BTreeMap>,
+ /// World clock -> time markers shown in commands.
+ pub clock_time_markers: BTreeMap>,
+ /// Trigger objectives the source may use (`/trigger` suggestions).
+ pub trigger_objectives: Vec,
+ /// Objectives with the `trigger` criterion -> holder -> whether its score is locked.
+ pub trigger_scores: BTreeMap>,
+}
+/// The ids and tag ids of one registry.
+#[derive(Clone, Debug, Default)]
+pub struct RegistryIds {
+ pub ids: Vec,
+ pub tags: Vec,
+}
+const EMPTY: &[String] = &[];
+impl Registries {
+ /// Fill what the game did not build itself from vanilla's exported
+ /// registries (`command-registries.json`, written by
+ /// `VanillaCommandParseOracle registries`): built-in registries such as
+ /// mob effects, data component types and dialogs, block entities and tag
+ /// members. Registries that data packs reload stay with the game.
+ pub fn fill_from_export(&mut self, r: &serde_json::Value) {
+ fn strings(v: &serde_json::Value) -> Vec {
+ v.as_array()
+ .map(|a| {
+ a.iter()
+ .filter_map(|x| x.as_str().map(str::to_owned))
+ .collect()
+ })
+ .unwrap_or_default()
+ }
+ let fill = |field: &mut Vec, key: &str| {
+ if field.is_empty() {
+ *field = strings(&r[key]);
+ }
+ };
+ fill(&mut self.effects, "effects");
+ fill(&mut self.enchantments, "enchantments");
+ fill(&mut self.attributes, "attributes");
+ fill(&mut self.damage_types, "damage_types");
+ fill(&mut self.templates, "templates");
+ fill(&mut self.persistent_components, "persistent_components");
+ fill(&mut self.learnable_recipes, "learnable_recipes");
+ const RELOADED: [&str; 5] = [
+ "minecraft:advancement",
+ "minecraft:recipe",
+ "minecraft:loot_table",
+ "minecraft:predicate",
+ "minecraft:item_modifier",
+ ];
+ for (name, entry) in r["by_registry"].as_object().into_iter().flatten() {
+ if RELOADED.contains(&name.as_str()) || self.by_registry.contains_key(name) {
+ continue;
+ }
+ self.by_registry.insert(
+ name.clone(),
+ RegistryIds {
+ ids: strings(&entry["ids"]),
+ tags: strings(&entry["tags"]),
+ },
+ );
+ }
+ if self.block_entities.is_empty() {
+ self.block_entities = strings(&r["block_entities"]).into_iter().collect();
+ }
+ if self.block_tag_members.is_empty() {
+ for (tag, members) in r["block_tag_members"].as_object().into_iter().flatten() {
+ self.block_tag_members.insert(tag.clone(), strings(members));
+ }
+ }
+ if self.clock_time_markers.is_empty() {
+ for (clock, markers) in r["clock_time_markers"].as_object().into_iter().flatten() {
+ self.clock_time_markers
+ .insert(clock.clone(), strings(markers));
+ }
+ }
+ if self.advancement_criteria.is_empty() {
+ for (id, criteria) in r["advancement_criteria"].as_object().into_iter().flatten() {
+ self.advancement_criteria
+ .insert(id.clone(), strings(criteria));
+ }
+ }
+ }
+ /// The element ids of a registry (sorted).
+ pub fn ids(&self, registry: &str) -> &[String] {
+ if let Some(r) = self.by_registry.get(registry) {
+ return &r.ids;
+ }
+ match registry {
+ "minecraft:item" => &self.items,
+ "minecraft:entity_type" => &self.entity_types,
+ "minecraft:mob_effect" => &self.effects,
+ "minecraft:enchantment" => &self.enchantments,
+ "minecraft:worldgen/structure" => &self.structures,
+ "minecraft:worldgen/biome" => &self.biomes,
+ "minecraft:world_clock" => &self.clocks,
+ "minecraft:timeline" => &self.timelines,
+ "minecraft:attribute" => &self.attributes,
+ "minecraft:damage_type" => &self.damage_types,
+ "minecraft:sound_event" => &self.sounds,
+ "minecraft:predicate" => &self.predicates,
+ "minecraft:item_modifier" => &self.item_modifiers,
+ "minecraft:loot_table" => &self.loot_tables,
+ "minecraft:recipe" => &self.recipes,
+ "minecraft:advancement" => &self.advancements,
+ _ => EMPTY,
+ }
+ }
+ /// The tag ids of a registry (sorted).
+ pub fn tags(&self, registry: &str) -> &[String] {
+ if let Some(r) = self.by_registry.get(registry) {
+ return &r.tags;
+ }
+ match registry {
+ "minecraft:item" => &self.item_tags,
+ "minecraft:block" => &self.block_tags,
+ _ => EMPTY,
+ }
+ }
+}
diff --git a/crates/horizon-client/src/scoreboard.rs b/crates/horizon-client-core/src/scoreboard.rs
similarity index 99%
rename from crates/horizon-client/src/scoreboard.rs
rename to crates/horizon-client-core/src/scoreboard.rs
index 4796be51a..3e820e4eb 100644
--- a/crates/horizon-client/src/scoreboard.rs
+++ b/crates/horizon-client-core/src/scoreboard.rs
@@ -2,9 +2,9 @@
//! `ObjectiveCriteria`, `NumberFormat`) and its saved data
//! (`data/minecraft/scoreboard.dat`, `ScoreboardSaveData.Packed`).
use crate::{
- command::Registries,
component,
fastutil_order::{HashSetOrder, OpenOrder},
+ registries::Registries,
text::{self, Style, Text},
};
use horizon_world::nbt::Tag;
@@ -1266,7 +1266,7 @@ fn entity_uuids(tag: &mut Tag) {
})
.collect::>>(),
Tag::String(s) => {
- crate::save::uuid_from_text(&s.to_string_lossy()).map(Vec::from)
+ crate::uuid::uuid_from_text(&s.to_string_lossy()).map(Vec::from)
}
_ => None,
};
diff --git a/crates/horizon-client/src/snbt.rs b/crates/horizon-client-core/src/snbt.rs
similarity index 100%
rename from crates/horizon-client/src/snbt.rs
rename to crates/horizon-client-core/src/snbt.rs
diff --git a/crates/horizon-client-core/src/sound_source.rs b/crates/horizon-client-core/src/sound_source.rs
new file mode 100644
index 000000000..d181d6ac5
--- /dev/null
+++ b/crates/horizon-client-core/src/sound_source.rs
@@ -0,0 +1,7 @@
+//! Sound sources (`SoundSource`), by name.
+
+/// SoundSource names in vanilla order.
+pub const SOUND_SOURCES: [&str; 11] = [
+ "master", "music", "record", "weather", "block", "hostile", "neutral", "player", "ambient",
+ "voice", "ui",
+];
diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client-core/src/text.rs
similarity index 99%
rename from crates/horizon-client/src/text.rs
rename to crates/horizon-client-core/src/text.rs
index 4c04c9da5..0a2b6eadb 100644
--- a/crates/horizon-client/src/text.rs
+++ b/crates/horizon-client-core/src/text.rs
@@ -67,7 +67,7 @@ pub struct Style {
}
/// A style's `font` field: an identifier (`alt` is `minecraft:alt`).
pub fn font_id(v: &Value) -> Option {
- crate::command::args::parse_identifier(v.as_str()?)
+ crate::identifier::parse_identifier(v.as_str()?)
}
impl Style {
pub fn color(c: u32) -> Self {
diff --git a/crates/horizon-client-core/src/uuid.rs b/crates/horizon-client-core/src/uuid.rs
new file mode 100644
index 000000000..4ede9b141
--- /dev/null
+++ b/crates/horizon-client-core/src/uuid.rs
@@ -0,0 +1,24 @@
+//! UUIDs as vanilla's four-int form, to and from their text form.
+
+pub fn uuid_text(u: [i32; 4]) -> String {
+ let hex: String = u.iter().map(|v| format!("{:08x}", *v as u32)).collect();
+ format!(
+ "{}-{}-{}-{}-{}",
+ &hex[0..8],
+ &hex[8..12],
+ &hex[12..16],
+ &hex[16..20],
+ &hex[20..32]
+ )
+}
+pub fn uuid_from_text(s: &str) -> Option<[i32; 4]> {
+ let hex: String = s.chars().filter(|c| *c != '-').collect();
+ if hex.len() != 32 {
+ return None;
+ }
+ let mut out = [0i32; 4];
+ for (i, v) in out.iter_mut().enumerate() {
+ *v = u32::from_str_radix(&hex[i * 8..i * 8 + 8], 16).ok()? as i32;
+ }
+ Some(out)
+}
diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml
index d7c6d812b..5611edbc9 100644
--- a/crates/horizon-client/Cargo.toml
+++ b/crates/horizon-client/Cargo.toml
@@ -9,9 +9,12 @@ description = "Horizon native development client"
[dependencies]
horizon-assets = { path = "../horizon-assets" }
+horizon-client-core = { path = "../horizon-client-core" }
+horizon-command = { path = "../horizon-command" }
horizon-core = { path = "../horizon-core" }
# The server thread ahead of the workers (MinecraftServer.spin's Thread.setPriority).
horizon-threads = { path = "../horizon-threads" }
+horizon-hdr = { path = "../horizon-hdr" }
horizon-world = { path = "../horizon-world" }
horizon-protocol = { path = "../horizon-protocol" }
# server.properties, eula.txt and the user lists, shared with horizon-server.
diff --git a/crates/horizon-client/examples/probe/arrow_probe.rs b/crates/horizon-client/examples/probe/arrow_probe.rs
index f72e6276e..411561c4e 100644
--- a/crates/horizon-client/examples/probe/arrow_probe.rs
+++ b/crates/horizon-client/examples/probe/arrow_probe.rs
@@ -163,6 +163,8 @@ pub fn main() -> Result<()> {
ArrowSound::HitGround => "hit",
ArrowSound::Splash => "splash",
ArrowSound::Extinguish => "extinguish",
+ ArrowSound::TridentHitGround => "trident_hit_ground",
+ ArrowSound::TridentHit => "trident_hit",
},
volume.to_bits(),
pitch.to_bits()
diff --git a/crates/horizon-client/examples/probe/creative_mining_probe.rs b/crates/horizon-client/examples/probe/creative_mining_probe.rs
new file mode 100644
index 000000000..897e4bf81
--- /dev/null
+++ b/crates/horizon-client/examples/probe/creative_mining_probe.rs
@@ -0,0 +1,48 @@
+use horizon_client::{
+ Result,
+ item_data::StackData,
+ items::{ItemStack, Items},
+};
+use horizon_world::nbt::Tag;
+use serde_json::Value;
+use std::{
+ fs::File,
+ io::{BufRead, BufReader, BufWriter, Write},
+ path::Path,
+};
+
+pub fn main() -> Result<()> {
+ let args: Vec<_> = crate::args().collect();
+ let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
+ let items = Items::catalog(&root)?;
+ let mut out = BufWriter::new(File::create(&args[2])?);
+ for line in BufReader::new(File::open(&args[1])?).lines() {
+ let row: Value = serde_json::from_str(&line?)?;
+ let mut stack = ItemStack::new(
+ row["item"].as_str().unwrap(),
+ row["count"].as_u64().unwrap() as u32,
+ );
+ match row["tool"].as_str().unwrap() {
+ "default" => {}
+ mode => {
+ let mut data = StackData::default();
+ let tool = if mode == "implicit" {
+ Tag::compound([] as [(&str, Tag); 0])
+ } else {
+ Tag::compound([(
+ "can_destroy_blocks_in_creative",
+ Tag::Byte(i8::from(mode == "allow")),
+ )])
+ };
+ data.set_other("minecraft:tool", Some(tool));
+ stack.extra = Some(Box::new(data));
+ }
+ }
+ writeln!(
+ out,
+ "{}",
+ items.can_destroy_block(Some(&stack), row["creative"].as_bool().unwrap())
+ )?;
+ }
+ Ok(())
+}
diff --git a/crates/horizon-client/examples/probe/cushion_placement_probe.rs b/crates/horizon-client/examples/probe/cushion_placement_probe.rs
new file mode 100644
index 000000000..45fbdbd72
--- /dev/null
+++ b/crates/horizon-client/examples/probe/cushion_placement_probe.rs
@@ -0,0 +1,89 @@
+use horizon_client::{
+ Result,
+ cushion::{self, World},
+};
+use horizon_core::geometry::{Aabb, ShapeOp, Vec3, VoxelShape};
+use serde_json::Value;
+use std::{
+ collections::HashMap,
+ fs::File,
+ io::{BufRead, BufReader, BufWriter, Write},
+};
+
+struct Cell {
+ outline: VoxelShape,
+ collision: VoxelShape,
+ suffocating: bool,
+}
+struct Fixture(HashMap<[i32; 3], Cell>);
+impl World for Fixture {
+ fn outline_bounds(&self, p: [i32; 3]) -> Option {
+ self.0
+ .get(&p)?
+ .outline
+ .bounds()
+ .map(|b| b.move_by(Vec3::new(p[0] as f64, p[1] as f64, p[2] as f64)))
+ }
+ fn collision_shapes(&self, _: Aabb) -> Vec {
+ self.0
+ .iter()
+ .map(|(p, c)| {
+ c.collision
+ .moved(Vec3::new(p[0] as f64, p[1] as f64, p[2] as f64))
+ })
+ .collect()
+ }
+ fn suffocating(&self, p: [i32; 3]) -> bool {
+ self.0.get(&p).is_some_and(|c| c.suffocating)
+ }
+}
+fn shape(value: &Value) -> Result {
+ let mut shape = VoxelShape::empty();
+ for b in value.as_array().unwrap() {
+ let f = |i: usize| b[i].as_f64().unwrap();
+ shape = shape.join(
+ &VoxelShape::from_box(Aabb::new(
+ Vec3::new(f(0), f(1), f(2)),
+ Vec3::new(f(3), f(4), f(5)),
+ ))?,
+ ShapeOp::OR,
+ )?;
+ }
+ Ok(shape)
+}
+pub fn main() -> Result<()> {
+ let args: Vec<_> = crate::args().collect();
+ let mut out = BufWriter::new(File::create(&args[2])?);
+ for line in BufReader::new(File::open(&args[1])?).lines() {
+ let row: Value = serde_json::from_str(&line?)?;
+ let mut world = Fixture(HashMap::new());
+ for c in row["cells"].as_array().unwrap() {
+ let p = std::array::from_fn(|i| c[i].as_i64().unwrap() as i32);
+ world.0.insert(
+ p,
+ Cell {
+ outline: shape(&c[3])?,
+ collision: shape(&c[4])?,
+ suffocating: c[5].as_bool().unwrap(),
+ },
+ );
+ }
+ let p = &row["pos"];
+ let (x, y, z) = (
+ p[0].as_f64().unwrap(),
+ p[1].as_f64().unwrap(),
+ p[2].as_f64().unwrap(),
+ );
+ let bounds = Aabb::new(
+ Vec3::new(x - 0.5, y, z - 0.5),
+ Vec3::new(x + 0.5, y + 0.25, z + 0.5),
+ );
+ writeln!(
+ out,
+ "{} {}",
+ cushion::can_place(&world, bounds),
+ cushion::survives(&world, bounds)
+ )?;
+ }
+ Ok(())
+}
diff --git a/crates/horizon-client/examples/probe/entity_anim_fixture.rs b/crates/horizon-client/examples/probe/entity_anim_fixture.rs
index 0a2e2951f..4582033fe 100644
--- a/crates/horizon-client/examples/probe/entity_anim_fixture.rs
+++ b/crates/horizon-client/examples/probe/entity_anim_fixture.rs
@@ -9,7 +9,7 @@ use horizon_client::mesher::Vertex;
use horizon_client::mobs::{
Mob, MobData, MobTypes, Part, Species, allay,
anim::{self, Poses, State},
- aquatic, body_anim as b_anim, equine, guardian,
+ aquatic, bat, body_anim as b_anim, equine, guardian,
keyframes::AnimationState,
render, shulker, sniffer, species, tame,
};
@@ -108,6 +108,22 @@ fn entity_state(mob: &mut Mob, species: Species, case: &Value) {
let flag = |k: &str| case[k].as_bool().unwrap_or(false);
let num = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32;
match species {
+ Species::Bat => {
+ mob.extra.flag = flag("isResting");
+ mob.anim.states[0].started = case["flyAnimationState"].as_f64().map(|v| v as f32);
+ mob.anim.states[1].started = case["restAnimationState"].as_f64().map(|v| v as f32);
+ if let Some(ticks) = case["@batTicks"].as_array() {
+ for (i, flags) in ticks.iter().enumerate() {
+ mob.age = i as u32 + 1;
+ bat::set_resting(mob, flags.as_i64().unwrap_or(0) & 1 != 0);
+ if flag("@batInFrame") {
+ bat::tick(mob);
+ } else {
+ bat::setup_animation_states(mob);
+ }
+ }
+ }
+ }
Species::Sheep => mob.extra.anim_ticks = num("eatTick") as i32,
Species::Guardian | Species::ElderGuardian => {
mob.anim.v[guardian::TAIL] = num("tailAnimation");
@@ -377,7 +393,7 @@ pub fn main() -> horizon_client::Result<()> {
mob.extra.age = -24000;
}
mob.age = f("ageInTicks") as u32;
- let state = State {
+ let mut state = State {
pos: f("walkAnimationPos"),
speed: f("walkAnimationSpeed"),
age: f("ageInTicks"),
@@ -389,6 +405,20 @@ pub fn main() -> horizon_client::Result<()> {
};
let mut poses = Poses::new(&model);
entity_state(&mut mob, def.species, case);
+ if let Some(ticks) = case["@walkTicks"].as_array() {
+ for speed in ticks {
+ mob.previous_limb_speed = mob.limb_speed;
+ mob.limb_speed += (speed.as_f64().unwrap() as f32 - mob.limb_speed) * 0.4;
+ mob.limb_position += mob.limb_speed;
+ }
+ if !case["@alive"].as_bool().unwrap() {
+ mob.health = 0.0;
+ }
+ let extracted = anim::state(&mob, f("@partial"));
+ state.pos = extracted.pos;
+ state.speed = extracted.speed;
+ }
+
let flag = |k: &str| case[k].as_bool().unwrap_or(false);
let num = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32;
let started = |k: &str| AnimationState {
@@ -456,14 +486,6 @@ pub fn main() -> horizon_client::Result<()> {
roll_amount: num("rollAmount"),
},
),
- Species::Bat => b_anim::bat(
- p,
- s,
- flag("isResting"),
- &started("flyAnimationState"),
- &started("restAnimationState"),
- &animations,
- ),
Species::Armadillo => b_anim::armadillo(
p,
s,
@@ -570,6 +592,7 @@ pub fn main() -> horizon_client::Result<()> {
pose,
num("maxCrossbowChageDuration"),
num("ticksUsingItem"),
+ false,
);
}
Species::Evoker | Species::Illusioner | Species::Pillager | Species::Vindicator => {
@@ -590,7 +613,11 @@ pub fn main() -> horizon_client::Result<()> {
}
_ => anim::setup(&mob, s, p, &animations),
}
- out.push_str(&format!("{}\n", emit(&model, &mut poses, case, layer)));
+ let mut result = emit(&model, &mut poses, case, layer);
+ if case["@walkTicks"].is_array() {
+ result["walk"] = json!([state.pos, state.speed]);
+ }
+ out.push_str(&format!("{result}\n"));
}
fs::write(&args[2], out)?;
Ok(())
diff --git a/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs b/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs
index 86ef275d9..3f47ba787 100644
--- a/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs
+++ b/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs
@@ -23,6 +23,7 @@ fn stack(spec: &str) -> LootStack {
map: false,
exploration: None,
ominous_amplifier: None,
+ stew_effects: Vec::new(),
};
for e in parts {
let (name, level) = e.rsplit_once(':').unwrap_or((e, "1"));
diff --git a/crates/horizon-client/examples/probe/main.rs b/crates/horizon-client/examples/probe/main.rs
index e80088fd0..6b4c3d7dd 100644
--- a/crates/horizon-client/examples/probe/main.rs
+++ b/crates/horizon-client/examples/probe/main.rs
@@ -27,7 +27,9 @@ mod chat_screen_fixture;
mod cloud_fixture;
mod command_parse_fixture;
mod container_screen_probe;
+mod creative_mining_probe;
mod creative_search_fixture;
+mod cushion_placement_probe;
mod emitter_particles_probe;
mod enchanting_fixture;
mod entity_anim_fixture;
@@ -83,6 +85,7 @@ mod sound_engine_fixture;
mod sound_event_fixture;
mod spawn_rules_fixture;
mod sprint_probe;
+mod squid_client_probe;
mod subtitle_fixture;
mod tab_list_fixture;
mod team_rules_fixture;
@@ -107,6 +110,9 @@ probes! {
block_transform_fixture,
breaking_fixture,
camera_probe,
+ squid_client_probe,
+ creative_mining_probe,
+ cushion_placement_probe,
cauldron_fixture,
chat_screen_fixture,
cloud_fixture,
diff --git a/crates/horizon-client/examples/probe/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs
index 49f56c250..5b6c26d2f 100644
--- a/crates/horizon-client/examples/probe/mob_ai_probe.rs
+++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs
@@ -49,6 +49,7 @@ struct Scenario {
name: String,
ticks: i32,
time: i64,
+ difficulty: u8,
rain: bool,
thunder: bool,
origin: [i32; 2],
@@ -85,11 +86,13 @@ fn parse(text: &str) -> Vec {
"scenario" => {
s.name = f[1].to_owned();
s.time = 6000;
+ s.difficulty = 2;
for kv in &f[2..] {
let (k, v) = kv.split_once('=').unwrap_or((kv, ""));
match k {
"ticks" => s.ticks = v.parse().unwrap(),
"time" => s.time = v.parse().unwrap(),
+ "difficulty" => s.difficulty = v.parse().unwrap(),
"rain" => s.rain = true,
"thunder" => s.thunder = true,
"levelseed" => {}
@@ -954,6 +957,10 @@ pub fn main() -> horizon_client::Result<()> {
for flag in &spec.flags {
match flag.as_str() {
"persistent" => m.persistent = true,
+ "named" => {
+ m.custom_name = Some("Peaceful regression".into());
+ m.persistent = true;
+ }
"ridden" => {
m.extra.head = Some("minecraft:red_harness".into());
m.rider = Some(horizon_client::mobs::equine::Rider::default());
@@ -1050,6 +1057,7 @@ pub fn main() -> horizon_client::Result<()> {
velocity: Vec3::ZERO,
yaw: 0.0,
hero: false,
+ effects: Vec::new(),
uuid: PLAYER_UUID,
allies: Default::default(),
remote: false,
@@ -1090,7 +1098,7 @@ pub fn main() -> horizon_client::Result<()> {
block_tags: &items.block_tags,
biomes: &biomes,
mob_griefing: true,
- difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0),
+ difficulty: LocalDifficulty::new(s.difficulty, world.day_time, 0, 0.0),
end: false,
world_seed: 0,
// FlatLevelSource.getSeaLevel.
diff --git a/crates/horizon-client/examples/probe/scene_motion_probe.rs b/crates/horizon-client/examples/probe/scene_motion_probe.rs
index 21977eeab..6153e098b 100644
--- a/crates/horizon-client/examples/probe/scene_motion_probe.rs
+++ b/crates/horizon-client/examples/probe/scene_motion_probe.rs
@@ -164,6 +164,8 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> {
.iter()
.filter_map(|e| match e {
MotionEvent::Fall(e) => Some(e.trace()),
+ // The oracle's player wears no armor; the game applies this one.
+ MotionEvent::Health(horizon_client::health::HealthEvent::ArmorHurt { .. }) => None,
MotionEvent::Health(e) => Some(e.trace()),
MotionEvent::Snowflake { position, velocity } => Some(format!(
"snowflake {:016x},{:016x},{:016x} {:016x},{:016x},{:016x}",
diff --git a/crates/horizon-client/examples/probe/section_mesh_fixture.rs b/crates/horizon-client/examples/probe/section_mesh_fixture.rs
index e212a5268..89624b78c 100644
--- a/crates/horizon-client/examples/probe/section_mesh_fixture.rs
+++ b/crates/horizon-client/examples/probe/section_mesh_fixture.rs
@@ -7,7 +7,7 @@ use horizon_client::{
biome::{BiomeInfo, Biomes, GrassModifier},
blocks::BlockFacts,
chunk::{Chunk, Light, MIN_Y, index},
- mesher::{MeshTables, Mesher, OPAQUE_LAYER, TerrainVertex},
+ mesher::{EMISSION_BITS, MeshTables, Mesher, OPAQUE_LAYER, TerrainVertex},
models,
};
use horizon_core::biome::BiomeZoom;
@@ -161,7 +161,15 @@ fn scene(
.iter()
.map(|v| {
let ([x, y, z], [u, w]) = (v.pos, v.uv());
- json!([x, y, z, u, w, argb(v.color), light_coords(v.light)])
+ json!([
+ x,
+ y,
+ z,
+ u,
+ w,
+ argb(v.color | EMISSION_BITS),
+ light_coords(v.light)
+ ])
})
.collect();
quads.push(json!({"layer": layer, "sprite": sprite, "vertices": vertices}));
diff --git a/crates/horizon-client/examples/probe/squid_client_probe.rs b/crates/horizon-client/examples/probe/squid_client_probe.rs
new file mode 100644
index 000000000..f9f9c9b2c
--- /dev/null
+++ b/crates/horizon-client/examples/probe/squid_client_probe.rs
@@ -0,0 +1,51 @@
+use horizon_client::{
+ Result,
+ mobs::{Mob, MobTypes, aquatic},
+};
+use horizon_core::geometry::Vec3;
+use serde_json::Value;
+use std::{
+ fs::File,
+ io::{BufRead, BufReader, BufWriter, Write},
+ path::Path,
+ sync::Arc,
+};
+
+pub fn main() -> Result<()> {
+ let args: Vec<_> = crate::args().collect();
+ let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
+ let types = MobTypes::load(&root)?;
+ let mut out = BufWriter::new(File::create(&args[2])?);
+ for line in BufReader::new(File::open(&args[1])?).lines() {
+ let row: Value = serde_json::from_str(&line?)?;
+ let kind = Arc::new(
+ types.types[&format!("minecraft:{}", row["species"].as_str().unwrap())].clone(),
+ );
+ let mut mob = Mob::new(1, kind, Vec3::ZERO, 0.0);
+ mob.fluids.in_water = row["water"].as_bool().unwrap();
+ mob.velocity = Vec3::new(
+ row["x"].as_f64().unwrap(),
+ row["y"].as_f64().unwrap(),
+ row["z"].as_f64().unwrap(),
+ );
+ mob.body_yaw = row["body"].as_f64().unwrap() as f32;
+ for (i, value) in row["v"].as_array().unwrap().iter().enumerate() {
+ mob.anim.v[i] = value.as_f64().unwrap() as f32;
+ }
+ if row["reset"].as_bool().unwrap() {
+ aquatic::squid_cycle_event(&mut mob);
+ }
+ let velocity = mob.velocity;
+ aquatic::squid_client_step(&mut mob);
+ assert_eq!(
+ velocity, mob.velocity,
+ "a remote animation must preserve packet velocity"
+ );
+ write!(out, "{:08x}", mob.body_yaw.to_bits())?;
+ for value in &mob.anim.v[..6] {
+ write!(out, " {:08x}", value.to_bits())?;
+ }
+ writeln!(out)?;
+ }
+ Ok(())
+}
diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs
index 48e8f16f4..0e0a3319b 100644
--- a/crates/horizon-client/src/animate_tick.rs
+++ b/crates/horizon-client/src/animate_tick.rs
@@ -35,8 +35,9 @@ enum Animate {
Campfire {
spawn_particles: bool,
},
- /// Leaves: optional falling-leaf particle and chance, tinted by foliage.
- Leaves(Option<(T, f32)>),
+ /// Leaves: optional falling-leaf particle and chance; a tinted leaf takes
+ /// the biome foliage colour unless a fixed colour is given (azalea).
+ Leaves(Option<(T, f32)>, Option),
NetherPortal,
EnchantingTable,
EndRod([i32; 3]),
@@ -49,6 +50,8 @@ enum Animate {
EnderChest,
/// FallingBlock with its dust colour.
Falling(u32),
+ /// A beehive or bee nest full of honey (`BeehiveBlock.animateTick`).
+ Beehive,
RedstoneOre,
RedstoneWire {
power: u8,
@@ -58,7 +61,10 @@ enum Animate {
BubbleColumn {
drag: bool,
},
- Fire,
+ /// `BaseFireBlock` (`SoulFireBlock.canBurn` is always true).
+ Fire {
+ soul: bool,
+ },
/// An active sculk sensor.
SculkSensor,
/// Potent sulfur that is not dry.
@@ -101,10 +107,17 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate {
spawn_particles: false,
},
"oak_leaves" | "birch_leaves" | "jungle_leaves" | "acacia_leaves" | "dark_oak_leaves"
- | "mangrove_leaves" => Animate::Leaves(Some((T::TintedLeaves, 0.01))),
- "cherry_leaves" => Animate::Leaves(Some((T::CherryLeaves, 0.1))),
- "pale_oak_leaves" => Animate::Leaves(Some((T::PaleOakLeaves, 0.02))),
- "spruce_leaves" | "azalea_leaves" | "flowering_azalea_leaves" => Animate::Leaves(None),
+ | "mangrove_leaves" => Animate::Leaves(Some((T::TintedLeaves, 0.01)), None),
+ "cherry_leaves" => Animate::Leaves(Some((T::CherryLeaves, 0.1)), None),
+ "pale_oak_leaves" => Animate::Leaves(Some((T::PaleOakLeaves, 0.02)), None),
+ "red_poplar_leaves" => Animate::Leaves(Some((T::RedPoplarLeaves, 0.01)), None),
+ "orange_poplar_leaves" => Animate::Leaves(Some((T::OrangePoplarLeaves, 0.01)), None),
+ "yellow_poplar_leaves" => Animate::Leaves(Some((T::YellowPoplarLeaves, 0.01)), None),
+ // The azalea blocks drop tinted leaves of the fixed colour -9399763.
+ "azalea_leaves" | "flowering_azalea_leaves" => {
+ Animate::Leaves(Some((T::TintedLeaves, 0.01)), Some(0x0070_922D))
+ }
+ "spruce_leaves" => Animate::Leaves(None, None),
"nether_portal" => Animate::NetherPortal,
"enchanting_table" => Animate::EnchantingTable,
"end_rod" => Animate::EndRod(facing()),
@@ -116,6 +129,14 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate {
"sand" => Animate::Falling(0xDBD3A0),
"red_sand" => Animate::Falling(0xA95821),
"gravel" => Animate::Falling(0x807C7B),
+ // AnvilBlock/ConcretePowderBlock.getDustColor is the map colour;
+ // DragonEggBlock's is black.
+ "anvil" | "chipped_anvil" | "damaged_anvil" => Animate::Falling(0xA7A7A7),
+ "dragon_egg" => Animate::Falling(0x000000),
+ _ if name.ends_with("_concrete_powder") => Animate::Falling(concrete_powder_color(
+ name.trim_end_matches("_concrete_powder"),
+ )),
+ "beehive" | "bee_nest" if prop("honey_level").as_deref() == Some("5") => Animate::Beehive,
"redstone_ore" | "deepslate_redstone_ore" if lit => Animate::RedstoneOre,
"redstone_wire" => {
let power = prop("power").and_then(|p| p.parse().ok()).unwrap_or(0);
@@ -140,7 +161,8 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate {
"bubble_column" => Animate::BubbleColumn {
drag: prop("drag").as_deref() == Some("true"),
},
- "fire" | "soul_fire" => Animate::Fire,
+ "fire" => Animate::Fire { soul: false },
+ "soul_fire" => Animate::Fire { soul: true },
"dried_ghast" => Animate::DriedGhast {
waterlogged: prop("waterlogged").as_deref() == Some("true"),
},
@@ -157,6 +179,27 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate {
_ => Animate::None,
}
}
+/// `DyeColor.getMapColor` of a concrete powder colour.
+fn concrete_powder_color(dye: &str) -> u32 {
+ match dye {
+ "white" => 0xFFFFFF,
+ "orange" => 0xD87F33,
+ "magenta" => 0xB24CD8,
+ "light_blue" => 0x6699D8,
+ "yellow" => 0xE5E533,
+ "lime" => 0x7FCC19,
+ "pink" => 0xF27FA5,
+ "gray" => 0x4C4C4C,
+ "light_gray" => 0x999999,
+ "cyan" => 0x4C7F99,
+ "purple" => 0x7F3FB2,
+ "blue" => 0x334CB2,
+ "brown" => 0x664C33,
+ "green" => 0x667F33,
+ "red" => 0x993333,
+ _ => 0x191919,
+ }
+}
/// `RedstoneWireBlock.COLORS`.
fn redstone_color(power: u8) -> [f32; 3] {
let f = f32::from(power) / 15.0;
@@ -190,6 +233,8 @@ pub struct AnimateTables {
power_transmitter: Vec,
/// `#triggers_ambient_dried_ghast_block_sounds` (soul sand, soul soil).
dried_ghast_sounds: Vec,
+ /// `FireBlock.canBurn`: states with ignite odds above zero (none waterlogged).
+ burnable: Vec,
/// Biome id -> ambient particles and probabilities (`minecraft:visual/ambient_particles`).
ambient: Vec>,
}
@@ -220,6 +265,21 @@ impl AnimateTables {
})
.collect()
};
+ let behaviour: serde_json::Value =
+ serde_json::from_slice(&std::fs::read(root.join("block-behaviours.json"))?)?;
+ let ignite_odds = behaviour["fire"]["igniteOdds"].as_object();
+ let burnable = (0..registry.len() as u32)
+ .map(|id| {
+ // FireBlock.getIgniteOdds: a waterlogged state never burns.
+ registry.state(BlockStateId(id)).is_some_and(|s| {
+ s.properties.get("waterlogged").map(String::as_str) != Some("true")
+ && ignite_odds
+ .and_then(|m| m.get(s.name.as_str()))
+ .and_then(serde_json::Value::as_i64)
+ .is_some_and(|odds| odds > 0)
+ })
+ })
+ .collect();
let mut ambient = vec![Vec::new(); biomes.list.len()];
for (name, &id) in &biomes.index {
let path = root.join(format!(
@@ -248,6 +308,7 @@ impl AnimateTables {
power_provider: by_state("minecraft:enchantment_power_provider"),
power_transmitter: by_state("minecraft:enchantment_power_transmitter"),
dried_ghast_sounds: by_state("minecraft:triggers_ambient_dried_ghast_block_sounds"),
+ burnable,
ambient,
})
}
@@ -482,6 +543,53 @@ fn try_spawn_drip(
}
}
}
+/// `BeehiveBlock.trySpawnDripParticles`.
+fn beehive_drip(
+ tables: &AnimateTables,
+ engine: &mut ParticleEngine,
+ ctx: &AnimateContext,
+ state: BlockStateId,
+ pos: [i32; 3],
+) {
+ if ctx.facts.get(state).fluid != Fluid::None || engine.random().next_float() < 0.3 {
+ return;
+ }
+ let Some((bottom, top, bounds)) = ctx.shape_y(pos) else {
+ return;
+ };
+ if top < 1.0
+ || tables
+ .impermeable
+ .get(state.0 as usize)
+ .copied()
+ .unwrap_or(false)
+ {
+ return;
+ }
+ let y = if bottom > 0.0 {
+ f64::from(pos[1]) + bottom - 0.05
+ } else {
+ let below = [pos[0], pos[1] - 1, pos[2]];
+ let below_top = ctx.shape_y(below).map_or(1.0, |s| s.1);
+ // `belowTop < 1 || !isCollisionShapeFullBlock` and no fluid below.
+ if (below_top < 1.0 || !ctx.sturdy(below))
+ && ctx.facts.get(ctx.state(below)).fluid == Fluid::None
+ {
+ f64::from(pos[1]) - 0.05
+ } else {
+ return;
+ }
+ };
+ let r = engine.random();
+ let (a, b) = (r.next_double(), r.next_double());
+ let (fx, fz) = (f64::from(pos[0]), f64::from(pos[2]));
+ let p = [
+ fx + bounds[0] + (bounds[1] - bounds[0]) * a,
+ y,
+ fz + bounds[2] + (bounds[3] - bounds[2]) * b,
+ ];
+ add(engine, T::DrippingHoney, p, [0.0; 3]);
+}
/// `WaterFluid.animateTick` / `LavaFluid.animateTick`.
fn fluid_animate_tick(
engine: &mut ParticleEngine,
@@ -663,7 +771,7 @@ fn block_animate_tick(
}
}
}
- Animate::Leaves(falling) => {
+ Animate::Leaves(falling, fixed_tint) => {
let below = [pos[0], pos[1] - 1, pos[2]];
// LeavesBlock.makeDrippingWaterParticles.
if (ctx.raining_at)([pos[0], pos[1] + 1, pos[2]]) && next_int(engine.random(), 15) == 1
@@ -683,7 +791,7 @@ fn block_animate_tick(
let r = engine.random();
let p = [fx + r.next_double(), fy - 0.05, fz + r.next_double()];
let options = if ty == T::TintedLeaves {
- let c = ctx.foliage(pos);
+ let c = fixed_tint.unwrap_or_else(|| ctx.foliage(pos));
let f = |s: u32| ((c >> s) & 255) as f32 / 255.0;
ParticleOptions::colored(ty, [f(16), f(8), f(0), 1.0])
} else {
@@ -955,6 +1063,13 @@ fn block_animate_tick(
}
}
}
+ Animate::Beehive => {
+ // BeehiveBlock.animateTick: nextInt(1) + 1 attempts.
+ let attempts = next_int(engine.random(), 1) + 1;
+ for _ in 0..attempts {
+ beehive_drip(tables, engine, ctx, state, pos);
+ }
+ }
Animate::RedstoneOre => {
for d in [
[0, -1, 0],
@@ -1103,7 +1218,7 @@ fn block_animate_tick(
}
}
}
- Animate::Fire => {
+ Animate::Fire { soul } => {
let r = engine.random();
if next_int(r, 24) == 0 {
let (volume, pitch) = (1.0 + r.next_float(), r.next_float() * 0.7 + 0.3);
@@ -1115,6 +1230,55 @@ fn block_animate_tick(
pitch,
);
}
+ // BaseFireBlock.animateTick: three large smoke above the fire, or
+ // two at each burnable neighbour's face when nothing burnable or
+ // sturdy supports it (SoulFireBlock.canBurn is always true).
+ let can_burn = |p: [i32; 3]| {
+ soul || tables
+ .burnable
+ .get(ctx.state(p).0 as usize)
+ .copied()
+ .unwrap_or(false)
+ };
+ let below = [pos[0], pos[1] - 1, pos[2]];
+ let sturdy = ctx.facts.get(ctx.state(below)).sturdy_full & (1 << 1) != 0;
+ if !can_burn(below) && !sturdy {
+ // (neighbour, coordinate axis, face at the axis' high end): the
+ // west, east, north, south and above faces, in vanilla order.
+ for (at, axis, high) in [
+ ([pos[0] - 1, pos[1], pos[2]], 0usize, false),
+ ([pos[0] + 1, pos[1], pos[2]], 0, true),
+ ([pos[0], pos[1], pos[2] - 1], 2, false),
+ ([pos[0], pos[1], pos[2] + 1], 2, true),
+ ([pos[0], pos[1] + 1, pos[2]], 1, true),
+ ] {
+ if !can_burn(at) {
+ continue;
+ }
+ for _ in 0..2 {
+ let r = engine.random();
+ let d = [r.next_double(), r.next_double(), r.next_double()];
+ let mut p = [fx + d[0], fy + d[1], fz + d[2]];
+ // The face coordinate hugs the edge: `* 0.1F` (float).
+ p[axis] = if high {
+ f64::from(pos[axis]) + 1.0 - d[axis] * f64::from(0.1f32)
+ } else {
+ f64::from(pos[axis]) + d[axis] * f64::from(0.1f32)
+ };
+ add(engine, T::LargeSmoke, p, [0.0; 3]);
+ }
+ }
+ } else {
+ for _ in 0..3 {
+ let r = engine.random();
+ let p = [
+ fx + r.next_double(),
+ fy + r.next_double() * 0.5 + 0.5,
+ fz + r.next_double(),
+ ];
+ add(engine, T::LargeSmoke, p, [0.0; 3]);
+ }
+ }
}
}
}
@@ -1138,32 +1302,71 @@ fn candle(engine: &mut ParticleEngine, p: [f64; 3]) {
}
add(engine, T::SmallFlame, p, [0.0; 3]);
}
-/// `CampfireBlockEntity.particleTick` for every lit campfire (no cooking items).
+/// `CampfireBlockEntity.particleTick` for every lit campfire; `cooking` says
+/// which of a campfire's four slots hold an item.
pub fn campfire_particles<'a>(
tables: &AnimateTables,
engine: &mut ParticleEngine,
ctx: &AnimateContext,
blocks: impl Iterator- ,
+ cooking: &dyn Fn([i32; 3]) -> [bool; 4],
) {
for &(pos, state) in blocks {
if !tables.is_lit_campfire(state) {
continue;
}
- let signal = ctx
+ let properties = ctx
.registry
.state(BlockStateId(state))
- .is_some_and(|s| s.properties.get("signal_fire").map(String::as_str) == Some("true"));
+ .map(|s| &s.properties);
+ let prop = |k: &str| properties.and_then(|p| p.get(k)).map(String::as_str);
+ let signal = prop("signal_fire") == Some("true");
+ // Direction.get2DDataValue: south, west, north, east.
+ let rotation = match prop("facing") {
+ Some("west") => 1,
+ Some("north") => 2,
+ Some("east") => 3,
+ _ => 0,
+ };
let r = engine.random();
if r.next_float() < 0.11 {
let count = next_int(r, 2) + 2;
for _ in 0..count {
- make_campfire_smoke(engine, pos, signal);
+ make_campfire_smoke(engine, pos, signal, false);
+ }
+ }
+ // The smoke over each cooking item, at the slot's corner of the fire.
+ let occupied = cooking(pos);
+ for (slot, _) in occupied.iter().enumerate().filter(|(_, held)| **held) {
+ if engine.random().next_float() >= 0.2 {
+ continue;
+ }
+ // Direction.from2DDataValue((slot + rotation) % 4) and its clockwise side.
+ let (step, clockwise) = match (slot + rotation) % 4 {
+ 0 => ([0.0, 1.0], [-1.0, 0.0]),
+ 1 => ([-1.0, 0.0], [0.0, -1.0]),
+ 2 => ([0.0, -1.0], [1.0, 0.0]),
+ _ => ([1.0, 0.0], [0.0, 1.0]),
+ };
+ let at = [
+ f64::from(pos[0]) + 0.5 - step[0] * 0.3125 + clockwise[0] * 0.3125,
+ f64::from(pos[1]) + 0.5,
+ f64::from(pos[2]) + 0.5 - step[1] * 0.3125 + clockwise[1] * 0.3125,
+ ];
+ for _ in 0..4 {
+ add(engine, T::Smoke, at, [0.0, 5.0e-4, 0.0]);
}
}
}
}
-/// `CampfireBlock.makeParticles` (always visible, overriding the limiter).
-pub fn make_campfire_smoke(engine: &mut ParticleEngine, pos: [i32; 3], signal: bool) {
+/// `CampfireBlock.makeParticles` (always visible, overriding the limiter);
+/// `smoking` adds the plain smoke puff at the logs.
+pub fn make_campfire_smoke(
+ engine: &mut ParticleEngine,
+ pos: [i32; 3],
+ signal: bool,
+ smoking: bool,
+) {
let r = engine.random();
let sign = |r: &mut LegacyRandom| if r.next_boolean() { 1.0 } else { -1.0 };
let dx = r.next_double() / 3.0;
@@ -1177,6 +1380,17 @@ pub fn make_campfire_smoke(engine: &mut ParticleEngine, pos: [i32; 3], signal: b
T::CampfireCosySmoke
};
engine.create(&ParticleOptions::simple(ty), [x, y, z], [0.0, 0.07, 0.0]);
+ if smoking {
+ let r = engine.random();
+ let dx = r.next_double() / 4.0 * sign(r);
+ let dz = r.next_double() / 4.0 * sign(r);
+ let at = [
+ f64::from(pos[0]) + 0.5 + dx,
+ f64::from(pos[1]) + 0.4,
+ f64::from(pos[2]) + 0.5 + dz,
+ ];
+ engine.create(&ParticleOptions::simple(T::Smoke), at, [0.0, 0.005, 0.0]);
+ }
}
#[cfg(test)]
diff --git a/crates/horizon-client/src/arrows.rs b/crates/horizon-client/src/arrows.rs
index 30b501011..6d8dc528b 100644
--- a/crates/horizon-client/src/arrows.rs
+++ b/crates/horizon-client/src/arrows.rs
@@ -9,7 +9,7 @@ use crate::{
collisions::SceneCollisions,
mobs::Who,
motion::{FluidResources, LAVA, WATER},
- projectiles::{Hit, Projectile},
+ projectiles::{Hit, Projectile, ProjectileKind},
world::World,
};
use horizon_core::{
@@ -132,6 +132,10 @@ pub enum ArrowSound {
HitGround,
/// `entity.generic.extinguish_fire`.
Extinguish,
+ /// A thrown trident's `getDefaultHitGroundSoundEvent` (`item.trident.hit_ground`).
+ TridentHitGround,
+ /// `ThrownTrident.onHitEntity`'s `item.trident.hit`.
+ TridentHit,
}
/// What a burning arrow does to the block it hits (`onProjectileHit`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -156,7 +160,11 @@ pub struct ArrowState {
/// `pickupItemStack`: what picking the arrow up gives.
pub pickup_item: crate::items::ItemStack,
pub no_physics: bool,
+ /// `AbstractArrow.getPierceLevel`.
pub pierce: u8,
+ /// `piercingIgnoreEntityIds`: the entities a piercing arrow has gone
+ /// through (cleared when it sticks in a block).
+ pub pierced: Vec
,
/// `Entity.remainingFireTicks`.
pub fire_ticks: i32,
pub fall_distance: f64,
@@ -165,6 +173,9 @@ pub struct ArrowState {
pub was_eye_in_water: bool,
pub first_tick: bool,
pub has_been_shot: bool,
+ /// `ThrownTrident.dealtDamage`: it has hit an entity (or sat in a block
+ /// for over 4 ticks) and hits no more.
+ pub dealt_damage: bool,
pub removed: bool,
/// The arrow's own random (`Entity.random`).
pub random: LegacyRandom,
@@ -199,6 +210,7 @@ impl ArrowState {
pickup_item: crate::items::ItemStack::new("minecraft:arrow", 1),
no_physics: false,
pierce: 0,
+ pierced: Vec::new(),
fire_ticks: 0,
fall_distance: 0.0,
fluids: EntityFluidInteraction::new([WATER, LAVA]),
@@ -206,6 +218,7 @@ impl ArrowState {
was_eye_in_water: false,
first_tick: true,
has_been_shot: false,
+ dealt_damage: false,
removed: false,
random,
events: Vec::new(),
@@ -362,6 +375,29 @@ fn bounds(at: Vec3) -> Aabb {
Vec3::new(at.x + w, at.y + f64::from(HEIGHT), at.z + w),
)
}
+/// The bounding box of an arrow, or a thrown trident, at `at`.
+pub fn arrow_bounds(at: Vec3) -> Aabb {
+ bounds(at)
+}
+/// The blocks an arrow that moved from `from` to `to` was inside
+/// (`Entity.checkInsideBlocks`: the sweep of its box, 16 steps at most), for
+/// the blocks that react to it (`entityInside`).
+pub fn blocks_inside(from: Vec3, to: Vec3) -> Vec {
+ let deflated = bounds(to).deflate(Vec3::new(
+ f64::from(1.0e-5f32),
+ f64::from(1.0e-5f32),
+ f64::from(1.0e-5f32),
+ ));
+ let mut inside = Vec::new();
+ let _ = sweep_intersected_blocks(from, to, deflated, 1_000_000, |p, iteration| {
+ if iteration >= 16 {
+ return false;
+ }
+ inside.push(p);
+ true
+ });
+ inside
+}
/// `Projectile.lerpRotation`.
fn lerp_rotation(mut old: f32, new: f32) -> f32 {
while new - old < -180.0 {
@@ -423,18 +459,29 @@ pub fn finish_entity_hit(p: &mut Projectile, scene: &ArrowScene, outcome: Entity
let Some(mut st) = p.arrow.take() else {
return false;
};
+ let trident = matches!(p.kind, ProjectileKind::Trident);
let mut ticker = Ticker {
p,
st: &mut st,
scene,
};
match outcome {
+ EntityHit::Hurt | EntityHit::Refused if trident => ticker.trident_bounce(),
EntityHit::Hurt => {
ticker.hit_sound();
- ticker.st.removed = true;
+ // A piercing arrow flies on (`getPierceLevel() <= 0` discards).
+ if ticker.st.pierce == 0 {
+ ticker.st.removed = true;
+ }
}
EntityHit::Refused => ticker.turn_back(),
- EntityHit::Deflected => {}
+ EntityHit::Deflected => {
+ // The deflection comes before `onHitEntity` adds the entity to
+ // `piercingIgnoreEntityIds`.
+ if ticker.st.pierce > 0 {
+ ticker.st.pierced.pop();
+ }
+ }
}
ticker.finish();
p.stuck = st.in_ground;
@@ -464,7 +511,16 @@ impl Ticker<'_, '_, '_, '_> {
p.z,
))
}
+ /// Whether this is a `ThrownTrident` (`AbstractArrow` with its own water
+ /// inertia, sounds and hit).
+ fn trident(&self) -> bool {
+ matches!(self.p.kind, ProjectileKind::Trident)
+ }
fn tick(&mut self, targets: &[(Who, Aabb)]) -> Hit {
+ // ThrownTrident.tick.
+ if self.trident() && self.st.in_ground_time > 4 {
+ self.st.dealt_damage = true;
+ }
let physics = !self.st.no_physics;
let movement = self.p.velocity;
let block_pos = self.block_position();
@@ -512,8 +568,9 @@ impl Ticker<'_, '_, '_, '_> {
self.st.in_ground_time = 0;
let original = self.position();
if self.st.was_touching_water {
- // getWaterInertia, then the bubbles behind it.
- self.p.velocity = self.p.velocity.scale(f64::from(0.6f32));
+ // getWaterInertia (0.99 for a trident), then the bubbles behind it.
+ let inertia = if self.trident() { 0.99f32 } else { 0.6f32 };
+ self.p.velocity = self.p.velocity.scale(f64::from(inertia));
let v = self.p.velocity;
for _ in 0..4 {
self.st.events.push(ArrowEvent::Particle {
@@ -639,7 +696,8 @@ impl Ticker<'_, '_, '_, '_> {
self.st.life = 0;
}
/// `AbstractArrow.stepMoveAndHit`: the nearest entity on the way, else the
- /// block (piercing is not modelled).
+ /// block. A piercing arrow that hits an entity here goes on from it next
+ /// tick (`finish_entity_hit`); vanilla's loop goes on within the same tick.
fn step_move_and_hit(&mut self, from: Vec3, to: Vec3, targets: &[(Who, Aabb)]) -> Hit {
let block = self.scene.clip(from, to);
let end = block.map_or(to, |b| b.0);
@@ -649,10 +707,16 @@ impl Ticker<'_, '_, '_, '_> {
.expand_towards(self.p.velocity)
.inflate(Vec3::new(1.0, 1.0, 1.0));
let mut best: Option<(Who, Vec3, f64)> = None;
+ // ThrownTrident.findHitEntity: none once it has dealt damage.
+ let targets = if self.st.dealt_damage { &[] } else { targets };
for (who, b) in targets {
if Some(*who) == self.p.owner && !self.p.left_owner || !b.intersects(area) {
continue;
}
+ // canHitEntity: not an entity a piercing arrow has gone through.
+ if self.st.pierced.contains(who) {
+ continue;
+ }
if let Some(at) = self.entity_hit(b, from, end, margin) {
// Sorted by the distance to the entity's position (the
// stable sort keeps the first of equals).
@@ -667,6 +731,15 @@ impl Ticker<'_, '_, '_, '_> {
self.p.position = next;
self.apply_effects_from_blocks(from, next);
if let Some((who, at, _)) = best {
+ // AbstractArrow.onHitEntity: past pierce level + 1 entities the
+ // arrow is discarded before it hurts the next one.
+ if self.st.pierce > 0 {
+ if self.st.pierced.len() > usize::from(self.st.pierce) {
+ self.st.removed = true;
+ return Hit::None;
+ }
+ self.st.pierced.push(who);
+ }
return Hit::Entity { who, at };
}
let Some((at, pos, face)) = block else {
@@ -706,12 +779,33 @@ impl Ticker<'_, '_, '_, '_> {
/// `playSound(soundEvent, 1, 1.2 / (random * 0.2 + 0.9))`.
fn hit_sound(&mut self) {
let pitch = 1.2 / (self.st.random.next_float() * 0.2 + 0.9);
+ let sound = if self.trident() {
+ ArrowSound::TridentHitGround
+ } else {
+ ArrowSound::HitGround
+ };
self.st.events.push(ArrowEvent::Sound {
- sound: ArrowSound::HitGround,
+ sound,
volume: 1.0,
pitch,
});
}
+ /// `ThrownTrident.onHitEntity` after the hurt, whether it landed or not:
+ /// the hit sound, then `deflect(REVERSE, ..., (0.02, 0.2, 0.02))`. The
+ /// trident keeps flying (it has dealt its damage) and falls.
+ fn trident_bounce(&mut self) {
+ self.st.dealt_damage = true;
+ self.st.events.push(ArrowEvent::Sound {
+ sound: ArrowSound::TridentHit,
+ volume: 1.0,
+ pitch: 1.0,
+ });
+ // ProjectileDeflection.REVERSE.
+ let rotation = 170.0 + self.st.random.next_float() * 20.0;
+ let v = self.p.velocity;
+ self.p.velocity = Vec3::new(v.x * (-0.02 * 0.5), v.y * (-0.2 * 0.5), v.z * (-0.02 * 0.5));
+ self.p.yaw += rotation;
+ }
/// `onHitEntity` when the entity took no damage: `deflect(REVERSE, 0.2)`,
/// a half turn give or take ten degrees at a tenth of the speed; one
/// left almost still drops its pickup (ALLOWED) and is discarded.
@@ -752,6 +846,7 @@ impl Ticker<'_, '_, '_, '_> {
self.st.shake = 7;
self.p.set_critical(false);
self.st.pierce = 0;
+ self.st.pierced.clear();
}
/// `Projectile.mayInteract`: a mob's arrows need `mob_griefing`.
fn may_interact(&self) -> bool {
diff --git a/crates/horizon-client/src/benchmark.rs b/crates/horizon-client/src/benchmark.rs
index bcb94589c..12e38e78a 100644
--- a/crates/horizon-client/src/benchmark.rs
+++ b/crates/horizon-client/src/benchmark.rs
@@ -323,10 +323,15 @@ const QUIET_MESHES_PER_S: f64 = 100.0;
/// happened (`tools/perf_bench.py`'s `wait_loaded`). With `status.streaming`, the sections are
/// drawn once no stage has held work for half a second: blocks changing after the load (fluids
/// settling, random ticks) only remesh in bursts. Without it, meshing has to go quiet.
+///
+/// Right after a teleport (and at spawn) the game reports nothing queued and steady counts for over
+/// a second before it starts loading: the counts must change once, or stay full for 5 s, and the
+/// resident chunks reach [`view_chunks`], before "steady" means loaded.
fn wait_loaded(control: &Control, near: impl Fn(&Value) -> bool) -> Result {
let deadline = Instant::now() + LOAD_LIMIT;
let (mut last, mut changed, mut meshing) = (None, Instant::now(), Instant::now());
let mut previous: Option<(Instant, f64)> = None;
+ let (mut first, mut moved, began) = (None, false, Instant::now());
while Instant::now() < deadline {
let s = control.status();
let now = Instant::now();
@@ -339,6 +344,19 @@ fn wait_loaded(control: &Control, near: impl Fn(&Value) -> bool) -> Result 0
+ && resident >= min_chunks
+ && now - began > Duration::from_secs(5));
+ if min_chunks > 0 && (!moved || resident < min_chunks) {
+ (last, changed, previous, meshing) = (None, now, None, now);
+ thread::sleep(Duration::from_millis(50));
+ continue;
+ }
if last != Some(counts) {
(last, changed) = (Some(counts), now);
}
@@ -370,6 +388,12 @@ fn wait_loaded(control: &Control, near: impl Fn(&Value) -> bool) -> Result u64 {
+ (0.8 * std::f64::consts::PI * (distance * distance) as f64) as u64
+}
+
/// Vanilla's yaw facing from `start` to `end`.
fn yaw(start: [f64; 3], end: [f64; 3]) -> f64 {
(-(end[0] - start[0])).atan2(end[2] - start[2]).to_degrees()
@@ -420,6 +444,13 @@ mod tests {
assert!(scenes("nether").is_none());
}
+ #[test]
+ fn view_chunks_matches_perf_bench() {
+ assert_eq!(view_chunks(12), 361);
+ assert_eq!(view_chunks(32), 2573);
+ assert_eq!(view_chunks(0), 0);
+ }
+
#[test]
fn yaw_matches_vanilla() {
// South (+Z) is 0, west (-X) 90, east (+X) -90.
diff --git a/crates/horizon-client/src/biome.rs b/crates/horizon-client/src/biome.rs
index 63ad004d4..46c1e16ca 100644
--- a/crates/horizon-client/src/biome.rs
+++ b/crates/horizon-client/src/biome.rs
@@ -1,7 +1,7 @@
//! Biome colours from the pinned biome definitions and colormaps
//! (`Biome.getGrassColor`/`getFoliageColor`/..., `BlockTintSources`).
use crate::Result;
-use horizon_core::{noise::SimplexNoise, random::LegacyRandom};
+use horizon_core::{noise::SimplexNoise, position::BlockPos, random::LegacyRandom};
use serde_json::Value;
use std::{collections::HashMap, fs, path::Path};
@@ -28,8 +28,13 @@ pub struct BiomeInfo {
pub spawn_costs: HashMap,
/// The `gameplay/creature_world_gen_spawn_probability` attribute.
pub creature_probability: f32,
+ /// The `gameplay/increased_fire_burnout` attribute (jungles, swamps, peaks,
+ /// mushroom fields).
+ pub increased_fire_burnout: bool,
pub name: String,
pub temperature: f32,
+ /// `temperature_modifier: frozen` (the frozen oceans).
+ pub frozen: bool,
pub downfall: f32,
pub precipitation: bool,
pub grass: u32,
@@ -42,6 +47,26 @@ pub struct BiomeInfo {
pub fog: Option,
pub water_fog: u32,
}
+impl BiomeInfo {
+ /// `Biome.getHeightAdjustedTemperature`: the frozen modifier, then cooler
+ /// with height above `sea_level + 17`.
+ pub fn temperature_at(&self, pos: BlockPos, sea_level: i32) -> f32 {
+ use horizon_world::worldgen::biome_temperature::{
+ BiomeTemperatureSettings, TemperatureModifier,
+ };
+ BiomeTemperatureSettings {
+ base_temperature: self.temperature,
+ modifier: if self.frozen {
+ TemperatureModifier::Frozen
+ } else {
+ TemperatureModifier::None
+ },
+ has_precipitation: self.precipitation,
+ downfall: self.downfall,
+ }
+ .height_adjusted(pos, sea_level)
+ }
+}
pub struct Biomes {
pub list: Vec,
pub index: HashMap,
@@ -128,7 +153,11 @@ impl Biomes {
attributes["minecraft:gameplay/creature_world_gen_spawn_probability"]
.as_f64()
.unwrap_or(0.1) as f32,
+ increased_fire_burnout: attributes["minecraft:gameplay/increased_fire_burnout"]
+ .as_bool()
+ .unwrap_or(false),
temperature,
+ frozen: v["temperature_modifier"].as_str() == Some("frozen"),
downfall,
precipitation: v["has_precipitation"].as_bool().unwrap_or(true),
grass: color(&effects["grass_color"])
diff --git a/crates/horizon-client/src/block_entity_anim.rs b/crates/horizon-client/src/block_entity_anim.rs
index d91748e73..fd91051fa 100644
--- a/crates/horizon-client/src/block_entity_anim.rs
+++ b/crates/horizon-client/src/block_entity_anim.rs
@@ -648,6 +648,61 @@ impl Conduit {
}
}
+/// What `ConduitBlockEntity.serverTick`'s 40-tick check decided.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct ConduitCheck {
+ /// The shape changed: `CONDUIT_ACTIVATE` (true) or `CONDUIT_DEACTIVATE`.
+ pub toggled: Option,
+ /// The frame blocks counted, while the conduit is active: `applyEffects`
+ /// and `updateAndAttackTarget` follow (the attack needs 42 or more).
+ pub frames: Option,
+}
+
+/// `ConduitBlockEntity` (server side): what `serverTick` keeps between ticks.
+#[derive(Clone, Debug, Default)]
+pub struct ConduitServer {
+ shape: Conduit,
+ /// `destroyTarget`: the mob id of the enemy being struck.
+ pub target: Option,
+ next_ambient_sound: i64,
+}
+
+impl ConduitServer {
+ /// The `gameTime % 40` part of `serverTick`: the shape is checked again.
+ pub fn check(
+ &mut self,
+ pos: [i32; 3],
+ game_time: i64,
+ is_water: impl Fn([i32; 3]) -> bool,
+ is_frame: impl Fn([i32; 3]) -> bool,
+ ) -> Option {
+ if game_time % 40 != 0 {
+ return None;
+ }
+ let active = self.shape.update_shape(pos, &is_water, &is_frame);
+ let toggled = (active != self.shape.is_active).then_some(active);
+ self.shape.is_active = active;
+ Some(ConduitCheck {
+ toggled,
+ frames: active.then_some(self.shape.effect_blocks.len()),
+ })
+ }
+ /// The sounds of an active conduit at the end of `serverTick`: whether
+ /// `CONDUIT_AMBIENT` (every 80 ticks) and `CONDUIT_AMBIENT_SHORT` (every
+ /// 60 to 99 ticks) play.
+ pub fn ambient(&mut self, game_time: i64, random: &mut impl RandomSource) -> (bool, bool) {
+ if !self.shape.is_active {
+ return (false, false);
+ }
+ let short = game_time > self.next_ambient_sound;
+ if short {
+ self.next_ambient_sound =
+ game_time + 60 + i64::from(random.next_int_bound(40).unwrap_or(0));
+ }
+ (game_time % 80 == 0, short)
+ }
+}
+
/// `SkullBlockEntity` animation (client ticker of dragon and piglin heads).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Skull {
@@ -832,6 +887,8 @@ pub struct BlockEntityAnims {
pub gateways: FxHashMap<[i32; 3], EndGateway>,
/// The integrated server's copies of the gateways (`portalTick`).
pub gateway_servers: FxHashMap<[i32; 3], EndGateway>,
+ /// The integrated server's copies of the conduits (`serverTick`).
+ pub conduit_servers: FxHashMap<[i32; 3], ConduitServer>,
/// The client level's random (conduit particles).
pub random: LegacyRandom,
/// [`Ticker`] by block state id (see [`BlockEntityAnims::classify`]).
@@ -854,6 +911,7 @@ impl Default for BlockEntityAnims {
pots: FxHashMap::default(),
gateways: FxHashMap::default(),
gateway_servers: FxHashMap::default(),
+ conduit_servers: FxHashMap::default(),
random: LegacyRandom::new(0x6c6576656c),
kinds: Vec::new(),
present: Vec::new(),
@@ -909,6 +967,7 @@ impl BlockEntityAnims {
self.pots.retain(|p, _| keep(*p));
self.gateways.retain(|p, _| keep(*p));
self.gateway_servers.retain(|p, _| keep(*p));
+ self.conduit_servers.retain(|p, _| keep(*p));
}
/// `getOpenNess(partial)` of the chest or ender chest at `pos`.
pub fn lid(&self, pos: [i32; 3], partial: f32) -> f32 {
diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs
index 10c5e2509..28a876d80 100644
--- a/crates/horizon-client/src/block_entity_render.rs
+++ b/crates/horizon-client/src/block_entity_render.rs
@@ -558,12 +558,11 @@ fn frac(x: f32) -> f32 {
/// `StringSplitter.splitLines(...).get(0)` for plain text: the first line,
/// wrapped at the last space that fits or mid-word when none does.
fn first_line(line: &str, max_width: f32, advance: &dyn Fn(char) -> f32) -> String {
- let chars: Vec = line.chars().collect();
let mut width = 0.0;
let mut last_space = None;
- for (i, &c) in chars.iter().enumerate() {
+ for (i, c) in line.char_indices() {
if c == '\n' {
- return chars[..i].iter().collect();
+ return line[..i].to_owned();
}
if c == ' ' {
last_space = Some(i);
@@ -572,9 +571,11 @@ fn first_line(line: &str, max_width: f32, advance: &dyn Fn(char) -> f32) -> Stri
if width > max_width {
let end = match last_space {
Some(s) if s > 0 => s,
- _ => i.max(1),
+ _ if i > 0 => i,
+ // The first char alone is too wide: take that one char.
+ _ => c.len_utf8(),
};
- return chars[..end].iter().collect();
+ return line[..end].to_owned();
}
}
line.to_owned()
@@ -2098,4 +2099,13 @@ mod tests {
assert_eq!(out[1].pos, [2.0, 0.0, 0.0]);
assert_eq!(out[2].uv, [0.5, 0.5]);
}
+
+ #[test]
+ fn first_line_wraps_on_bytes_without_splitting_a_char() {
+ let advance = |c: char| if c == ' ' { 4.0 } else { 6.0 };
+ assert_eq!(first_line("ab cd ef", 13.0, &advance), "ab");
+ assert_eq!(first_line("abcdef", 13.0, &advance), "ab");
+ assert_eq!(first_line("\u{6771}", 3.0, &advance), "\u{6771}");
+ assert_eq!(first_line("ab\ncd", 100.0, &advance), "ab");
+ }
}
diff --git a/crates/horizon-client/src/blocks.rs b/crates/horizon-client/src/blocks.rs
index 27a36396a..8e906e1bc 100644
--- a/crates/horizon-client/src/blocks.rs
+++ b/crates/horizon-client/src/blocks.rs
@@ -90,7 +90,7 @@ pub const MAP_COLORS: [u32; 62] = [
14200723, 8365974,
];
/// The 12 edges of the unit cube (outline data predating the export).
-fn cube_edges() -> Vec<[f64; 6]> {
+pub fn cube_edges() -> Vec<[f64; 6]> {
let mut edges = Vec::new();
for a in 0..3 {
for (u, v) in [(0., 0.), (1., 0.), (0., 1.), (1., 1.)] {
diff --git a/crates/horizon-client/src/bundle.rs b/crates/horizon-client/src/bundle.rs
index 8658b5815..948e2f4a9 100644
--- a/crates/horizon-client/src/bundle.rs
+++ b/crates/horizon-client/src/bundle.rs
@@ -1,6 +1,7 @@
//! `BundleContents.Mutable`: what a bundle takes in and gives back, by
//! weight. The menus (`menu`, `lan::menu`) run `BundleItem`'s click
//! overrides on it.
+use crate::item_data::BundleSelected;
use crate::items::{ItemStack, Items};
use horizon_world::nbt::Tag;
@@ -97,6 +98,8 @@ pub fn can_be_in_bundle(stack: &ItemStack) -> bool {
pub struct Contents {
items: Vec,
weight: Weight,
+ /// `selectedItem`: an index into `items`, -1 for none.
+ selected: i32,
}
impl Contents {
@@ -104,9 +107,11 @@ impl Contents {
pub fn of(items: &Items, stack: &ItemStack) -> Option {
let inside = contents_of(items, stack)?.to_vec();
let weight = contents_weight(items, &inside);
+ let selected = stack.data().map_or(-1, |d| d.bundle_selected.0);
Some(Self {
items: inside,
weight,
+ selected,
})
}
@@ -154,25 +159,82 @@ impl Contents {
amount
}
- /// `removeOne`: the first stack (Horizon keeps no selected item).
+ /// `removeOne`: the selected stack, else the first; nothing is selected after.
pub fn remove_one(&mut self, items: &Items) -> Option {
if self.items.is_empty() {
return None;
}
- let stack = self.items.remove(0);
+ let at =
+ usize::try_from(self.selected).map_or(0, |i| if i < self.items.len() { i } else { 0 });
+ let stack = self.items.remove(at);
self.weight = self
.weight
.sub(item_weight(items, &stack).times(stack.count));
+ self.selected = -1;
Some(stack)
}
+ /// `getSelectedItemIndex`.
+ pub fn selected(&self) -> i32 {
+ self.selected
+ }
+
+ /// The stacks inside, in display order (the first is the next out).
+ pub fn items(&self) -> &[ItemStack] {
+ &self.items
+ }
+
+ /// `getNumberOfItemsToShow`: a full grid shows 11 and a `+N`, so the last
+ /// row keeps its fourth cell for the count.
+ pub fn shown_count(&self) -> usize {
+ let count = self.items.len();
+ let available: usize = if count > 12 { 11 } else { 12 };
+ let on_last_row = count % 4;
+ let empty = if on_last_row == 0 { 0 } else { 4 - on_last_row };
+ count.min(available.saturating_sub(empty))
+ }
+
+ /// The items the tooltip shows, and how many sit beyond them.
+ pub fn shown(&self) -> (&[ItemStack], u32) {
+ let n = self.shown_count();
+ let hidden = self.items[n..].iter().map(|s| s.count).sum();
+ (&self.items[..n], hidden)
+ }
+
+ /// The `Fraction` weight as the float the progress bar reads.
+ pub fn weight_fraction(&self) -> f32 {
+ self.weight.n as f32 / self.weight.d as f32
+ }
+
+ /// `Fraction.ONE`: a full bundle draws the full bar and says so.
+ pub fn is_full(&self) -> bool {
+ self.weight.n >= self.weight.d
+ }
+
/// `toImmutable`, written back into the bundle's component.
pub fn store(self, bundle: &mut ItemStack) {
- bundle.data_mut().bundle_contents = self.items;
+ let data = bundle.data_mut();
+ data.bundle_contents = self.items;
+ data.bundle_selected = BundleSelected(self.selected);
bundle.tidy();
}
}
+/// `BundleItem.toggleSelectedItem`: select `index`, or nothing when it is the
+/// selected one already or outside the contents.
+pub fn toggle_selected(bundle: &mut ItemStack, index: i32) {
+ let Some(data) = bundle.extra.as_deref_mut() else {
+ return;
+ };
+ let inside = (0..data.bundle_contents.len() as i32).contains(&index);
+ let selected = if data.bundle_selected.0 != index && inside {
+ index
+ } else {
+ -1
+ };
+ data.bundle_selected = BundleSelected(selected);
+}
+
#[cfg(test)]
mod tests {
use super::Weight;
@@ -190,3 +252,184 @@ mod tests {
assert_eq!(over.how_many(Weight::new(1, 64)), 0);
}
}
+
+// ------------------------------------------------------------- the tooltip
+
+/// `ClientBundleTooltip`'s geometry, relative to the tooltip box's top-left:
+/// the 96 pixel column of a 4 wide slot grid and the progress bar under it.
+#[derive(Clone, Debug, PartialEq)]
+pub struct TooltipLayout {
+ /// The component's own width (96) and height, the text's excluded.
+ pub width: f32,
+ pub height: f32,
+ /// Each slot's top-left and the stack in it, in drawing order.
+ pub slots: Vec<([f32; 2], ItemStack)>,
+ /// The position in `slots` of the selected item, which is drawn highlighted.
+ pub selected: Option,
+ /// The `+N` of the items past the grid: its top-left and the count.
+ pub overflow: Option<([f32; 2], u32)>,
+ /// The progress bar's top-left, its fill's width out of 94, and whether
+ /// the weight fills it (the full sprite).
+ pub bar: [f32; 2],
+ pub fill: f32,
+ pub full: bool,
+ /// `item.minecraft.bundle.empty` / `.full`, centred over the bar.
+ pub label: Option<&'static str>,
+ /// An empty bundle's description, wrapped at `width` from here.
+ pub empty_description: Option<[f32; 2]>,
+}
+
+/// The tooltip of a bundle's contents (`ClientBundleTooltip`), or None when
+/// the stack is not a bundle. `x`/`y` are the box's top-left, `box_width` the
+/// tooltip's width, which the component is centred in.
+pub fn tooltip_layout(
+ items: &Items,
+ stack: &ItemStack,
+ x: f32,
+ y: f32,
+ box_width: f32,
+) -> Option {
+ let contents = Contents::of(items, stack)?;
+ let offset = ((box_width - 96.0) / 2.0).floor();
+ if contents.items().is_empty() {
+ // The description takes the top; the bar follows it.
+ let description_height = 9.0 * 2.0;
+ return Some(TooltipLayout {
+ width: 96.0,
+ height: description_height + 13.0 + 8.0,
+ slots: Vec::new(),
+ selected: None,
+ overflow: None,
+ bar: [x + offset, y + description_height + 4.0],
+ fill: 0.0,
+ full: false,
+ label: Some("item.minecraft.bundle.empty"),
+ empty_description: Some([x + offset, y]),
+ });
+ }
+ let (shown, hidden) = contents.shown();
+ // `gridSizeY` counts `slotCount()` (at most twelve), not the slots the
+ // overflow count leaves room for.
+ let rows = contents.items().len().min(12).div_ceil(4).max(1);
+ let grid_height = rows as f32 * 24.0;
+ let x_start = x + offset + 96.0;
+ let y_start = y + grid_height;
+ let mut slots = Vec::with_capacity(shown.len());
+ let mut selected = None;
+ let mut overflow = None;
+ // Rows fill bottom-up and columns right-to-left, as vanilla draws them.
+ let mut slot = 0;
+ for row in 1..=rows {
+ for column in 1..=4 {
+ let at = [x_start - column as f32 * 24.0, y_start - row as f32 * 24.0];
+ if hidden > 0 && row == 1 && column == 1 {
+ overflow = Some((at, hidden));
+ } else if slot < shown.len() {
+ // `extractSlot`: the cell of slot number n holds item `size - n`.
+ let index = shown.len() - 1 - slot;
+ if usize::try_from(contents.selected()) == Ok(index) {
+ selected = Some(slots.len());
+ }
+ slots.push((at, shown[index].clone()));
+ slot += 1;
+ }
+ }
+ }
+ let weight = contents.weight_fraction();
+ Some(TooltipLayout {
+ width: 96.0,
+ height: grid_height + 13.0 + 8.0,
+ slots,
+ selected,
+ overflow,
+ bar: [x + offset, y + grid_height + 4.0],
+ // `Mth.mulAndTruncate(weight, 94)`, kept within the bar.
+ fill: (weight * 94.0).trunc().clamp(0.0, 94.0),
+ full: contents.is_full(),
+ label: if contents.is_full() {
+ Some("item.minecraft.bundle.full")
+ } else {
+ None
+ },
+ empty_description: None,
+ })
+}
+
+#[cfg(test)]
+mod tooltip_tests {
+ use super::*;
+
+ /// The prepared resources, when they are on this machine: the tooltip
+ /// asks the item registry whether a stack is a bundle.
+ fn items() -> Option {
+ let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("../../.local/horizon-client/26.3");
+ if !root.join("items.json").exists() {
+ return None;
+ }
+ let assets = crate::assets::Assets::load(&root).ok()?;
+ let facts = crate::blocks::BlockFacts::load(&root, assets.registry).ok()?;
+ Items::load(&root, assets.registry, &facts).ok()
+ }
+
+ fn bundle_with(counts: &[(&str, u32)]) -> ItemStack {
+ let mut bundle = ItemStack::new("minecraft:bundle", 1);
+ bundle.data_mut().bundle_contents = counts
+ .iter()
+ .map(|(item, n)| ItemStack::new(item, *n))
+ .collect();
+ bundle
+ }
+
+ #[test]
+ fn a_grid_shows_twelve_stacks_and_counts_the_rest() {
+ let Some(items) = items() else { return };
+ let twelve: Vec<(&str, u32)> = (0..12).map(|_| ("minecraft:stone", 1)).collect();
+ let layout = tooltip_layout(&items, &bundle_with(&twelve), 0.0, 0.0, 96.0).unwrap();
+ assert_eq!(layout.slots.len(), 12);
+ assert_eq!(layout.overflow, None);
+ assert_eq!(layout.height, 3.0 * 24.0 + 13.0 + 8.0);
+ // Rows fill bottom-up and columns right-to-left: the twelfth item is in
+ // the bottom-right cell, the first in the top-left.
+ assert_eq!(layout.slots[0].0, [96.0 - 24.0, 3.0 * 24.0 - 24.0]);
+ assert_eq!(&*layout.slots[0].1.item, "minecraft:stone");
+ assert_eq!(layout.slots[11].0, [0.0, 0.0]);
+ // A wider tooltip centres the 96 pixel column in it.
+ let centred = tooltip_layout(&items, &bundle_with(&twelve), 0.0, 0.0, 120.0).unwrap();
+ assert_eq!(centred.slots[0].0[0], 12.0 + 96.0 - 24.0);
+ // Thirteen stacks: `getNumberOfItemsToShow` leaves the last row room
+ // for the count, so 8 slots show and `+6` (four stones and two dirt)
+ // takes the first cell.
+ let mut counts = twelve;
+ counts.push(("minecraft:dirt", 2));
+ let layout = tooltip_layout(&items, &bundle_with(&counts), 0.0, 0.0, 96.0).unwrap();
+ assert_eq!(layout.slots.len(), 8);
+ assert_eq!(layout.overflow, Some(([96.0 - 24.0, 48.0], 6)));
+ }
+
+ #[test]
+ fn the_bar_fills_with_the_weight_and_an_empty_bundle_explains_itself() {
+ let Some(items) = items() else { return };
+ let layout = tooltip_layout(&items, &bundle_with(&[]), 4.0, 8.0, 96.0).unwrap();
+ assert!(layout.slots.is_empty());
+ assert_eq!(layout.fill, 0.0);
+ assert_eq!(layout.label, Some("item.minecraft.bundle.empty"));
+ assert_eq!(layout.empty_description, Some([4.0, 8.0]));
+ assert_eq!(layout.bar, [4.0, 8.0 + 18.0 + 4.0]);
+ // A bundle holding one 64 stack is full: the whole bar, the full label.
+ let layout = tooltip_layout(
+ &items,
+ &bundle_with(&[("minecraft:stone", 64)]),
+ 0.0,
+ 0.0,
+ 96.0,
+ )
+ .unwrap();
+ assert!(layout.full);
+ assert_eq!(layout.fill, 94.0);
+ assert_eq!(layout.label, Some("item.minecraft.bundle.full"));
+ // Something that is not a bundle has no component.
+ let dirt = ItemStack::new("minecraft:dirt", 1);
+ assert!(tooltip_layout(&items, &dirt, 0.0, 0.0, 96.0).is_none());
+ }
+}
diff --git a/crates/horizon-client/src/chat_tests.rs b/crates/horizon-client/src/chat_tests.rs
index 6b058c0fb..beec6cd81 100644
--- a/crates/horizon-client/src/chat_tests.rs
+++ b/crates/horizon-client/src/chat_tests.rs
@@ -436,3 +436,34 @@ fn the_chat_option_filters_the_lines_both_ways() {
chat.set_abilities(&font, ChatAbilities::new(ChatVisibility::Full));
assert_eq!(shown(&chat), ["client", "server", "player"]);
}
+
+/// The in-frame LAN host's chat: a guest's line is a player message, so the
+/// Chat option's player-message permission hides it at Commands Only and
+/// Hidden; command feedback (`/list`, `/tp`) is a system message and stays
+/// at Commands Only.
+#[test]
+fn a_guests_line_follows_the_player_message_permission() {
+ let font = font();
+ let shown = |visibility, source| {
+ let mut chat = Chat::default();
+ chat.set_abilities(&font, ChatAbilities::new(visibility));
+ chat.add_message(&font, Text::literal("line"), None, source, 0, false);
+ chat.messages.len()
+ };
+ for (visibility, player, system) in [
+ (ChatVisibility::Full, 1, 1),
+ (ChatVisibility::System, 0, 1),
+ (ChatVisibility::Hidden, 0, 0),
+ ] {
+ assert_eq!(
+ shown(visibility, ChatSource::Player),
+ player,
+ "{visibility:?}"
+ );
+ assert_eq!(
+ shown(visibility, ChatSource::Server),
+ system,
+ "{visibility:?}"
+ );
+ }
+}
diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs
index 41330df5f..7cd375343 100644
--- a/crates/horizon-client/src/chunk.rs
+++ b/crates/horizon-client/src/chunk.rs
@@ -24,6 +24,20 @@ pub fn block_strategy() -> Strategy {
Strategy::blocks(BLOCK_BITS.load(std::sync::atomic::Ordering::Relaxed))
}
+/// Frees `columns` (`count` of them) on a short-lived thread of its own
+/// when there are many: a teleport or a dimension change drops a few
+/// thousand columns at once, and freeing their sections took the frame
+/// 15-20 ms. A few are freed here.
+pub fn free_columns(columns: T, count: usize) {
+ if count < 64 {
+ return;
+ }
+ // Should the thread not start, the closure drops `columns` here.
+ let _ = std::thread::Builder::new()
+ .name("Chunk freeing".into())
+ .spawn(move || drop(columns));
+}
+
/// Sizes the block states' global palette for a registry of `states`.
pub fn set_block_states(states: usize) {
let bits = horizon_core::paletted::ceil_log2(states).max(16);
@@ -147,6 +161,9 @@ pub struct Chunk {
/// Structure starts reaching into this chunk (`structures.References`):
/// structure id and the start's chunk.
pub structure_refs: Vec<(Arc, (i32, i32))>,
+ /// The starts generation made in this chunk (`structures.starts`), saved
+ /// with the state their placement has reached by then.
+ pub structure_starts: Vec>,
}
impl Chunk {
pub fn empty(x: i32, z: i32) -> Self {
@@ -164,6 +181,7 @@ impl Chunk {
block_entities: Vec::new(),
block_names: Vec::new(),
structure_refs: Vec::new(),
+ structure_starts: Vec::new(),
postprocess: Vec::new(),
saved: None,
entities: Vec::new(),
diff --git a/crates/horizon-client/src/clipboard.rs b/crates/horizon-client/src/clipboard.rs
index c21460cdb..76872091c 100644
--- a/crates/horizon-client/src/clipboard.rs
+++ b/crates/horizon-client/src/clipboard.rs
@@ -346,6 +346,11 @@ mod tests {
assert_eq!(filter_text(s, true), "abc\nde\u{80}");
assert_eq!(strip_formatting("§aRed§r §zx§"), "Red §zx§");
assert_eq!(helper_clipboard_contents("§lone\r\ntwo"), "one\ntwo");
+ // TextFieldHelper.getClipboardContents runs before insertText's filter.
+ assert_eq!(
+ filter_text(&helper_clipboard_contents("§aHello"), false),
+ "Hello"
+ );
}
struct Field {
diff --git a/crates/horizon-client/src/container_screen.rs b/crates/horizon-client/src/container_screen.rs
index 2c490861a..77c7ad8aa 100644
--- a/crates/horizon-client/src/container_screen.rs
+++ b/crates/horizon-client/src/container_screen.rs
@@ -275,4 +275,30 @@ mod tests {
Release::Click(Input::QuickMove)
);
}
+
+ /// A press whose release never arrives (the pointer left the window, or
+ /// the screen closed first) leaves `isQuickCrafting` set; the next screen
+ /// starts with its own state, as `AbstractContainerScreen` does, so the
+ /// reset the game runs on open/close makes clicks work again.
+ #[test]
+ fn a_lost_release_does_not_wedge_the_next_screen() {
+ let mut clicks = Clicks::default();
+ let slot = Target::::Slot(3);
+ // Pressed with a stack carried: a quick craft drag starts, and its
+ // release is lost.
+ assert_eq!(clicks.press(&slot, Button::Left, false, false, false), None);
+ assert!(clicks.quick_crafting().is_some());
+ assert_eq!(
+ clicks.press(&slot, Button::Left, true, false, false),
+ None,
+ "the stuck drag swallows the next press"
+ );
+ // A new screen: fresh state, so the press is a normal click again.
+ clicks = Clicks::default();
+ assert!(clicks.quick_crafting().is_none());
+ assert_eq!(
+ clicks.press(&slot, Button::Left, true, false, false),
+ Some(Input::Pickup)
+ );
+ }
}
diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs
index d13c5e45b..8ca9af0ad 100644
--- a/crates/horizon-client/src/containers.rs
+++ b/crates/horizon-client/src/containers.rs
@@ -49,6 +49,17 @@ pub struct Furnace {
/// rather than per item, and a save keeps it as the `RecipesUsed` compound.
pub recipes_used: HashMap,
}
+/// The key `recipes_used` keeps a recipe under: its full id, as vanilla's `ResourceKey`
+/// writes it in `RecipesUsed`. Horizon's own recipe ids are file names without the namespace, so
+/// keeping both forms would write a key twice, and vanilla refuses such a furnace
+/// ("Duplicate entry for key").
+pub fn recipe_used_key(id: &str) -> String {
+ if id.contains(':') {
+ id.to_owned()
+ } else {
+ format!("minecraft:{id}")
+ }
+}
/// A hopper's slots: the only plain container with five.
pub const HOPPER_SLOTS: usize = 5;
@@ -83,8 +94,68 @@ pub enum BlockEntity {
Beehive(Box),
/// `CommandBlockEntity` of the three command blocks (`crate::command_block`).
CommandBlock(Box),
+ /// `CampfireBlockEntity` of campfires and soul campfires.
+ Campfire(Box),
/// `SkullBlockEntity` of every skull and head block.
Skull(Skull),
+ /// `DaylightDetectorBlockEntity`: no data, only the ticker
+ /// (`DaylightDetectorBlock.tickEntity`).
+ DaylightDetector,
+}
+/// `CampfireBlockEntity`: four cooking slots, each with its
+/// `cookingProgress` and `cookingTime` (the recipe's).
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Campfire {
+ pub items: [Option; 4],
+ pub progress: [i32; 4],
+ pub total: [i32; 4],
+}
+impl Campfire {
+ /// `placeFood`'s slot: the first empty one, given the item's
+ /// `campfire_cooking` time; it takes one item of `held`.
+ pub fn place_food(&mut self, held: &mut ItemStack, cooking_time: i32) -> bool {
+ let Some(slot) = self.items.iter().position(Option::is_none) else {
+ return false;
+ };
+ self.total[slot] = cooking_time;
+ self.progress[slot] = 0;
+ self.items[slot] = Some(ItemStack {
+ count: 1,
+ ..held.clone()
+ });
+ held.count = held.count.saturating_sub(1);
+ true
+ }
+ /// `cookTick` (lit): each item's progress rises by one; the slots whose
+ /// progress reached their cooking time give up their item (the caller
+ /// drops its result).
+ pub fn cook_tick(&mut self) -> Vec<(usize, ItemStack)> {
+ let mut done = Vec::new();
+ for i in 0..4 {
+ if self.items[i].is_none() {
+ continue;
+ }
+ self.progress[i] += 1;
+ if self.progress[i] >= self.total[i]
+ && let Some(item) = self.items[i].take()
+ {
+ done.push((i, item));
+ }
+ }
+ done
+ }
+ /// `cooldownTick` (unlit): the progress falls by two, no lower than 0.
+ /// Whether anything changed (`setChanged`).
+ pub fn cooldown_tick(&mut self) -> bool {
+ let mut changed = false;
+ for i in 0..4 {
+ if self.progress[i] > 0 {
+ changed = true;
+ self.progress[i] = (self.progress[i] - 2).clamp(0, self.total[i]);
+ }
+ }
+ changed
+ }
}
/// `SkullBlockEntity`: the player profile the head shows (kept as loaded:
/// a compound, or a string when it names a player only), the note block
@@ -295,6 +366,9 @@ impl BlockEntity {
if is_skull(name) {
return Some(Self::Skull(Skull::default()));
}
+ if name == "minecraft:daylight_detector" {
+ return Some(Self::DaylightDetector);
+ }
if name == "minecraft:beacon" {
return Some(Self::Beacon(Box::new(Beacon {
last_check_y: i32::MIN / 2,
@@ -304,6 +378,9 @@ impl BlockEntity {
if name == "minecraft:brewing_stand" {
return Some(Self::Brewing(Box::new(crate::brewing::BrewingStand::new())));
}
+ if name == "minecraft:campfire" || name == "minecraft:soul_campfire" {
+ return Some(Self::Campfire(Box::default()));
+ }
let size = match name {
"minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" => 27,
n if n.ends_with("copper_chest") => 27,
@@ -341,6 +418,8 @@ impl BlockEntity {
Self::Beehive(_) => "minecraft:beehive",
Self::CommandBlock(_) => "minecraft:command_block",
Self::Skull(_) => "minecraft:skull",
+ Self::DaylightDetector => "minecraft:daylight_detector",
+ Self::Campfire(_) => "minecraft:campfire",
}
}
pub fn contents(&self) -> Vec {
@@ -357,11 +436,13 @@ impl BlockEntity {
| Self::Vault(_)
| Self::Beehive(_)
| Self::CommandBlock(_)
- | Self::Skull(_) => Vec::new(),
+ | Self::Skull(_)
+ | Self::DaylightDetector => Vec::new(),
Self::Lectern(l) => l.book.iter().cloned().collect(),
Self::Sculk(_) => Vec::new(),
Self::Banner(_) => Vec::new(),
Self::Crafter(c) => c.items.iter().flatten().cloned().collect(),
+ Self::Campfire(c) => c.items.iter().flatten().cloned().collect(),
}
}
pub fn slots(&self) -> &[Option] {
@@ -375,14 +456,17 @@ impl BlockEntity {
| Self::Lectern(_)
| Self::Sculk(_)
| Self::Banner(_)
- | Self::Skull(_) => &[],
+ | Self::Skull(_)
+ | Self::DaylightDetector => &[],
Self::Crafter(c) => &c.items,
Self::CreakingHeart(_)
| Self::Spawner(_)
| Self::TrialSpawner(_)
| Self::Vault(_)
| Self::Beehive(_)
- | Self::CommandBlock(_) => &[],
+ | Self::CommandBlock(_)
+ // Not a Container (only Clearable): hoppers don't reach in.
+ | Self::Campfire(_) => &[],
}
}
pub fn slots_mut(&mut self) -> &mut [Option] {
@@ -396,14 +480,16 @@ impl BlockEntity {
| Self::Lectern(_)
| Self::Sculk(_)
| Self::Banner(_)
- | Self::Skull(_) => &mut [],
+ | Self::Skull(_)
+ | Self::DaylightDetector => &mut [],
Self::Crafter(c) => &mut c.items,
Self::CreakingHeart(_)
| Self::Spawner(_)
| Self::TrialSpawner(_)
| Self::Vault(_)
| Self::Beehive(_)
- | Self::CommandBlock(_) => &mut [],
+ | Self::CommandBlock(_)
+ | Self::Campfire(_) => &mut [],
}
}
}
@@ -638,7 +724,10 @@ impl Furnace {
Some(out) => out.count += recipe.result.count,
None => self.items[2] = Some(recipe.result.clone()),
}
- *self.recipes_used.entry(recipe.id.clone()).or_insert(0) += 1;
+ *self
+ .recipes_used
+ .entry(recipe_used_key(&recipe.id))
+ .or_insert(0) += 1;
if let Some(i) = self.items[0].as_mut() {
i.count -= 1;
if i.count == 0 {
@@ -692,6 +781,41 @@ mod tests {
use super::*;
use horizon_core::random::{LegacyRandom, RandomSource};
+ #[test]
+ fn campfire_slots_take_food_cook_it_and_cool_down() {
+ let mut c = Campfire::default();
+ let mut beef = ItemStack::new("minecraft:beef", 2);
+ // placeFood: the first free slot, one item, its recipe's time.
+ assert!(c.place_food(&mut beef, 600));
+ assert_eq!(beef.count, 1);
+ assert_eq!(c.items[0].as_ref().map(|s| s.count), Some(1));
+ assert_eq!((c.progress[0], c.total[0]), (0, 600));
+ let mut fish = ItemStack::new("minecraft:cod", 1);
+ assert!(c.place_food(&mut fish, 3));
+ assert_eq!(c.items[1].as_ref().map(|s| &*s.item), Some("minecraft:cod"));
+ // cookTick: the cod is done on its third tick, the beef keeps cooking.
+ assert!(c.cook_tick().is_empty());
+ assert!(c.cook_tick().is_empty());
+ let done = c.cook_tick();
+ assert_eq!(done.len(), 1);
+ assert_eq!((done[0].0, &*done[0].1.item), (1, "minecraft:cod"));
+ assert!(c.items[1].is_none());
+ assert_eq!(c.progress[0], 3);
+ // cooldownTick: two a tick, never below zero.
+ assert!(c.cooldown_tick());
+ assert_eq!(c.progress[0], 1);
+ assert!(c.cooldown_tick());
+ assert_eq!(c.progress[0], 0);
+ // Full: four slots, no fifth.
+ for _ in 0..3 {
+ let mut more = ItemStack::new("minecraft:potato", 1);
+ assert!(c.place_food(&mut more, 600));
+ }
+ let mut fifth = ItemStack::new("minecraft:potato", 1);
+ assert!(!c.place_food(&mut fifth, 600));
+ assert_eq!(fifth.count, 1);
+ }
+
/// A whole amount pays itself without a draw; a fraction is a chance of one more.
#[test]
fn create_experience_rounds_the_fraction_by_chance() {
diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs
index 690383963..899ce90d9 100644
--- a/crates/horizon-client/src/crafting.rs
+++ b/crates/horizon-client/src/crafting.rs
@@ -1612,7 +1612,9 @@ impl Recipes {
}
/// The `experience` of the cooking recipe with this file name, and 0 for one this data
/// pack does not have (a save from another pack can name it).
+ /// `id` with or without the `minecraft:` namespace (a furnace keeps the full id).
pub fn cooking_experience(&self, id: &str) -> f32 {
+ let id = id.strip_prefix("minecraft:").unwrap_or(id);
self.cooking
.iter()
.find(|c| c.id == id)
diff --git a/crates/horizon-client/src/creative.rs b/crates/horizon-client/src/creative.rs
index 249e40b11..1a227db65 100644
--- a/crates/horizon-client/src/creative.rs
+++ b/crates/horizon-client/src/creative.rs
@@ -1,9 +1,14 @@
//! Creative inventory (CreativeModeInventoryScreen): vanilla's tabs and their
//! contents as built by the game's own display generators
//! (`creative-inventory.json`), a 9x5 scrolling grid and the search tab.
-use crate::{Result, items::ItemStack};
+use crate::{Result, items::ItemStack, ui::EditBox};
use serde_json::Value;
-use std::{collections::HashMap, fs, path::Path};
+use std::{
+ collections::HashMap,
+ fs,
+ path::Path,
+ sync::{Arc, Mutex},
+};
#[derive(Clone, Debug)]
pub struct Tab {
@@ -35,13 +40,22 @@ pub struct Creative {
pub scroll: f32,
/// The scrollbar is held (scrolling): dragging moves it.
pub scrolling: bool,
- pub search: String,
- /// When the search box took the focus (`EditBox.setFocused`): its
- /// cursor blinks from then.
- pub search_focused: std::time::Instant,
+ /// CreativeModeInventoryScreen's search box: an unbordered `EditBox` of 50.
+ pub search: EditBox,
/// The search tab's stacks, in its display order.
search_items: Vec,
search_index: Vec,
+ /// ItemPickerMenu.items: what the grid shows, filled when the tab or the
+ /// search changes (selectTab, refreshSearchResults), not on every frame.
+ shown: Mutex>,
+}
+/// The grid's stacks for one tab, search text and language.
+struct Shown {
+ tab: usize,
+ search: String,
+ /// A display name, so a language change refills the search results.
+ language: String,
+ items: Arc<[ItemStack]>,
}
/// Display names from the pinned en_us language file.
#[derive(Default)]
@@ -284,10 +298,16 @@ impl Creative {
selected: 0,
scroll: 0.0,
scrolling: false,
- search: String::new(),
- search_focused: std::time::Instant::now(),
+ search: {
+ let mut search = EditBox::new(0.0, 0.0, 80.0, 9.0);
+ search.bordered = false;
+ search.max_length = 50;
+ search.text_color = u32::MAX;
+ search
+ },
search_items,
search_index,
+ shown: Mutex::new(None),
}
}
/// Where a stack comes in the creative tabs (the search tab lists them
@@ -300,18 +320,35 @@ impl Creative {
.position(|s| s.same_item_same_components(stack))
.or_else(|| items.iter().position(|s| s.item == stack.item))
}
+ /// The tabs without their stacks: what the screen draws of them each frame.
+ pub fn tab_headers(&self) -> Vec {
+ self.tabs
+ .iter()
+ .map(|t| Tab {
+ id: t.id.clone(),
+ title: t.title.clone(),
+ icon: t.icon.clone(),
+ items: Vec::new(),
+ top: t.top,
+ column: t.column,
+ search: t.search,
+ inventory: t.inventory,
+ })
+ .collect()
+ }
pub fn tab(&self) -> &Tab {
&self.tabs[self.selected.min(self.tabs.len() - 1)]
}
/// selectTab: a different tab empties the search box; the scrollbar goes to the top.
pub fn select(&mut self, tab: usize) {
if tab != self.selected {
- self.search.clear();
+ self.search.set_value("");
}
self.selected = tab;
self.scroll = 0.0;
if self.tab().search {
- self.search_focused = std::time::Instant::now();
+ self.search.focused = true;
+ self.search.reset_blink();
}
}
/// The search tab's stacks.
@@ -380,17 +417,44 @@ impl Creative {
})
.collect()
}
- /// Items shown by the selected tab (the search tab filters by `search`).
- pub fn items(&self, names: &Names) -> Vec {
- let tab = self.tab();
- if tab.search {
- return self
- .search_results(&self.search, names)
+ /// Items shown by the selected tab (the search tab filters by `search`),
+ /// worked out again only when the tab, the search or the language changed.
+ pub fn items(&self, names: &Names) -> Arc<[ItemStack]> {
+ let tab = self.selected.min(self.tabs.len() - 1);
+ let search = if self.tab().search {
+ self.search.value.as_str()
+ } else {
+ ""
+ };
+ let language = names.display_get("itemGroup.search").unwrap_or_default();
+ let mut shown = self.shown.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some(s) = shown.as_ref()
+ && s.tab == tab
+ && s.search == search
+ && s.language == language
+ {
+ return s.items.clone();
+ }
+ let items: Arc<[ItemStack]> = if self.tab().search {
+ self.search_results(search, names)
.into_iter()
.map(|i| self.search_items[i].clone())
- .collect();
- }
- tab.items.clone()
+ .collect()
+ } else {
+ self.tab().items.as_slice().into()
+ };
+ *shown = Some(Shown {
+ tab,
+ search: search.to_owned(),
+ language,
+ items: items.clone(),
+ });
+ items
+ }
+ /// Drop the shown items, so the next `items` works them out again: a
+ /// reload can rename items without changing the Search label.
+ pub fn forget_items(&self) {
+ *self.shown.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
pub fn rows(&self, names: &Names) -> usize {
self.items(names).len().div_ceil(9)
@@ -754,13 +818,13 @@ mod tests {
(1, false, true),
(2, true, false),
] {
- c.search = "anvil".into();
+ c.search.set_value("anvil");
c.scroll = 0.5;
c.select(selected);
assert_eq!(c.selected, selected);
assert_eq!(c.tab().inventory, inventory);
assert_eq!(c.tab().search, search);
- assert!(c.search.is_empty());
+ assert!(c.search.value.is_empty());
assert_eq!(c.scroll, 0.0);
}
}
@@ -780,12 +844,12 @@ mod tests {
assert_eq!(c.tabs[0].items[0].item.as_ref(), "minecraft:anvil");
let mut c = c;
c.select(1);
- c.search = "anvil".into();
+ c.search.set_value("anvil");
c.scroll = 0.5;
c.select(1);
- assert_eq!((c.search.as_str(), c.scroll), ("anvil", 0.0));
+ assert_eq!((c.search.value.as_str(), c.scroll), ("anvil", 0.0));
c.select(0);
- assert_eq!(c.search, "");
+ assert_eq!(c.search.value, "");
}
#[test]
@@ -899,4 +963,25 @@ mod tests {
c.scroll = 1.0;
assert_eq!(c.scroller_offset(), 95.0);
}
+
+ #[test]
+ fn search_edits_at_its_cursor() {
+ use winit::keyboard::KeyCode;
+ let mut c = creative(0);
+ c.select(1);
+ c.search.insert_text("hello world");
+ for _ in 0..5 {
+ assert!(c.search.key(KeyCode::ArrowLeft, false, false));
+ }
+ c.search.insert_text("X");
+ assert_eq!(c.search.value, "hello Xworld");
+ c.search.key(KeyCode::Home, false, true);
+ c.search.insert_text("Y");
+ assert_eq!(c.search.value, "Yworld");
+ // Ctrl+Left jumps a word; one step right and Backspace deletes before the cursor.
+ c.search.key(KeyCode::ArrowLeft, true, false);
+ c.search.key(KeyCode::ArrowRight, false, false);
+ c.search.key(KeyCode::Backspace, false, false);
+ assert_eq!(c.search.value, "world");
+ }
}
diff --git a/crates/horizon-client/src/cushion.rs b/crates/horizon-client/src/cushion.rs
new file mode 100644
index 000000000..7610a4aab
--- /dev/null
+++ b/crates/horizon-client/src/cushion.rs
@@ -0,0 +1,59 @@
+//! Cushion placement and support checks (`Cushion.canBePlacedAt`/`wouldSurviveAt`).
+use horizon_core::geometry::{Aabb, ShapeOp, Vec3, VoxelShape};
+
+pub trait World {
+ fn outline_bounds(&self, pos: [i32; 3]) -> Option;
+ fn collision_shapes(&self, bounds: Aabb) -> Vec;
+ fn suffocating(&self, pos: [i32; 3]) -> bool;
+}
+
+pub fn blocks_in(a: Aabb) -> impl Iterator- {
+ let (lo, hi) = (a.min_position(), a.max_position());
+ let (x0, y0, z0) = (
+ lo.x.floor() as i32,
+ lo.y.floor() as i32,
+ lo.z.floor() as i32,
+ );
+ let (x1, y1, z1) = (
+ hi.x.floor() as i32,
+ hi.y.floor() as i32,
+ hi.z.floor() as i32,
+ );
+ (y0..=y1).flat_map(move |y| (z0..=z1).flat_map(move |z| (x0..=x1).map(move |x| [x, y, z])))
+}
+
+pub fn survives(world: &impl World, bounds: Aabb) -> bool {
+ let (lo, hi) = (bounds.min_position(), bounds.max_position());
+ let anchor = Aabb::new(
+ Vec3::new(lo.x, lo.y - 0.015625, lo.z),
+ Vec3::new(hi.x.next_down(), lo.y, hi.z.next_down()),
+ );
+ // The extra eighth block expands the scan, not the intersection test.
+ let supported = blocks_in(anchor.expand_towards(Vec3::new(0.0, -0.125, 0.0))).any(|p| {
+ world
+ .outline_bounds(p)
+ .is_some_and(|shape| shape.intersects(anchor))
+ });
+ supported && !blocks_in(bounds.next_deflated()).all(|p| world.suffocating(p))
+}
+
+pub fn can_place(world: &impl World, bounds: Aabb) -> bool {
+ if !survives(world, bounds) {
+ return false;
+ }
+ let (lo, hi) = (bounds.min_position(), bounds.max_position());
+ let slab = Aabb::new(lo, Vec3::new(hi.x, lo.y + 0.015625, hi.z)).next_deflated();
+ let Ok(mut remaining) = VoxelShape::from_box(slab) else {
+ return false;
+ };
+ for shape in world.collision_shapes(slab) {
+ let Ok(next) = remaining.join(&shape, ShapeOp::ONLY_FIRST) else {
+ return false;
+ };
+ remaining = next;
+ if remaining.is_empty() {
+ return false;
+ }
+ }
+ true
+}
diff --git a/crates/horizon-client/src/debug_overlay.rs b/crates/horizon-client/src/debug_overlay.rs
index 7140905a8..f55d4ee6e 100644
--- a/crates/horizon-client/src/debug_overlay.rs
+++ b/crates/horizon-client/src/debug_overlay.rs
@@ -221,18 +221,17 @@ pub fn scale(
pub fn draw(font: &Font, columns: [&[String]; 2], scale: f32, width: i32) -> Vec
{
let mut out = vec![GuiDraw::Push(vec![PoseOp::Scale(scale, scale)])];
for (lines, align_left) in [(columns[0], true), (columns[1], false)] {
- let placed: Vec<(&String, i32, i32)> = lines
+ let placed: Vec<(&String, i32, i32, i32)> = lines
.iter()
.enumerate()
.filter(|(_, l)| !l.is_empty())
.map(|(i, l)| {
let w = font.width(l) as i32;
let left = if align_left { 2 } else { width - 2 - w };
- (l, left, 2 + LINE_HEIGHT * i as i32)
+ (l, left, 2 + LINE_HEIGHT * i as i32, w)
})
.collect();
- for (line, left, top) in &placed {
- let w = font.width(line) as i32;
+ for (_, left, top, w) in &placed {
out.push(fill(
left - 1,
top - 1,
@@ -241,7 +240,7 @@ pub fn draw(font: &Font, columns: [&[String]; 2], scale: f32, width: i32) -> Vec
BACKGROUND,
));
}
- for (line, left, top) in placed {
+ for (line, left, top, _) in placed {
out.push(GuiDraw::Text {
text: Text::literal(line.clone()),
x: left,
diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs
index 2f418ae82..73b9bf090 100644
--- a/crates/horizon-client/src/enchant.rs
+++ b/crates/horizon-client/src/enchant.rs
@@ -545,6 +545,32 @@ impl Enchantments {
}
out
}
+ /// `EnchantmentHelper.forEachModifier` as an item's tooltip lists them: the
+ /// `minecraft:attributes` effects of `stack`'s enchantments as rows of
+ /// (attribute, id, amount, operation, slot group), one per slot group the
+ /// enchantment lists.
+ pub fn modifier_rows(&self, stack: &ItemStack) -> Vec<(String, String, f64, String, String)> {
+ let mut rows = Vec::new();
+ for (id, level) in stack.enchantments() {
+ let Some(e) = self.get(id) else { continue };
+ for a in e.effects["minecraft:attributes"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ {
+ for slot in &e.slots {
+ rows.push((
+ a["attribute"].as_str().unwrap_or("").to_owned(),
+ a["id"].as_str().unwrap_or("").to_owned(),
+ f64::from(level_value(&a["amount"], *level)),
+ a["operation"].as_str().unwrap_or("add_value").to_owned(),
+ slot.clone(),
+ ));
+ }
+ }
+ }
+ rows
+ }
/// Sum of `add_value` amounts of one attribute from enchantments on `stack`.
pub fn attribute_add(&self, stack: Option<&ItemStack>, attribute: &str) -> f64 {
stack.map_or(0.0, |s| {
diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs
index 6e8089e9d..44f07dc82 100644
--- a/crates/horizon-client/src/entities.rs
+++ b/crates/horizon-client/src/entities.rs
@@ -95,6 +95,15 @@ impl ItemEntity {
self.health -= fire_damage as i32;
}
}
+ // CactusBlock.entityInside: `entity.hurt(cactus, 1.0)`. An item has no
+ // hurt cooldown, so it loses 1 health every tick it touches a cactus
+ // (5 health: gone in 5 ticks). Fire resistance does not help;
+ // `ItemStack.canBeHurtBy` only skips it for a damage_resistant stack.
+ if crate::motion::environment::cactus_contact(world, registry, self.bounds())
+ && !items.resists_cactus(&self.stack)
+ {
+ self.health -= 1;
+ }
ItemEnvironmentTick {
alive: self.health > 0,
lava_hurt,
@@ -385,8 +394,29 @@ pub struct ExperienceOrb {
pub value: u32,
pub age: u32,
pub on_ground: bool,
+ /// `ExperienceOrb.count`: orbs merged into this one; each pickup gives
+ /// `value` once and takes one off.
+ pub count: u32,
+ /// `Entity.tickCount`, which paces `ExperienceOrb.scanForMerges`.
+ pub ticks: u32,
}
impl ExperienceOrb {
+ pub fn bounds(&self) -> Aabb {
+ let h = 0.25;
+ Aabb::new(
+ Vec3::new(self.position.x - h, self.position.y, self.position.z - h),
+ Vec3::new(
+ self.position.x + h,
+ self.position.y + 0.5,
+ self.position.z + h,
+ ),
+ )
+ }
+ /// `ExperienceOrb.canMerge(orb, id, value)` for an orb that is not removed:
+ /// the same value and ids a multiple of 40 apart.
+ pub fn can_merge(&self, id: u32, value: u32) -> bool {
+ self.value == value && (self.id as i32).wrapping_sub(id as i32) % 40 == 0
+ }
/// ExperienceOrb.getExperienceValue: the largest orb size not above `value`.
pub fn split(value: u32) -> u32 {
[2477, 1237, 617, 307, 149, 73, 37, 17, 7, 3, 1]
@@ -416,7 +446,9 @@ impl ExperienceOrb {
facts: &BlockFacts,
collision: &BlockCollisionRegistry<'_>,
player: Option<[f64; 3]>,
+ next_float: &mut dyn FnMut() -> f32,
) -> bool {
+ self.ticks += 1;
self.previous = self.position;
let block = world.block(
self.position.x.floor() as i32,
@@ -432,6 +464,14 @@ impl ExperienceOrb {
} else {
self.velocity.y -= 0.03;
}
+ if facts.get(block).fluid == Fluid::Lava {
+ // ExperienceOrb.tick: lava throws the orb back out.
+ self.velocity = Vec3::new(
+ f64::from((next_float() - next_float()) * 0.2),
+ f64::from(0.2f32),
+ f64::from((next_float() - next_float()) * 0.2),
+ );
+ }
if let Some(p) = player {
let d = [
(p[0] - self.position.x) / 8.0,
@@ -449,15 +489,7 @@ impl ExperienceOrb {
);
}
}
- let h = 0.25;
- let bounds = Aabb::new(
- Vec3::new(self.position.x - h, self.position.y, self.position.z - h),
- Vec3::new(
- self.position.x + h,
- self.position.y + 0.5,
- self.position.z + h,
- ),
- );
+ let bounds = self.bounds();
let mut scene = SceneCollisions {
world,
binding: collision,
@@ -494,6 +526,31 @@ impl ExperienceOrb {
self.age < 6000
}
}
+/// `ExperienceOrb.scanForMerges`, run by each orb on `tickCount % 20 == 1`:
+/// it absorbs the orbs that `canMerge` within 0.5 blocks of its box,
+/// adding their counts and keeping the smaller age.
+pub fn merge_orbs(orbs: &mut Vec) {
+ let mut removed = vec![false; orbs.len()];
+ for i in 0..orbs.len() {
+ if removed[i] || orbs[i].ticks % 20 != 1 {
+ continue;
+ }
+ let area = orbs[i].bounds().inflate(Vec3::new(0.5, 0.5, 0.5));
+ for j in 0..orbs.len() {
+ if j != i
+ && !removed[j]
+ && orbs[j].can_merge(orbs[i].id, orbs[i].value)
+ && orbs[j].bounds().intersects(area)
+ {
+ orbs[i].count += orbs[j].count;
+ orbs[i].age = orbs[i].age.min(orbs[j].age);
+ removed[j] = true;
+ }
+ }
+ }
+ let mut removed = removed.into_iter();
+ orbs.retain(|_| !removed.next().unwrap_or(false));
+}
/// Player experience (Player.giveExperiencePoints / getXpNeededForNextLevel).
#[derive(Clone, Copy, Debug, Default)]
pub struct Experience {
@@ -591,6 +648,57 @@ impl Painting {
)
}
}
+/// The `DyeColor` ordinal of a colour name (`DyeColor.byName`), white when
+/// the name is unknown.
+pub fn dye_index(name: &str) -> u8 {
+ crate::mobs::render::DYE_NAMES
+ .iter()
+ .position(|n| *n == name)
+ .unwrap_or(0) as u8
+}
+/// A cushion (`Cushion`, a `BlockAttachedEntity`): a 1 x 0.25 block pillow
+/// that seats a player. It sits on the top face of a block, at the clicked
+/// height, and is coloured by its `DyeColor`.
+#[derive(Clone, Debug)]
+pub struct Cushion {
+ pub id: u32,
+ /// `Entity.position`: the bottom centre of the cushion.
+ pub position: Vec3,
+ /// `BlockAttachedEntity.pos` (the saved `block_pos`).
+ pub pos: [i32; 3],
+ pub yaw: f32,
+ /// `DyeColor` ordinal: white 0, orange 1, ..., black 15.
+ pub color: u8,
+ /// BlockAttachedEntity.ticksSinceLastCheck.
+ pub check_interval: u32,
+}
+impl Cushion {
+ /// `Entity.makeBoundingBox`: x and z half a block out, y to y + 0.25.
+ pub fn bounds(&self) -> ([f64; 3], [f64; 3]) {
+ let p = self.position;
+ (
+ [p.x - 0.5, p.y, p.z - 0.5],
+ [p.x + 0.5, p.y + 0.25, p.z + 0.5],
+ )
+ }
+ /// The `DyeColor` name of the cushion.
+ pub fn color_name(&self) -> &'static str {
+ crate::mobs::render::DYE_NAMES[usize::from(self.color.min(15))]
+ }
+ /// `Cushion.getCushionItemStackWithData`: the matching coloured item.
+ pub fn item(&self) -> String {
+ format!("minecraft:{}_cushion", self.color_name())
+ }
+ /// `Cushion.interact`'s seat: the vehicle's PASSENGER attachment
+ /// `(0, 0.25, 0)` less the player's `(0, 0.6, 0)`.
+ pub fn seat(&self) -> Vec3 {
+ Vec3::new(self.position.x, self.position.y - 0.35, self.position.z)
+ }
+ /// `Entity.getDismountLocationForPassenger`: on top of the cushion.
+ pub fn dismount(&self) -> Vec3 {
+ Vec3::new(self.position.x, self.position.y + 0.25, self.position.z)
+ }
+}
/// An item frame or glow item frame (`ItemFrame`).
#[derive(Clone, Debug)]
pub struct ItemFrame {
diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl
index 2e865dfb1..79e11719f 100644
--- a/crates/horizon-client/src/entity.wgsl
+++ b/crates/horizon-client/src/entity.wgsl
@@ -166,12 +166,23 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
if d >= end { return 1.0; }
return (d - start) / (end - start);
}
+// CRUMBLING_UV_BEGIN
+fn crumbling_uv(uv: vec2, packed_origin: vec2, sprite_size: vec2, dimensions: vec2) -> vec2 {
+ let size = vec2(dimensions);
+ // Undo stage_light's 16-bit quantization before adding local texels. Otherwise
+ // different stages can fall on opposite sides of a nearest-sampling boundary.
+ let origin = round(packed_origin * size);
+ let extent = max(round(sprite_size * size), vec2(1.0));
+ let local = min(floor(fract(uv) * extent), extent - vec2(1.0));
+ return (origin + local + vec2(0.5)) / size;
+}
+// CRUMBLING_UV_END
@fragment fn fs_entity(in: Out, @builtin(front_facing) front: bool) -> @location(0) vec4 {
var uv = in.uv;
if in.overlay == 6u { uv.y = in.wrap.x + fract(in.uv.y) * in.wrap.y; }
if in.overlay == 11u || in.overlay == 12u {
// Each crack's stage sprite origin comes in its light bytes (breaking::stage_light).
- uv = in.wrap + fract(in.uv) * globals.crumbling_sprite.zw;
+ uv = crumbling_uv(in.uv, in.wrap, globals.crumbling_sprite.zw, textureDimensions(atlas));
}
var color = textureSample(atlas, atlas_sampler, uv) * select(in.back_color, in.color, front);
if in.overlay == 9u || in.overlay == 10u {
diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs
index 00576ea02..c49af48c9 100644
--- a/crates/horizon-client/src/entity_nbt.rs
+++ b/crates/horizon-client/src/entity_nbt.rs
@@ -6,7 +6,7 @@
//! survive a Horizon save.
use crate::{
arrows::Pickup,
- entities::{ArmorStand, ExperienceOrb, ItemEntity, ItemFrame, Painting},
+ entities::{ArmorStand, Cushion, ExperienceOrb, ItemEntity, ItemFrame, Painting},
mobs::{Mob, MobType, Who},
projectiles::{Projectile, ProjectileKind},
save::{
@@ -180,7 +180,6 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
("Silent", m.silent),
("NoGravity", m.no_gravity),
("Glowing", m.glowing),
- ("Invulnerable", m.invulnerable_flag),
] {
if on {
map.insert(key.into(), Tag::Byte(1));
@@ -188,6 +187,26 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
map.remove(&horizon_world::nbt::JavaString::from(key));
}
}
+ map.insert(
+ "Invulnerable".into(),
+ Tag::Byte(i8::from(m.invulnerable_flag)),
+ );
+ map.insert(
+ "LeftHanded".into(),
+ Tag::Byte(i8::from(m.extra.left_handed)),
+ );
+ // Keys of older formats that structure templates still carry.
+ for key in [
+ "HandItems",
+ "ArmorItems",
+ "HandDropChances",
+ "ArmorDropChances",
+ "Dimension",
+ "HurtByTimestamp",
+ "Leashed",
+ ] {
+ map.remove(&horizon_world::nbt::JavaString::from(key));
+ }
if m.ticks_frozen > 0 {
map.insert("TicksFrozen".into(), Tag::Int(m.ticks_frozen));
} else {
@@ -197,7 +216,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
("AbsorptionAmount", Tag::Float(0)),
("FallFlying", Tag::Byte(0)),
("CanPickUpLoot", Tag::Byte(i8::from(m.can_pick_up_loot()))),
- ("LeftHanded", Tag::Byte(0)),
+ ("current_impulse_context_reset_grace_time", Tag::Int(0)),
(
"Brain",
Tag::compound([("memories", Tag::Compound(Compound::new()))]),
@@ -209,7 +228,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
// Only breedable animals have an age; a loaded creature that was saved without
// one (a frog) stays without.
let aged = raw.is_none_or(|r| r.get("Age").is_some());
- if m.kind.category == "creature" && aged {
+ if (m.kind.category == "creature" || m.species() == crate::mobs::Species::Hoglin) && aged {
map.insert("Age".into(), Tag::Int(m.extra.age));
map.insert("AgeLocked".into(), Tag::Byte(i8::from(m.extra.age_locked)));
map.insert("ForcedAge".into(), Tag::Int(m.extra.forced_age));
@@ -260,11 +279,28 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
.or_insert_with(|| string("minecraft:classic"));
}
"minecraft:piglin" | "minecraft:piglin_brute" | "minecraft:hoglin" => {
+ // Only Piglin.addAdditionalSaveData writes CannotHunt.
+ if id == "minecraft:piglin_brute" {
+ map.remove(&"CannotHunt".into());
+ }
map.insert(
"IsImmuneToZombification".into(),
Tag::Byte(i8::from(m.extra.flag2)),
);
map.insert("TimeInOverworld".into(), Tag::Int(m.extra.counter2));
+ if id == "minecraft:piglin" {
+ // InventoryCarrier.writeInventoryToTag.
+ map.insert(
+ "Inventory".into(),
+ Tag::List(
+ m.extra
+ .inventory
+ .iter()
+ .map(crate::save::item_to_nbt)
+ .collect(),
+ ),
+ );
+ }
}
"minecraft:horse"
| "minecraft:donkey"
@@ -357,6 +393,12 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
"minecraft:bat" => {
map.insert("BatFlags".into(), Tag::Byte(i8::from(m.extra.flag)));
}
+ "minecraft:turtle" => {
+ map.insert("has_egg".into(), Tag::Byte(i8::from(m.extra.flag)));
+ if let Some(home) = m.extra.home {
+ map.insert("home_pos".into(), Tag::IntArray(home.to_vec()));
+ }
+ }
"minecraft:creaking" => {
// home_pos: the heart it is bound to.
if let Some(home) = m.extra.home {
@@ -479,10 +521,8 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
)])
});
}
- "minecraft:zombie" => {
- map.insert("IsBaby".into(), Tag::Byte(i8::from(m.is_baby())));
+ "minecraft:zombie" | "minecraft:husk" | "minecraft:drowned" => {
for (key, value) in [
- ("CanBreakDoors", Tag::Byte(0)),
("DrownedConversionTime", Tag::Int(-1)),
("InWaterTime", Tag::Int(-1)),
] {
@@ -507,6 +547,28 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
}
_ => {}
}
+ // Zombie.addAdditionalSaveData: CanBreakDoors.
+ if crate::mobs::doors::is_zombie(m.species()) {
+ map.insert(
+ "CanBreakDoors".into(),
+ Tag::Byte(i8::from(m.extra.can_break_doors)),
+ );
+ }
+ if matches!(
+ id,
+ "minecraft:zombie"
+ | "minecraft:husk"
+ | "minecraft:drowned"
+ | "minecraft:zombie_villager"
+ | "minecraft:zombified_piglin"
+ | "minecraft:piglin"
+ | "minecraft:zoglin"
+ ) {
+ map.insert("IsBaby".into(), Tag::Byte(i8::from(m.is_baby())));
+ }
+ if let Some(a) = m.extra.attributes.as_deref() {
+ put_attributes(map, m, a);
+ }
crate::mobs::raider::write_nbt(m, map);
crate::mobs::riders::write_nbt(m, map);
// LivingEntity equipment: what the mob holds now.
@@ -589,6 +651,89 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
}
tag
}
+/// `AttributeMap.pack` for the attributes with a base or permanent modifier
+/// finalizeSpawn set, over the saved list.
+fn put_attributes(map: &mut Compound, m: &Mob, a: &crate::mobs::finalize::Attributes) {
+ use crate::mobs::finalize::{self, Attr, Op};
+ let mut list = match map.get(&"attributes".into()) {
+ Some(Tag::List(l)) => l.clone(),
+ _ => Vec::new(),
+ };
+ for attr in Attr::ALL {
+ let modifiers: Vec = a
+ .modifiers
+ .iter()
+ .filter(|x| x.attr == attr)
+ .map(|x| {
+ let op = match x.op {
+ Op::AddValue => "add_value",
+ Op::AddMultipliedBase => "add_multiplied_base",
+ Op::AddMultipliedTotal => "add_multiplied_total",
+ };
+ Tag::compound([
+ ("id", string(x.id)),
+ ("amount", Tag::Double(x.amount.to_bits())),
+ ("operation", string(op)),
+ ])
+ })
+ .collect();
+ if modifiers.is_empty() && !a.bases.iter().any(|(b, _)| *b == attr) {
+ continue;
+ }
+ let id = format!("minecraft:{}", attr.name());
+ let mut entry = vec![
+ ("id", string(&id)),
+ ("base", Tag::Double(finalize::base_value(m, attr).to_bits())),
+ ];
+ if !modifiers.is_empty() {
+ entry.push(("modifiers", Tag::List(modifiers)));
+ }
+ let entry = Tag::compound(entry);
+ match list
+ .iter_mut()
+ .find(|t| text(t.get("id")).as_deref() == Some(id.as_str()))
+ {
+ Some(t) => *t = entry,
+ None => list.push(entry),
+ }
+ }
+ map.insert("attributes".into(), Tag::List(list));
+}
+/// `Brain.Packed`: the memories finalizeSpawn set, over the saved ones.
+pub fn put_brain(map: &mut Compound, m: &Mob, dimension: &str) {
+ if m.extra.memories.is_empty() {
+ return;
+ }
+ let mut memories = match map.get(&"Brain".into()).and_then(|b| b.get("memories")) {
+ Some(Tag::Compound(c)) => c.clone(),
+ _ => Compound::new(),
+ };
+ for &(name, value, ttl) in &m.extra.memories {
+ let value = match name {
+ "hunted_recently" => Tag::Byte(value as i8),
+ "home" => match m.extra.home {
+ Some(p) => Tag::compound([
+ ("dimension", string(dimension)),
+ ("pos", Tag::IntArray(p.to_vec())),
+ ]),
+ None => continue,
+ },
+ _ => Tag::Int(value as i32),
+ };
+ let mut memory = vec![("value", value)];
+ if ttl != i64::MAX {
+ memory.push(("ttl", Tag::Long(ttl)));
+ }
+ memories.insert(
+ format!("minecraft:{name}").as_str().into(),
+ Tag::compound(memory),
+ );
+ }
+ map.insert(
+ "Brain".into(),
+ Tag::compound([("memories", Tag::Compound(memories))]),
+ );
+}
/// `CustomName`: a text component saved as a string or a `{text: ..}` compound.
fn custom_name(tag: &Tag) -> Option {
match tag.get("CustomName")? {
@@ -608,6 +753,22 @@ pub fn name_text(tag: &Tag) -> Text {
t => crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t)),
}
}
+/// Mob.finalizeSpawn's follow range bonus in the saved attributes.
+pub(crate) fn spawn_bonus(tag: &Tag) -> Option {
+ let Some(Tag::List(attrs)) = tag.get("attributes") else {
+ return None;
+ };
+ let range = attrs
+ .iter()
+ .find(|a| text(a.get("id")).as_deref() == Some("minecraft:follow_range"))?;
+ let Some(Tag::List(modifiers)) = range.get("modifiers") else {
+ return None;
+ };
+ let bonus = modifiers
+ .iter()
+ .find(|x| text(x.get("id")).as_deref() == Some("minecraft:random_spawn_bonus"))?;
+ float(bonus.get("amount"))
+}
pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) -> Option {
let kind = types.get(&self::kind(tag)?)?.clone();
let position = position(tag)?;
@@ -633,6 +794,11 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) -
}
}
}
+ if let Some(bonus) = spawn_bonus(tag) {
+ use crate::mobs::finalize::{Attr, Op, add_modifier};
+ let id = "minecraft:random_spawn_bonus";
+ add_modifier(&mut m, Attr::FollowRange, id, bonus, Op::AddMultipliedBase);
+ }
m.health = float(tag.get("Health")).map_or(m.attrs.max_health, |h| h as f32);
m.hurt_time = number(tag.get("HurtTime")).unwrap_or(0) as i32;
// What it holds (equipment.mainhand / offhand), when saved.
@@ -674,7 +840,8 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) -
m.extra.pick_up_loot = flag(tag, "CanPickUpLoot");
m.custom_name = custom_name(tag);
m.custom_name_text = tag.get("CustomName").map(name_text);
- if m.kind.category == "creature" {
+ m.extra.left_handed = flag(tag, "LeftHanded");
+ if m.kind.category == "creature" || m.species() == crate::mobs::Species::Hoglin {
m.extra.age = number(tag.get("Age")).unwrap_or(0) as i32;
m.extra.forced_age = number(tag.get("ForcedAge")).unwrap_or(0) as i32;
m.extra.age_locked = flag(tag, "AgeLocked");
@@ -706,6 +873,16 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) -
) {
m.extra.flag2 = flag(tag, "IsImmuneToZombification");
m.extra.counter2 = number(tag.get("TimeInOverworld")).unwrap_or(0) as i32;
+ if m.species() == crate::mobs::Species::Piglin
+ && let Some(Tag::List(items)) = tag.get("Inventory")
+ {
+ // InventoryCarrier.readInventoryFromTag (eight slots).
+ m.extra.inventory = items
+ .iter()
+ .filter_map(crate::save::item_from_nbt)
+ .take(8)
+ .collect();
+ }
}
if matches!(
m.species(),
@@ -847,6 +1024,18 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) -
{
crate::mobs::creaking::set_transient(&mut m, [home[0], home[1], home[2]]);
}
+ if m.species() == crate::mobs::Species::Turtle {
+ // Turtle.readAdditionalSaveData: `home_pos` (else where it stands) and `has_egg`.
+ m.extra.flag = flag(tag, "has_egg");
+ m.extra.home = Some(match tag.get("home_pos") {
+ Some(Tag::IntArray(home)) if home.len() == 3 => [home[0], home[1], home[2]],
+ _ => [
+ m.position.x.floor() as i32,
+ m.position.y.floor() as i32,
+ m.position.z.floor() as i32,
+ ],
+ });
+ }
if m.species() == crate::mobs::Species::Wither {
m.extra.counter = number(tag.get("Invul")).unwrap_or(0) as i32;
}
@@ -925,6 +1114,10 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) -
if !crate::mobs::finalize::ageable(m.species()) && flag(tag, "IsBaby") {
crate::mobs::finalize::set_baby(&mut m, true);
}
+ // Zombie.readAdditionalSaveData: setCanBreakDoors.
+ if crate::mobs::doors::is_zombie(m.species()) {
+ crate::mobs::doors::set_can_break_doors(&mut m, flag(tag, "CanBreakDoors"));
+ }
crate::mobs::raider::read_nbt(&mut m, tag);
crate::mobs::riders::read_nbt(&mut m, tag);
// A mob saved mid-death finishes dying; one saved dead is dropped.
@@ -1043,18 +1236,18 @@ pub fn orb_to_nbt(o: &ExperienceOrb, uuid: [i32; 4]) -> Tag {
("Health", Tag::Short(5)),
("Age", Tag::Short(o.age.min(i16::MAX as u32) as i16)),
("Value", Tag::Short(o.value.min(i16::MAX as u32) as i16)),
- ("Count", Tag::Int(1)),
+ ("Count", Tag::Int(o.count.min(i32::MAX as u32) as i32)),
] {
put(&mut tag, key, value);
}
tag
}
-/// One Horizon orb per counted orb (vanilla merges orbs of equal value).
+/// One orb with its merged `Count`.
pub fn orbs_from_nbt(tag: &Tag) -> Vec {
let Some(position) = position(tag) else {
return Vec::new();
};
- let count = number(tag.get("Count")).unwrap_or(1).clamp(1, 64) as usize;
+ let count = number(tag.get("Count")).unwrap_or(1).max(1) as u32;
let orb = ExperienceOrb {
id: 0,
position,
@@ -1063,8 +1256,10 @@ pub fn orbs_from_nbt(tag: &Tag) -> Vec {
value: number(tag.get("Value")).unwrap_or(1).max(1) as u32,
age: number(tag.get("Age")).unwrap_or(0).max(0) as u32,
on_ground: flag(tag, "OnGround"),
+ count,
+ ticks: 0,
};
- vec![orb; count]
+ vec![orb]
}
/// `Projectile` + `AbstractArrow.addAdditionalSaveData` of a live arrow;
@@ -1313,6 +1508,79 @@ pub fn painting_from_nbt(tag: &Tag) -> Option<([i32; 3], u8, String)> {
let facing = (number(tag.get("facing")).unwrap_or(0) & 3) as u8;
Some((pos, facing, text(tag.get("variant"))?))
}
+/// Cushion.addAdditionalSaveData: the block it sits on and its colour.
+pub fn cushion_to_nbt(c: &Cushion, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
+ let base = Base {
+ id: "minecraft:cushion",
+ uuid,
+ position: c.position,
+ motion: Vec3::ZERO,
+ rotation: [c.yaw, 0.0],
+ on_ground: false,
+ fall_distance: 0.0,
+ };
+ let mut tag = base.tag(raw);
+ put(&mut tag, "block_pos", Tag::IntArray(c.pos.to_vec()));
+ put(&mut tag, "color", string(c.color_name()));
+ tag
+}
+/// The position, block position, yaw and colour of a saved cushion.
+pub fn cushion_from_nbt(tag: &Tag, id: u32) -> Option {
+ let position = position(tag)?;
+ let pos = match tag.get("block_pos") {
+ Some(Tag::IntArray(v)) if v.len() == 3 => [v[0], v[1], v[2]],
+ _ => [
+ position.x.floor() as i32,
+ position.y.floor() as i32,
+ position.z.floor() as i32,
+ ],
+ };
+ let yaw = match tag.get("Rotation") {
+ Some(Tag::List(l)) => l
+ .first()
+ .and_then(|v| crate::save::float(Some(v)))
+ .unwrap_or(0.0) as f32,
+ _ => 0.0,
+ };
+ let color =
+ crate::entities::dye_index(&text(tag.get("color")).unwrap_or_else(|| "white".into()));
+ Some(Cushion {
+ id,
+ position,
+ pos,
+ yaw,
+ color,
+ check_interval: 0,
+ })
+}
+
+#[cfg(test)]
+mod cushion_tests {
+ use super::*;
+
+ #[test]
+ fn cushion_save_preserves_color_anchor_rotation_and_unknown_data() {
+ let cushion = Cushion {
+ id: 7,
+ position: Vec3::new(-1.5, 64.5, 3.5),
+ pos: [-2, 64, 3],
+ yaw: 270.0,
+ color: 14,
+ check_interval: 55,
+ };
+ let raw = Tag::compound([("CustomName", string("Seat"))]);
+ let tag = cushion_to_nbt(&cushion, [1, 2, 3, 4], Some(&raw));
+ assert_eq!(text(tag.get("CustomName")).as_deref(), Some("Seat"));
+ let loaded = cushion_from_nbt(&tag, 8).unwrap();
+ assert_eq!(loaded.id, 8);
+ assert_eq!(loaded.position, cushion.position);
+ assert_eq!(loaded.pos, cushion.pos);
+ assert_eq!(loaded.yaw, cushion.yaw);
+ assert_eq!(loaded.color_name(), "red");
+ assert_eq!(loaded.check_interval, 0);
+ assert_eq!(loaded.bounds(), cushion.bounds());
+ }
+}
/// ItemFrame.addAdditionalSaveData.
pub fn item_frame_to_nbt(f: &ItemFrame, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
let (lo, hi) = f.bounds();
@@ -1840,7 +2108,7 @@ mod tests {
assert_eq!(number(tag.get("Health")), Some(5));
}
#[test]
- fn orbs_expand_their_count() {
+ fn orbs_keep_their_count() {
let o = ExperienceOrb {
id: 0,
position: Vec3::new(1.0, 2.0, 3.0),
@@ -1849,12 +2117,14 @@ mod tests {
value: 7,
age: 3,
on_ground: false,
+ count: 3,
+ ticks: 0,
};
- let mut tag = orb_to_nbt(&o, [0; 4]);
- put(&mut tag, "Count", Tag::Int(3));
+ let tag = orb_to_nbt(&o, [0; 4]);
let back = orbs_from_nbt(&tag);
- assert_eq!(back.len(), 3);
+ assert_eq!(back.len(), 1);
assert_eq!(back[0].value, 7);
+ assert_eq!(back[0].count, 3);
}
}
@@ -1919,12 +2189,39 @@ fn restore_axolotl_memories(m: &mut Mob, tag: &Tag) {
}
}
const AXOLOTL_VARIANTS: [&str; 5] = ["lucy", "wild", "gold", "cyan", "blue"];
+/// `Salmon.Variant` names, by id.
+const SALMON_SIZES: [&str; 3] = ["small", "medium", "large"];
+/// `TropicalFish.Pattern` names in enum order: the six small patterns, then
+/// the six large ones (the order of `extra.variant`).
+const TROPICAL_PATTERNS: [&str; 12] = [
+ "kob",
+ "sunstreak",
+ "snooper",
+ "dasher",
+ "brinely",
+ "spotty",
+ "flopper",
+ "stripey",
+ "glitter",
+ "blockfish",
+ "betty",
+ "clayfish",
+];
+/// `Bucketable.saveDefaultDataToBucketTag`, with the age an axolotl and a
+/// tadpole add (`saveToBucketTag`).
pub fn bucket_data(m: &Mob) -> Tag {
- let mut data = Tag::compound([
- ("Age", Tag::Int(m.extra.age)),
- ("AgeLocked", Tag::Byte(i8::from(m.extra.age_locked))),
- ("Health", Tag::Float(m.health.to_bits())),
- ]);
+ let mut data = Tag::compound([("Health", Tag::Float(m.health.to_bits()))]);
+ if matches!(
+ m.species(),
+ crate::mobs::Species::Axolotl | crate::mobs::Species::Tadpole
+ ) {
+ put(&mut data, "Age", Tag::Int(m.extra.age));
+ put(
+ &mut data,
+ "AgeLocked",
+ Tag::Byte(i8::from(m.extra.age_locked)),
+ );
+ }
for (key, on) in [
("NoAI", m.no_ai),
("Silent", m.silent),
@@ -1954,6 +2251,29 @@ pub fn bucket_components(m: &Mob) -> crate::item_data::StackData {
.unwrap_or(&"lucy");
data.set_other("minecraft:axolotl/variant", Some(string(variant)));
}
+ // Salmon.saveToBucketTag: the size.
+ if m.species() == crate::mobs::Species::Salmon {
+ let size = SALMON_SIZES
+ .get(usize::from(m.extra.variant))
+ .unwrap_or(&"medium");
+ data.set_other("minecraft:salmon/size", Some(string(size)));
+ }
+ // TropicalFish.saveToBucketTag: the pattern and both colours.
+ if m.species() == crate::mobs::Species::TropicalFish {
+ let dye = |i: u8| crate::mobs::render::DYE_NAMES[usize::from(i) & 15];
+ let pattern = TROPICAL_PATTERNS
+ .get(usize::from(m.extra.variant))
+ .unwrap_or(&"kob");
+ data.set_other("minecraft:tropical_fish/pattern", Some(string(pattern)));
+ data.set_other(
+ "minecraft:tropical_fish/base_color",
+ Some(string(dye(m.extra.variant2))),
+ );
+ data.set_other(
+ "minecraft:tropical_fish/pattern_color",
+ Some(string(dye(m.extra.variant3))),
+ );
+ }
data
}
pub fn load_bucket_data(m: &mut Mob, stack: &crate::items::ItemStack) {
@@ -2004,6 +2324,39 @@ pub fn load_bucket_data(m: &mut Mob, stack: &crate::items::ItemStack) {
{
m.extra.variant = id as u8;
}
+ // Salmon.applyImplicitComponents: the size.
+ if m.species() == crate::mobs::Species::Salmon
+ && let Some(name) = text(components.other("minecraft:salmon/size"))
+ && let Some(id) = SALMON_SIZES
+ .iter()
+ .position(|&v| v == name.trim_start_matches("minecraft:"))
+ {
+ m.extra.variant = id as u8;
+ }
+ // TropicalFish.applyImplicitComponent: the pattern and both colours.
+ if m.species() == crate::mobs::Species::TropicalFish {
+ let name = |key| text(components.other(key));
+ let dye = |key| {
+ name(key).and_then(|n| {
+ crate::mobs::render::DYE_NAMES
+ .iter()
+ .position(|&v| v == n.trim_start_matches("minecraft:"))
+ })
+ };
+ if let Some(id) = name("minecraft:tropical_fish/pattern").and_then(|n| {
+ TROPICAL_PATTERNS
+ .iter()
+ .position(|&v| v == n.trim_start_matches("minecraft:"))
+ }) {
+ m.extra.variant = id as u8;
+ }
+ if let Some(id) = dye("minecraft:tropical_fish/base_color") {
+ m.extra.variant2 = id as u8;
+ }
+ if let Some(id) = dye("minecraft:tropical_fish/pattern_color") {
+ m.extra.variant3 = id as u8;
+ }
+ }
}
#[cfg(test)]
diff --git a/crates/horizon-client/src/falling_block.rs b/crates/horizon-client/src/falling_block.rs
index 79ca28f7a..4faf105b9 100644
--- a/crates/horizon-client/src/falling_block.rs
+++ b/crates/horizon-client/src/falling_block.rs
@@ -35,6 +35,18 @@ impl Damage {
..Self::default()
}
}
+ /// A block that starts to fall: anvils hurt, and a brushable block
+ /// breaks where it lands (BrushableBlock.tick: disableDrop).
+ pub fn falling(block: &str) -> Self {
+ if block.ends_with("anvil") {
+ Self::anvil()
+ } else {
+ Self {
+ cancel_drop: block.starts_with("minecraft:suspicious_"),
+ ..Self::default()
+ }
+ }
+ }
pub fn from_nbt(tag: &Tag, anvil: bool) -> Self {
Self {
hurt_entities: number(tag.get("HurtEntities")).map_or(anvil, |v| v != 0),
@@ -181,6 +193,14 @@ pub fn hurt_mobs(mobs: &mut [Mob], position: Vec3, amount: f32) {
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn only_brushable_blocks_break_where_they_land() {
+ assert!(Damage::falling("minecraft:suspicious_gravel").cancel_drop);
+ assert!(Damage::falling("minecraft:suspicious_sand").cancel_drop);
+ assert!(!Damage::falling("minecraft:gravel").cancel_drop);
+ assert!(Damage::falling("minecraft:chipped_anvil").hurt_entities);
+ }
+
#[test]
fn impact_uses_ceil_distance_capped_damage_and_positive_damage_wear() {
let damage = Damage::anvil();
diff --git a/crates/horizon-client/src/font.rs b/crates/horizon-client/src/font.rs
index 1903cab7e..d0e8c8499 100644
--- a/crates/horizon-client/src/font.rs
+++ b/crates/horizon-client/src/font.rs
@@ -1201,6 +1201,31 @@ mod tests {
assert!(!font.take_patches().is_empty());
}
+ /// A renderer rebuilt over the same font (the loading screen's handoff)
+ /// makes its atlas texture from the textures alone, so the glyphs it had
+ /// rasterized into the previous texture must be placed into the new one.
+ #[test]
+ fn a_rebuilt_atlas_gets_its_glyphs_again() {
+ let sheet = png(16, 8, |x, _| x < 2 || (8..14).contains(&x));
+ let default = br#"{"providers":[{"type":"bitmap","file":"minecraft:font/a.png","ascent":7,"chars":["ab"]}]}"#;
+ let root = root(
+ "rebuild",
+ &[
+ ("assets/minecraft/font/default.json", default),
+ ("assets/minecraft/textures/font/a.png", &sheet),
+ ],
+ );
+ let font = load(&root);
+ let _ = std::fs::remove_dir_all(&root);
+ let first = font.glyph('a');
+ assert_eq!(font.take_patches().len(), 1);
+ font.reset_cache();
+ // Nothing is left over: drawing the character again places its pixels.
+ assert!(font.take_patches().is_empty());
+ assert_eq!(font.glyph('a').advance, first.advance);
+ assert_eq!(font.take_patches().len(), 1);
+ }
+
#[test]
fn provider_filters_follow_the_font_options() {
let sheet = png(8, 8, |x, _| x < 4);
diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs
index f042bc28d..23e28eab7 100644
--- a/crates/horizon-client/src/game.rs
+++ b/crates/horizon-client/src/game.rs
@@ -18,6 +18,9 @@ mod boats;
mod books;
mod bossbars;
mod breezes;
+mod bundles;
+mod campfire;
+mod campfire_douse;
mod cartography;
mod chat;
mod client_ambient;
@@ -33,6 +36,7 @@ mod copper_golems;
mod creaking;
mod creatures;
mod crossbow;
+pub(crate) mod cushions;
mod debug_keys;
mod decorated_pot;
mod dedicated;
@@ -80,6 +84,7 @@ mod lan_mobs;
mod lan_mount_menu;
mod lan_particles;
mod lan_pvp;
+mod lan_quiet;
mod lan_screen;
mod lan_stations;
mod lan_trading;
@@ -98,7 +103,12 @@ mod maps;
mod minecarts;
mod mob_blocks;
mod mob_gear;
+mod mod_browser;
+#[cfg(feature = "mods")]
+mod mod_browser_recipes;
mod mod_input;
+#[cfg(feature = "mods")]
+mod mod_recipes;
mod mod_render;
mod mods;
mod mount_menu;
@@ -147,6 +157,7 @@ mod scoreboard;
mod screens;
mod sculk;
mod sculk_fixture;
+mod server_mods;
mod server_packs;
mod server_travel;
mod shader_packs;
@@ -181,6 +192,7 @@ mod win;
mod wind;
mod wither;
mod world_loading;
+mod zombie_reinforcements;
mod zombie_villagers;
use horizon_client::{
Result,
@@ -364,7 +376,7 @@ impl Options {
match arg.as_str() {
"--help" | "-h" => {
println!(
- "Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --width N, --height N Window size (default 1280 x 720)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --in-frame Run single player's world in the frame, not on its server thread\n --pregen Add Horizon's /pregen command (docs/pregeneration.md)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.",
+ "Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --width N, --height N Window size (default 1280 x 720)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --quickPlaySingleplayer WORLD Open this world of saves/ at start, only if it exists (vanilla's)\n --quickPlayMultiplayer HOST[:PORT] The same as --server (vanilla's name)\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --in-frame Run single player's world in the frame, not on its server thread\n --pregen Add Horizon's /pregen command (docs/pregeneration.md)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.",
horizon_core::VANILLA_VERSION
);
return Ok(None);
@@ -419,6 +431,16 @@ impl Options {
"--width" => o.window_size[0] = value.parse::()?.max(1),
"--height" => o.window_size[1] = value.parse::()?.max(1),
"--world" => o.world = Some(value),
+ // Vanilla's quick play (Main, QuickPlay.joinSingleplayerWorld): only a
+ // world that exists opens; else the title screen. --world also creates one.
+ "--quickPlaySingleplayer" => {
+ let folder = std::env::current_dir()?.join("saves").join(&value);
+ if folder.join("level.dat").is_file() {
+ o.world = Some(value);
+ } else {
+ eprintln!("Quick play: there is no world {value} in saves/");
+ }
+ }
"--dev-mod" => o.dev_mods.push(std::path::absolute(&value)?),
"--benchmark" => {
if horizon_client::benchmark::scenes(&value).is_none() {
@@ -429,7 +451,7 @@ impl Options {
}
o.benchmark = Some(value);
}
- "--server" => o.server = Some(value),
+ "--server" | "--quickPlayMultiplayer" => o.server = Some(value),
"--name" => o.player_name = Some(value),
"--session-file" => session_file = Some(value),
"--control-socket" => o.control = Some(value.into()),
@@ -532,6 +554,8 @@ struct GameLevel<'w> {
events: &'w mut Vec,
dimension: LevelDimension,
darken: i32,
+ /// The environment of the level's dimension (`SUN_ANGLE`).
+ environment: &'w Environment,
raining: bool,
thundering: bool,
player_box: Option<([f64; 3], [f64; 3])>,
@@ -540,6 +564,8 @@ struct GameLevel<'w> {
player_collision: Option,
/// Minecart boxes (detector rails).
cart_boxes: Vec<([f64; 3], [f64; 3])>,
+ /// Arrow and thrown trident boxes (wooden buttons).
+ arrow_boxes: Vec<([f64; 3], [f64; 3])>,
/// The other entities that keep blocks from being placed into them.
blockers: Blockers<'w>,
biomes: &'w Biomes,
@@ -552,6 +578,11 @@ struct GameLevel<'w> {
loot: Option>,
registry: &'static horizon_world::registry::BlockRegistry,
rules: horizon_world::level::GameRules,
+ /// `Difficulty.getId()` (peaceful 0 .. hard 3).
+ difficulty: i32,
+ /// The feet of the players who keep fire spreading around them: the local
+ /// player and the LAN guests in this level, spectators aside.
+ fire_players: Vec<[f64; 3]>,
/// Block loot random sequences (`ServerLevel.getRandomSequence`).
rand_sequences: &'w mut horizon_client::random_sequences::RandomSequences,
pending: &'w mut spill::Pending,
@@ -561,6 +592,9 @@ struct GameLevel<'w> {
random_tick_sections: &'w mut horizon_client::random_tick_sections::RandomTickSections,
/// Players with each chest open (a trapped chest's signal).
lid_openers: &'w HashMap<(i32, i32, i32), i32>,
+ /// `Level.isClientSide`: a client's copy of the level (a guest of a LAN
+ /// world, a window on its server thread, a dedicated server's client).
+ client_side: bool,
}
struct PlayerCollision {
y: f64,
@@ -650,6 +684,9 @@ impl GameLevel<'_> {
}
}
impl LevelAccess for GameLevel<'_> {
+ fn is_client_side(&self) -> bool {
+ self.client_side
+ }
fn world_surface(&self, x: i32, z: i32) -> i32 {
self.world.world_surface(x, z, |s| self.facts.is_air(s))
}
@@ -715,6 +752,34 @@ impl LevelAccess for GameLevel<'_> {
fn game_rules(&self) -> horizon_world::level::GameRules {
self.rules
}
+ fn difficulty(&self) -> i32 {
+ self.difficulty
+ }
+ /// `ServerLevel.canSpreadFireAround`: a player (not a spectator) closer
+ /// than the `fire_spread_radius_around_player` rule to the block's corner
+ /// (`ChunkMap.anyPlayerCloseEnoughTo`); -1 spreads everywhere.
+ fn can_spread_fire_around(&self, pos: BlockPos) -> bool {
+ let radius = self.rules.fire_spread_radius_around_player;
+ radius == -1
+ || self.fire_players.iter().any(|p| {
+ let d = [
+ p[0] - f64::from(pos.x),
+ p[1] - f64::from(pos.y),
+ p[2] - f64::from(pos.z),
+ ];
+ d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < f64::from(radius) * f64::from(radius)
+ })
+ }
+ fn increased_fire_burnout(&self, pos: BlockPos) -> bool {
+ self.world
+ .chunks
+ .get(&(pos.x >> 4, pos.z >> 4))
+ .is_some_and(|chunk| {
+ self.biomes
+ .get(chunk.biome(pos.x, pos.y, pos.z))
+ .increased_fire_burnout
+ })
+ }
fn block_state(&self, pos: BlockPos) -> BlockStateId {
self.world.block(pos.x, pos.y, pos.z)
}
@@ -759,6 +824,11 @@ impl LevelAccess for GameLevel<'_> {
fn sky_darken(&self) -> i32 {
self.darken
}
+ fn sun_angle(&self, _pos: BlockPos) -> f32 {
+ self.environment
+ .sample(self.world.day_time, None, None)
+ .sun_angle
+ }
fn is_raining(&self) -> bool {
self.raining
}
@@ -827,8 +897,9 @@ impl LevelAccess for GameLevel<'_> {
fn is_ticking_chunk(&self, chunk: horizon_core::position::ChunkPos) -> bool {
self.tickets.block_ticking(chunk.x, chunk.z) && ticking_chunk(self.world, chunk.x, chunk.z)
}
- /// Entities that trigger pressure plates, tripwires and detector rails:
- /// the players (the host and the LAN guests, mobs) and the minecarts.
+ /// Entities that trigger pressure plates, tripwires, detector rails and
+ /// wooden buttons: the players (the host and the LAN guests, mobs) and
+ /// the minecarts, and for `EntityQuery::Arrows` the arrows.
fn count_entities(&self, area: Aabb, query: EntityQuery) -> usize {
let hit = |(lo, hi): &([f64; 3], [f64; 3])| {
area.intersects(Aabb::new(
@@ -837,6 +908,7 @@ impl LevelAccess for GameLevel<'_> {
))
};
let carts = || self.cart_boxes.iter().filter(|b| hit(b)).count();
+ let arrows = || self.arrow_boxes.iter().filter(|b| hit(b)).count();
let players = || {
self.player_box
.iter()
@@ -846,6 +918,7 @@ impl LevelAccess for GameLevel<'_> {
};
match query {
EntityQuery::Minecart => carts(),
+ EntityQuery::Arrows => arrows(),
EntityQuery::Mobs => players(),
EntityQuery::Everything => players() + carts(),
}
@@ -853,7 +926,16 @@ impl LevelAccess for GameLevel<'_> {
fn emit(&mut self, event: LevelEvent) {
match event {
// Block.dropResources draws its loot and spots right away.
- LevelEvent::DropResources { pos, state } => self.drop_resources_now(pos, state),
+ // `popResource` only drops server-side (`!level.isClientSide`):
+ // a client's moveBlocks (a piston's block event) skips it.
+ LevelEvent::DropResources { pos, state } if !self.client_side => {
+ self.drop_resources_now(pos, state)
+ }
+ LevelEvent::DropResources { .. } => {}
+ // `ClientLevel.playSeededSound` plays only when the excluded
+ // player is this client's own: the block's `playSound(null, ...)`
+ // (a piston's move, a note) reaches it from the server instead.
+ LevelEvent::Sound { .. } if self.client_side => {}
// Block.popResource of the block's own item (tall flowers, flower beds).
LevelEvent::BlockEvent {
pos,
@@ -1194,6 +1276,8 @@ struct Game<'a> {
inv_clicks: horizon_client::container_screen::Clicks,
/// The Mouse Tweaks extra's drag and wheel (`tweaks`).
tweaks: tweaks::Tweaks,
+ /// The wheel and hovered slot of `BundleMouseActions`.
+ bundle_mouse: bundles::BundleMouse,
/// The last inventory click, for the double click that gathers a stack.
last_inv_click: Option<(std::time::Instant, usize, bool)>,
/// `lastQuickMoved`: what the last Shift click moved, which a Shift
@@ -1266,6 +1350,13 @@ struct Game<'a> {
/// Controllers (Horizon's own).
pad: pad::Pads,
frames: u64,
+ /// `item_level` for one frame, game time, day time and dimension.
+ item_level_cache: std::cell::RefCell<
+ Option<(
+ (u64, i64, i64, &'static str),
+ horizon_assets::item_model::LevelState,
+ )>,
+ >,
/// Frames drawn with the player in the world, for `--world-frames`.
world_frames: u64,
fps: f32,
@@ -1354,6 +1445,10 @@ struct Game<'a> {
titles: titles::Titles,
/// `Hud.toolHighlightTimer`: the selected item name.
tool_highlight: horizon_client::hud_overlays::ToolHighlight,
+ /// `Hud.autosaveIndicatorValue`.
+ saving_indicator: horizon_client::hud_overlays::SavingIndicator,
+ /// This game's world is autosaving this tick (`MinecraftServer.isSaving`).
+ autosaving: bool,
applied_modifiers: Vec<(String, String)>,
experience: Experience,
orbs: Vec,
@@ -1429,6 +1524,8 @@ struct Game<'a> {
map_frame_model: frames::FrameModel,
glow_map_frame_model: frames::FrameModel,
armor_stands: Vec,
+ /// `Cushion` decoration entities (game/cushions.rs).
+ cushions: Vec,
/// Entities of types Horizon does not simulate.
others: Vec,
armor_stand_assets: armor_stands::ArmorStandAssets,
@@ -1444,6 +1541,8 @@ struct Game<'a> {
boat_models: boats::BoatModels,
/// EndCrystalModel's baked layer.
crystal_model: Option,
+ /// CushionModel's baked layer.
+ cushion_model: Option,
carts: Vec,
/// Songs playing from jukeboxes (tracked sound handles).
jukebox_sounds: HashMap<(i32, i32, i32), u64>,
@@ -1580,6 +1679,8 @@ struct Game<'a> {
/// position) for the guests.
lan_block_events: Vec<([i32; 3], i32, i32, u32)>,
lan_entity_events: Vec<(i32, i8, [f64; 3])>,
+ /// Successful crits (attacking guest, hit entity), queued while the hub is taken.
+ lan_critical_hits: Vec<(Option, i32, bool)>,
/// Global level events for every guest (`ServerLevel.globalLevelEvent`).
lan_global_events: Vec<(i32, [i32; 3], i32)>,
/// `ContainerOpenersCounter`: how many players (the host and the guests)
@@ -1727,9 +1828,46 @@ impl Game<'_> {
fn reach(&self) -> f64 {
if self.creative { 5.0 } else { 4.5 }
}
+ /// Outline shapes that depend on more than the block state, as one box
+ /// in block space: `LightBlock` and `ScaffoldingBlock.getShape` are a full
+ /// block while the main hand holds the block's own item
+ /// (`CollisionContext.isHoldingItem`), and `ShulkerBoxBlock.getShape`
+ /// grows with the lid (`ShulkerBoxBlockEntity.getBoundingBox`).
+ fn context_outline(&self, pos: [i32; 3], state: BlockStateId) -> Option<[f64; 6]> {
+ let name = &self.res.facts().get(state).name;
+ if matches!(&**name, "minecraft:light" | "minecraft:scaffolding") {
+ return self
+ .held()
+ .is_some_and(|s| *s.item == **name)
+ .then_some([0.0, 0.0, 0.0, 1.0, 1.0, 1.0]);
+ }
+ if !name.ends_with("shulker_box") {
+ return None;
+ }
+ let progress = self.be_anims.shulkers.get(&pos).map_or(0.0, |s| s.progress);
+ let facing = self
+ .pack
+ .assets
+ .registry
+ .state(state)
+ .and_then(|s| s.properties.get("facing").cloned());
+ let d = facing_offset(facing.as_deref().unwrap_or("up"));
+ let mut b = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
+ for a in 0..3 {
+ match d[a] {
+ 1 => b[a + 3] += 0.5 * f64::from(progress),
+ -1 => b[a] -= 0.5 * f64::from(progress),
+ _ => {}
+ }
+ }
+ Some(b)
+ }
/// A block's outline boxes in world space (`getShape` plus the random offset).
fn outline_boxes(&self, pos: [i32; 3]) -> Vec<[f64; 6]> {
let state = self.world.block(pos[0], pos[1], pos[2]);
+ if let Some(b) = self.context_outline(pos, state) {
+ return vec![std::array::from_fn(|i| f64::from(pos[i % 3]) + b[i])];
+ }
let f = self.res.facts().get(state);
let o = if f.outline_offset {
self.pack
@@ -2024,6 +2162,33 @@ impl Game<'_> {
}
/// `TerrainParticle` at `pos`: the model's particle sprite and tint source
/// 0's `colorAsTerrainParticle` (white when the block has none).
+ /// `HoneyBlock.showSlideParticles` (entity event 53): five honey block
+ /// particles at the entity.
+ fn honey_slide_particles(&mut self, at: [f64; 3]) {
+ use horizon_client::particles::{ParticleOptions, ParticleType};
+ let Some(honey) = self
+ .pack
+ .assets
+ .registry
+ .default_state("minecraft:honey_block")
+ else {
+ return;
+ };
+ let block = [
+ at[0].floor() as i32,
+ at[1].floor() as i32,
+ at[2].floor() as i32,
+ ];
+ if let Some((sprite, tint)) = self.particle_sprite(honey, block) {
+ for _ in 0..5 {
+ self.particles.add(
+ &ParticleOptions::block(ParticleType::Block, sprite.clone(), tint),
+ at,
+ [0.0; 3],
+ );
+ }
+ }
+ }
fn particle_sprite(&self, state: BlockStateId, pos: [i32; 3]) -> Option<(String, u32)> {
let sprite = Self::block_particle_sprite(&self.pack, state)?;
let chunks = &self.world.chunks;
@@ -2159,8 +2324,9 @@ impl Game<'_> {
ticks: 0,
});
}
- /// `Block.getDrops`: the block's loot table, drawing from its server random
- /// sequence (`LootContext.Builder.create`), else the level random.
+ /// `Block.getDrops` for a block a player breaks: the block's loot table
+ /// with the player as `this`, drawing from its server random sequence
+ /// (`LootContext.Builder.create`), else the level random.
fn block_loot_at(
&mut self,
pos: [i32; 3],
@@ -2174,9 +2340,9 @@ impl Game<'_> {
let random = self.rand_sequences.get(&sequence, self.level.seed);
self.res
.items()
- .block_drops_with(registry, state, held, &dynamic, random)
+ .block_drops_by_player(registry, state, held, &dynamic, random)
}
- None => self.res.items().block_drops_with(
+ None => self.res.items().block_drops_by_player(
registry,
state,
held,
@@ -2220,11 +2386,13 @@ impl Game<'_> {
// Player.drop: the drop statistics.
self.stats.add("dropped", &thrown.item, thrown.count as i32);
self.stats.custom("drop", 1);
- self.throw_from_eyes(thrown, eye);
+ self.throw_from_eyes(thrown, eye, true);
}
/// `Player.createItemStackToDrop`: an item entity thrown from the eyes
- /// along the view direction.
- fn throw_from_eyes(&mut self, thrown: ItemStack, eye: [f64; 3]) {
+ /// along the view direction. `thrown_from_hand` (`drop(stack, true)`, the
+ /// drop key) names the player as the thrower; `drop(stack, false)`, for
+ /// what no longer fits in the inventory, does not.
+ fn throw_from_eyes(&mut self, thrown: ItemStack, eye: [f64; 3], thrown_from_hand: bool) {
let (yaw, pitch) = (
f64::from(self.yaw).to_radians(),
f64::from(self.pitch).to_radians(),
@@ -2238,11 +2406,18 @@ impl Game<'_> {
yaw.cos() * pitch.cos() * 0.3 + spread.sin() * strength,
];
self.spawn_item(thrown, [eye[0], eye[1] - 0.3, eye[2]], v, 40);
- if self.lan_acting.is_none() {
- let uuid = self.level.ensure_player_uuid();
+ if thrown_from_hand {
+ let uuid = self.acting_player_uuid();
self.dropped.last_mut().unwrap().thrower = Some(uuid);
}
}
+ /// The UUID of the player acting: the guest whose turn it is, else the host.
+ pub(super) fn acting_player_uuid(&mut self) -> [i32; 4] {
+ match self.lan_acting_uuid {
+ Some(guest) => horizon_client::lan::playerdata::uuid_ints(guest),
+ None => self.level.ensure_player_uuid(),
+ }
+ }
fn tick_items(&mut self) {
let mut items = std::mem::take(&mut self.dropped);
// ServerLevel.tick: only entities in entity-ticking chunks tick.
@@ -2445,6 +2620,18 @@ impl Game<'_> {
)
})
.collect();
+ let arrow_boxes = self
+ .creatures
+ .projectiles
+ .iter()
+ .filter(|p| p.arrow.is_some())
+ .map(|p| p.position)
+ .chain(self.tridents.iter().map(|t| t.position))
+ .map(|at| {
+ let b = horizon_client::arrows::arrow_bounds(at);
+ (b.min_position().components(), b.max_position().components())
+ })
+ .collect();
let guest_boxes = self.lan_block_trigger_boxes();
let dimension = match self.dim {
Dim::Overworld => LevelDimension::Overworld,
@@ -2452,6 +2639,19 @@ impl Game<'_> {
Dim::End => LevelDimension::End,
};
let rules = self.level_rules();
+ let fire_players: Vec<[f64; 3]> = self
+ .player
+ .iter()
+ .filter(|_| !spectator)
+ .map(|p| [p.position.x, p.position.y, p.position.z])
+ .chain(self.lan.iter().flat_map(|h| {
+ h.hub
+ .guests
+ .iter()
+ .filter(|g| h.hub.here(g) && !g.spectator())
+ .map(|g| g.position)
+ }))
+ .collect();
let blockers = Blockers {
mobs: &self.mobs,
armor_stands: &self.armor_stands,
@@ -2462,6 +2662,7 @@ impl Game<'_> {
};
let mut level = GameLevel {
cart_boxes,
+ arrow_boxes,
blockers,
world: &mut self.world,
facts: self.res.facts(),
@@ -2469,6 +2670,11 @@ impl Game<'_> {
events: &mut self.level_events,
dimension,
darken,
+ environment: match dimension {
+ LevelDimension::Overworld => self.res.environment(),
+ LevelDimension::Nether => self.res.nether_environment(),
+ LevelDimension::End => self.res.end_environment(),
+ },
raining: rain > 0.2,
thundering: thunder > 0.9,
player_box,
@@ -2482,12 +2688,15 @@ impl Game<'_> {
loot: horizon_client::structure_blocks::loot_data(&self.options.resources),
registry: self.pack.assets.registry,
rules,
+ difficulty: i32::from(self.ui.difficulty),
+ fire_players,
rand_sequences: &mut self.rand_sequences,
pending: &mut self.pending,
spill: &mut self.spill,
tickets: self.tickets.levels(),
random_tick_sections: &mut self.random_tick_sections,
lid_openers: &self.lid_openers,
+ client_side: self.remote.is_some(),
};
let result = f(self.res.behaviours(), &mut level, &mut self.block_ticks);
self.flush_spill();
@@ -2549,14 +2758,15 @@ impl Game<'_> {
(p.position.z.floor() as i32) >> 4,
));
}
- let sources = (self.options.dedicated.is_some() || !players.is_empty()).then(|| {
- horizon_client::ticket_levels::Sources {
- players,
- forced: self.streaming.forced.iter().copied().collect(),
- view_distance: self.settings.render_distance.clamp(2, 32),
- simulation_distance: self.settings.simulation_distance.max(2),
- }
- });
+ let sources =
+ (!self.options.execution_role.is_client() || !players.is_empty()).then(|| {
+ horizon_client::ticket_levels::Sources {
+ players,
+ forced: self.streaming.forced.iter().copied().collect(),
+ view_distance: self.settings.render_distance.clamp(2, 32),
+ simulation_distance: self.settings.simulation_distance.max(2),
+ }
+ });
self.tickets.update(sources);
}
/// `ServerLevel.startTickingChunk`: a loaded chunk's saved ticks are
@@ -2591,8 +2801,9 @@ impl Game<'_> {
.copied()
.filter(|&(x, z)| levels.random_ticking(x, z) && ticking_chunk(&self.world, x, z))
.collect();
- // Entity.checkInsideBlocks for the plates, tripwires and detector rails
- // under the players (the host and the LAN guests) and the minecarts.
+ // Entity.checkInsideBlocks for the plates, tripwires, detector rails and
+ // buttons under the players (the host and the LAN guests), the minecarts
+ // and the arrows.
let mut inside = Vec::new();
let guests = self.lan_block_trigger_boxes();
let boxes = self
@@ -2624,6 +2835,24 @@ impl Game<'_> {
}
}
}
+ // AbstractArrow.applyEffectsFromBlocks: the blocks every arrow passed
+ // through this tick (a wooden button is pressed by one inside it), and
+ // the ones a thrown trident is in.
+ for p in self
+ .creatures
+ .projectiles
+ .iter()
+ .filter(|p| p.arrow.is_some())
+ {
+ inside.extend(horizon_client::arrows::blocks_inside(
+ p.previous, p.position,
+ ));
+ }
+ for t in &self.tridents {
+ inside.extend(horizon_client::arrows::blocks_inside(
+ t.position, t.position,
+ ));
+ }
// BigDripleafBlock.entityInside also asks whether the player stands on
// the ground and how high its feet are: the leaves its box's feet
// layer is inside (the host and the LAN guests).
@@ -2785,11 +3014,25 @@ impl Game<'_> {
pos,
data,
} => self.consume_teleport_particles([pos.x, pos.y, pos.z], data),
+ LevelEvent::LevelEvent { id: 2003, pos, .. } => {
+ self.eye_break_particles([pos.x, pos.y, pos.z]);
+ }
LevelEvent::LevelEvent {
id: 2013,
pos,
data,
} => self.smash_dust(pos, data),
+ // LevelEventHandler 2002 and 2007: a potion's splash.
+ LevelEvent::LevelEvent {
+ id: 2002,
+ pos,
+ data,
+ } => self.potion_splash_particles(pos, data, false),
+ LevelEvent::LevelEvent {
+ id: 2007,
+ pos,
+ data,
+ } => self.potion_splash_particles(pos, data, true),
LevelEvent::LevelEvent {
id: id @ 3002..=3005,
pos,
@@ -2853,6 +3096,9 @@ impl Game<'_> {
"minecraft:block.pointed_dripstone.drip_water_into_cauldron",
2.0,
)),
+ // LevelEvent.SOUND_ZOMBIE_WOODEN_DOOR (attack, break).
+ 1019 => Some(("minecraft:entity.zombie.attack_wooden_door", 2.0)),
+ 1021 => Some(("minecraft:entity.zombie.break_wooden_door", 2.0)),
1030 => Some(("minecraft:block.anvil.use", 1.0)),
1029 => Some(("minecraft:block.anvil.destroy", 1.0)),
1031 => Some(("minecraft:block.anvil.land", 0.3)),
@@ -2860,6 +3106,8 @@ impl Game<'_> {
1044 => Some(("minecraft:block.smithing_table.use", 1.0)),
// LevelEvent.SOUND_PAGE_TURN (a lectern's page).
1043 => Some(("minecraft:item.book.page_turn", 1.0)),
+ // LevelEvent.SOUND_SPLASH_POTION and its instant twin.
+ 1053 | 1054 => Some(("minecraft:entity.splash_potion.break", 1.0)),
_ => None,
};
if let Some((name, volume)) = sound {
@@ -2869,12 +3117,17 @@ impl Game<'_> {
- self.world.random.next_float())
* 0.8
}
- 1029 | 1030 | 1042 | 1043 | 1044 | 1046 | 1047 => {
+ 1029 | 1030 | 1042 | 1043 | 1044 | 1046 | 1047 | 1053 | 1054 => {
self.world.random.next_float() * 0.1 + 0.9
}
+ 1019 | 1021 => {
+ (self.world.random.next_float() - self.world.random.next_float())
+ * 0.2
+ + 1.0
+ }
_ => 1.0,
};
- if matches!(id, 1029 | 1030) {
+ if matches!(id, 1019 | 1021 | 1029 | 1030 | 1053 | 1054) {
// Clients play the anvil sound from its level event;
// capturing it also sends a duplicate sound packet.
self.audio.play_unshared(name, c, volume, pitch);
@@ -2932,11 +3185,9 @@ impl Game<'_> {
drop_item: true,
fall_distance: 0.0,
stuck: Vec3::ZERO,
- damage: if self.res.facts().get(state).name.ends_with("anvil") {
- horizon_client::falling_block::Damage::anvil()
- } else {
- Default::default()
- },
+ damage: horizon_client::falling_block::Damage::falling(
+ &self.res.facts().get(state).name,
+ ),
saved: None,
});
}
@@ -3013,6 +3264,11 @@ impl Game<'_> {
kind: "hatch_sniffer",
..
} => self.hatch_sniffer([pos.x, pos.y, pos.z]),
+ LevelEvent::BlockEvent {
+ pos,
+ state,
+ kind: "hatch_turtles",
+ } => self.hatch_turtles([pos.x, pos.y, pos.z], state),
LevelEvent::BlockEvent {
pos,
kind: "portal_spawn",
@@ -3034,6 +3290,31 @@ impl Game<'_> {
LevelEvent::BlockEntityEvent { pos, a, b, .. } => {
self.block_entity_event([pos.x, pos.y, pos.z], a, b)
}
+ // NoteBlock.triggerEvent: a NOTE particle above, coloured by
+ // the note (`note / 24.0` in the x speed).
+ LevelEvent::BlockEvent {
+ pos,
+ state,
+ kind: "note_particle",
+ } => {
+ use horizon_client::particles::{ParticleOptions, ParticleType};
+ let note = self
+ .pack
+ .assets
+ .registry
+ .state(state)
+ .and_then(|s| s.properties.get("note")?.parse::().ok())
+ .unwrap_or(0.0);
+ self.particles.add(
+ &ParticleOptions::simple(ParticleType::Note),
+ [
+ f64::from(pos.x) + 0.5,
+ f64::from(pos.y) + 1.2,
+ f64::from(pos.z) + 0.5,
+ ],
+ [note / 24.0, 0.0, 0.0],
+ );
+ }
LevelEvent::GrowTree { .. }
| LevelEvent::PlaceFeature { .. }
| LevelEvent::BlockEvent { .. } => {}
@@ -3050,6 +3331,10 @@ impl Game<'_> {
.name
.clone();
let key = (pos[0], pos[1], pos[2]);
+ if self.chest_menu_blocked(key, &name) {
+ // The use still succeeds, but no menu, stat or piglin anger.
+ return;
+ }
if &*name == "minecraft:lectern" {
self.open_lectern(pos);
return;
@@ -3380,9 +3665,17 @@ impl Game<'_> {
self.with_player_actor(|game| game.break_block_as_player(pos))
}
fn break_block_as_player(&mut self, pos: [i32; 3]) -> Result<()> {
+ if !self
+ .res
+ .items()
+ .can_destroy_block(self.held(), self.creative)
+ {
+ return Ok(());
+ }
self.pad_rumble(horizon_client::gamepad::Rumble::BlockBroken);
// ServerPlayerGameMode.destroyBlock.
let state = self.world.block(pos[0], pos[1], pos[2]);
+ let broken = state;
let facts = self.res.facts().get(state).clone();
let state = self.crack_mined_pot(pos, state);
// Block.playerWillDestroy: mining their gold angers all nearby piglins.
@@ -3397,7 +3690,7 @@ impl Game<'_> {
} else if let Some(tag) = spill::saved_entity(&self.world, pos) {
self.pending.record_saved(pos, &tag);
}
- self.creaking_heart_broken(pos);
+ self.creaking_heart_broken(pos, true);
let hive = match self.world.block_entities.get(&key) {
Some(BlockEntity::Beehive(h)) => self.hive_state(pos).map(|s| ((**h).clone(), s)),
_ => None,
@@ -3414,6 +3707,9 @@ impl Game<'_> {
creative,
)
});
+ if removed {
+ self.mod_block_event(pos, broken, false);
+ }
if removed && !creative {
let held = self.held().cloned();
self.mine_block_with_held(&facts.name, facts.hardness);
@@ -3522,6 +3818,7 @@ impl Game<'_> {
fn interact_entity(&mut self) -> Result {
Ok(self.interact_frame()
|| self.interact_armor_stand()
+ || self.interact_cushion()
|| self.interact_boat()
|| self.interact_cart()
|| self.interact_mob()?
@@ -3583,6 +3880,10 @@ impl Game<'_> {
self.swing_arm();
return Ok(true);
}
+ if self.use_campfire_douse(hit.pos, held.as_ref())? {
+ self.swing_arm();
+ return Ok(true);
+ }
match self.use_respawn_anchor(hit.pos, held.as_ref())? {
respawn_anchor::AnchorUse::Charged => {
self.swing_arm();
@@ -3708,6 +4009,7 @@ impl Game<'_> {
|| self.place_painting(hit, &stack)
|| self.place_item_frame(hit, &stack)
|| self.place_armor_stand(hit, &stack)
+ || self.place_cushion(hit, &stack)
|| self.place_end_crystal(hit, &stack))
{
return Ok(true);
@@ -3756,6 +4058,7 @@ impl Game<'_> {
return Ok(true);
};
let target = [pos.x, pos.y, pos.z];
+ self.mod_block_event(target, state, true);
if let Some(entity) = BlockEntity::for_block(&self.res.facts().get(state).name) {
let key = (target[0], target[1], target[2]);
self.world.block_entities.insert(key, entity);
@@ -3998,7 +4301,12 @@ impl Game<'_> {
return Ok(());
};
// GameType.isBlockPlacingRestricted: adventure and spectator.
- if !self.may_build() {
+ if !self.may_build()
+ || !self
+ .res
+ .items()
+ .can_destroy_block(self.held(), self.creative)
+ {
self.mining = None;
return Ok(());
}
@@ -4174,6 +4482,12 @@ impl Game<'_> {
// The world's spawn from the start, not only once saved: a bed set
// before the first save must not become it.
self.level.world_spawn.get_or_insert([x, y, z]);
+ // The "Bonus Chest" create-world option, placed once with the spawn.
+ if horizon_client::save::WorldGen::read(&self.world_root)
+ .is_some_and(|g| g.bonus_chest)
+ {
+ self.place_bonus_chest([x, y, z])?;
+ }
}
let s = self
.level
@@ -4272,11 +4586,16 @@ impl Game<'_> {
if running {
self.world.game_time += 1;
if self.ui.rules.bool("advance_weather") {
- self.world.weather.tick(&mut self.world.random);
+ self.world.weather.tick_timers(&mut self.world.random);
}
+ self.world.weather.tick_levels();
self.tick_weather_effects();
}
- if self.ticks.is_multiple_of(6000) {
+ self.autosaving = self.ticks.is_multiple_of(6000);
+ if let Some(serving) = &self.serving {
+ serving.set_saving(self.autosaving);
+ }
+ if self.autosaving {
self.save_game_with(false)?;
}
if running {
@@ -4289,6 +4608,7 @@ impl Game<'_> {
self.update_totem_ready();
self.tick_command_extras();
self.tick_mods();
+ self.tick_server_mods();
let camera_eye = self.camera_eye_height();
let stick = self.pad_move();
if self.riding.is_some() && self.player.is_some() {
@@ -4371,12 +4691,6 @@ impl Game<'_> {
let events = std::mem::take(&mut player.events);
let spin_hit = player.spin_hit.take();
let glider_wear = std::mem::take(&mut player.glider_wear);
- if glider_wear > 0
- && !self.creative
- && let Some(elytra) = self.armor[1].as_mut()
- {
- elytra.damage += glider_wear;
- }
let feet = [player.position.x, player.position.y, player.position.z];
let player_velocity = [player.velocity.x, player.velocity.y, player.velocity.z];
self.previous_eye = self.eye;
@@ -4387,9 +4701,36 @@ impl Game<'_> {
};
self.eye += (camera_eye.unwrap_or(eye_height) - self.eye) * 0.5;
let crouching = player.pose == horizon_client::pose::Pose::Crouching;
+ // `LivingEntity.baseTick` (Soul Speed) comes before `aiStep` (the
+ // glide's wear): both draw from the level random.
+ if let Some((at, velocity)) = self.tick_soul_speed() {
+ self.particles.send_particles(
+ &horizon_client::particles::ParticleOptions::simple(
+ horizon_client::particles::ParticleType::Soul,
+ ),
+ at,
+ velocity,
+ 1.0,
+ 0,
+ );
+ if let Some(host) = self.lan.as_ref() {
+ lan_particles::send_soul_particle(host, at, velocity);
+ }
+ }
+ // `ItemStack.hurtAndBreak` for the glide: Unbreaking can save the wear.
+ if glider_wear > 0
+ && !self.creative
+ && let Some(stack) = self.armor[1].clone()
+ {
+ let loss = self.durability_loss(&stack, glider_wear);
+ if let Some(elytra) = self.armor[1].as_mut() {
+ elytra.damage += loss;
+ }
+ }
self.tick_avatar(before, riding);
self.end_spin_attack(spin_hit);
self.record_combat(&events);
+ self.wear_armor(&events);
for event in events {
match event {
MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, feet),
@@ -4465,9 +4806,32 @@ impl Game<'_> {
};
self.audio.play(name, Some(feet), volume, pitch);
}
+ // LivingEntity.checkFallDamage: the block's crumbs where the fall landed.
+ MotionEvent::Fall(horizon_client::landing::FallEvent::Particles {
+ state,
+ position,
+ count,
+ speed,
+ }) => self.landing_dust(None, state, position, count, speed),
MotionEvent::Fall(event) => self.landing_block_updates(&event),
MotionEvent::Snowflake { position, velocity } => self.snowflake(position, velocity),
MotionEvent::EnterBlock { state } => self.trigger_enter_block(state),
+ MotionEvent::HoneySlide {
+ sound, particles, ..
+ } => {
+ if sound {
+ self.audio
+ .play("minecraft:block.honey_block.slide", Some(feet), 1.0, 1.0);
+ }
+ if particles {
+ self.honey_slide_particles(feet);
+ // The server's event 53 reaches the guests too.
+ let id = self.lan.as_ref().map(|h| h.host_entity);
+ if let Some(id) = id {
+ self.lan_entity_event(id, 53, feet);
+ }
+ }
+ }
MotionEvent::InsidePortal { pos } => self.player_inside_nether_portal(pos),
MotionEvent::CauldronExtinguish { pos } => self.cauldron_extinguish(pos),
MotionEvent::InsideWitherRose => self.wither_rose_contact(),
@@ -4562,7 +4926,7 @@ impl Game<'_> {
&& let Some(stack) = self.carried.take()
&& let Some(eye) = self.eye_position()
{
- self.throw_from_eyes(stack, eye);
+ self.throw_from_eyes(stack, eye, false);
}
}
self.tick_world(running)
@@ -4570,6 +4934,7 @@ impl Game<'_> {
/// What the tick runs after the local player's own update: effects, the
/// world's entities and blocks, and the network hub.
fn tick_world(&mut self, running: bool) -> Result<()> {
+ self.share_spawn_conditions();
self.update_chunk_tickets();
horizon_client::spans::time("tick_effects", || self.tick_effects(running));
// Player.tick's ItemCooldowns.tick for the window's player (a
@@ -4577,6 +4942,7 @@ impl Game<'_> {
self.shield_cooldown = self.shield_cooldown.saturating_sub(1);
self.cooldowns.tick();
horizon_client::spans::time("tick_using", || self.tick_using());
+ self.tick_bundle_hover();
horizon_client::spans::time("tick_hud", || self.tick_hud());
// The player's digging comes in with its packets, before the level
// ticks; ServerLevel.tick then runs the scheduled and random block
@@ -4591,6 +4957,7 @@ impl Game<'_> {
horizon_client::spans::time("tick_paintings", || self.tick_paintings());
horizon_client::spans::time("tick_item_frames", || self.tick_item_frames());
horizon_client::spans::time("tick_armor_stands", || self.tick_armor_stands());
+ horizon_client::spans::time("tick_cushions", || self.tick_cushions());
horizon_client::spans::time("tick_boats", || self.tick_boats());
horizon_client::spans::time("tick_carts", || self.tick_carts());
horizon_client::spans::time("tick_thunder", || self.tick_thunder());
@@ -4799,7 +5166,10 @@ impl Game<'_> {
if capture && !self.focused {
return;
}
- if !capture {
+ if capture {
+ // The inventory's screens are behind us: no drag survives them.
+ self.reset_inventory_clicks();
+ } else {
self.stop_mining();
}
// The real pointer takes over from an agent's.
@@ -4878,7 +5248,7 @@ impl Game<'_> {
self.capture(true);
}
}
- fn draw_item(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) {
+ fn draw_item(&self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) {
// `GuiGraphics.renderItem`: the resolved item model (tints, foil and
// special renderers included), then the decorations.
self.draw_item_model(batch, stack, x, y);
@@ -4968,7 +5338,7 @@ impl Game<'_> {
/// `GuiGraphicsExtractor.itemDecorations`: the count (or `count_text`)
/// and damage bar.
fn draw_item_decorations(
- &mut self,
+ &self,
batch: &mut HudBatch,
stack: &ItemStack,
x: f32,
@@ -5095,12 +5465,12 @@ impl Game<'_> {
for d in &draws {
if let hud_layout::GuiDraw::Item { slot, x, y, .. } = *d {
let stack = if slot == 40 {
- self.offhand.clone()
+ self.offhand.as_ref()
} else {
- self.inventory[slot as usize].clone()
+ self.inventory[slot as usize].as_ref()
};
if let Some(stack) = stack {
- self.draw_item(&mut batch, &stack, x as f32, y as f32);
+ self.draw_item(&mut batch, stack, x as f32, y as f32);
}
}
}
@@ -5261,6 +5631,7 @@ impl Game<'_> {
Screen::CommandBlock => self.draw_command_block(&mut batch),
Screen::Inventory => {
self.draw_inventory(&mut batch);
+ self.draw_mod_browser(&mut batch);
}
Screen::Creative => {
self.draw_creative(&mut batch);
@@ -5269,6 +5640,7 @@ impl Game<'_> {
Screen::Mod => self.draw_mod_screen(&mut batch),
Screen::Playing | Screen::Options | Screen::Win => {}
}
+ self.draw_saving_indicator(&mut batch);
self.draw_toasts(&mut batch);
self.draw_pack_toasts(&mut batch);
self.remote_hud(&mut batch);
@@ -5325,7 +5697,9 @@ impl Game<'_> {
| BlockEntity::Vault(_)
| BlockEntity::Beehive(_)
| BlockEntity::CommandBlock(_)
- | BlockEntity::Skull(_),
+ | BlockEntity::Skull(_)
+ | BlockEntity::DaylightDetector
+ | BlockEntity::Campfire(_),
) => {}
None => {
v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i));
@@ -5595,7 +5969,9 @@ impl Game<'_> {
| BlockEntity::Vault(_)
| BlockEntity::Beehive(_)
| BlockEntity::CommandBlock(_)
- | BlockEntity::Skull(_),
+ | BlockEntity::Skull(_)
+ | BlockEntity::DaylightDetector
+ | BlockEntity::Campfire(_),
) => {}
None if self.mount_active() => self.draw_mount_background(batch, ox, oy),
None => {
@@ -5638,7 +6014,19 @@ impl Game<'_> {
self.draw_inventory_effects(batch, (ox, oy), 176);
}
}
+ /// `AbstractContainerScreen` keeps `isQuickCrafting` and the drag it
+ /// belongs to on the screen; Horizon keeps them on the game, so they are
+ /// dropped when a screen closes. A press whose release never reaches the
+ /// screen (the pointer left the window, or the screen closed first) would
+ /// otherwise leave every later press on every later screen swallowed.
+ pub(super) fn reset_inventory_clicks(&mut self) {
+ self.inv_clicks = Default::default();
+ self.inv_drag = None;
+ self.last_inv_click = None;
+ }
pub(super) fn close_container(&mut self) {
+ self.mod_browser_closed();
+ self.reset_inventory_clicks();
self.close_station();
self.mount_closed();
self.recipe_ui.reset_screen();
@@ -5651,7 +6039,8 @@ impl Game<'_> {
if let Some(rest) = self.give(stack)
&& let Some(eye) = self.eye_position()
{
- self.spawn_item(rest, [eye[0], eye[1] - 0.3, eye[2]], [0.0, 0.1, 0.0], 40);
+ // AbstractContainerMenu.dropOrPlaceInInventory: `drop(stack, false)`.
+ self.throw_from_eyes(rest, eye, false);
}
}
self.craft_size = 2;
@@ -5734,8 +6123,9 @@ impl Game<'_> {
if self.creative_screen.tab().search {
// CreativeModeInventoryScreen.slotClicked: moveCursorToEnd, then
// setHighlightPos(0), so typing replaces the whole query.
- let search = &self.creative_screen.search;
- self.text_selection.select(("creative.search", 0), search);
+ let search = &mut self.creative_screen.search;
+ search.move_cursor_to_end(false);
+ search.highlight = 0;
}
let items = self.creative_screen.items(&self.pack.names);
let first = self.creative_screen.first_row(&self.pack.names);
@@ -5751,6 +6141,12 @@ impl Game<'_> {
/// Several clicks on one menu instance (a quick craft drag is three).
fn menu_ops(&mut self, ops: &[(Option, i32, horizon_client::menu::Input)]) -> bool {
use horizon_client::menu::Input;
+ // BundleMouseActions.onSlotClicked: a Shift click or a swap clears the bundle's selection.
+ for &(slot, _, input) in ops {
+ if let (Some(slot), Input::QuickMove | Input::Swap) = (slot, input) {
+ self.unselect_bundle(slot);
+ }
+ }
if self.remote.is_some() && self.screen == Screen::Inventory {
// On a server the clicks are the server's: predicted and sent.
return self.remote_menu_ops(ops);
@@ -6363,6 +6759,9 @@ impl Game<'_> {
fn inventory_press(&mut self, right: bool) {
use horizon_client::container_screen::Target;
use horizon_client::menu::Input;
+ if self.mod_browser_press(right) {
+ return;
+ }
if !right && self.sort_press() {
return;
}
@@ -6377,6 +6776,13 @@ impl Game<'_> {
false,
);
if outside {
+ // AbstractRecipeBookScreen.mouseClicked: the book takes the click
+ // before the outside test, and its tabs sit left of the strip
+ // hasClickedOutside counts as the book.
+ if self.recipe_book_click(right) {
+ self.inv_clicks.skip_release();
+ return;
+ }
// slotId -999: an empty hand throws nothing; a carried stack
// starts a drag whose release drops it.
match input {
@@ -6539,24 +6945,8 @@ impl Game<'_> {
}
/// `hasClickedOutside` of the open screen at the cursor.
fn clicked_outside(&self, batch: &HudBatch) -> bool {
- use horizon_client::container_screen::{Book, Image, clicked_outside};
- let (ox, oy) = self.inventory_origin(batch);
- let (shift, width, height) = if self.screen == Screen::Creative {
- (0.0, Creative::WIDTH as i32, Creative::HEIGHT as i32)
- } else {
- let (shift, width) = match self.station.as_ref().map(|s| s.kind) {
- Some(stations::Kind::Merchant) => (-50.0, 276),
- Some(stations::Kind::Beacon) => (beacon::SHIFT, 230),
- _ => (0.0, 176),
- };
- (shift, width, self.screen_height() as i32)
- };
- let image = Image {
- left: (ox + shift) as i32,
- top: oy as i32,
- width,
- height,
- };
+ use horizon_client::container_screen::{Book, clicked_outside};
+ let image = self.container_image(batch);
let book = self
.recipe_book_area(batch)
.map(|(visible, tab_hovered)| Book {
@@ -6570,6 +6960,26 @@ impl Game<'_> {
book,
)
}
+ /// The open container screen's window: its place and size.
+ fn container_image(&self, batch: &HudBatch) -> horizon_client::container_screen::Image {
+ let (ox, oy) = self.inventory_origin(batch);
+ let (shift, width, height) = if self.screen == Screen::Creative {
+ (0.0, Creative::WIDTH as i32, Creative::HEIGHT as i32)
+ } else {
+ let (shift, width) = match self.station.as_ref().map(|s| s.kind) {
+ Some(stations::Kind::Merchant) => (-50.0, 276),
+ Some(stations::Kind::Beacon) => (beacon::SHIFT, 230),
+ _ => (0.0, 176),
+ };
+ (shift, width, self.screen_height() as i32)
+ };
+ horizon_client::container_screen::Image {
+ left: (ox + shift) as i32,
+ top: oy as i32,
+ width,
+ height,
+ }
+ }
/// A click outside the window (slot id -999): `THROW` does nothing; a
/// `PICKUP` drops the carried stack (left) or one of it (right), thrown
/// from the hand (`AbstractContainerMenu.doClick`, `LivingEntity.drop`).
@@ -6730,7 +7140,7 @@ impl Game<'_> {
}
}
fn click_inventory(&mut self, right: bool) {
- if self.mount_click(right) {
+ if self.mod_browser_press(right) || self.mount_click(right) {
return;
}
if self.recipe_book_click(right) {
@@ -6942,6 +7352,9 @@ impl Game<'_> {
self.prepare_entity_culling(camera);
self.prepare_trims();
self.mark_entity(out.len(), "minecraft:entity_flame");
+ // One scan for both passes that draw them (block entities below and the
+ // overlay near the end of this function).
+ let cracks = self.cracks(camera);
let fire_yaw = if self.camera_type == perspective::CameraType::ThirdPersonFront {
self.yaw + 180.0
} else {
@@ -7038,6 +7451,9 @@ impl Game<'_> {
// `VaultRenderer`.
self.mark_entity(out.len(), "");
self.vault_geometry(camera, alpha, &mut out);
+ // `CampfireRenderer`.
+ self.mark_entity(out.len(), "");
+ self.campfire_geometry(camera, &mut out);
self.mark_entity(out.len(), "minecraft:ominous_item_spawner");
self.ominous_item_spawner_geometry(camera, alpha, &mut out);
// Mobs and their projectiles (a span each).
@@ -7056,7 +7472,12 @@ impl Game<'_> {
self.see_through_vertices = see_through;
// Entity shadows (EntityRenderer.extractShadow).
self.mark_translucent_entity(out.len(), "minecraft:entity_shadow");
- if let Some(sprite) = self.gui.atlas.sprites.get("misc/shadow").copied() {
+ let shadow_sprite = self
+ .settings
+ .entity_shadows
+ .then(|| self.gui.atlas.sprites.get("misc/shadow").copied())
+ .flatten();
+ if let Some(sprite) = shadow_sprite {
let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 };
let darken = self.sky_darken();
let a = alpha;
@@ -7167,7 +7588,7 @@ impl Game<'_> {
.render(&scene, visible, &mut out);
}
self.mark_stage(out.len(), "DESTROY");
- for (pos, stage) in self.cracks(camera) {
+ for &(pos, stage) in &cracks {
let state = self.world.block(pos[0], pos[1], pos[2]);
self.res
.block_entity_render()
@@ -7280,6 +7701,7 @@ impl Game<'_> {
self.frame_geometry(camera, &mut out);
self.mark_entity(out.len(), "minecraft:armor_stand");
self.armor_stand_geometry(camera, alpha, &mut out);
+ self.cushion_geometry(camera, &mut out);
self.mark_entity(out.len(), "minecraft:oak_boat");
self.boat_geometry(camera, alpha, &mut out);
self.mark_entity(out.len(), "minecraft:minecart");
@@ -7310,7 +7732,7 @@ impl Game<'_> {
);
// Breaking progress overlays (destroy_stage_0..9): ours and the other players'.
self.mark_stage(out.len(), "DESTROY");
- for (pos, stage) in self.cracks(camera) {
+ for &(pos, stage) in &cracks {
let o = (glam::DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2]))
- camera)
.as_vec3();
@@ -7358,6 +7780,20 @@ impl Game<'_> {
/// other players' (`renderBlockDestroyAnimation`: within 32 blocks of the camera, the
/// furthest progress on each block).
fn cracks(&self, camera: glam::DVec3) -> Vec<([i32; 3], [f32; 2])> {
+ // `destroy_stage_0` .. `destroy_stage_9`: the sprite name by stage, so the
+ // lookup does not format a string per crack.
+ const DESTROY_STAGES: [&str; 10] = [
+ "block/destroy_stage_0",
+ "block/destroy_stage_1",
+ "block/destroy_stage_2",
+ "block/destroy_stage_3",
+ "block/destroy_stage_4",
+ "block/destroy_stage_5",
+ "block/destroy_stage_6",
+ "block/destroy_stage_7",
+ "block/destroy_stage_8",
+ "block/destroy_stage_9",
+ ];
let mut stages: Vec<([i32; 3], u32)> = Vec::new();
let mut add = |pos: [i32; 3], stage: u32| match stages.iter_mut().find(|c| c.0 == pos) {
Some(c) => c.1 = c.1.max(stage),
@@ -7383,11 +7819,8 @@ impl Game<'_> {
d.length_squared() <= 1024.0
})
.filter_map(|(pos, stage)| {
- let r = self
- .gui
- .atlas
- .sprites
- .get(&format!("block/destroy_stage_{stage}"))?;
+ let name = DESTROY_STAGES.get(stage as usize)?;
+ let r = self.gui.atlas.sprites.get(*name)?;
Some((pos, [r.u0, r.v0]))
})
.collect()
@@ -7443,7 +7876,7 @@ impl Game<'_> {
/// strength and whether it is a critical hit): the weapon and effects
/// scaled by the attack strength, a mace's smash, the critical hit, then
/// enchantments.
- pub(super) fn melee_damage(&mut self, target_kind: &str) -> (f32, f32, bool) {
+ pub(super) fn melee_damage(&mut self, target_kind: &str) -> (f32, f32, bool, bool) {
let hand_damage = 1.0 + self.attack_item_info().map_or(0.0, |i| i.attack_damage);
// Riptide's spin replaces the attack damage attribute.
let spin = self.player.as_ref().map_or(0.0, |p| p.auto_spin_attack_dmg);
@@ -7471,8 +7904,9 @@ impl Game<'_> {
amount *= 1.5;
}
// Enchantment damage (sharpness, smite, bane) scaled by the attack strength.
- amount += self.enchant_damage_bonus(target_kind) * scale;
- (amount, scale, crit)
+ let magic_boost = self.enchant_damage_bonus(target_kind) * scale;
+ amount += magic_boost;
+ (amount, scale, crit, magic_boost > 0.0)
}
/// `Player.getAttackStrengthScale(0.5)`.
fn attack_strength_scale(&self) -> f32 {
@@ -7512,6 +7946,69 @@ impl Game<'_> {
self.audio
.play("minecraft:entity.player.attack.sweep", from, 1.0, 1.0);
}
+ /// The damage and knockback part of `Player.doSweepAttack` after a sweep
+ /// hit on the mob at `target`: every other living mob in its box grown by
+ /// (1, 0.25, 1) and closer than 3 blocks (`distanceToSqr < 9`, in creative
+ /// too), but the player's allies
+ /// (`isAlliedTo`), takes `1 + sweeping_damage_ratio * baseDamage` with the
+ /// weapon's enchantments, scaled by the attack strength, and is pushed 0.4
+ /// along the player's yaw.
+ pub(super) fn sweep_damage(&mut self, target: usize, scale: f32) {
+ let Some(p) = self.player.as_ref() else {
+ return;
+ };
+ let from = [p.position.x, p.position.y, p.position.z];
+ // `baseDamage` of `Player.attack` before a critical hit (a sweep has
+ // none) and the enchantments: the attack damage attribute with the
+ // strength and weakness effects, scaled by the attack strength.
+ let hand_damage = 1.0 + self.attack_item_info().map_or(0.0, |i| i.attack_damage);
+ let base_damage = (hand_damage + self.effect_attack_bonus()) * (0.2 + scale * scale * 0.8);
+ // The enchantment's attribute modifier on the attribute's 0 to 1 range.
+ let ratio = self
+ .res
+ .stations()
+ .enchantments
+ .attribute_add(
+ self.inventory[self.selected].as_ref(),
+ "minecraft:sweeping_damage_ratio",
+ )
+ .clamp(0.0, 1.0) as f32;
+ let sweep_damage = 1.0 + ratio * base_damage;
+ let hit_box = self.mobs[target]
+ .bounds()
+ .inflate(horizon_core::geometry::Vec3::new(1.0, 0.25, 1.0));
+ let (uuid, allies) = (
+ self.level.player_uuid.or(Some([0, 0, 0, 1])),
+ self.player_allies(),
+ );
+ let nearby: Vec = self
+ .mobs
+ .iter()
+ .enumerate()
+ .filter(|(i, m)| {
+ *i != target
+ && m.alive()
+ && !m.removed
+ && !allies.contains(&m.id)
+ && !mace::ally_of_player(m, uuid)
+ && m.bounds().intersects(hit_box)
+ && m.position.distance_squared(p.position) < 9.0
+ })
+ .map(|(i, _)| i)
+ .collect();
+ let (xd, zd) = self.extra_knockback_direction();
+ for i in nearby {
+ let kind = self.mobs[i].kind.id.clone();
+ let kind = format!("minecraft:{}", kind.trim_start_matches("minecraft:"));
+ let damage = (sweep_damage + self.enchant_damage_bonus(&kind)) * scale;
+ let source = self.attack_source(from);
+ if self.hurt_by_player(i, damage, source) {
+ self.mobs[i].knockback(0.4, xd, zd);
+ self.last_hurt_by_player
+ .insert(self.mobs[i].id, self.lan_acting);
+ }
+ }
+ }
/// `Player.attack`'s sounds when a vehicle takes the hit (it always does,
/// and can't be hit critically): knockback when sprinting at full
/// strength, then strong or weak. Before `swing_arm` resets the charge.
@@ -7565,6 +8062,7 @@ impl Game<'_> {
.map_or(0.0, |i| i.attack_damage);
if self.attack_frame()
|| self.attack_armor_stand()
+ || self.attack_cushion()
|| self.attack_boat(hand_damage)
|| self.attack_cart(hand_damage)
|| self.attack_dragon()
@@ -7595,7 +8093,7 @@ impl Game<'_> {
pub(super) fn attack_mob(&mut self, index: usize) {
let target_kind = self.mobs[index].kind.id.clone();
let target_kind = format!("minecraft:{}", target_kind.trim_start_matches("minecraft:"));
- let (amount, scale, crit) = self.melee_damage(&target_kind);
+ let (amount, scale, crit, magic) = self.melee_damage(&target_kind);
let sweep = self.sweep_attack_position(scale, crit);
let (knockback, knockback_attack) = self.extra_knockback(&target_kind, scale);
self.attack_ticks = 0;
@@ -7652,13 +8150,24 @@ impl Game<'_> {
self.stats
.custom("damage_dealt", (actual * 10.0).round() as i32);
if crit {
- self.particles.tracking_emitter(
- horizon_client::particles::ParticleOptions::simple(
- horizon_client::particles::ParticleType::Crit,
- ),
+ self.critical_hit(
+ self.lan_acting,
+ self.mobs[index].id as i32,
feet,
width,
height,
+ false,
+ );
+ }
+ // Player.attackVisualEffects: magicCrit when the enchantments added damage.
+ if magic {
+ self.critical_hit(
+ self.lan_acting,
+ self.mobs[index].id as i32,
+ feet,
+ width,
+ height,
+ true,
);
}
if actual > 2.0 {
@@ -7685,6 +8194,7 @@ impl Game<'_> {
// Player.playServerSideSound: at the player.
if let Some(at) = sweep {
self.sweep_attack(at, from);
+ self.sweep_damage(index, scale);
} else {
self.audio.play(sound, from, 1.0, 1.0);
}
@@ -7695,6 +8205,9 @@ impl Game<'_> {
if let horizon_client::mobs::MobEvent::Sound(s, at, volume, pitch) = event {
self.audio
.play(&format!("minecraft:{s}"), Some(at), volume, pitch);
+ } else {
+ // Left for the end of the tick.
+ self.mobs[index].outbox.push(event);
}
}
self.weapon_hit(index);
@@ -7704,15 +8217,18 @@ impl Game<'_> {
}
}
/// ServerExplosion: rays from a 16^3 grid lose (resistance + 0.3) * 0.3 per step.
- /// A mob explosion (`Level.ExplosionInteraction.MOB`: drop decay with the
- /// default mobGriefing rule).
+ /// A mob explosion (`ServerLevel.explode` with `ExplosionInteraction.MOB`:
+ /// blocks are kept without mobGriefing, else the mob_explosion_drop_decay
+ /// rule picks decay).
fn explode(&mut self, center: [f64; 3], radius: f32) -> Result<()> {
- self.server_explode(
- center,
- radius,
- explosion::BlockInteraction::DestroyWithDecay,
- false,
- )
+ let interaction = if !self.ui.rules.bool("mob_griefing") {
+ explosion::BlockInteraction::Keep
+ } else if self.ui.rules.bool("mob_explosion_drop_decay") {
+ explosion::BlockInteraction::DestroyWithDecay
+ } else {
+ explosion::BlockInteraction::Destroy
+ };
+ self.server_explode(center, radius, interaction, false)
}
/// Copies of a save batch carrying its live block entities and save data.
fn with_entities<'a>(
@@ -7814,6 +8330,7 @@ impl Game<'_> {
creative: bool,
create: Option<&horizon_client::title::WorldOptions>,
) -> Result<()> {
+ world_loading::world_data_used();
if self.defer_world_entry(PendingWorldEntry::Local {
folder: folder.to_owned(),
name: name.map(str::to_owned),
@@ -7879,6 +8396,7 @@ impl Game<'_> {
);
self.session_lock = Some(session_lock);
self.end.set_locator(locator);
+ self.share_spawn_conditions();
self.score = Default::default();
self.fns = Default::default();
self.bosses = Default::default();
@@ -8017,6 +8535,7 @@ impl Game<'_> {
seed,
)?;
self.end.set_locator(locator);
+ self.share_spawn_conditions();
Ok((streaming, save))
}
/// Change dimension through a portal (Entity.changeDimension with
@@ -8037,6 +8556,7 @@ impl Game<'_> {
/// (scaled coordinates, or the End portal's fixed destination).
pub(super) fn switch_level(&mut self, target: Dim, from: Vec3) -> Result {
// Save the departing dimension's changed chunks.
+ self.save.save_forced_chunks(&self.streaming.forced)?;
self.streaming.save(&mut self.world, true);
let keys: Vec<_> = self.world.modified.drain().collect();
let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k)));
@@ -8310,6 +8830,7 @@ impl Game<'_> {
self.boats.clear();
self.carts.clear();
self.armor_stands.clear();
+ self.cushions.clear();
self.item_frames.clear();
self.paintings.clear();
self.others.clear();
@@ -8364,15 +8885,54 @@ impl Game<'_> {
}
self.apply_enchantment_attributes();
}
- /// Inventory.hurtArmor: each piece loses max(1, damage / 4) durability.
- fn hurt_armor(&mut self, damage: f32) {
+ /// The armor hits among a tick's motion events (`Player.hurtArmor` from
+ /// `getDamageAfterArmorAbsorb`), whatever the damage: a mob, an explosion,
+ /// a cactus, lava, a campfire.
+ fn wear_armor(&mut self, events: &[MotionEvent]) {
+ for event in events {
+ if let MotionEvent::Health(horizon_client::health::HealthEvent::ArmorHurt {
+ source,
+ amount,
+ }) = event
+ {
+ self.hurt_armor(*source, *amount);
+ }
+ }
+ }
+ /// `Player.hurtArmor` -> `LivingEntity.doHurtEquipment`: each worn piece that
+ /// wears when its wearer is hurt loses max(1, damage / 4) durability, except
+ /// to a fire source when the piece resists fire (`ItemStack.canBeHurtBy`).
+ fn hurt_armor(&mut self, source: horizon_world::damage_source::DamageTypeId, damage: f32) {
+ if damage <= 0.0 {
+ return;
+ }
let amount = ((damage / 4.0) as u32).max(1);
+ let name = self
+ .motion
+ .health
+ .damage
+ .definition(source)
+ .map(|d| d.name.clone())
+ .unwrap_or_default();
+ let fire = self
+ .motion
+ .health
+ .damage
+ .in_tag(source, "minecraft:is_fire");
let mut broke = false;
let losses: Vec = (0..4)
- .map(|i| {
- self.armor[i]
- .clone()
- .map_or(amount, |s| self.durability_loss(&s, amount))
+ .map(|i| match self.armor[i].clone() {
+ Some(s)
+ if self
+ .res
+ .items()
+ .get(&s.item)
+ .is_some_and(|info| info.equip_damage_on_hurt)
+ && !(fire && self.res.items().resists_fire(&s, &name)) =>
+ {
+ self.durability_loss(&s, amount)
+ }
+ _ => 0,
})
.collect();
for (slot, amount) in self.armor.iter_mut().zip(losses) {
@@ -8469,7 +9029,8 @@ impl Game<'_> {
}
fn drop_stack(&mut self, stack: ItemStack) {
if let Some(eye) = self.0.eye_position() {
- self.0.spawn_item(stack, eye, [0.0, 0.1, 0.0], 40);
+ // ItemUtils.createFilledResult: `player.drop(stack, false)`.
+ self.0.throw_from_eyes(stack, eye, false);
}
}
}
@@ -8707,6 +9268,24 @@ impl Game<'_> {
}
}
}
+ /// `ItemStack.hurtWithoutBreaking`: Unbreaking applies, but the stack stops at
+ /// one point of durability left instead of breaking.
+ fn hurt_held_without_breaking(&mut self, amount: u32) {
+ if self.creative {
+ return;
+ }
+ let Some(held) = self.held().cloned() else {
+ return;
+ };
+ let amount = self.durability_loss(&held, amount);
+ let max = self.res.items().get(&held.item).map_or(0, |i| i.max_damage);
+ if amount == 0 || max == 0 {
+ return;
+ }
+ if let Some(stack) = self.held_mut().as_mut() {
+ stack.damage = (stack.damage + amount).min(max - 1);
+ }
+ }
/// Block tool use: distinguish success, failure and fall-through for hand feedback.
fn use_tool(
&mut self,
@@ -8728,6 +9307,13 @@ impl Game<'_> {
{
return Ok(UseResult::Success { swing: true });
}
+ if allow_block_actions
+ && let Some(hit) = self.pick()
+ && let Some(placed) = self.use_on_campfire(hit.pos)?
+ {
+ // SUCCESS_SERVER swings; a full campfire's CONSUME does not.
+ return Ok(UseResult::Success { swing: placed });
+ }
// BucketItem has no useOn: a guest's UseItemOn leaves it to UseItem.
let bucket = horizon_client::items::bucket_contents(&stack.item);
if matches!(self.guest_use, Some(GuestUse::OnBlock(_)))
@@ -8787,7 +9373,8 @@ impl Game<'_> {
} else if let Some(rest) = self.give(filled)
&& let Some(eye) = self.eye_position()
{
- self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40);
+ // ItemUtils.createFilledResult: `player.drop(stack, false)`.
+ self.throw_from_eyes(rest, eye, false);
}
}
return Ok(UseResult::Success { swing: true });
@@ -8937,8 +9524,29 @@ impl Game<'_> {
while value > 0 {
let v = ExperienceOrb::split(value);
value -= v;
- let _merge_id = self.world.random.next_int_bound(40);
- self.add_orb(at, v);
+ let merge_id = self.world.random.next_int_bound(40).unwrap_or(0);
+ self.award_orb(at, v, merge_id);
+ }
+ }
+ /// `ExperienceOrb.tryMergeToExisting`: an orb of the same value within a
+ /// 1 block box of `at`, whose id is a multiple of 40 from `merge_id`, takes
+ /// the new one as one more in its count (and restarts its age); otherwise
+ /// a fresh orb spawns.
+ fn award_orb(&mut self, at: [f64; 3], value: u32, merge_id: i32) {
+ let centre = Vec3::new(at[0], at[1], at[2]);
+ let half = Vec3::new(0.5, 0.5, 0.5);
+ let area = Aabb::new(centre.subtract(half), centre.add_vector(half));
+ // A server's orbs are its own; a LAN or server guest only shows them.
+ let target = self.remote.is_none().then(|| {
+ self.orbs
+ .iter_mut()
+ .find(|o| o.can_merge(merge_id as u32, value) && o.bounds().intersects(area))
+ });
+ if let Some(Some(orb)) = target {
+ orb.count += 1;
+ orb.age = 0;
+ } else {
+ self.add_orb(at, value);
}
}
/// `new ExperienceOrb(level, pos, Vec3.ZERO, value)`: yaw and motion from
@@ -8960,6 +9568,8 @@ impl Game<'_> {
value,
age: 0,
on_ground: false,
+ count: 1,
+ ticks: 0,
});
}
fn can_place_used_fire(&mut self, target: [i32; 3]) -> bool {
@@ -9036,18 +9646,31 @@ impl Game<'_> {
}),
);
}
+ // Player.aiStep: the pickup area is the box inflated by (1, 0.5, 1).
let bounds = player.map(|p| {
let w = f64::from(p.dimensions.width) / 2.0;
(
- [p.position.x - w, p.position.y, p.position.z - w],
[
- p.position.x + w,
- p.position.y + f64::from(p.dimensions.height),
- p.position.z + w,
+ p.position.x - w - 1.0,
+ p.position.y - 0.5,
+ p.position.z - w - 1.0,
+ ],
+ [
+ p.position.x + w + 1.0,
+ p.position.y + f64::from(p.dimensions.height) + 0.5,
+ p.position.z + w + 1.0,
],
)
});
let mut orbs = std::mem::take(&mut self.orbs);
+ // An orb has no random of its own here: lava draws from one made on
+ // first use, apart from the level stream.
+ let mut lava_random = None;
+ let mut next_float = || {
+ lava_random
+ .get_or_insert_with(dispenser::entity_random)
+ .next_float()
+ };
orbs.retain_mut(|o| {
let distance = |feet: &[f64; 3]| -> f64 {
(feet[0] - o.position.x).powi(2)
@@ -9059,12 +9682,22 @@ impl Game<'_> {
.filter(|(feet, _)| distance(feet) < 64.0)
.min_by(|a, b| distance(&a.0).total_cmp(&distance(&b.0)))
.map(|(_, target)| *target);
- o.tick(&self.world, self.res.facts(), self.collision, target)
+ o.tick(
+ &self.world,
+ self.res.facts(),
+ self.collision,
+ target,
+ &mut next_float,
+ )
});
+ // ExperienceOrb.scanForMerges runs on the server only.
+ if self.remote.is_none() {
+ horizon_client::entities::merge_orbs(&mut orbs);
+ }
let mut gained = 0;
let mut taken = Vec::new();
if let Some((min, max)) = bounds {
- orbs.retain(|o| {
+ orbs.retain_mut(|o| {
let touching = o.position.x + 0.25 > min[0]
&& o.position.x - 0.25 < max[0]
&& o.position.y + 0.5 > min[1]
@@ -9072,11 +9705,13 @@ impl Game<'_> {
&& o.position.z + 0.25 > min[2]
&& o.position.z - 0.25 < max[2];
if touching && self.xp_delay == 0 {
- // ExperienceOrb.playerTouch: one orb every 2 ticks.
+ // ExperienceOrb.playerTouch: one orb every 2 ticks; a
+ // merged orb gives its value once per count.
self.xp_delay = 2;
gained += o.value;
taken.push(o.clone());
- return false;
+ o.count -= 1;
+ return o.count > 0;
}
true
});
@@ -9152,7 +9787,10 @@ impl Game<'_> {
};
// BowItem.shootProjectile: shootFromRotation(power * 3, inaccuracy 1).
let p = Vec3::new(eye[0], eye[1] - 0.1, eye[2]);
- let (power_bonus, infinity) = self.bow_enchantments();
+ let ammo = arrow_slot
+ .and_then(|i| self.stack_in(i).cloned())
+ .unwrap_or_else(|| ItemStack::new("minecraft:arrow", 1));
+ let (power_bonus, infinity) = self.bow_enchantments(&ammo.item);
let kind = horizon_client::projectiles::ProjectileKind::Arrow {
base_damage: 2.0 + power_bonus,
critical: power >= 1.0,
@@ -9166,9 +9804,6 @@ impl Game<'_> {
// ProjectileWeaponItem.useAmmo: creative and Infinity draw without
// using the ammo, so the arrow is CREATIVE_ONLY; else setOwner(player)
// lets it be picked up.
- let ammo = arrow_slot
- .and_then(|i| self.stack_in(i).cloned())
- .unwrap_or_else(|| ItemStack::new("minecraft:arrow", 1));
if let Some(a) = arrow.arrow.as_mut() {
a.set_item(&horizon_client::arrows::drawn_ammo(
&ammo,
@@ -9626,8 +10261,9 @@ impl Game<'_> {
rain.extend(snow_vertices);
rain
}
- /// Player.startSleepInBed: night or thunder, no monsters within 8 blocks;
- /// the bed becomes the respawn point either way.
+ /// ServerPlayer.startSleepInBed: in reach, not obstructed, night or thunder,
+ /// and (outside creative) no monsters within 8 blocks; the bed becomes the
+ /// respawn point either way.
fn try_sleep(&mut self, pos: [i32; 3]) {
let Some(p) = self.player.as_ref() else {
return;
@@ -9642,22 +10278,40 @@ impl Game<'_> {
.state(state)
.map(|s| s.properties.clone())
.unwrap_or_default();
- let head = if props.get("part").map(String::as_str) == Some("foot") {
- let d = facing_offset(props.get("facing").map_or("north", String::as_str));
- [pos[0] + d[0], pos[1], pos[2] + d[2]]
+ // The head and the foot: the block faces from the foot to the head.
+ let d = facing_offset(props.get("facing").map_or("north", String::as_str));
+ let (head, foot) = if props.get("part").map(String::as_str) == Some("foot") {
+ ([pos[0] + d[0], pos[1], pos[2] + d[2]], pos)
} else {
- pos
+ (pos, [pos[0] - d[0], pos[1], pos[2] - d[2]])
};
- let dist = ((p.position.x - f64::from(head[0]) - 0.5).powi(2)
- + (p.position.z - f64::from(head[2]) - 0.5).powi(2))
- .sqrt();
- if dist > 3.0 {
+ // ServerPlayer.bedInRange / isReachableBedBlock: within 3 blocks
+ // sideways and 2 vertically of the head or the foot.
+ let reachable = |bed: [i32; 3]| {
+ (p.position.x - f64::from(bed[0]) - 0.5).abs() <= 3.0
+ && (p.position.y - f64::from(bed[1])).abs() <= 2.0
+ && (p.position.z - f64::from(bed[2]) - 0.5).abs() <= 3.0
+ };
+ if !reachable(head) && !reachable(foot) {
self.message = Some((
"You may not rest now; the bed is too far away".into(),
Instant::now(),
));
return;
}
+ // ServerPlayer.bedBlocked: Player.freeAt (not suffocating) for the
+ // blocks above the head and the foot, as `in_wall` reads suffocating.
+ let blocked = [head, foot].iter().any(|bed| {
+ let f = self
+ .res
+ .facts()
+ .get(self.world.block(bed[0], bed[1] + 1, bed[2]));
+ f.full_collision && f.solid_render
+ });
+ if blocked {
+ self.message = Some(("This bed is obstructed".into(), Instant::now()));
+ return;
+ }
// In reach (bedInRange), day or night: setRespawnPosition(
// RespawnConfig(the head, the player's yaw), not forced). It replaces
// an anchor or a spawnpoint; respawning checks the bed is still there
@@ -9687,13 +10341,15 @@ impl Game<'_> {
));
return;
}
- let monsters = self.mobs.iter().any(|m| {
- m.hostile()
- && m.alive()
- && (m.position.x - p.position.x).abs() < 8.0
- && (m.position.y - p.position.y).abs() < 5.0
- && (m.position.z - p.position.z).abs() < 8.0
- });
+ // Creative players skip the monster check (`!this.isCreative()`).
+ let monsters = !self.creative
+ && self.mobs.iter().any(|m| {
+ m.hostile()
+ && m.alive()
+ && (m.position.x - p.position.x).abs() < 8.0
+ && (m.position.y - p.position.y).abs() < 5.0
+ && (m.position.z - p.position.z).abs() < 8.0
+ });
if monsters {
self.message = Some((
"You may not rest now; there are monsters nearby".into(),
@@ -9743,14 +10399,20 @@ impl Game<'_> {
}
}
// ServerLevel.tick: once enough of the players have slept 100 ticks,
- // skip to morning, clear the weather and wake everyone.
+ // skip to morning if `advance_time` is on, wake everyone, and
+ // resetWeatherCycle if `advance_weather` is on and it is raining.
if self.enough_slept() {
- let t = self.world.day_time;
- self.world.day_time = t + 24000 - t.rem_euclid(24000);
- self.world.weather.raining = false;
- self.world.weather.thundering = false;
- self.world.weather.rain_time = 0;
- self.world.weather.thunder_time = 0;
+ if self.ui.rules.bool("advance_time") {
+ let t = self.world.day_time;
+ self.world.day_time = t + 24000 - t.rem_euclid(24000);
+ }
+ // Level.isRaining: the rain level is above 0.2.
+ if self.ui.rules.bool("advance_weather") && self.world.weather.levels(1.0).0 > 0.2 {
+ self.world.weather.raining = false;
+ self.world.weather.thundering = false;
+ self.world.weather.rain_time = 0;
+ self.world.weather.thunder_time = 0;
+ }
if self.sleeping.is_some() {
self.wake_up();
}
@@ -9778,8 +10440,9 @@ impl Game<'_> {
fn draw_creative(&mut self, batch: &mut HudBatch) {
let (ox, oy) = Self::creative_origin(batch);
let selected = self.creative_screen.selected;
- let tabs = self.creative_screen.tabs.clone();
- let tab = self.creative_screen.tab().clone();
+ // Only what is drawn of the tabs: their stacks stay where they are.
+ let tabs = self.creative_screen.tab_headers();
+ let tab = tabs[selected.min(tabs.len() - 1)].clone();
let tab_sprite = |t: &horizon_client::creative::Tab, on: bool| {
format!(
"gui/sprites/container/creative_inventory/tab_{}_{}_{}",
@@ -9845,20 +10508,16 @@ impl Game<'_> {
);
}
if tab.search {
- // The search box: an unbordered EditBox of 80 at (82, 6), white.
- let search = &self.creative_screen.search;
- horizon_client::ui::append_field(
- batch,
- atlas,
- search,
- (ox + 82.0, oy + 6.0, 80.0),
- (u32::MAX, true),
- clipboard::CREATIVE_SEARCH_CHARS,
- self.text_selection
- .covers(clipboard::CREATIVE_SEARCH, search),
- true,
- self.creative_screen.search_focused.elapsed().as_millis(),
- );
+ // CreativeModeInventoryScreen: an unbordered EditBox of 50 at (82, 6).
+ let search = &mut self.creative_screen.search;
+ search.x = ox + 82.0;
+ search.y = oy + 6.0;
+ search.width = 80.0;
+ search.bordered = false;
+ search.focused = true;
+ search.text_color = u32::MAX;
+ search.max_length = clipboard::CREATIVE_SEARCH_CHARS;
+ search.draw(batch, atlas, None);
}
let mut hovered: Option = None;
if tab.inventory {
@@ -9966,8 +10625,7 @@ impl Game<'_> {
} else if self.carried.is_none()
&& let Some(item) = hovered
{
- let lines = self.stack_tooltip(&item);
- self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
+ self.draw_stack_tooltip(batch, &item, self.cursor.0, self.cursor.1);
}
self.draw_inventory_effects(batch, (ox, oy), Creative::WIDTH as i32);
}
@@ -10020,6 +10678,9 @@ impl Game<'_> {
}
return;
}
+ if !right && self.creative_search_click(ox, oy) {
+ return;
+ }
// Holding the scrollbar scrolls as the mouse moves (mouseDragged).
if !right
&& self
@@ -10032,6 +10693,24 @@ impl Game<'_> {
self.inventory_press(right);
}
}
+ /// A click on the search tab's box (`EditBox.onClick`).
+ fn creative_search_click(&mut self, ox: f32, oy: f32) -> bool {
+ if !self.creative_screen.tab().search {
+ return false;
+ }
+ let (x, y, w, h) = (ox + 82.0, oy + 6.0, 80.0, 9.0);
+ let (mx, my) = self.cursor;
+ if mx < x || my < y || mx >= x + w || my >= y + h {
+ return false;
+ }
+ let shift = self.has_shift_down();
+ let search = &mut self.creative_screen.search;
+ search.x = x;
+ search.y = y;
+ search.width = w;
+ search.click(&self.gui.atlas, mx, shift, false);
+ true
+ }
/// Copy the live player and world state into the `Level` that gets saved.
pub(super) fn sync_level(&mut self) {
// Level.write saves the game rules (game_rules.dat) with the rest.
@@ -10151,6 +10830,7 @@ impl Game<'_> {
}
/// Save the level in place: its changed chunks, its entities and its raids.
fn save_level(&mut self, wait: bool) -> Result<()> {
+ self.save.save_forced_chunks(&self.streaming.forced)?;
self.streaming.save(&mut self.world, wait);
let keys: Vec<_> = self.world.modified.drain().collect();
let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k)));
@@ -10340,6 +11020,17 @@ impl Game<'_> {
[0.0; 3]
};
let p = h.pos.map(f64::from);
+ if let Some(b) = self.context_outline(h.pos, state) {
+ return horizon_client::blocks::cube_edges()
+ .iter()
+ .map(|e| {
+ std::array::from_fn(|i| {
+ let k = i % 3;
+ p[k] + b[k] + e[i] * (b[k + 3] - b[k])
+ })
+ })
+ .collect();
+ }
f.outline_edges
.iter()
.map(|e| std::array::from_fn(|i| p[i % 3] + o[i % 3] + e[i]))
@@ -10350,8 +11041,6 @@ impl Game<'_> {
Vec::new()
};
let mut hud = horizon_client::spans::time("hud", || self.hud(size));
- // Map textures changed since the last drawn frame (game/maps.rs).
- hud.patches.append(&mut self.map_patches);
// LevelLoadingScreen (Reason.OTHER) draws the title's panorama.
let title = self.title.is_some()
|| self.loading_reason() == Some(horizon_client::level_loading::Reason::Other);
@@ -10453,6 +11142,10 @@ impl Game<'_> {
} else {
self.shader_pack_inputs(camera, alpha as f32)
};
+ // Map textures and font glyphs changed while building this frame's
+ // geometry (game/maps.rs, world text) upload with this batch; draining
+ // map_patches any earlier leaves them a frame behind.
+ hud.patches.append(&mut self.map_patches);
let entity_spans = std::mem::take(self.entity_spans.get_mut());
let frame = Frame {
weather: &weather,
@@ -11068,11 +11761,7 @@ impl Game<'_> {
bytes += size;
}
}
- for c in unloaded {
- for sy in 0..(HEIGHT / 16) {
- renderer.remove((c.x, sy, c.z));
- }
- }
+ renderer.remove_columns(unloaded.iter().map(|c| (c.x, c.z)));
if let (Some(lod), Some(player)) = (&mut self.lod, &self.player) {
let lod_distance = self.settings.horizon.lod_distance_on(&renderer.info);
lod.set_near_loading(self.streaming.busy());
@@ -11402,6 +12091,7 @@ impl ApplicationHandler for Game<'_> {
}
if self.screen == Screen::Inventory
&& d != 0.0
+ && !self.bundle_scroll(scaled(raw_x), scaled(raw_y))
&& !self.tweak_scroll(d, self.inventory_target().0)
{
self.station_scroll(d);
@@ -11543,16 +12233,17 @@ impl ApplicationHandler for Game<'_> {
}
self.extras_mouse(button, pressed);
self.mod_mouse_key(button, pressed);
- match self.settings.keys.translate_mouse(button) {
- Some(Err(b)) => self.play_mouse(b, pressed)?,
- Some(Ok(k)) if pressed => {
- self.keys.insert(k);
- self.key_pressed(k)?;
+ for mapped in self.settings.keys.translate_mouse_all(button) {
+ match mapped {
+ Err(b) => self.play_mouse(b, pressed)?,
+ Ok(k) if pressed => {
+ self.keys.insert(k);
+ self.key_pressed(k)?;
+ }
+ Ok(k) => {
+ self.keys.remove(&k);
+ }
}
- Some(Ok(k)) => {
- self.keys.remove(&k);
- }
- None => {}
}
}
Screen::Inventory | Screen::Creative
@@ -11679,8 +12370,17 @@ impl ApplicationHandler for Game<'_> {
// The hovered slot took the key (`ignoreTextInput`).
} else if let Some(shortcut) = self.edit_shortcut(&event) {
self.creative_search_shortcut(shortcut);
- } else if event.physical_key == PhysicalKey::Code(KeyCode::Backspace) {
- self.creative_search_backspace(self.has_control_down());
+ } else if let PhysicalKey::Code(key) = event.physical_key {
+ // EditBox.keyPressed: arrows, Home, End, Delete and Backspace.
+ let before = self.creative_screen.search.value.clone();
+ let (ctrl, shift) = (self.has_control_down(), self.has_shift_down());
+ if self.creative_screen.search.key(key, ctrl, shift) {
+ if self.creative_screen.search.value != before {
+ self.creative_screen.scroll = 0.0;
+ }
+ } else {
+ self.creative_search_edit(event.text.as_deref());
+ }
} else {
self.creative_search_edit(event.text.as_deref());
}
@@ -11693,6 +12393,14 @@ impl ApplicationHandler for Game<'_> {
// The recipe book's search box takes every key but Escape.
self.recipe_key(&event);
}
+ WindowEvent::KeyboardInput { event, .. }
+ if self.mod_browser_typing()
+ && event.state == ElementState::Pressed
+ && !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) =>
+ {
+ // A mod's item panel's search box, as the recipe book's.
+ self.mod_browser_key(&event);
+ }
WindowEvent::KeyboardInput { event, .. }
if self.station_typing()
&& event.state == ElementState::Pressed
@@ -11701,6 +12409,9 @@ impl ApplicationHandler for Game<'_> {
// The anvil rename box takes every key but Escape (AnvilScreen.keyPressed).
if let Some(shortcut) = self.edit_shortcut(&event) {
self.station_shortcut(shortcut);
+ } else if let PhysicalKey::Code(key) = event.physical_key
+ && self.station_key(key)
+ {
} else {
let backspace = event.physical_key == PhysicalKey::Code(KeyCode::Backspace);
self.station_text(event.text.as_deref(), backspace);
@@ -11788,18 +12499,24 @@ impl ApplicationHandler for Game<'_> {
{
self.smooth_camera = !self.smooth_camera;
}
- // Key binds: act as the default key of the bound mapping.
- let key = match self.settings.keys.translate(key) {
- Some(Ok(k)) => k,
- Some(Err(button)) => {
- if self.screen == Screen::Playing && !event.repeat {
- self.play_mouse(button, event.state == ElementState::Pressed)?;
+ // Key binds: act as the default key of every mapping bound
+ // to it (KeyMapping.set drives them all).
+ for mapped in self.settings.keys.translate_all(key) {
+ match mapped {
+ Ok(k) => {
+ self.mapped_key(
+ k,
+ event.state == ElementState::Pressed,
+ event.repeat,
+ )?;
+ }
+ Err(button) => {
+ if self.screen == Screen::Playing && !event.repeat {
+ self.play_mouse(button, event.state == ElementState::Pressed)?;
+ }
}
- return Ok(());
}
- None => return Ok(()),
- };
- self.mapped_key(key, event.state == ElementState::Pressed, event.repeat)?;
+ }
}
WindowEvent::RedrawRequested => {
self.observe_fullscreen();
@@ -12164,6 +12881,7 @@ impl<'a> Game<'a> {
craft_table: None,
inv_drag: None,
tweaks: Default::default(),
+ bundle_mouse: Default::default(),
inv_clicks: Default::default(),
last_inv_click: None,
last_quick_moved: None,
@@ -12213,6 +12931,7 @@ impl<'a> Game<'a> {
last_input: now,
pad: Default::default(),
frames: 0,
+ item_level_cache: Default::default(),
world_frames: 0,
fps: 0.0,
fps_frames: 0,
@@ -12224,7 +12943,14 @@ impl<'a> Game<'a> {
level,
session_lock: None,
audio,
- music: Default::default(),
+ music: {
+ // The manager starts with the saved option (MusicManager's constructor).
+ let mut music = horizon_client::music::MusicManager::default();
+ music.frequency = horizon_client::music::MusicFrequency::parse(
+ &settings.file.name("musicFrequency"),
+ );
+ music
+ },
ambience: Default::default(),
sound_paused: false,
cart_sounds: HashSet::new(),
@@ -12268,6 +12994,8 @@ impl<'a> Game<'a> {
command_source: None,
titles: Default::default(),
tool_highlight: Default::default(),
+ saving_indicator: Default::default(),
+ autosaving: false,
applied_modifiers: Vec::new(),
experience: Experience::default(),
orbs: Vec::new(),
@@ -12317,6 +13045,7 @@ impl<'a> Game<'a> {
map_frame_model: prepared.map_frame_model,
glow_map_frame_model: prepared.glow_map_frame_model,
armor_stands: Vec::new(),
+ cushions: Vec::new(),
others: Vec::new(),
armor_stand_assets: prepared.armor_stand_assets,
waypoint_styles: prepared.waypoint_styles,
@@ -12326,6 +13055,7 @@ impl<'a> Game<'a> {
boats: Vec::new(),
boat_models: prepared.boat_models,
crystal_model: prepared.crystal_model,
+ cushion_model: prepared.cushion_model,
carts: Vec::new(),
jukebox_sounds: HashMap::new(),
bolts: Vec::new(),
@@ -12412,6 +13142,7 @@ impl<'a> Game<'a> {
lan_events: Vec::new(),
lan_block_events: Vec::new(),
lan_entity_events: Vec::new(),
+ lan_critical_hits: Vec::new(),
lan_global_events: Vec::new(),
lid_openers: HashMap::new(),
lan_acting: None,
@@ -12463,6 +13194,7 @@ struct GameCpuResources {
boat_models: boats::BoatModels,
cart_models: minecarts::CartModels,
crystal_model: Option,
+ cushion_model: Option,
dragon_model: Option,
arrow_model: Option,
trident_model: Option,
@@ -12483,6 +13215,7 @@ impl GameCpuResources {
boat_models: boats::BoatModels::load(document.as_ref()),
cart_models: minecarts::CartModels::load(document.as_ref()),
crystal_model: model("minecraft:end_crystal#main"),
+ cushion_model: model("minecraft:cushion#main"),
dragon_model: model("minecraft:ender_dragon#main"),
arrow_model: model("minecraft:arrow#main"),
trident_model: model("minecraft:trident#main"),
@@ -12586,6 +13319,17 @@ impl Game<'_> {
if self.rest_loader.is_some() {
return Ok(());
}
+ let on_world_screens = self.title.as_ref().is_some_and(|title| {
+ !matches!(
+ title.mode,
+ horizon_client::title::Mode::Main | horizon_client::title::Mode::Multiplayer(_)
+ )
+ });
+ world_loading::preload_world_data(
+ on_world_screens,
+ &self.options.resources,
+ self.pack.assets.registry,
+ );
if std::mem::take(&mut self.pending_pack_reload) {
self.reload_packs();
}
@@ -13042,6 +13786,14 @@ fn build_renderer(
) -> Result {
let assets = &pack.render;
let atlas = &gui.atlas;
+ // The new renderer's atlas texture starts from `HudAtlas.pixels`, which
+ // holds the textures but never a glyph rasterized at run time. The font's
+ // cache still answers with the rects it drew into the previous renderer's
+ // texture, so forget them: the glyphs that are drawn again are placed into
+ // this texture (as `ui_theme` does when its atlas changes). Without this,
+ // Chinese and Japanese menu labels go blank when the loading screen hands
+ // over to the game.
+ atlas.font.reset_cache();
let mut renderer = pollster::block_on(Renderer::new(
window,
offscreen,
@@ -13088,6 +13840,12 @@ fn loading_renderer(
Some(atlas) => (atlas.pixels.as_slice(), atlas.width, atlas.height),
None => (EMPTY_HUD.as_slice(), 1, 1),
};
+ // A glyph rasterized into an earlier texture is not in these pixels; the
+ // new texture gets it again when the character is drawn (see
+ // `build_renderer`).
+ if let Some(atlas) = atlas {
+ atlas.font.reset_cache();
+ }
let mut renderer = pollster::block_on(Renderer::new(
window,
offscreen,
@@ -13824,7 +14582,7 @@ mod startup_cpu_tests {
r#"{
"minecraft:end_crystal#main": {}, "minecraft:ender_dragon#main": {},
"minecraft:arrow#main": {}, "minecraft:trident#main": {},
- "minecraft:armor_stand#main": {}
+ "minecraft:armor_stand#main": {}, "minecraft:cushion#main": {}
}"#,
)
.unwrap();
@@ -13844,6 +14602,7 @@ mod startup_cpu_tests {
.unwrap();
std::fs::remove_dir_all(&root).unwrap();
assert!(prepared.crystal_model.is_some());
+ assert!(prepared.cushion_model.is_some());
assert!(prepared.dragon_model.is_some());
assert!(prepared.arrow_model.is_some());
assert!(prepared.trident_model.is_some());
diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs
index f175af401..9a8c846c5 100644
--- a/crates/horizon-client/src/game/armor_stands.rs
+++ b/crates/horizon-client/src/game/armor_stands.rs
@@ -453,6 +453,11 @@ impl Game<'_> {
}
// ArmorStand.swapItem.
match held {
+ // A player with infinite materials puts a copy of one on an empty
+ // slot and keeps the stack.
+ Some(h) if self.creative && current.is_none() => {
+ self.armor_stands[i].equipment[slot] = Some(ItemStack { count: 1, ..h });
+ }
Some(h) if h.count > 1 => {
if current.is_some() {
return true;
diff --git a/crates/horizon-client/src/game/beacon.rs b/crates/horizon-client/src/game/beacon.rs
index 24ead3a3d..97177f2b9 100644
--- a/crates/horizon-client/src/game/beacon.rs
+++ b/crates/horizon-client/src/game/beacon.rs
@@ -515,8 +515,7 @@ impl Game<'_> {
if self.carried.is_some() {
self.draw_carried(batch);
} else if let Some(stack) = stack_tip {
- let lines = self.stack_tooltip(&stack);
- self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
+ self.draw_stack_tooltip(batch, &stack, self.cursor.0, self.cursor.1);
} else if let Some(key) = tooltip {
let text = self.translate(&key, &key);
self.draw_tooltip_lines(
diff --git a/crates/horizon-client/src/game/block_entity_anims.rs b/crates/horizon-client/src/game/block_entity_anims.rs
index 3d452596e..6f92d7f55 100644
--- a/crates/horizon-client/src/game/block_entity_anims.rs
+++ b/crates/horizon-client/src/game/block_entity_anims.rs
@@ -5,10 +5,14 @@
//! [`Game::block_anim`] and [`Game::chest_lid`].
use super::Game;
use horizon_client::{
- block_entity_anim::{BellEntity, EndGateway, Shulker, ShulkerStatus, Ticker},
+ block_entity_anim::{
+ BellEntity, ConduitServer, ConduitTarget, EndGateway, Shulker, ShulkerStatus, Ticker,
+ },
block_entity_render::BlockAnim,
collisions::{SceneCollisions, no_collision_empty},
containers::BlockEntity,
+ effects::EffectInstance,
+ mobs::{Damage, DamageKind},
particles::{ParticleOptions, ParticleType},
save::number,
skins,
@@ -16,6 +20,7 @@ use horizon_client::{
use horizon_core::{
geometry::{Aabb, Vec3},
position::BlockPos,
+ random::RandomSource,
};
use horizon_world::nbt::Tag;
@@ -218,9 +223,12 @@ impl Game<'_> {
/// The client tickers of the loaded animated block entities, once per
/// client tick (`ClientLevel.tickBlockEntities`).
pub(super) fn tick_block_entity_anims(&mut self) {
+ // A server has no window, but its gateways and conduits still run
+ // their server tickers; a client of one only animates what it is sent.
+ if self.remote.is_none() {
+ self.tick_conduit_servers();
+ }
let Some(r) = &self.renderer else {
- // A server has no window, but its gateways still run their
- // server ticker.
if self.remote.is_none() {
self.tick_gateway_servers();
}
@@ -337,6 +345,7 @@ impl Game<'_> {
}
}
Ticker::Conduit => {
+ let target = self.conduit_target(pos);
let world = &self.world;
let facts = self.res.facts();
let registry = self.pack.assets.registry;
@@ -356,7 +365,7 @@ impl Game<'_> {
time,
is_water,
is_frame,
- None,
+ target,
self.particles.random(),
);
let nautilus = ParticleOptions::simple(ParticleType::Nautilus);
@@ -383,6 +392,248 @@ impl Game<'_> {
}
self.be_anims.present = positions;
}
+ /// `ConduitBlockEntity.serverTick` of every conduit in the chunks that
+ /// tick blocks, with or without a renderer. The conduits are looked for
+ /// when the shape is checked, every 40 ticks (they have no block entity
+ /// of their own here).
+ fn tick_conduit_servers(&mut self) {
+ if self.world.game_time % 40 == 0 {
+ self.find_conduits();
+ }
+ let mut positions: Vec<[i32; 3]> = self.be_anims.conduit_servers.keys().copied().collect();
+ positions.sort_unstable();
+ for pos in positions {
+ self.tick_conduit_server(pos);
+ }
+ }
+ /// Sets `be_anims.conduit_servers` to the conduits in the
+ /// chunks that tick blocks, keeping the state of those already known.
+ fn find_conduits(&mut self) {
+ let levels = self.tickets.levels();
+ let kinds = &self.be_anims.kinds;
+ let is_conduit = |id: u32| matches!(kinds.get(id as usize), Some(Some(Ticker::Conduit)));
+ let mut found = Vec::new();
+ for (&(cx, cz), chunk) in &self.world.chunks {
+ if !levels.block_ticking_at(cx * 16, cz * 16) {
+ continue;
+ }
+ for (si, section) in chunk.sections.iter().enumerate() {
+ if !section.blocks.maybe_has(is_conduit) {
+ continue;
+ }
+ for i in 0..4096 {
+ if is_conduit(section.get(i)) {
+ found.push([
+ cx * 16 + (i & 15) as i32,
+ horizon_client::chunk::MIN_Y + si as i32 * 16 + (i >> 8) as i32,
+ cz * 16 + ((i >> 4) & 15) as i32,
+ ]);
+ }
+ }
+ }
+ }
+ let mut old = std::mem::take(&mut self.be_anims.conduit_servers);
+ for pos in found {
+ let known = old.remove(&pos).unwrap_or_default();
+ self.be_anims.conduit_servers.insert(pos, known);
+ }
+ }
+ /// `ConduitBlockEntity.serverTick` of the conduit at `pos`, in a chunk
+ /// that ticks blocks: the shape check every 40 ticks with its sounds, the
+ /// power for players in range, the hurt for an enemy, then the ambient
+ /// sounds.
+ fn tick_conduit_server(&mut self, pos: [i32; 3]) {
+ let state = self.world.block(pos[0], pos[1], pos[2]).0;
+ if self.be_anims.ticker(state) != Some(Ticker::Conduit) {
+ // Broken since the chunks were searched.
+ self.be_anims.conduit_servers.remove(&pos);
+ return;
+ }
+ if !self.tickets.levels().block_ticking_at(pos[0], pos[2])
+ || !self.border.contains(f64::from(pos[0]), f64::from(pos[2]))
+ {
+ return;
+ }
+ let time = self.world.game_time;
+ let mut conduit = self
+ .be_anims
+ .conduit_servers
+ .remove(&pos)
+ .unwrap_or_default();
+ let check = {
+ let world = &self.world;
+ let facts = self.res.facts();
+ let registry = self.pack.assets.registry;
+ let frames = self
+ .res
+ .items()
+ .block_tags
+ .get("minecraft:conduit_effect_block");
+ // Level.isWaterAt: the fluid at the position is water.
+ let is_water = |p: [i32; 3]| {
+ facts.get(world.block(p[0], p[1], p[2])).fluid
+ == horizon_client::blocks::Fluid::Water
+ };
+ let is_frame = |p: [i32; 3]| {
+ registry
+ .state(world.block(p[0], p[1], p[2]))
+ .is_some_and(|s| frames.is_some_and(|f| f.contains(&s.name)))
+ };
+ conduit.check(pos, time, is_water, is_frame)
+ };
+ let centre = [
+ f64::from(pos[0]) + 0.5,
+ f64::from(pos[1]) + 0.5,
+ f64::from(pos[2]) + 0.5,
+ ];
+ if let Some(check) = check {
+ if let Some(active) = check.toggled {
+ let sound = if active {
+ "minecraft:block.conduit.activate"
+ } else {
+ "minecraft:block.conduit.deactivate"
+ };
+ self.audio.play(sound, Some(centre), 1.0, 1.0);
+ }
+ if let Some(frames) = check.frames {
+ self.conduit_apply_effects(pos, frames);
+ self.conduit_attack(&mut conduit, pos, frames >= 42);
+ }
+ }
+ let (ambient, short) = conduit.ambient(time, &mut self.world.random);
+ if ambient {
+ self.audio
+ .play("minecraft:block.conduit.ambient", Some(centre), 1.0, 1.0);
+ }
+ if short {
+ self.audio.play(
+ "minecraft:block.conduit.ambient_short",
+ Some(centre),
+ 1.0,
+ 1.0,
+ );
+ }
+ self.be_anims.conduit_servers.insert(pos, conduit);
+ }
+ /// `ConduitBlockEntity.applyEffects`: conduit power for every player
+ /// in water or rain within `frames / 7 * 16` blocks.
+ fn conduit_apply_effects(&mut self, pos: [i32; 3], frames: usize) {
+ let range = (frames / 7 * 16) as i64;
+ self.for_each_player(|g| {
+ let Some(p) = g.player.as_ref().filter(|p| !p.health.dead_or_dying()) else {
+ return;
+ };
+ if g.spectator() {
+ return;
+ }
+ let at = p.position;
+ let in_water = p.fluids.was_touching_water;
+ let top = at.y + f64::from(p.dimensions.height);
+ // BlockPos.closerThan: the squared distance under range squared.
+ let d = [at.x, at.y, at.z]
+ .map(|v| v.floor() as i64)
+ .iter()
+ .zip(pos)
+ .map(|(a, b)| (a - i64::from(b)).pow(2))
+ .sum::();
+ if d >= range * range || !(in_water || g.in_rain(at, top)) {
+ return;
+ }
+ let power = EffectInstance {
+ ambient: true,
+ ..EffectInstance::new("conduit_power", 260, 0)
+ };
+ g.potions.effects.add(power);
+ });
+ }
+ /// `Entity.isInRain`: rain at the block position or at the top of the box.
+ fn in_rain(&mut self, at: Vec3, top: f64) -> bool {
+ let p = BlockPos::new(
+ at.x.floor() as i32,
+ at.y.floor() as i32,
+ at.z.floor() as i32,
+ );
+ let up = BlockPos::new(p.x, top.floor() as i32, p.z);
+ self.with_level(|b, level, _| b.is_raining_at(level, p) || b.is_raining_at(level, up))
+ }
+ /// `ConduitBlockEntity.updateAndAttackTarget`: while the conduit hunts
+ /// (42 frame blocks) its target stays until it dies or leaves the 8
+ /// blocks, else a random enemy in water or rain is chosen; the target
+ /// takes 4 magic damage.
+ fn conduit_attack(&mut self, conduit: &mut ConduitServer, pos: [i32; 3], hunting: bool) {
+ conduit.target = match conduit.target {
+ _ if !hunting => None,
+ None => self.conduit_new_target(pos),
+ Some(id) => self
+ .mobs
+ .iter()
+ .find(|m| m.id == id && !m.removed)
+ .filter(|m| {
+ let at = [m.position.x, m.position.y, m.position.z].map(|v| v.floor() as i64);
+ m.alive()
+ && at
+ .iter()
+ .zip(pos)
+ .map(|(a, b)| (a - i64::from(b)).pow(2))
+ .sum::()
+ < 64
+ })
+ .map(|m| m.id),
+ };
+ let Some(m) = conduit
+ .target
+ .and_then(|id| self.mobs.iter_mut().find(|m| m.id == id))
+ else {
+ return;
+ };
+ let at = [m.position.x, m.position.y, m.position.z];
+ m.damage(4.0, Damage::of(DamageKind::Magic));
+ self.audio
+ .play("minecraft:block.conduit.attack.target", Some(at), 1.0, 1.0);
+ }
+ /// `ConduitBlockEntity.selectNewTarget`: one of the enemies in water or
+ /// rain whose box meets the conduit's block inflated by 8.
+ fn conduit_new_target(&mut self, pos: [i32; 3]) -> Option {
+ let [x, y, z] = pos.map(f64::from);
+ let area = Aabb::new(
+ Vec3::new(x - 8.0, y - 8.0, z - 8.0),
+ Vec3::new(x + 9.0, y + 9.0, z + 9.0),
+ );
+ let near: Vec<(u32, bool, Vec3, f64)> = self
+ .mobs
+ .iter()
+ .filter(|m| m.hostile() && !m.removed && m.bounds().intersects(area))
+ .map(|m| {
+ let top = m.position.y + f64::from(m.height());
+ (m.id, m.fluids.in_water, m.position, top)
+ })
+ .collect();
+ let candidates: Vec = near
+ .into_iter()
+ .filter(|&(_, in_water, at, top)| in_water || self.in_rain(at, top))
+ .map(|(id, ..)| id)
+ .collect();
+ if candidates.is_empty() {
+ return None;
+ }
+ let pick = self
+ .world
+ .random
+ .next_int_bound(candidates.len() as i32)
+ .unwrap_or(0);
+ Some(candidates[pick as usize])
+ }
+ /// The conduit's `destroyTarget` as the client draws it.
+ fn conduit_target(&self, pos: [i32; 3]) -> Option {
+ let id = self.be_anims.conduit_servers.get(&pos)?.target?;
+ let m = self.mobs.iter().find(|m| m.id == id && !m.removed)?;
+ Some(ConduitTarget {
+ position: [m.position.x, m.position.y, m.position.z],
+ eye_y: m.eye_y(),
+ width: m.width(),
+ height: m.height(),
+ })
+ }
/// `TheEndGatewayBlockEntity.portalTick` (the server ticker) of the
/// gateways a server keeps a copy of, in block-ticking chunks
/// (`Level.tickBlockEntities`): the cooldown an entry started runs out,
diff --git a/crates/horizon-client/src/game/block_entity_ticks.rs b/crates/horizon-client/src/game/block_entity_ticks.rs
index e48c8f398..2778bb531 100644
--- a/crates/horizon-client/src/game/block_entity_ticks.rs
+++ b/crates/horizon-client/src/game/block_entity_ticks.rs
@@ -10,6 +10,7 @@ use horizon_client::{
block_entities::{Pos, Ticking},
containers::{BlockEntity, FurnaceKind, HOPPER_SLOTS},
};
+use horizon_core::position::BlockPos;
use horizon_world::registry::BlockStateId;
impl Game<'_> {
@@ -56,6 +57,8 @@ impl Game<'_> {
Some(BlockEntity::Beehive(_)) => self.tick_beehive(pos),
Some(BlockEntity::Furnace(_)) => self.tick_furnace(pos)?,
Some(BlockEntity::Brewing(_)) => self.tick_brewing_stand(pos)?,
+ Some(BlockEntity::DaylightDetector) => self.tick_daylight_detector(pos),
+ Some(BlockEntity::Campfire(_)) => self.tick_campfire(pos)?,
_ => {}
}
}
@@ -92,7 +95,11 @@ impl Game<'_> {
| "minecraft:vault"
| "minecraft:beehive"
| "minecraft:bee_nest"
- | "minecraft:brewing_stand" => Ticking::Yes,
+ | "minecraft:brewing_stand"
+ | "minecraft:daylight_detector"
+ // Lit, cookTick; unlit, cooldownTick.
+ | "minecraft:campfire"
+ | "minecraft:soul_campfire" => Ticking::Yes,
"minecraft:jukebox" => {
let record = registry
.state(state)
@@ -113,6 +120,16 @@ impl Game<'_> {
let levels = self.tickets.levels();
move |x, z| levels.block_ticking_at(x, z)
}
+ /// `DaylightDetectorBlock.tickEntity` of the detector at `pos`.
+ fn tick_daylight_detector(&mut self, pos: Pos) {
+ // It updates every 20 game ticks (the behaviour checks this too).
+ if self.world.game_time % 20 != 0 {
+ return;
+ }
+ let at = BlockPos::new(pos.0, pos.1, pos.2);
+ self.with_level(|b, level, ticks| b.tick_daylight_detector(level, ticks, at));
+ let _ = self.process_level_events();
+ }
/// `AbstractFurnaceBlockEntity.serverTick` of the furnace at `pos`, and
/// its block's `lit` following it.
fn tick_furnace(&mut self, pos: Pos) -> Result<()> {
diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs
index df7158d9a..06dfab22d 100644
--- a/crates/horizon-client/src/game/boats.rs
+++ b/crates/horizon-client/src/game/boats.rs
@@ -55,7 +55,7 @@ pub(super) struct Boat {
/// `ChestBoat.CONTAINER_SIZE`.
pub(super) const CHEST_SLOTS: usize = 27;
pub(super) const WIDTH: f64 = 1.375;
-const HEIGHT: f64 = 0.5625;
+pub(super) const HEIGHT: f64 = 0.5625;
impl Boat {
pub fn new(id: u32, wood: Arc, position: Vec3, yaw: f32) -> Self {
Self {
@@ -587,6 +587,9 @@ impl Game<'_> {
}
/// The player's tick while riding: steer, tick the boat, sit in it.
pub(super) fn tick_riding(&mut self, keys: Keys) -> horizon_client::Result<()> {
+ if self.tick_cushion_riding(keys) {
+ return Ok(());
+ }
let Some(i) = self.boats.iter().position(|b| Some(b.id) == self.riding) else {
if self.tick_cart_riding(keys) || self.tick_mount_riding(keys) {
return Ok(());
diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs
index 9af1da70c..2f38dffd9 100644
--- a/crates/horizon-client/src/game/books.rs
+++ b/crates/horizon-client/src/game/books.rs
@@ -17,7 +17,6 @@ use horizon_client::{
use horizon_core::position::BlockPos;
use horizon_protocol::packets::play::{self, Clientbound as C, Serverbound as S};
use horizon_world::level::flags as level_flags;
-use std::time::Instant;
use winit::{
event::{ElementState, KeyEvent},
keyboard::{KeyCode, PhysicalKey},
@@ -27,8 +26,24 @@ const BLACK: u32 = 0xFF00_0000;
const PAGE_CHARS: usize = 1024;
const MAX_PAGES: usize = 100;
const LINES: usize = 14;
-/// `BookSignScreen`'s title box.
-const BOOK_TITLE: horizon_client::clipboard::FieldId = ("book.title", 0);
+
+fn book_title_box() -> ui::EditBox {
+ let mut edit = ui::EditBox::new(0.0, 0.0, 114.0, 9.0);
+ edit.bordered = false;
+ edit.max_length = 15;
+ edit.text_color = BLACK;
+ edit.focused = true;
+ edit
+}
+fn book_page_box() -> ui::EditBox {
+ let mut edit = ui::EditBox::new(0.0, 0.0, 114.0, 9.0);
+ edit.bordered = false;
+ edit.multiline = true;
+ edit.max_length = PAGE_CHARS;
+ edit.text_color = BLACK;
+ edit.focused = true;
+ edit
+}
pub(super) enum BookScreen {
Edit {
@@ -38,7 +53,10 @@ pub(super) enum BookScreen {
page: usize,
signing: bool,
title: String,
- opened: Instant,
+ /// BookSignScreen's title box (`EditBox` of 15).
+ title_edit: ui::EditBox,
+ /// BookEditScreen's page (`MultiLineEditBox`).
+ page_edit: ui::EditBox,
},
View {
pages: Vec,
@@ -84,13 +102,16 @@ impl Game<'_> {
if pages.is_empty() {
pages.push(String::new());
}
+ let mut page_edit = book_page_box();
+ page_edit.set_value(&pages[0]);
BookScreen::Edit {
slot: self.held_slot(),
pages,
page: 0,
signing: false,
title: String::new(),
- opened: Instant::now(),
+ title_edit: book_title_box(),
+ page_edit,
}
}
"minecraft:written_book" => BookScreen::View {
@@ -239,34 +260,24 @@ impl Game<'_> {
Some(KeyCode::PageDown) => self.turn_page(true),
_ => {}
},
- Some(BookScreen::Edit {
- signing: true,
- title,
- ..
- }) => match key {
+ Some(BookScreen::Edit { signing: true, .. }) => match key {
Some(KeyCode::Escape) => {
if let Some(BookScreen::Edit { signing, .. }) = self.book.as_mut() {
*signing = false;
}
}
- Some(KeyCode::Backspace) => {
- if !self.text_selection.take(BOOK_TITLE, title) {
- title.pop();
- }
- }
Some(KeyCode::Enter | KeyCode::NumpadEnter) => {
- if !title.trim().is_empty() {
+ let blank = self.book.as_ref().is_some_and(
+ |b| matches!(b, BookScreen::Edit { title, .. } if title.trim().is_empty()),
+ );
+ if !blank {
self.save_book(true);
}
}
+ Some(key) if self.book_title_key(key) => {}
_ => {
if let Some(typed) = text {
- self.text_selection.take(BOOK_TITLE, title);
- for c in typed.chars().filter(|c| !c.is_control()) {
- if title.chars().count() < 15 {
- title.push(c);
- }
- }
+ self.book_title_insert(typed);
}
}
},
@@ -274,24 +285,13 @@ impl Game<'_> {
Some(KeyCode::Escape) => self.save_book(false),
Some(KeyCode::PageUp) => self.turn_page(false),
Some(KeyCode::PageDown) => self.turn_page(true),
- Some(KeyCode::Backspace) => {
- if !self.take_page_selection() {
- self.edit_page(|p| {
- p.pop();
- })
- }
- }
- Some(KeyCode::Enter | KeyCode::NumpadEnter) => {
- self.take_page_selection();
- self.type_into_page("\n")
- }
+ Some(KeyCode::ArrowUp) => self.book_move_line(-1),
+ Some(KeyCode::ArrowDown) => self.book_move_line(1),
+ Some(KeyCode::Enter | KeyCode::NumpadEnter) => self.page_insert("\n"),
+ Some(key) if self.book_page_key(key) => {}
_ => {
if let Some(typed) = text {
- let typed: String = typed.chars().filter(|c| !c.is_control()).collect();
- if !typed.is_empty() {
- self.take_page_selection();
- }
- self.type_into_page(&typed);
+ self.page_insert(typed);
}
}
},
@@ -302,99 +302,258 @@ impl Game<'_> {
pub(super) fn book_type(&mut self, text: &str) {
let text = text.replace("\\n", "\n");
match self.book.as_mut() {
- Some(BookScreen::Edit {
- signing: true,
- title,
- ..
- }) => {
- for c in text.chars().filter(|c| !c.is_control()) {
- if title.chars().count() < 15 {
- title.push(c);
- }
- }
- }
- Some(BookScreen::Edit { .. }) => self.type_into_page(&text),
+ Some(BookScreen::Edit { signing: true, .. }) => self.book_title_insert(&text),
+ Some(BookScreen::Edit { .. }) => self.page_insert(&text),
_ => {}
}
}
- /// Before typing on a page: Select All's selection is cleared (true).
- fn take_page_selection(&mut self) -> bool {
- match self.book.as_mut() {
- Some(BookScreen::Edit { pages, page, .. }) => self
- .text_selection
- .take(("book.page", *page), &mut pages[*page]),
- _ => false,
+ /// `BookSignScreen.keyPressed` on the title box.
+ fn book_title_key(&mut self, key: KeyCode) -> bool {
+ let (ctrl, shift) = (self.has_control_down(), self.has_shift_down());
+ let Some(BookScreen::Edit {
+ title, title_edit, ..
+ }) = self.book.as_mut()
+ else {
+ return false;
+ };
+ if !title_edit.key(key, ctrl, shift) {
+ return false;
}
+ title.clone_from(&title_edit.value);
+ true
}
- /// Ctrl+A/C/V/X: the title box (an `EditBox` of 15) while signing, else
- /// the page (`MultilineTextField.insertText`: line breaks kept, cut to
- /// the 1024 characters left, rejected when it overflows the 14 lines).
- pub(super) fn book_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) {
- let font = &self.gui.atlas.font;
- match self.book.as_mut() {
- Some(BookScreen::Edit {
- signing: true,
- title,
- ..
- }) => {
- Self::append_shortcut(
- &mut self.text_selection,
- &mut self.clipboard,
- BOOK_TITLE,
- title,
- shortcut,
- 15,
- );
- }
- Some(BookScreen::Edit { pages, page, .. }) => {
- // truncateInsertionText counts the whole value, selection included.
- let room = PAGE_CHARS.saturating_sub(pages[*page].chars().count());
- self.text_selection.apply(
- ("book.page", *page),
- &mut pages[*page],
- shortcut,
- &mut self.clipboard,
- |value, pasted| {
- let text: String = horizon_client::clipboard::filter_text(pasted, true)
- .chars()
- .take(room)
- .collect();
- let next = format!("{value}{text}");
- font.split(&Text::literal(&next), 114.0).len() <= LINES && {
- *value = next;
- true
- }
- },
- );
- }
- _ => {}
- }
- }
- fn edit_page(&mut self, f: impl FnOnce(&mut String)) {
- if let Some(BookScreen::Edit { pages, page, .. }) = self.book.as_mut() {
- f(&mut pages[*page]);
- }
- }
- /// MultiLineEditBox: characters that keep the page within 14 lines and 1024 characters.
- fn type_into_page(&mut self, typed: &str) {
- let Some(BookScreen::Edit { pages, page, .. }) = self.book.as_ref() else {
+ fn book_title_insert(&mut self, text: &str) {
+ let Some(BookScreen::Edit {
+ title, title_edit, ..
+ }) = self.book.as_mut()
+ else {
return;
};
- let mut text = pages[*page].clone();
- for c in typed.chars() {
- let mut next = text.clone();
- next.push(c);
- if next.chars().count() <= PAGE_CHARS && self.book_lines(&next).len() <= LINES {
- text = next;
+ title_edit.insert_text(text);
+ title.clone_from(&title_edit.value);
+ }
+ /// `BookEditScreen.keyPressed` on the page, apart from the line moves.
+ fn book_page_key(&mut self, key: KeyCode) -> bool {
+ let (ctrl, shift) = (self.has_control_down(), self.has_shift_down());
+ let before = match self.book.as_ref() {
+ Some(BookScreen::Edit { page_edit, .. }) => Some((
+ page_edit.value.clone(),
+ page_edit.cursor,
+ page_edit.highlight,
+ )),
+ _ => return false,
+ };
+ let handled = if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() {
+ page_edit.key(key, ctrl, shift)
+ } else {
+ false
+ };
+ if handled {
+ self.page_keep(before);
+ }
+ handled
+ }
+ /// One character at a time, so a page stops at the last character that fits.
+ fn page_insert(&mut self, text: &str) {
+ for c in text.chars() {
+ self.page_change(|edit| edit.insert_text(&c.to_string()));
+ }
+ }
+ /// Ctrl+A/C/V/X: the title box while signing, else the page.
+ pub(super) fn book_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) {
+ let signing = matches!(self.book, Some(BookScreen::Edit { signing: true, .. }));
+ if signing {
+ if let Some(BookScreen::Edit {
+ title, title_edit, ..
+ }) = self.book.as_mut()
+ {
+ title_edit.shortcut(shortcut, &mut self.clipboard);
+ title.clone_from(&title_edit.value);
+ }
+ return;
+ }
+ let before = match self.book.as_ref() {
+ Some(BookScreen::Edit { page_edit, .. }) => Some((
+ page_edit.value.clone(),
+ page_edit.cursor,
+ page_edit.highlight,
+ )),
+ _ => None,
+ };
+ if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() {
+ page_edit.shortcut(shortcut, &mut self.clipboard);
+ }
+ self.page_keep(before);
+ }
+ /// Edit the page box, then keep it only within 14 lines and 1024 characters.
+ fn page_change(&mut self, f: impl FnOnce(&mut ui::EditBox)) -> bool {
+ let before = match self.book.as_ref() {
+ Some(BookScreen::Edit { page_edit, .. }) => Some((
+ page_edit.value.clone(),
+ page_edit.cursor,
+ page_edit.highlight,
+ )),
+ _ => return false,
+ };
+ let ran = if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() {
+ f(page_edit);
+ true
+ } else {
+ false
+ };
+ ran && self.page_keep(before)
+ }
+ /// Write the page, or put the previous text back when it no longer fits.
+ fn page_keep(&mut self, before: Option<(String, usize, usize)>) -> bool {
+ let next = match self.book.as_ref() {
+ Some(BookScreen::Edit { page_edit, .. }) => page_edit.value.clone(),
+ _ => return false,
+ };
+ let ok = next.chars().count() <= PAGE_CHARS && self.book_lines(&next).len() <= LINES;
+ let Some(BookScreen::Edit {
+ pages,
+ page,
+ page_edit,
+ ..
+ }) = self.book.as_mut()
+ else {
+ return false;
+ };
+ if ok {
+ pages[*page].clone_from(&page_edit.value);
+ } else if let Some((value, cursor, highlight)) = before {
+ page_edit.value = value;
+ page_edit.cursor = cursor;
+ page_edit.highlight = highlight;
+ }
+ ok
+ }
+ /// ArrowUp and ArrowDown move a visual line, keeping the column.
+ fn book_move_line(&mut self, dir: isize) {
+ let shift = self.has_shift_down();
+ let (text, cursor) = match self.book.as_ref() {
+ Some(BookScreen::Edit {
+ pages,
+ page,
+ page_edit,
+ ..
+ }) => (pages[*page].clone(), page_edit.cursor),
+ _ => return,
+ };
+ let rows = self.page_rows(&text);
+ let (x, line) = self.caret_on(&text, &rows, cursor);
+ let next = (line as isize + dir).clamp(0, rows.len() as isize - 1) as usize;
+ let (start, end) = rows[next];
+ let chars: Vec = text.chars().collect();
+ let slice: String = chars[start..end].iter().collect();
+ let pos = start + self.gui.atlas.font.fit(&slice, x);
+ if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() {
+ page_edit.set_cursor(pos, shift);
+ }
+ }
+ /// Wrapped rows of a page as character ranges, the same breaks as `font.split`.
+ fn page_rows(&self, page: &str) -> Vec<(usize, usize)> {
+ let font = &self.gui.atlas.font;
+ let chars: Vec = page.chars().collect();
+ let mut rows = Vec::new();
+ let mut start = 0;
+ while start < chars.len() {
+ let mut end = chars.len();
+ let mut next = chars.len();
+ let mut last_space = None;
+ for i in start..chars.len() {
+ if chars[i] == '\n' {
+ end = i;
+ next = i + 1;
+ break;
+ }
+ if chars[i] == ' ' {
+ last_space = Some(i);
+ }
+ let slice: String = chars[start..=i].iter().collect();
+ if font.width(&slice) > 114.0 {
+ match last_space {
+ Some(s) if s > start => {
+ end = s;
+ next = s + 1;
+ }
+ _ => {
+ end = i.max(start + 1);
+ next = end;
+ }
+ }
+ break;
+ }
+ }
+ rows.push((start, end));
+ start = next;
+ if start == chars.len() && chars.last() == Some(&'\n') {
+ rows.push((chars.len(), chars.len()));
}
}
- self.edit_page(|p| *p = text);
+ if rows.is_empty() {
+ rows.push((0, 0));
+ }
+ rows
+ }
+ /// GUI x of the caret and the row it sits on.
+ fn caret_on(&self, page: &str, rows: &[(usize, usize)], cursor: usize) -> (f32, usize) {
+ let chars: Vec = page.chars().collect();
+ for (i, &(start, end)) in rows.iter().enumerate() {
+ if cursor <= end || i + 1 == rows.len() {
+ let take = cursor.saturating_sub(start).min(end.saturating_sub(start));
+ let prefix: String = chars.iter().skip(start).take(take).collect();
+ return (self.gui.atlas.font.width(&prefix), i);
+ }
+ }
+ (0.0, 0)
+ }
+ fn page_index_at(&self, page: &str, local_x: f32, local_y: f32) -> usize {
+ let rows = self.page_rows(page);
+ let line = (local_y / 9.0).floor().max(0.0) as usize;
+ let line = line.min(rows.len().saturating_sub(1));
+ let (start, end) = rows[line];
+ let chars: Vec = page.chars().collect();
+ let slice: String = chars[start..end].iter().collect();
+ start + self.gui.atlas.font.fit(&slice, local_x.max(0.0))
+ }
+ /// A click on the centred title (`EditBox.onClick`).
+ fn book_title_click(&mut self, field_x: f32, mx: f32) {
+ let shift = self.has_shift_down();
+ let Some(BookScreen::Edit {
+ title, title_edit, ..
+ }) = self.book.as_mut()
+ else {
+ return;
+ };
+ let tx = field_x + ((114.0 - self.gui.atlas.font.width(title)) / 2.0).floor();
+ let rel = (mx - tx).max(0.0);
+ let pos = self.gui.atlas.font.fit(title, rel);
+ title_edit.set_cursor(pos, shift);
+ }
+ /// A click on the open page.
+ fn book_page_click(&mut self, origin_x: f32, origin_y: f32, mx: f32, my: f32) {
+ let shift = self.has_shift_down();
+ let text = match self.book.as_ref() {
+ Some(BookScreen::Edit { pages, page, .. }) => pages[*page].clone(),
+ _ => return,
+ };
+ let pos = self.page_index_at(&text, mx - origin_x, my - origin_y);
+ if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() {
+ page_edit.set_cursor(pos, shift);
+ }
}
/// The page buttons (`pageForward` adds a page while editing).
fn turn_page(&mut self, forward: bool) {
let mut lectern_page = None;
match self.book.as_mut() {
- Some(BookScreen::Edit { pages, page, .. }) => {
+ Some(BookScreen::Edit {
+ pages,
+ page,
+ page_edit,
+ ..
+ }) => {
+ let before = *page;
if forward {
if *page + 1 >= pages.len() && pages.len() < MAX_PAGES {
pages.push(String::new());
@@ -405,6 +564,10 @@ impl Game<'_> {
} else if *page > 0 {
*page -= 1;
}
+ if *page != before {
+ let text = pages[*page].clone();
+ page_edit.set_value(&text);
+ }
}
Some(BookScreen::View {
lectern: Some(key), ..
@@ -764,6 +927,8 @@ impl Game<'_> {
if let Some(BookScreen::Edit { signing, .. }) = self.book.as_mut() {
*signing = false;
}
+ } else if inside(left + 36.0, 50.0, 114.0, 9.0) {
+ self.book_title_click(left + 36.0, mx);
}
}
Some(BookScreen::Edit { page, .. }) => {
@@ -780,6 +945,8 @@ impl Game<'_> {
} else if inside(w / 2.0 + 2.0, 196.0, 98.0, 20.0) {
click(self);
self.save_book(false);
+ } else if inside(left + 36.0, 32.0, 114.0, 14.0 * 9.0) {
+ self.book_page_click(left + 36.0, 32.0, mx, my);
}
}
Some(BookScreen::View {
@@ -865,7 +1032,7 @@ impl Game<'_> {
BookScreen::Edit {
signing: true,
title,
- opened,
+ title_edit,
..
} => {
let edit = tr("book.editTitle", "Enter Book Title:");
@@ -881,19 +1048,35 @@ impl Game<'_> {
// The title box: an unbordered, centred EditBox of 114 with
// black text and no shadow; the value alone is centred, the
// cursor follows it.
+ let value = &title_edit.value;
let x = left + 36.0;
- let tx = x + ((114.0 - HudBatch::text_width(atlas, title)) / 2.0).floor();
- horizon_client::ui::append_field(
- batch,
- atlas,
- title,
- (tx, 50.0, x + 114.0 - tx),
- (BLACK, false),
- 15,
- self.text_selection.covers(BOOK_TITLE, title),
- true,
- opened.elapsed().as_millis(),
- );
+ let tx = x + ((114.0 - HudBatch::text_width(atlas, value)) / 2.0).floor();
+ batch.text(atlas, value, tx, 50.0, BLACK, false);
+ if title_edit.cursor != title_edit.highlight {
+ let (a, b) = (
+ title_edit.cursor.min(title_edit.highlight),
+ title_edit.cursor.max(title_edit.highlight),
+ );
+ let pre: String = value.chars().take(a).collect();
+ let sel: String = value.chars().skip(a).take(b - a).collect();
+ let sx = tx + HudBatch::text_width(atlas, &pre);
+ batch.text_highlight(
+ atlas,
+ (sx, 49.0, HudBatch::text_width(atlas, &sel), 11.0),
+ true,
+ );
+ }
+ if title_edit.cursor_visible() {
+ let pre: String = value.chars().take(title_edit.cursor).collect();
+ batch.fill(
+ atlas,
+ tx + HudBatch::text_width(atlas, &pre),
+ 49.0,
+ 1.0,
+ 9.0,
+ BLACK,
+ );
+ }
let by = tr("book.byAuthor", "by %1$s").replace("%1$s", super::chat::PLAYER_NAME);
let tw = HudBatch::text_width(atlas, &by);
batch.text(
@@ -941,12 +1124,12 @@ impl Game<'_> {
BookScreen::Edit {
pages,
page,
- opened,
+ page_edit,
..
} => {
indicator(batch, *page, pages.len());
- let blink = (opened.elapsed().as_millis() / 300) % 2 == 0;
- let lines = self.book_lines(&pages[*page]);
+ let text = &pages[*page];
+ let lines = self.book_lines(text);
for (i, line) in lines.iter().take(LINES).enumerate() {
batch.text_styled(
atlas,
@@ -957,27 +1140,39 @@ impl Game<'_> {
false,
);
}
- if blink {
- // The cursor after the last character.
- let last = lines
- .last()
- .map(|l| atlas.font.width_text(l))
- .unwrap_or(0.0);
- let row = lines.len().saturating_sub(1) as f32
- + if pages[*page].ends_with('\n') {
- 1.0
- } else {
- 0.0
- };
- let x = if pages[*page].ends_with('\n') {
- 0.0
- } else {
- last
- };
+ let rows = self.page_rows(text);
+ let (sel_a, sel_b) = (
+ page_edit.cursor.min(page_edit.highlight),
+ page_edit.cursor.max(page_edit.highlight),
+ );
+ if sel_a != sel_b {
+ let chars: Vec = text.chars().collect();
+ for (i, &(start, end)) in rows.iter().enumerate().take(LINES) {
+ let from = sel_a.max(start);
+ let to = sel_b.min(end);
+ if from >= to {
+ continue;
+ }
+ let pre: String = chars[start..from].iter().collect();
+ let sel: String = chars[from..to].iter().collect();
+ batch.text_highlight(
+ atlas,
+ (
+ left + 36.0 + atlas.font.width(&pre),
+ top + 29.0 + i as f32 * 9.0,
+ atlas.font.width(&sel),
+ 9.0,
+ ),
+ true,
+ );
+ }
+ }
+ if page_edit.cursor_visible() {
+ let (x, row) = self.caret_on(text, &rows, page_edit.cursor);
batch.fill(
atlas,
left + 36.0 + x,
- top + 29.0 + row * 9.0,
+ top + 29.0 + row as f32 * 9.0,
1.0,
9.0,
BLACK,
diff --git a/crates/horizon-client/src/game/bundles.rs b/crates/horizon-client/src/game/bundles.rs
new file mode 100644
index 000000000..198964803
--- /dev/null
+++ b/crates/horizon-client/src/game/bundles.rs
@@ -0,0 +1,103 @@
+//! `BundleMouseActions`: the wheel over a bundle in a container screen selects
+//! one of the items it shows, which a click that takes one out of it then takes
+//! (`BundleContents.Mutable.removeOne`). Moving off the bundle clears the
+//! selection. On a server the selection is sent to it (`ServerboundSelectBundleItemPacket`).
+use super::{Game, Screen};
+use horizon_client::{
+ bundle::{Contents, toggle_selected},
+ mouse::ScrollWheelHandler,
+};
+use horizon_protocol::packets::play::{self, Serverbound as S};
+
+#[derive(Default)]
+pub(super) struct BundleMouse {
+ wheel: ScrollWheelHandler,
+ /// The slot under the cursor at the last tick (`AbstractContainerScreen.hoveredSlot`).
+ hovered: Option,
+}
+
+impl Game<'_> {
+ /// A slot a bundle can be selected in: the player's inventory, the off hand and a
+ /// container's own slots. A server only knows these in the inventory and chest-like menus.
+ fn bundle_slot(&mut self, slot: usize) -> bool {
+ (slot < 36 || slot == 504 || (300..500).contains(&slot))
+ && (self.remote.is_none() || self.remote_storage_open())
+ && (slot < 36 || slot == 504 || self.slots().contains(&slot))
+ }
+
+ /// `BundleMouseActions.onMouseScrolled`: the wheel over a bundle moves the selection
+ /// through the items its tooltip shows. True when the bundle took the wheel.
+ pub(super) fn bundle_scroll(&mut self, x: f64, y: f64) -> bool {
+ let Some(slot) = self.inventory_target().0 else {
+ return false;
+ };
+ if !self.bundle_slot(slot) {
+ return false;
+ }
+ let stack = self.slot_mut(slot).clone();
+ let items = self.res.items();
+ let Some(bundle) = stack.filter(|s| items.get(&s.item).is_some_and(|i| i.bundle)) else {
+ return false;
+ };
+ let shown = Contents::of(items, &bundle).map_or(0, |c| c.shown_count());
+ if shown == 0 {
+ return false;
+ }
+ let (wheel_x, wheel_y) = self.bundle_mouse.wheel.on_mouse_scroll(x, y);
+ let wheel = if wheel_y == 0 { -wheel_x } else { wheel_y };
+ if wheel != 0 {
+ let selected = bundle.data().map_or(-1, |d| d.bundle_selected.0);
+ let next = ScrollWheelHandler::next_selection(f64::from(wheel), selected, shown as i32);
+ if next != selected {
+ self.select_bundle(slot, next);
+ }
+ }
+ true
+ }
+
+ /// `BundleMouseActions.toggleSelectedBundleItem`: the stack here and, on a server, there.
+ fn select_bundle(&mut self, slot: usize, index: i32) {
+ if let Some(stack) = self.slot_mut(slot) {
+ toggle_selected(stack, index);
+ }
+ if self.remote.is_some() {
+ let (_, menu) = self.remote_menu();
+ if let Some(menu_slot) = Self::menu_slot_index(&menu, slot) {
+ self.send(S::SelectBundleItem(play::SelectBundleItem {
+ slot: menu_slot as i32,
+ index,
+ }));
+ }
+ }
+ }
+
+ /// `BundleMouseActions.unselectedBundleItem` for the bundle in `slot`, if it has a selection.
+ pub(super) fn unselect_bundle(&mut self, slot: usize) {
+ if !self.bundle_slot(slot) {
+ return;
+ }
+ let selected = self
+ .slot_mut(slot)
+ .as_ref()
+ .and_then(|s| s.data())
+ .is_some_and(|d| d.bundle_selected.0 >= 0);
+ if selected {
+ self.select_bundle(slot, -1);
+ }
+ }
+
+ /// `AbstractContainerScreen.onStopHovering` (and `onClose`): leaving a slot, or the
+ /// screen, clears the bundle's selection.
+ pub(super) fn tick_bundle_hover(&mut self) {
+ let now = if self.screen == Screen::Inventory {
+ self.inventory_target().0
+ } else {
+ None
+ };
+ if let Some(left) = std::mem::replace(&mut self.bundle_mouse.hovered, now)
+ && Some(left) != now
+ {
+ self.unselect_bundle(left);
+ }
+ }
+}
diff --git a/crates/horizon-client/src/game/campfire.rs b/crates/horizon-client/src/game/campfire.rs
new file mode 100644
index 000000000..c388b7561
--- /dev/null
+++ b/crates/horizon-client/src/game/campfire.rs
@@ -0,0 +1,190 @@
+//! Campfires' cooking: `CampfireBlock.useItemOn` (`CampfireBlockEntity.placeFood`)
+//! and the block entity's `cookTick` (lit) and `cooldownTick` (unlit). The
+//! items drawn on the fire are `campfire_geometry`'s; a server's clients get
+//! them through the block entity's update tag (`lan::chunks::entity_tag`).
+use super::Game;
+use horizon_assets::item_model::DisplayContext;
+use horizon_client::{
+ Result, block_entities::Pos, block_entity_render::vertex_light, containers::BlockEntity,
+ items::ItemStack, mesher::Vertex, mobs::Who,
+};
+use horizon_core::position::BlockPos;
+
+/// The `campfire_cooking` recipe kind (`RecipeType.CAMPFIRE_COOKING`).
+const KIND: &str = "minecraft:campfire_cooking";
+
+fn is_campfire(name: &str) -> bool {
+ name == "minecraft:campfire" || name == "minecraft:soul_campfire"
+}
+
+impl Game<'_> {
+ /// `CampfireBlock.useItemOn` with a held item that is a campfire recipe's
+ /// input (`RecipePropertySet.CAMPFIRE_INPUT`): on a server level the food
+ /// goes into the first free slot (`placeFood`), and the use is consumed
+ /// whether or not there was room. A client of a server leaves the placing
+ /// to the server. Whether the food went in; None when this isn't a
+ /// campfire use, so the item's own use runs.
+ pub(super) fn use_on_campfire(&mut self, pos: [i32; 3]) -> Result> {
+ let state = self.world.block(pos[0], pos[1], pos[2]);
+ if !is_campfire(&self.res.facts().get(state).name) {
+ return Ok(None);
+ }
+ let Some(held) = self.held().cloned() else {
+ return Ok(None);
+ };
+ let Some(time) = self.res.recipes().cook(KIND, &held).map(|r| r.time as i32) else {
+ return Ok(None);
+ };
+ // A client of a server predicts the placing; the server decides.
+ if self.remote.is_some() {
+ return Ok(Some(true));
+ }
+ let key = (pos[0], pos[1], pos[2]);
+ let placed = match self.world.block_entities.get_mut(&key) {
+ Some(BlockEntity::Campfire(c)) => {
+ let mut one = held.clone();
+ c.place_food(&mut one, time)
+ }
+ _ => false,
+ };
+ if placed {
+ // ItemStack.consumeAndReturn: creative keeps the item.
+ self.consume_held();
+ self.stats.custom("interact_with_campfire", 1);
+ self.post_block_game_event(
+ "minecraft:block_change",
+ pos,
+ Some(Who::Player),
+ Some(state),
+ );
+ self.mark_block_entity_updated(key);
+ }
+ Ok(Some(placed))
+ }
+
+ /// `CampfireBlockEntity.cookTick` of a lit campfire, `cooldownTick` of an
+ /// unlit one. A finished item's result (the recipe's, or the item itself
+ /// when no recipe takes it any more) drops at the block's corner
+ /// (`Containers.dropItemStack` at its integer position), then the clients
+ /// see the slot empty and a `block_change` goes out.
+ pub(super) fn tick_campfire(&mut self, pos: Pos) -> Result<()> {
+ let state = self.world.block(pos.0, pos.1, pos.2);
+ let lit = self
+ .pack
+ .assets
+ .registry
+ .state(state)
+ .and_then(|s| s.properties.get("lit"))
+ .is_some_and(|v| v == "true");
+ let Some(BlockEntity::Campfire(c)) = self.world.block_entities.get_mut(&pos) else {
+ return Ok(());
+ };
+ // BlockEntity.setChanged: a timer that moved is saved with the
+ // chunk (no update to the clients, who don't see the timers).
+ let changed = if lit {
+ c.items.iter().any(Option::is_some)
+ } else {
+ c.cooldown_tick()
+ };
+ if changed {
+ self.world.modified.insert((pos.0 >> 4, pos.2 >> 4));
+ }
+ if !lit {
+ return Ok(());
+ }
+ let Some(BlockEntity::Campfire(c)) = self.world.block_entities.get_mut(&pos) else {
+ return Ok(());
+ };
+ let done = c.cook_tick();
+ for (_, item) in done {
+ let result = self
+ .res
+ .recipes()
+ .cook(KIND, &item)
+ .map_or_else(|| item.clone(), |r| r.result.clone());
+ self.campfire_drop(pos, result);
+ self.mark_block_entity_updated(pos);
+ self.post_block_game_event(
+ "minecraft:block_change",
+ [pos.0, pos.1, pos.2],
+ None,
+ Some(state),
+ );
+ }
+ Ok(())
+ }
+
+ /// `CampfireRenderer`: each cooking item lies on the fire, slot `i`
+ /// turned to `Direction.from2DDataValue((i + facing) % 4)`, laid flat
+ /// (90° about X), at a corner and three eighths of its size, drawn as a
+ /// FIXED item seeded by the block's position plus the slot.
+ pub(super) fn campfire_geometry(&self, camera: glam::DVec3, out: &mut Vec) {
+ for (key, entity) in &self.world.block_entities {
+ let BlockEntity::Campfire(c) = entity else {
+ continue;
+ };
+ if c.items.iter().all(Option::is_none) {
+ continue;
+ }
+ let at = glam::DVec3::new(f64::from(key.0), f64::from(key.1), f64::from(key.2));
+ if at.distance_squared(camera) >= 64.0 * 64.0 {
+ continue;
+ }
+ // Direction.get2DDataValue: south 0, west 1, north 2, east 3.
+ let state = self.world.block(key.0, key.1, key.2);
+ let facing = match self
+ .pack
+ .assets
+ .registry
+ .state(state)
+ .and_then(|s| s.properties.get("facing"))
+ .map(String::as_str)
+ {
+ Some("west") => 1,
+ Some("north") => 2,
+ Some("east") => 3,
+ _ => 0,
+ };
+ let light = vertex_light(self.world.light(key.0, key.1, key.2));
+ let packed = BlockPos::new(key.0, key.1, key.2).pack();
+ for (i, stack) in c.items.iter().enumerate() {
+ let Some(stack) = stack else {
+ continue;
+ };
+ let seed = (packed as i32).wrapping_add(i as i32);
+ let item = self.resolve_item(stack, DisplayContext::Fixed, None, seed);
+ if item.is_empty() {
+ continue;
+ }
+ // Direction.toYRot: 90° per 2D step from south.
+ let yaw = -(((i + facing) % 4) as f32 * 90.0);
+ let pose = glam::Mat4::from_translation(
+ (at - camera).as_vec3() + glam::Vec3::new(0.5, 0.449_218_75, 0.5),
+ ) * glam::Mat4::from_rotation_y(yaw.to_radians())
+ * glam::Mat4::from_rotation_x(90f32.to_radians())
+ * glam::Mat4::from_translation(glam::Vec3::new(-0.3125, -0.3125, 0.0))
+ * glam::Mat4::from_scale(glam::Vec3::splat(0.375));
+ self.submit_item_world(&item, pose, light, out);
+ }
+ }
+ }
+
+ /// `Containers.dropItemStack(level, x, y, z, stack)` at the block's
+ /// integer position.
+ fn campfire_drop(&mut self, pos: Pos, stack: ItemStack) {
+ let at = BlockPos::new(pos.0, pos.1, pos.2);
+ for piece in
+ horizon_world::level::removal::drop_item_stack(&mut self.world.random, at, stack.count)
+ {
+ self.spawn_item(
+ ItemStack {
+ count: piece.count,
+ ..stack.clone()
+ },
+ piece.pos,
+ piece.motion,
+ 0,
+ );
+ }
+ }
+}
diff --git a/crates/horizon-client/src/game/campfire_douse.rs b/crates/horizon-client/src/game/campfire_douse.rs
new file mode 100644
index 000000000..04accb2d3
--- /dev/null
+++ b/crates/horizon-client/src/game/campfire_douse.rs
@@ -0,0 +1,53 @@
+//! `CampfireBlock.useItemOn`: an item in `#minecraft:douses_campfires` (the
+//! shovels) put on a lit campfire puts it out.
+use super::Game;
+use horizon_client::{Result, animate_tick::make_campfire_smoke, items::ItemStack};
+
+impl Game<'_> {
+ /// `CampfireBlock.useItemOn` with `held` in the hand that acts, the block
+ /// at `pos` clicked: true when it doused a lit campfire (SUCCESS).
+ pub(super) fn use_campfire_douse(
+ &mut self,
+ pos: [i32; 3],
+ held: Option<&ItemStack>,
+ ) -> Result {
+ let Some(tool) = held.filter(|s| {
+ self.res
+ .items()
+ .item_tags
+ .get("minecraft:douses_campfires")
+ .is_some_and(|members| members.contains(&*s.item))
+ }) else {
+ return Ok(false);
+ };
+ let registry = self.pack.assets.registry;
+ let Some(mut state) = registry
+ .state(self.world.block(pos[0], pos[1], pos[2]))
+ .filter(|s| matches!(&*s.name, "minecraft:campfire" | "minecraft:soul_campfire"))
+ .filter(|s| s.properties.get("lit").map(String::as_str) == Some("true"))
+ .cloned()
+ else {
+ return Ok(false);
+ };
+ // Level event 1009 (SOUND_EXTINGUISH_FIRE) goes to every player.
+ self.level_event_at(1009, pos, 0);
+ // CampfireBlock.douse: the acting client's own smoke (twenty puffs),
+ // then the block change game event from the player.
+ if self.lan_acting.is_none() {
+ let signal = state.properties.get("signal_fire").map(String::as_str) == Some("true");
+ for _ in 0..20 {
+ make_campfire_smoke(&mut self.particles, pos, signal, true);
+ }
+ }
+ self.post_block_game_event("minecraft:block_change", pos, self.sculk_actor(), None);
+ state.properties.insert("lit".into(), "false".into());
+ if let Ok(unlit) = registry.resolve(&state) {
+ self.level_set(pos, unlit)?;
+ }
+ let used = tool.clone();
+ self.damage_held(1);
+ // ServerPlayerGameMode.useItemOn: the action was consumed.
+ self.trigger_block("minecraft:item_used_on_block", pos, &used);
+ Ok(true)
+ }
+}
diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs
index 5d3919c8b..03174c009 100644
--- a/crates/horizon-client/src/game/chat.rs
+++ b/crates/horizon-client/src/game/chat.rs
@@ -464,7 +464,28 @@ impl Game<'_> {
return;
}
// The Chat option's Hidden level takes the server's messages too.
- if !self.ui.chat.shows(ChatSource::Server) {
+ self.local_chat_line(text, Some(SYSTEM_INDICATOR), ChatSource::Server);
+ }
+ /// A player's chat line on the window's own chat: a LAN guest's message
+ /// while the host runs in-frame (`HostEvent::Chat`). `ChatListener`
+ /// checks `canReceivePlayerMessages` for these, so Commands Only and
+ /// Hidden drop them; command feedback (`/list`, `/tp`) is a system
+ /// message and takes the system-message permission instead.
+ pub(super) fn player_message(&mut self, text: Text) {
+ if let Some(capture) = self.chat_capture.as_mut() {
+ capture.push(text);
+ return;
+ }
+ // A server's client receives the line as a packet (PlayerChat or
+ // DisguisedChat) and filters it there.
+ if self.remote.is_none() {
+ self.local_chat_line(text, None, ChatSource::Player);
+ }
+ }
+ /// A line on the window's own chat when the Chat option lets `source`
+ /// through; running mods hear it.
+ fn local_chat_line(&mut self, text: Text, indicator: Option, source: ChatSource) {
+ if !self.ui.chat.shows(source) {
return;
}
let focused = self.screen == Screen::Chat;
@@ -472,8 +493,8 @@ impl Game<'_> {
self.ui.chat.add(
&self.gui.atlas,
text,
- Some(SYSTEM_INDICATOR),
- ChatSource::Server,
+ indicator,
+ source,
self.ticks,
focused,
);
@@ -602,7 +623,10 @@ impl Game<'_> {
return;
}
if let Some(command) = message.strip_prefix('/') {
- self.run_command(command);
+ // A client mod's command first, then a server mod's, as on a server.
+ if !self.mod_command(command) && !self.local_server_mod_command(command) {
+ self.run_command(command);
+ }
} else {
let line = Text::translate(
"chat.type.text",
@@ -622,6 +646,7 @@ impl Game<'_> {
self.mods_chat(&line);
}
self.lan_host_chat(message);
+ self.mod_player_chat(super::server_mods::Who::Local, message);
}
}
pub(super) fn chat_scroll(&mut self, amount: f32) {
@@ -757,6 +782,7 @@ impl Game<'_> {
max_snow_accumulation_height: r.int("max_snow_accumulation_height"),
spawn_mobs: r.bool("spawn_mobs"),
spawn_monsters: r.bool("spawn_monsters"),
+ fire_spread_radius_around_player: r.int("fire_spread_radius_around_player"),
}
}
/// Apply rules mirrored in other state (natural regeneration, difficulty).
diff --git a/crates/horizon-client/src/game/client_ambient.rs b/crates/horizon-client/src/game/client_ambient.rs
index a10c6da49..1cf59733d 100644
--- a/crates/horizon-client/src/game/client_ambient.rs
+++ b/crates/horizon-client/src/game/client_ambient.rs
@@ -4,8 +4,12 @@
//! on the game that has the window, in-frame or following a server, never on
//! a server: nothing of them goes over the network.
use super::Game;
+use horizon_client::blocks::RenderShape;
use horizon_client::mobs::{MobEvent, ambient};
-use horizon_client::particles::{ParticleOptions, ParticleType};
+use horizon_client::motion::{LAVA, WATER};
+use horizon_client::particles::{ParticleEngine, ParticleOptions, ParticleType};
+use horizon_client::pose::Pose;
+use horizon_core::{geometry::Vec3, random::RandomSource};
impl Game<'_> {
pub(super) fn tick_client_ambient(&mut self) {
@@ -33,5 +37,209 @@ impl Game<'_> {
}
}
self.eye_particles();
+ self.sprint_dust();
+ self.effect_swirls();
+ }
+
+ /// `Entity.baseTick`'s `spawnSprintParticle` on a client: dust of the
+ /// block under a sprinting player's feet streams back from them every
+ /// tick, for the window's own player and for the other players it sees.
+ fn sprint_dust(&mut self) {
+ // Each runner's feet, movement and supporting block.
+ let mut runners: Vec<(Vec3, Vec3, Option<[i32; 3]>)> = Vec::new();
+ // Entity.canSpawnSprintParticle.
+ if let Some(p) = self.player.as_ref()
+ && p.sprinting
+ && !p.spectator
+ && p.pose != Pose::Crouching
+ && !p.health.dead_or_dying()
+ && !p.fluids.was_touching_water
+ && !p.is_in_lava()
+ && p.fluid_height(WATER) <= 0.0
+ && p.fluid_height(LAVA) <= 0.0
+ {
+ let support = p.ground.supporting_block.map(|b| [b.x, b.y, b.z]);
+ runners.push((p.position, p.velocity, support));
+ }
+ let guests = self.lan.iter().flat_map(|host| host.models.values());
+ for m in self.mobs.iter().chain(guests) {
+ // Another player's fluids aren't known here: none where they stand.
+ let feet = [
+ m.position.x.floor() as i32,
+ m.position.y.floor() as i32,
+ m.position.z.floor() as i32,
+ ];
+ if m.extra.sprinting
+ && !m.extra.crouching
+ && m.alive()
+ && &*m.kind.id == "minecraft:player"
+ && self
+ .res
+ .facts()
+ .get(self.world.block(feet[0], feet[1], feet[2]))
+ .fluid_level
+ == 0
+ {
+ runners.push((m.position, m.position.subtract(m.previous), None));
+ }
+ }
+ for (position, movement, support) in runners {
+ // Entity.getOnPosLegacy: getOnPos(0.2).
+ let below = (position.y - f64::from(0.2f32)).floor() as i32;
+ let tall = |game: &Self, s: [i32; 3]| {
+ let name = game.block_name(s);
+ [
+ "minecraft:fences",
+ "minecraft:walls",
+ "minecraft:fence_gates",
+ ]
+ .iter()
+ .any(|tag| game.block_in_tag(tag, &name))
+ };
+ let at = match support {
+ Some(s) if tall(self, s) => s,
+ Some(s) => [s[0], below, s[2]],
+ None => [position.x.floor() as i32, below, position.z.floor() as i32],
+ };
+ let state = self.world.block(at[0], at[1], at[2]);
+ if self.res.facts().get(state).render_shape == RenderShape::Invisible {
+ continue;
+ }
+ let Some((sprite, tint)) = self.particle_sprite(state, at) else {
+ continue;
+ };
+ let width = f64::from(0.6f32);
+ let r = self.particles.random();
+ let mut x = position.x + (r.next_double() - 0.5) * width;
+ let mut z = position.z + (r.next_double() - 0.5) * width;
+ // Clamped into the block when the feet are in another column.
+ if position.x.floor() as i32 != at[0] {
+ x = x.clamp(f64::from(at[0]), f64::from(at[0]) + 1.0);
+ }
+ if position.z.floor() as i32 != at[2] {
+ z = z.clamp(f64::from(at[2]), f64::from(at[2]) + 1.0);
+ }
+ self.particles.add(
+ &ParticleOptions::block(ParticleType::Block, sprite, tint),
+ [x, position.y + 0.1, z],
+ [movement.x * -4.0, 1.5, movement.z * -4.0],
+ );
+ }
+ }
+
+ /// `LivingEntity.tickEffects` on a client: the swirls around an entity
+ /// with visible effects, from the particles its synched data lists. The
+ /// window's player has its own effects, a server's mobs and players the
+ /// list the server sent, and the mobs and guests of a game in the frame
+ /// theirs.
+ fn effect_swirls(&mut self) {
+ if let Some(p) = self.player.as_ref() {
+ let effects = &self.potions.effects.list;
+ let list: Vec<_> = effects
+ .iter()
+ .filter(|e| e.visible)
+ .filter_map(|e| effect_particle(e.id, e.ambient))
+ .collect();
+ let ambient = effects.iter().filter(|e| e.visible).all(|e| e.ambient);
+ let invisible = effects.iter().any(|e| e.id == "invisibility");
+ let size = (
+ f64::from(p.dimensions.width),
+ f64::from(p.dimensions.height),
+ );
+ swirl(
+ &mut self.particles,
+ p.position,
+ size,
+ &list,
+ ambient,
+ invisible,
+ );
+ }
+ let guests = self.lan.iter().flat_map(|host| host.models.values());
+ for m in self.mobs.iter().chain(guests) {
+ if !m.alive() {
+ continue;
+ }
+ let size = (f64::from(m.width()), f64::from(m.height()));
+ let invisible = m.invisible || m.has_effect("minecraft:invisibility");
+ if m.extra.effect_particles.is_empty() {
+ // A mob of this game: its own effects, visible and not ambient.
+ if m.extra.effects.is_empty() {
+ continue;
+ }
+ let list: Vec<_> = m
+ .extra
+ .effects
+ .iter()
+ .filter(|e| !m.extra.hidden_effects.contains(&e.0))
+ .filter_map(|e| effect_particle(e.0, false))
+ .collect();
+ swirl(
+ &mut self.particles,
+ m.position,
+ size,
+ &list,
+ false,
+ invisible,
+ );
+ } else {
+ let list = &m.extra.effect_particles;
+ let ambient = m.extra.effect_ambient;
+ swirl(
+ &mut self.particles,
+ m.position,
+ size,
+ list,
+ ambient,
+ invisible,
+ );
+ }
+ }
}
}
+
+/// `MobEffect.particleFactory`: the omens have particles of their own, any
+/// other effect an entity effect in its colour, faint when ambient.
+pub(super) fn effect_particle(effect: &str, ambient: bool) -> Option {
+ Some(match effect.trim_start_matches("minecraft:") {
+ "trial_omen" => ParticleOptions::simple(ParticleType::TrialOmen),
+ "raid_omen" => ParticleOptions::simple(ParticleType::RaidOmen),
+ other => {
+ let color = horizon_client::brewing::effect(other)?.color;
+ let channel = |shift: u32| ((color >> shift) & 255) as f32 / 255.0;
+ // MobEffect.AMBIENT_ALPHA is 38 of 255.
+ let alpha = if ambient { 38.0 / 255.0 } else { 1.0 };
+ ParticleOptions::colored(
+ ParticleType::EntityEffect,
+ [channel(16), channel(8), channel(0), alpha],
+ )
+ }
+ })
+}
+
+/// One tick of `LivingEntity.tickEffects`' client branch: a one in four
+/// chance (one in fifteen while invisible, a fifth of either when all the
+/// effects are ambient) of one of the particles at a random spot of the box.
+fn swirl(
+ particles: &mut ParticleEngine,
+ feet: Vec3,
+ size: (f64, f64),
+ list: &[ParticleOptions],
+ ambient: bool,
+ invisible: bool,
+) {
+ if list.is_empty() {
+ return;
+ }
+ let bound = if invisible { 15 } else { 4 } * if ambient { 5 } else { 1 };
+ let r = particles.random();
+ let Ok(0) = r.next_int_bound(bound) else {
+ return;
+ };
+ // Util.getRandom, then getRandomX(0.5), getRandomY and getRandomZ.
+ let pick = r.next_int_bound(list.len() as i32).unwrap_or_default() as usize;
+ let x = feet.x + size.0 * (2.0 * r.next_double() - 1.0) * 0.5;
+ let y = feet.y + size.1 * r.next_double();
+ let z = feet.z + size.0 * (2.0 * r.next_double() - 1.0) * 0.5;
+ particles.add(&list[pick], [x, y, z], [1.0; 3]);
+}
diff --git a/crates/horizon-client/src/game/clipboard.rs b/crates/horizon-client/src/game/clipboard.rs
index c87aa3681..6e81bf3ee 100644
--- a/crates/horizon-client/src/game/clipboard.rs
+++ b/crates/horizon-client/src/game/clipboard.rs
@@ -63,8 +63,8 @@ impl Game<'_> {
}
}
}
- /// Typing or a backspace in a field of the title screens: in the server
- /// screens' append-only fields Select All's selection is replaced first.
+ /// Typing or a backspace in a title-screen field. A field that still only
+ /// appends replaces a Select All selection before the edit.
pub(super) fn title_edit(&mut self, typed: Option<&str>, backspace: bool) {
let Some(title) = self.title.as_mut() else {
return;
@@ -86,42 +86,31 @@ impl Game<'_> {
}
/// Shortcuts in the creative inventory's search box (an `EditBox` of 50).
pub(super) fn creative_search_shortcut(&mut self, shortcut: EditShortcut) {
- if Self::append_shortcut(
- &mut self.text_selection,
- &mut self.clipboard,
- CREATIVE_SEARCH,
- &mut self.creative_screen.search,
- shortcut,
- CREATIVE_SEARCH_CHARS,
- ) {
+ if self
+ .creative_screen
+ .search
+ .shortcut(shortcut, &mut self.clipboard)
+ {
self.creative_screen.scroll = 0.0;
}
}
/// A backspace in the creative search box: with Ctrl, the whole word
/// before the caret (`EditBox.deleteWords(-1)`), otherwise one character.
- /// A Select All selection is what it deletes, as in `EditBox.keyPressed`.
+ /// A selection is what it deletes, as in `EditBox.keyPressed`.
pub(super) fn creative_search_backspace(&mut self, ctrl: bool) {
- let search = &mut self.creative_screen.search;
- if !self.text_selection.take(CREATIVE_SEARCH, search) {
- if ctrl {
- horizon_client::ui::delete_words(search, -1);
- } else {
- search.pop();
- }
- }
+ self.creative_screen
+ .search
+ .key(KeyCode::Backspace, ctrl, false);
self.creative_screen.scroll = 0.0;
}
/// Typing in the creative search box.
pub(super) fn creative_search_edit(&mut self, typed: Option<&str>) {
- let search = &mut self.creative_screen.search;
- self.text_selection.take(CREATIVE_SEARCH, search);
if let Some(text) = typed {
- clipboard::append_limited(search, text, CREATIVE_SEARCH_CHARS);
+ self.creative_screen.search.insert_text(text);
+ self.creative_screen.scroll = 0.0;
}
- self.creative_screen.scroll = 0.0;
}
}
/// `CreativeModeInventoryScreen`'s search box: `setMaxLength(50)`.
pub(super) const CREATIVE_SEARCH_CHARS: usize = 50;
-pub(super) const CREATIVE_SEARCH: horizon_client::clipboard::FieldId = ("creative.search", 0);
diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs
index 227aa0332..2d6b75902 100644
--- a/crates/horizon-client/src/game/combat.rs
+++ b/crates/horizon-client/src/game/combat.rs
@@ -10,6 +10,9 @@ struct Entry {
fall_distance: f32,
/// The causing entity: its id (for comparisons) and display name.
attacker: Option<(u32, Text)>,
+ /// The direct entity's display name when no entity caused the damage
+ /// (`DamageSource.directEntity`: a potion with no thrower, a cloud).
+ direct: Option,
}
#[derive(Default)]
pub(super) struct CombatTracker {
@@ -19,6 +22,8 @@ pub(super) struct CombatTracker {
/// Attackers of damage dealt this tick, claimed by the matching
/// `RecordedDamage` event.
pending: Vec<(String, (u32, Text))>,
+ /// `pending` for a direct entity with no causing entity: only its name.
+ pending_direct: Vec<(String, Text)>,
/// `LivingEntity.lastHurtByMob` and its timestamp (the kill credit).
last_hurt_by: Option<((u32, Text), i64)>,
/// The mob the player last hurt (`getLastHurtMob`) and when.
@@ -31,6 +36,10 @@ pub(super) struct CombatTracker {
/// The mob exploding now (`ServerExplosion.source`): its team's friendly
/// fire decides whom the blast may hurt.
pub(super) explosion_source: Option,
+ /// Charged creepers whose blast just went off and that have not dropped
+ /// a head yet (`Creeper.droppedSkulls`): they are gone from the mob list,
+ /// but the mobs they killed still ask for their loot.
+ pub(super) charged_exploders: Vec,
/// The player's fall distance before this tick's movement (as of the
/// end of the last one).
fall_before: f64,
@@ -52,11 +61,24 @@ impl Game<'_> {
/// Remember who deals the next `damage_type` damage to the player.
pub(super) fn note_attacker(&mut self, damage_type: &str, mob: u32) {
if let Some(name) = self.mob_display_name(mob) {
- self.combat
- .pending
- .push((damage_type.to_owned(), (mob, name)));
+ self.note_named_attacker(damage_type, mob, name);
}
}
+ /// `note_attacker` for an entity that is not one of `self.mobs` (the
+ /// ender dragon).
+ pub(super) fn note_named_attacker(&mut self, damage_type: &str, id: u32, name: Text) {
+ self.combat
+ .pending
+ .push((damage_type.to_owned(), (id, name)));
+ }
+ /// The `DamageSource.directEntity` of the next `damage_type` damage when
+ /// nothing caused it (a splash potion nobody threw): the death message
+ /// names it instead (`getLocalizedDeathMessage`). It is no kill credit.
+ pub(super) fn note_direct_entity(&mut self, damage_type: &str, name: Text) {
+ self.combat
+ .pending_direct
+ .push((damage_type.to_owned(), name));
+ }
/// `LivingEntity.handleDamageEvent` for the player: the hurt sound of the
/// source's `DamageEffects` (`Player.getHurtSound`).
pub(super) fn player_hurt_sound(&mut self, sound: &str, at: [f64; 3]) {
@@ -85,6 +107,15 @@ impl Game<'_> {
.iter()
.position(|(t, _)| *t == name)
.map(|i| self.combat.pending.remove(i).1);
+ let direct = match attacker {
+ Some(_) => None,
+ None => self
+ .combat
+ .pending_direct
+ .iter()
+ .position(|(t, _)| *t == name)
+ .map(|i| self.combat.pending_direct.remove(i).1),
+ };
let (fall_location, fall_distance) = self.fall_location();
let now = self.world.game_time;
if let Some(a) = &attacker {
@@ -102,10 +133,12 @@ impl Game<'_> {
fall_location,
fall_distance,
attacker,
+ direct,
});
self.combat.last_damage = now;
}
self.combat.pending.clear();
+ self.combat.pending_direct.clear();
self.combat.fall_before = self.player.as_ref().map_or(0.0, |p| p.fall_distance);
}
/// `FallLocation.getCurrentFallLocation` and the fall distance so far.
@@ -215,6 +248,7 @@ impl Game<'_> {
let entries = std::mem::take(&mut self.combat.entries);
let killing = entries.last().expect("checked above");
let killer = killing.attacker.clone();
+ let direct = killing.direct.clone();
if def.1 == "fall_variants"
&& let Some(knock) = knock.and_then(|i| entries.get(i))
{
@@ -239,15 +273,22 @@ impl Game<'_> {
.append(Text::literal("]"));
return Text::translate(&format!("{key}.message"), &[me, link]);
}
+ // `getLocalizedDeathMessage`: the causing entity's name, or the
+ // direct entity's when nothing caused the damage.
if let Some((_, name)) = killer {
return Text::translate(&key, &[me, name]);
}
+ if let Some(name) = direct {
+ return Text::translate(&key, &[me, name]);
+ }
// getKillCredit: the last mob that hurt the player in the past 100 ticks.
if let Some(((_, name), at)) = &self.combat.last_hurt_by
&& self.world.game_time - at <= 100
{
return Text::translate(&format!("{key}.player"), &[me, name.clone()]);
}
+ // No entity at all: the one-argument message, as vanilla sends it (a
+ // template that names a killer then shows as written).
Text::translate(&key, &[me])
}
}
diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs
index f3afdcab6..f308cfec6 100644
--- a/crates/horizon-client/src/game/commands.rs
+++ b/crates/horizon-client/src/game/commands.rs
@@ -85,16 +85,16 @@ fn format_double(v: f64) -> String {
impl Game<'_> {
/// Commands.performCommand for a line without its slash.
- pub(super) fn run_command(&mut self, command: &str) {
+ pub(super) fn run_command(&mut self, command: &str) -> bool {
if self.mod_command(command) {
- return;
+ return true;
}
let d = vanilla::game_dispatcher();
let parse = d.parse(command, &self.ui.registries);
let result = match parse.executable() {
Err(e) => {
self.syntax_failure(&e, command);
- return;
+ return false;
}
Ok((ctx, _)) => {
let ctx = ctx.clone();
@@ -103,6 +103,7 @@ impl Game<'_> {
self.run_chain(&root, &ctx)
}
};
+ let ok = result.is_ok();
if let Err(e) = result {
if e.input.is_some() {
self.syntax_failure(&e, command);
@@ -114,6 +115,20 @@ impl Game<'_> {
if self.player.is_some() {
self.check_inventory_trigger();
}
+ ok
+ }
+ /// `run_command` with its output suppressed
+ /// (`CommandSourceStack.withSuppressedOutput`): the player's own source,
+ /// rights and checks, no feedback and no failure in the chat.
+ pub(super) fn run_command_quietly(&mut self, command: &str) -> bool {
+ let quiet = execute::Source {
+ silent: true,
+ ..self.player_source()
+ };
+ let outer = self.command_source.replace(quiet);
+ let ok = self.run_command(command);
+ self.command_source = outer;
+ ok
}
fn syntax_failure(&mut self, e: &CommandError, command: &str) {
self.command_failure(e.message.clone());
@@ -526,8 +541,7 @@ impl Game<'_> {
.enumerate()
// The kinds /data can write (entity_nbt).
.filter(|(_, p)| {
- p.arrow.is_some()
- || matches!(p.kind, K::LargeFireball { .. } | K::SmallFireball)
+ p.is_arrow() || matches!(p.kind, K::LargeFireball { .. } | K::SmallFireball)
})
.map(|(i, _)| Target::Projectile(i)),
);
@@ -1682,6 +1696,8 @@ impl Game<'_> {
value: 0,
age: 0,
on_ground: false,
+ count: 1,
+ ticks: 0,
});
name = Text::translate("entity.minecraft.experience_orb", &[]);
}
@@ -1870,11 +1886,12 @@ impl Game<'_> {
}
}
}
- let Some((_, new)) = horizon_client::save::decode_block_entity(&tag) else {
+ let Some((_, mut new)) = horizon_client::save::decode_block_entity(&tag) else {
return false;
};
+ let rolled = self.take_loot_table(key, &tag, &mut new);
let after = horizon_client::save::encode_block_entity(key, &new, &name);
- if after == before {
+ if after == before && !rolled {
return false;
}
self.world.block_entities.insert(key, new);
@@ -1882,6 +1899,79 @@ impl Game<'_> {
let _ = self.world.set(pos[0], pos[1], pos[2], state);
true
}
+ /// RandomizableContainer.tryLoadLootTable for a tag a command gives a
+ /// container (`setblock`, `data`): an empty container with a `LootTable`
+ /// is rolled now, as a loaded chunk's are (`save::roll_loaded_loot`), and
+ /// the roll is kept with its chunk, so that the container saves, and
+ /// `data get` shows, its table and seed until its items change. A tag
+ /// without one drops what the container had. True when it had a table.
+ pub(super) fn take_loot_table(
+ &mut self,
+ key: (i32, i32, i32),
+ tag: &horizon_world::nbt::Tag,
+ entity: &mut horizon_client::containers::BlockEntity,
+ ) -> bool {
+ use horizon_client::{containers::BlockEntity, save, structure_blocks};
+ let table = save::text(tag.get("LootTable"));
+ let rolled = match (table, entity) {
+ (Some(table), BlockEntity::Chest(slots)) if slots.iter().all(Option::is_none) => {
+ let loot = structure_blocks::loot_data(&self.options.resources);
+ let at = Vec3::new(f64::from(key.0), f64::from(key.1), f64::from(key.2));
+ let biome = self.biome_name_at(at).unwrap_or_default();
+ Some(structure_blocks::roll_container(
+ slots,
+ loot.as_deref(),
+ table,
+ structure_blocks::loot_seed(tag),
+ key,
+ &biome,
+ ))
+ }
+ _ => None,
+ };
+ let Some(chunk) = self.world.chunks.get_mut(&(key.0 >> 4, key.2 >> 4)) else {
+ return false;
+ };
+ let held = |c: &horizon_client::chunk::Chunk| {
+ c.saved
+ .as_ref()
+ .is_some_and(|s| s.rolled_loot.iter().any(|r| r.pos == key))
+ };
+ if rolled.is_none() && !held(chunk) {
+ return false;
+ }
+ let chunk = std::sync::Arc::make_mut(chunk);
+ let mut extras = chunk
+ .saved
+ .take()
+ .map(std::sync::Arc::unwrap_or_clone)
+ .unwrap_or_default();
+ extras.rolled_loot.retain(|r| r.pos != key);
+ let taken = rolled.is_some();
+ extras.rolled_loot.extend(rolled);
+ chunk.saved = Some(std::sync::Arc::new(extras));
+ taken
+ }
+ /// The loot table and seed a container still holding its roll saves
+ /// (`RolledLoot::restore`), in place of its items.
+ pub(super) fn restore_loot_table(
+ &self,
+ key: (i32, i32, i32),
+ tag: &mut horizon_world::nbt::Tag,
+ ) {
+ let horizon_world::nbt::Tag::Compound(map) = tag else {
+ return;
+ };
+ let rolled = self
+ .world
+ .chunks
+ .get(&(key.0 >> 4, key.2 >> 4))
+ .and_then(|c| c.saved.as_ref())
+ .and_then(|s| s.rolled_loot.iter().find(|r| r.pos == key));
+ if let Some(r) = rolled {
+ r.restore(map);
+ }
+ }
fn cmd_fill(&mut self, ctx: &Context) -> R {
let a = self.block_pos_arg(ctx, "from")?;
let b = self.block_pos_arg(ctx, "to")?;
@@ -2578,38 +2668,7 @@ impl Game<'_> {
/// `PoiTypes`: the point of interest type of a block state.
fn poi_type(&self, state: horizon_world::registry::BlockStateId) -> Option<&'static str> {
let s = self.pack.assets.registry.state(state)?;
- let name = s.name.strip_prefix("minecraft:")?;
- Some(match name {
- "blast_furnace" => "minecraft:armorer",
- "smoker" => "minecraft:butcher",
- "cartography_table" => "minecraft:cartographer",
- "brewing_stand" => "minecraft:cleric",
- "composter" => "minecraft:farmer",
- "barrel" => "minecraft:fisherman",
- "fletching_table" => "minecraft:fletcher",
- "cauldron" | "lava_cauldron" | "water_cauldron" | "powder_snow_cauldron" => {
- "minecraft:leatherworker"
- }
- "lectern" => "minecraft:librarian",
- "stonecutter" => "minecraft:mason",
- "loom" => "minecraft:shepherd",
- "smithing_table" => "minecraft:toolsmith",
- "grindstone" => "minecraft:weaponsmith",
- "bell" => "minecraft:meeting",
- "beehive" => "minecraft:beehive",
- "bee_nest" => "minecraft:bee_nest",
- "nether_portal" => "minecraft:nether_portal",
- "lodestone" => "minecraft:lodestone",
- "test_instance_block" => "minecraft:test_instance",
- n if n.ends_with("_bed") => {
- if s.properties.get("part").map(String::as_str) != Some("head") {
- return None;
- }
- "minecraft:home"
- }
- n if n.ends_with("lightning_rod") => "minecraft:lightning_rod",
- _ => return None,
- })
+ horizon_client::save::poi_type(s).map(|(kind, _)| kind)
}
/// `LocateCommand.locatePoi`: `PoiManager.findClosestWithType` within
/// 256 blocks of the source, over the loaded chunks.
diff --git a/crates/horizon-client/src/game/commands/data.rs b/crates/horizon-client/src/game/commands/data.rs
index 18035ddd7..ac16c5e7c 100644
--- a/crates/horizon-client/src/game/commands/data.rs
+++ b/crates/horizon-client/src/game/commands/data.rs
@@ -286,6 +286,7 @@ impl Game<'_> {
if let Tag::Compound(c) = &mut tag {
c.remove(&"keepPacked".into());
}
+ self.restore_loot_table(key, &mut tag);
Ok(tag)
}
DataRef::Storage(id) => Ok(self.score.storage.get(id)),
@@ -296,7 +297,8 @@ impl Game<'_> {
DataRef::Entity(t) => self.apply_entity_nbt(*t, tag),
DataRef::Block(p) => {
let key = (p[0], p[1], p[2]);
- if let Some((_, new)) = save::decode_block_entity(&tag) {
+ if let Some((_, mut new)) = save::decode_block_entity(&tag) {
+ self.take_loot_table(key, &tag, &mut new);
self.world.block_entities.insert(key, new);
let state = self.world.block(p[0], p[1], p[2]);
// Redraw what shows the block entity (signs, banners).
diff --git a/crates/horizon-client/src/game/commands/effects.rs b/crates/horizon-client/src/game/commands/effects.rs
index 65d6592f7..6516bfe6c 100644
--- a/crates/horizon-client/src/game/commands/effects.rs
+++ b/crates/horizon-client/src/game/commands/effects.rs
@@ -91,7 +91,12 @@ impl Game<'_> {
}
Target::Mob(id) => match self.mobs.iter_mut().find(|m| m.id == id) {
Some(m) => {
- m.add_effect(namespaced(effect.id), duration, amplifier);
+ let name = namespaced(effect.id);
+ m.add_effect(name, duration, amplifier);
+ m.extra.hidden_effects.retain(|h| *h != name);
+ if !particles {
+ m.extra.hidden_effects.push(name);
+ }
true
}
None => false,
@@ -154,6 +159,10 @@ impl Game<'_> {
m.extra
.effects
.retain(|x| e.is_some_and(|e| x.0 != namespaced(e.id)));
+ let left = &m.extra.effects;
+ m.extra
+ .hidden_effects
+ .retain(|h| left.iter().any(|x| x.0 == *h));
m.extra.effects.len() != before
}
None => false,
diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs
index 3f7e4c2a0..eb4d4b157 100644
--- a/crates/horizon-client/src/game/commands/execute.rs
+++ b/crates/horizon-client/src/game/commands/execute.rs
@@ -145,9 +145,42 @@ impl Game<'_> {
.iter()
.find(|m| m.id == id)
.map_or(0.0, |m| m.eye_y() - m.position.y),
- _ => 0.0,
+ // ArmorStand.getDefaultDimensions: a marker's are empty, a small
+ // stand's are BABY_DIMENSIONS, whose eye height is 0.9875F.
+ Target::Stand(id) => match self.armor_stands.iter().find(|a| a.id == id) {
+ Some(a) if a.marker => 0.0,
+ Some(a) if a.small => f64::from(0.9875f32),
+ _ => self.type_eye_height(&self.target_type(t)),
+ },
+ // Entity.getEyeHeight: the type's dimensions.
+ _ => self.type_eye_height(&self.target_type(t)),
}
}
+ /// `EntityType.getDimensions().eyeHeight()` from `entity-types.json`,
+ /// read once: a float, widened as `Entity.getEyeY` does.
+ fn type_eye_height(&self, ty: &str) -> f64 {
+ static EYE_HEIGHTS: std::sync::OnceLock> =
+ std::sync::OnceLock::new();
+ EYE_HEIGHTS
+ .get_or_init(|| {
+ std::fs::read(self.options.resources.join("entity-types.json"))
+ .ok()
+ .and_then(|b| serde_json::from_slice::(&b).ok())
+ .and_then(|v| {
+ v.as_object().map(|o| {
+ o.iter()
+ .filter_map(|(k, t)| {
+ Some((k.clone(), f64::from(t["eye_height"].as_f64()? as f32)))
+ })
+ .collect()
+ })
+ })
+ .unwrap_or_default()
+ })
+ .get(ty)
+ .copied()
+ .unwrap_or(0.0)
+ }
/// EntityAnchorArgument.Anchor.apply.
pub(super) fn anchor_position(&self, s: &Source) -> [f64; 3] {
match s.entity {
@@ -467,9 +500,10 @@ impl Game<'_> {
"positioned" if c.has("as") => targets(self)?
.into_iter()
.filter_map(|t| {
+ // withPosition keeps the anchor (only `positioned `
+ // resets it to the feet).
Some(Source {
pos: self.target_position(t)?,
- eyes: false,
..s
})
})
@@ -606,6 +640,72 @@ impl Game<'_> {
.collect(),
_ => Vec::new(),
},
+ // Leashable.getLeashHolder: a fence knot is not an entity here.
+ Some("leasher") => match entity {
+ Target::Mob(id) => self
+ .mobs
+ .iter()
+ .find(|m| m.id == id)
+ .and_then(|m| m.extra.leash.map(|holder| (holder, m.extra.leash_player)))
+ .and_then(|(holder, player)| match holder {
+ // The player who tied it (the host's when unrecorded).
+ horizon_client::mobs::leash::Holder::Player => {
+ let uuid = player.or(self.level.player_uuid)?;
+ self.target_by_uuid(horizon_client::lan::playerdata::ints_uuid(uuid))
+ }
+ horizon_client::mobs::leash::Holder::Mob(i) => Some(Target::Mob(i)),
+ horizon_client::mobs::leash::Holder::Knot(_) => None,
+ })
+ .into_iter()
+ .collect(),
+ _ => Vec::new(),
+ },
+ // TraceableEntity.getOwner: who shot a projectile, who threw an
+ // item, who summoned a vex.
+ Some("origin") => match entity {
+ Target::Projectile(i) => self
+ .creatures
+ .projectiles
+ .get(i)
+ .and_then(|p| match (p.owner?, p.guest) {
+ // A guest's shot: `Who::Player` is them.
+ (horizon_client::mobs::Who::Player, Some(conn))
+ if self.lan_acting == Some(conn) =>
+ {
+ Some(Target::Player)
+ }
+ (horizon_client::mobs::Who::Player, Some(conn)) => {
+ Some(Target::Guest(conn))
+ }
+ (horizon_client::mobs::Who::Player, None) => Some(Target::Player),
+ (horizon_client::mobs::Who::Mob(id), _) => Some(Target::Mob(id)),
+ })
+ .into_iter()
+ .collect(),
+ Target::Item(id) => self
+ .dropped
+ .iter()
+ .find(|d| d.id == id)
+ .and_then(|d| d.thrower)
+ .and_then(|words| {
+ let uuid = words
+ .iter()
+ .fold(0u128, |all, w| all << 32 | u128::from(*w as u32));
+ self.target_by_uuid(uuid)
+ })
+ .into_iter()
+ .collect(),
+ Target::Mob(id) => self
+ .mobs
+ .iter()
+ .find(|m| m.id == id && m.kind.id == "minecraft:vex")
+ .map(|m| m.extra.counter2 as u32)
+ .filter(|owner| *owner != 0)
+ .map(Target::Mob)
+ .into_iter()
+ .collect(),
+ _ => Vec::new(),
+ },
Some("vehicle") => self.ride_vehicle(entity).into_iter().collect(),
Some("controller") | Some("passengers") => match entity {
Target::Mob(id) if self.mobs.iter().any(|m| m.id == id && m.rider.is_some()) => {
diff --git a/crates/horizon-client/src/game/commands/pregen.rs b/crates/horizon-client/src/game/commands/pregen.rs
index d497e2734..eb3c37688 100644
--- a/crates/horizon-client/src/game/commands/pregen.rs
+++ b/crates/horizon-client/src/game/commands/pregen.rs
@@ -244,7 +244,11 @@ impl Game<'_> {
/// hand them the next jobs as soon as each one is done, rather than once
/// a tick.
pub(in crate::game) fn pump_pregen(&mut self, until: Instant) {
- while self.pregen_runs_here() {
+ // Force-loaded chunks too: decorating in vanilla's order, a chunk
+ // waits for its neighbours far more often than once a tick allows.
+ while self.pregen_runs_here()
+ || (!self.streaming.forced.is_empty() && self.streaming.busy())
+ {
let now = Instant::now();
if now >= until {
break;
diff --git a/crates/horizon-client/src/game/commands/terrain_cmds.rs b/crates/horizon-client/src/game/commands/terrain_cmds.rs
index d4b1c125c..824ca4d60 100644
--- a/crates/horizon-client/src/game/commands/terrain_cmds.rs
+++ b/crates/horizon-client/src/game/commands/terrain_cmds.rs
@@ -120,6 +120,9 @@ impl Game<'_> {
tracker.track(&holder(chunk_text(x, z)), i32::from(changed));
}
}
+ if add {
+ self.streaming.rank_forced(cx0, cz0, cx1, cz1);
+ }
let (lo, hi) = (chunk_text(cx0, cz0), chunk_text(cx1, cz1));
let verb = if add { "added" } else { "removed" };
let (message, total) = tracker.message(
diff --git a/crates/horizon-client/src/game/commands/text_commands.rs b/crates/horizon-client/src/game/commands/text_commands.rs
index dead07d71..020157f83 100644
--- a/crates/horizon-client/src/game/commands/text_commands.rs
+++ b/crates/horizon-client/src/game/commands/text_commands.rs
@@ -14,10 +14,11 @@ impl Game<'_> {
serde_json::from_str(json).map_err(|e| err("argument.component.invalid", &[&e]))?;
// NbtContents.resolve: the path's values in the entity, block or
// storage data, rich-styled (or plain, or interpreted), ", "-joined.
+ // ScoreContents.resolve: the holder's score in the objective.
let nbt_values = std::cell::RefCell::new(Vec::new());
{
let mut collect = |o: &serde_json::Map| {
- if o.contains_key("nbt") {
+ if o.contains_key("nbt") || o.contains_key("score") {
nbt_values.borrow_mut().push(o.clone());
}
};
@@ -40,7 +41,11 @@ impl Game<'_> {
}
let mut resolved: Vec<(serde_json::Map, Text)> = Vec::new();
for o in nbt_values.into_inner() {
- let t = self.resolve_nbt_component(&o);
+ let t = if o.contains_key("score") {
+ self.resolve_score_component(&o)?
+ } else {
+ self.resolve_nbt_component(&o)
+ };
resolved.push((o, t));
}
let mut resolve = |raw: &str| -> Text {
@@ -73,6 +78,54 @@ impl Game<'_> {
},
))
}
+ /// The text of a `score` component (ScoreContents.resolve): the named
+ /// holder's score, `*` being the player the command runs for.
+ fn resolve_score_component(
+ &mut self,
+ o: &serde_json::Map,
+ ) -> R {
+ let score = o.get("score");
+ let field = |k: &str| score.and_then(|s| s.get(k)).and_then(|v| v.as_str());
+ let (name, objective) = (
+ field("name").unwrap_or(""),
+ field("objective").unwrap_or(""),
+ );
+ // findTargetName: a selector that matches one entity is that entity,
+ // one that matches none is just the name.
+ let mut reader = horizon_client::command::Reader::new(name);
+ let ty = horizon_client::command::args::ArgType::Entity {
+ single: false,
+ players: false,
+ };
+ let mut holder = name.to_owned();
+ if let Ok(Arg::Entity(sel)) = ty.parse(&mut reader, &self.ui.registries)
+ && !reader.can_read()
+ {
+ let found = self.select(&sel);
+ if found.len() > 1 {
+ return Err(err("argument.entity.toomany", &[]));
+ }
+ if let Some(t) = found.first().and_then(|t| self.holder_name(*t)) {
+ holder = t;
+ }
+ }
+ if holder == "*" {
+ holder = self.acting_player_name().to_owned();
+ }
+ let board = &self.score.board;
+ let (Some(objective), Some(score)) =
+ (board.objective(objective), board.score(&holder, objective))
+ else {
+ return Ok(Text::empty());
+ };
+ // numberFormatOrDefault(StyledFormat.NO_STYLE).
+ let format = (score.number_format.clone())
+ .or_else(|| objective.number_format.clone())
+ .unwrap_or(horizon_client::scoreboard::NumberFormat::Styled(
+ serde_json::json!({}),
+ ));
+ Ok(format.format(score.value))
+ }
/// The text of an `nbt` component.
fn resolve_nbt_component(&mut self, o: &serde_json::Map) -> Text {
use horizon_world::nbt::Tag;
@@ -136,28 +189,40 @@ impl Game<'_> {
}
out
}
- fn player_targets(&mut self, ctx: &Context) -> R {
- // Only the local player can receive messages and titles.
+ /// The players the command reaches: the window's own and the LAN guests.
+ fn player_targets(&mut self, ctx: &Context) -> R> {
let targets = self.entities(ctx, "targets", true)?;
- Ok(targets.iter().filter(|t| **t == Target::Player).count())
+ Ok(targets
+ .into_iter()
+ .filter(|t| matches!(t, Target::Player | Target::Guest(_)))
+ .collect())
}
pub(super) fn cmd_tellraw(&mut self, ctx: &Context) -> R {
- let n = self.player_targets(ctx)?;
+ let players = self.player_targets(ctx)?;
let message = self.component_arg(ctx, "message")?;
- if n > 0 {
- self.system_message(message);
+ // Each player's chat (a guest's through the connection).
+ for &t in &players {
+ self.for_player(t, |g| g.system_message(message.clone()));
}
- Ok(n as i32)
+ Ok(players.len() as i32)
}
pub(super) fn cmd_title(&mut self, ctx: &Context) -> R {
- let n = self.player_targets(ctx)?;
- let name = self.target_name(Target::Player);
+ let players = self.player_targets(ctx)?;
+ let n = players.len();
+ let name = players
+ .first()
+ .map_or_else(Text::empty, |t| self.target_name(*t));
let single = n == 1;
let key = if ctx.has("clear") {
- self.titles_or_packet(Titles::clear, C::ClearTitles(play::Bool1 { value: false }));
+ self.titles_or_packet(
+ &players,
+ Titles::clear,
+ C::ClearTitles(play::Bool1 { value: false }),
+ );
"cleared"
} else if ctx.has("reset") {
self.titles_or_packet(
+ &players,
|t| {
t.clear();
t.reset_times();
@@ -172,6 +237,7 @@ impl Game<'_> {
};
let (fade_in, stay, fade_out) = (get("fadeIn"), get("stay"), get("fadeOut"));
self.titles_or_packet(
+ &players,
|t| t.set_times(fade_in, stay, fade_out),
C::SetTitlesAnimation(play::TitlesAnimation {
fade_in,
@@ -186,13 +252,17 @@ impl Game<'_> {
text: component_nbt(&text.component()),
};
if ctx.has("subtitle") {
- self.titles_or_packet(|t| t.set_subtitle(text), C::SetSubtitleText(sent));
+ self.titles_or_packet(&players, |t| t.set_subtitle(text), C::SetSubtitleText(sent));
"show.subtitle"
} else if ctx.has("actionbar") {
- self.titles_or_packet(|t| t.set_overlay(text, false), C::SetActionBarText(sent));
+ self.titles_or_packet(
+ &players,
+ |t| t.set_overlay(text, false),
+ C::SetActionBarText(sent),
+ );
"show.actionbar"
} else {
- self.titles_or_packet(|t| t.set_title(text), C::SetTitleText(sent));
+ self.titles_or_packet(&players, |t| t.set_title(text), C::SetTitleText(sent));
"show.title"
}
};
@@ -207,13 +277,27 @@ impl Game<'_> {
self.feedback(message);
Ok(n as i32)
}
- /// The player the title is for: the guest acting now is sent the packet
- /// (TitleCommand's `connection.send`), the window's own player shows it.
- fn titles_or_packet(&mut self, local: impl FnOnce(&mut Titles), packet: C) {
- if self.lan_acting.is_some() {
- self.guest_packets.push(packet);
- } else {
- local(&mut self.titles);
+ /// TitleCommand's `connection.send` for each player: a guest is sent the
+ /// packet, the window's own player shows it.
+ fn titles_or_packet(&mut self, players: &[Target], local: impl FnOnce(&mut Titles), packet: C) {
+ let mut local = Some(local);
+ for &t in players {
+ match t {
+ Target::Player if self.lan_acting.is_some() => {
+ self.guest_packets.push(packet.clone());
+ }
+ Target::Player => {
+ if let Some(local) = local.take() {
+ local(&mut self.titles);
+ }
+ }
+ Target::Guest(conn) => {
+ if let Some(host) = self.lan.as_ref() {
+ host.hub.send_to(conn, &packet);
+ }
+ }
+ _ => {}
+ }
}
}
}
diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs
index 30f019997..559d30db4 100644
--- a/crates/horizon-client/src/game/commands/world_cmds.rs
+++ b/crates/horizon-client/src/game/commands/world_cmds.rs
@@ -49,26 +49,12 @@ impl Game<'_> {
let mut tracker = Tracker::default();
for &t in &targets {
let h = holder(self.target_name(t));
- // ServerRecipeBook.addRecipes/removeRecipes count recipe book
- // displays (a transmute recipe has one per material count).
- let mut n = 0;
- // ServerPlayer.awardRecipes / resetRecipes: the displays changed.
- let index = &self.res.stations().recipe_index;
- n += if give {
- let (count, unlocked) = self.level.recipe_book.add_recipes(index, &recipes);
- self.recipe_unlocked(&unlocked);
- count as i32
- } else {
- let removed = self.level.recipe_book.remove_recipes(index, &recipes);
- let count = removed.len() as i32;
- // A network player's client drops them from its book.
- if self.lan_acting.is_some() && !removed.is_empty() {
- self.guest_packets.push(C::RecipeBookRemove(
- horizon_protocol::packets::recipes::RecipeBookRemove { ids: removed },
- ));
- }
- count
- };
+ // ServerPlayer.awardRecipes / resetRecipes on the target's own
+ // ServerRecipeBook: a guest's is swapped in for the call, and the
+ // packets go to its client.
+ let n = self
+ .for_player(t, |g| g.change_recipes(give, &recipes))
+ .unwrap_or(0);
tracker.track(&h, n);
}
let verb = if give { "give" } else { "take" };
@@ -92,6 +78,27 @@ impl Game<'_> {
Ok(total)
}
+ /// ServerRecipeBook.addRecipes/removeRecipes for the player in place: how
+ /// many recipe book displays changed (a transmute recipe has one per
+ /// material count).
+ fn change_recipes(&mut self, give: bool, recipes: &[String]) -> i32 {
+ let index = &self.res.stations().recipe_index;
+ if give {
+ let (count, unlocked) = self.level.recipe_book.add_recipes(index, recipes);
+ self.recipe_unlocked(&unlocked);
+ return count as i32;
+ }
+ let removed = self.level.recipe_book.remove_recipes(index, recipes);
+ let count = removed.len() as i32;
+ // A network player's client drops them from its book.
+ if self.lan_acting.is_some() && !removed.is_empty() {
+ self.guest_packets.push(C::RecipeBookRemove(
+ horizon_protocol::packets::recipes::RecipeBookRemove { ids: removed },
+ ));
+ }
+ count
+ }
+
// ---- /damage ----------------------------------------------------------------
fn damage_kind(ty: &str) -> DamageKind {
@@ -108,6 +115,7 @@ impl Game<'_> {
"in_fire" | "campfire" | "hot_floor" => DamageKind::InFire,
"lava" => DamageKind::Lava,
"drown" => DamageKind::Drown,
+ "dry_out" => DamageKind::DryOut,
"magic" | "indirect_magic" | "dragon_breath" => DamageKind::Magic,
"sting" => DamageKind::Sting,
"cactus" | "sweet_berry_bush" => DamageKind::Cactus,
@@ -133,27 +141,37 @@ impl Game<'_> {
Some(Arg::Entity(_)) => self.entities(ctx, "entity", false)?.first().copied(),
_ => None,
};
+ let cause = match ctx.get("cause") {
+ Some(Arg::Entity(_)) => self.entities(ctx, "cause", false)?.first().copied(),
+ _ => None,
+ };
let from = match ctx.get("location") {
Some(Arg::Coords(_)) => self.position_arg(ctx, "location"),
_ => by.and_then(|t| self.target_position(t)),
};
let hurt = match target {
+ // The causing mob is the one the hit is credited to and thorns
+ // answer; the source position gives the knockback its direction.
Target::Player => {
- if self.creative || self.spectator() {
+ // `DamageSource(type, cause, by)`: the death message names the
+ // causing entity, else the direct one. A mob is noted by
+ // `hurt_player_from`, a player here.
+ if let Some(t @ (Target::Player | Target::Guest(_))) = cause.or(by) {
+ let name = self.target_name(t);
+ self.note_direct_entity(&ty, name);
+ }
+ if self.spectator() {
false
- } else if let Some(player) = self.player.as_mut() {
- match self.motion.health.damage.id(&ty) {
- Some(id) => player
- .hurt(&self.motion.health, self.world.health_rules, id, amount)
- .unwrap_or(false),
- None => false,
- }
} else {
- false
+ let attacker = match cause.or(by) {
+ Some(Target::Mob(i)) => Some(Some(i)),
+ _ => Some(None),
+ };
+ self.hurt_player_from(amount, from, &ty, attacker)
}
}
Target::Mob(id) => {
- let attacker = by.and_then(|t| match t {
+ let attacker = cause.or(by).and_then(|t| match t {
Target::Player => Some(Who::Player),
Target::Mob(i) => Some(Who::Mob(i)),
_ => None,
@@ -294,9 +312,18 @@ impl Game<'_> {
float("minVolume", 0.0),
);
let range = if volume > 1.0 { 16.0 * volume } else { 16.0 };
+ // PlaySoundCommand: one seed for every player.
+ let seed = self.world.random.next_long();
+ let here = self.dim.id();
let mut tracker = Tracker::default();
for t in targets {
- if t != Target::Player {
+ if !matches!(t, Target::Player | Target::Guest(_)) {
+ continue;
+ }
+ // Only players in the source's level hear it.
+ if let Target::Guest(conn) = t
+ && self.command_guest(conn).is_none_or(|g| g.dimension != here)
+ {
continue;
}
let Some(p) = self.target_position(t) else {
@@ -320,8 +347,26 @@ impl Game<'_> {
} else {
(pos, volume)
};
- self.audio.play_on(source, &sound, Some(at), v, pitch);
- tracker.mark(&holder(Text::literal(self.acting_player_name())));
+ // The connection is sent the sound; the window's own player
+ // plays it.
+ let guest = match t {
+ Target::Guest(conn) => Some(conn),
+ _ => self.lan_acting,
+ };
+ match guest.and_then(|conn| Some((conn, self.lan.as_ref()?))) {
+ Some((conn, host)) => {
+ let packet = host
+ .hub
+ .sound_packet(&sound, at, v, pitch, source as i32, seed);
+ if t == Target::Player {
+ self.guest_packets.push(packet);
+ } else {
+ host.hub.send_to(conn, &packet);
+ }
+ }
+ None => self.audio.play_on(source, &sound, Some(at), v, pitch),
+ }
+ tracker.mark(&holder(self.target_name(t)));
}
let name = Text::literal(sound.clone());
let (message, total) = tracker.message(
@@ -598,8 +643,10 @@ impl Game<'_> {
let reached = reached.len() as i32;
if !local {
} else if count <= 0 {
- // No count: one particle with the delta as velocity.
- self.particles.create(&options, pos, delta);
+ // handleParticleEvent, count 0: one particle, the speed times
+ // the delta as velocity (both sent as floats, multiplied as floats).
+ self.particles
+ .create(&options, pos, delta.map(|d| f64::from(speed * d as f32)));
} else {
for _ in 0..count {
let r = self.particles.random();
diff --git a/crates/horizon-client/src/game/composter.rs b/crates/horizon-client/src/game/composter.rs
index 3f57229ad..4013155ad 100644
--- a/crates/horizon-client/src/game/composter.rs
+++ b/crates/horizon-client/src/game/composter.rs
@@ -5,6 +5,7 @@
use super::{Game, commands::compute::ComputeContext};
use horizon_client::{
items::ItemStack,
+ mobs::villager,
particles::{ParticleOptions, ParticleType},
};
use horizon_core::{position::BlockPos, random::RandomSource};
@@ -86,6 +87,82 @@ impl Game<'_> {
self.composter_add(pos, &layers);
(stack.count > 0).then_some(stack)
}
+ /// `WorkAtComposter.compostItems` for the villager at `mob`: a full
+ /// composter is emptied, then up to 20 wheat or beetroot seeds go in
+ /// (keeping 10 of each kind) until the composter reaches level 7. Level
+ /// event 1500 plays once, at the end.
+ pub(super) fn villager_compost_items(&mut self, mob: usize, pos: [i32; 3]) {
+ let at = BlockPos::new(pos[0], pos[1], pos[2]);
+ let Some(mut before) = self.composter_level(pos) else {
+ return;
+ };
+ if before == 8 {
+ self.with_level(|b, level, ticks| b.composter_extract(level, ticks, at));
+ let _ = self.process_level_events();
+ before = 0;
+ }
+ let mut remaining = 20;
+ let mut amounts: Vec<(std::sync::Arc, i32)> = Vec::new();
+ let slots = villager::ext(&self.mobs[mob]).map_or(0, |e| e.inventory.len());
+ 'slots: for slot in (0..slots).rev() {
+ if remaining <= 0 {
+ break;
+ }
+ let stack = villager::ext_mut(&mut self.mobs[mob]).inventory[slot].clone();
+ if !matches!(
+ &*stack.item,
+ "minecraft:wheat_seeds" | "minecraft:beetroot_seeds"
+ ) {
+ continue;
+ }
+ let known = amounts.iter().position(|(item, _)| *item == stack.item);
+ let total = known.map_or(0, |k| amounts[k].1) + stack.count as i32;
+ match known {
+ Some(k) => amounts[k].1 = total,
+ None => amounts.push((stack.item.clone(), total)),
+ }
+ let uses = (total - 10).min(remaining).min(stack.count as i32);
+ if uses <= 0 {
+ continue;
+ }
+ remaining -= uses;
+ for _ in 0..uses {
+ self.villager_insert_item(mob, slot, &stack, pos);
+ if self.composter_level(pos) == Some(7) {
+ break 'slots;
+ }
+ }
+ }
+ let after = self.composter_level(pos).unwrap_or(before);
+ self.with_level(|b, level, ticks| {
+ b.composter_fill_effects(level, ticks, at, after != before)
+ });
+ let _ = self.process_level_events();
+ }
+ /// `ComposterBlock.insertItem` with a villager's stack: below level 7 a
+ /// compostable item is used up and may add a layer.
+ fn villager_insert_item(&mut self, mob: usize, slot: usize, stack: &ItemStack, pos: [i32; 3]) {
+ if self.composter_level(pos).is_none_or(|level| level >= 7) {
+ return;
+ }
+ let Some(layers) = self.compostable(stack) else {
+ return;
+ };
+ let context = ComputeContext {
+ block: Some(pos),
+ target: None,
+ };
+ let layers = self.provider_int(&layers, &context, 0).unwrap_or(0);
+ let at = BlockPos::new(pos[0], pos[1], pos[2]);
+ self.with_level(|b, level, ticks| b.composter_layer(level, ticks, at, layers));
+ self.world.modified.insert((pos[0] >> 4, pos[2] >> 4));
+ let _ = self.process_level_events();
+ let inventory = &mut villager::ext_mut(&mut self.mobs[mob]).inventory;
+ inventory[slot].count -= 1;
+ if inventory[slot].count == 0 {
+ inventory.remove(slot);
+ }
+ }
/// `ComposterBlock.handleFill` (level event 1500) on the client: the
/// fill sound and ten composter particles above the compost.
pub(super) fn composter_fill_event(&mut self, pos: BlockPos, success: bool) {
diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs
index 3202b23f4..9b5cd93e7 100644
--- a/crates/horizon-client/src/game/control.rs
+++ b/crates/horizon-client/src/game/control.rs
@@ -628,6 +628,9 @@ impl Game<'_> {
// The port, or the game rules' search and number boxes.
Screen::WorldOptions if text == "\\b" => self.world_options_text(None),
Screen::WorldOptions => self.world_options_text(Some(text)),
+ Screen::Inventory if self.mod_browser_typing() => {
+ self.mod_browser_text((text != "\\b").then_some(text), text == "\\b")
+ }
Screen::Inventory if self.recipe_search_focused() => {
self.recipe_text(Some(text), false)
}
@@ -1080,6 +1083,9 @@ impl Game<'_> {
"flashes": self.lightning_seen[1], "flash": self.flash});
// Primed TNT, falling blocks, projectiles, tridents and end crystals.
status["projectiles"] = json!(self.projectiles_status());
+ let mut fangs_vertices = Vec::new();
+ self.fangs_geometry(glam::DVec3::ZERO, 0.5, &mut fangs_vertices);
+ status["fangs_vertices"] = json!(fangs_vertices.len());
status["maps"] = json!(self.maps_status());
// The particles made so far, by type.
status["particles"] = json!(self.particles.made());
diff --git a/crates/horizon-client/src/game/creaking.rs b/crates/horizon-client/src/game/creaking.rs
index c75325c2f..19b3442c2 100644
--- a/crates/horizon-client/src/game/creaking.rs
+++ b/crates/horizon-client/src/game/creaking.rs
@@ -218,8 +218,9 @@ impl Game<'_> {
);
}
/// `CreakingHeartBlock.playerWillDestroy`: the heart's creaking twitches to
- /// death and a natural heart drops experience.
- pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3]) {
+ /// death and a natural heart drops experience. `onExplosionHit` does the
+ /// same for the creaking (`by_player` false), without the experience.
+ pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3], by_player: bool) {
let key = (pos[0], pos[1], pos[2]);
if !matches!(
self.world.block_entities.get(&key),
@@ -242,7 +243,7 @@ impl Game<'_> {
.state(state)
.and_then(|s| s.properties.get("natural").cloned())
.is_some_and(|v| v == "true");
- if natural && !self.creative && !self.spectator() {
+ if by_player && natural && !self.creative && !self.spectator() {
let xp = 20 + self.world.random.next_int_bound(5).unwrap_or(0) as u32;
self.spawn_orbs(
[
diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs
index 3a8562ee1..2bc40a7af 100644
--- a/crates/horizon-client/src/game/creatures.rs
+++ b/crates/horizon-client/src/game/creatures.rs
@@ -18,6 +18,7 @@ use horizon_client::{
spawning::{self, BiomeFacts},
},
projectiles::{Hit, Projectile, ProjectileKind, ProjectileWorld},
+ text::Text,
};
use horizon_core::{
geometry::{Aabb, Vec3, traverse_blocks},
@@ -50,9 +51,9 @@ pub(super) struct Creatures {
/// The wandering trader spawner's clock.
pub trader: super::wandering_trader::Spawner,
}
-struct ProjWorld<'a, 'w> {
- w: &'a MobWorld<'w>,
- targets: Vec<(Who, Aabb)>,
+pub(super) struct ProjWorld<'a, 'w> {
+ pub w: &'a MobWorld<'w>,
+ pub targets: Vec<(Who, Aabb)>,
}
impl ProjectileWorld for ProjWorld<'_, '_> {
fn clip(&self, from: Vec3, to: Vec3) -> Option<(Vec3, [i32; 3], [i32; 3])> {
@@ -193,6 +194,7 @@ impl Game<'_> {
velocity: p.velocity,
yaw: self.yaw,
hero: self.potions.effects.get("hero_of_the_village").is_some(),
+ effects: self.potions.effects.list.iter().map(|e| e.id).collect(),
uuid: self.level.player_uuid.unwrap_or_default(),
allies: std::sync::Arc::new(self.player_allies()),
remote: false,
@@ -373,6 +375,7 @@ impl Game<'_> {
// Drawn seated (Entity.isPassenger); set apart because the
// json! above is at the macro recursion limit.
state["passenger"] = m.extra.passenger.into();
+ state["guardian_beam"] = serde_json::json!(horizon_client::mobs::guardian::beam(m, 0.0));
state
})
.collect();
@@ -391,6 +394,9 @@ impl Game<'_> {
}
pub(super) fn mob_world_base<'s>(&'s self, others: &'s [Seen]) -> MobWorld<'s> {
let (rain, thunder) = self.world.weather.levels(1.0);
+ // Level.canHaveWeather: only the overworld's rain and thunder levels
+ // ever rise, so nothing rains or thunders in the Nether or the End.
+ let weather = self.dim == Dim::Overworld;
let player = self.player_view();
MobWorld {
world: &self.world,
@@ -407,8 +413,8 @@ impl Game<'_> {
daylight: self.dim != Dim::Nether && self.sky_darken() < 4,
game_time: self.world.game_time,
day_time: self.world.day_time,
- raining: rain > 0.2,
- thundering: thunder > 0.9,
+ raining: weather && rain > 0.2,
+ thundering: weather && thunder > 0.9,
nether: self.dim == Dim::Nether,
block_tags: &self.res.items().block_tags,
biomes: self.res.biomes(),
@@ -425,6 +431,12 @@ impl Game<'_> {
),
}
}
+ /// What the generator finalizes this level's structure mobs with.
+ pub(super) fn share_spawn_conditions(&self) {
+ if let Some(terrain) = self.end.locator() {
+ terrain.set_spawn_conditions(self.difficulty_id() as u8, self.world.day_time);
+ }
+ }
/// `ServerLevel.getCurrentDifficultyAt`.
pub(super) fn local_difficulty(&self, at: [f64; 3]) -> spawning::LocalDifficulty {
use horizon_world::food::Difficulty;
@@ -493,6 +505,8 @@ impl Game<'_> {
self.died.insert(m.id);
self.mob_died(&m);
}
+ // Their victims have been looted: no charged creeper is waiting any more.
+ self.combat.charged_exploders.clear();
let uuid = self.level.player_uuid;
let mut snapshot: Vec = self.mobs.iter().map(|m| seen(m, uuid)).collect();
let mut events = Vec::new();
@@ -519,6 +533,8 @@ impl Game<'_> {
_ => Vec::new(),
};
let mut guest_events = Vec::new();
+ // The mobs whose bodies go this tick: (id, feet, width, height).
+ let mut gone = Vec::new();
let level_random;
{
// The level random, lent to the mobs (brain behaviours draw from
@@ -591,6 +607,11 @@ impl Game<'_> {
let from = events.len();
let kept = m.tick(&w, &mut scratch, &mut events);
horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes);
+ // LivingEntity.tickDeath: after twenty ticks the body is removed.
+ if !kept && !m.removed && !m.alive() && m.death_time >= 20 {
+ let (width, height) = (f64::from(m.width()), f64::from(m.height()));
+ gone.push((m.id, m.position, width, height));
+ }
if let Some(conn) = seen_guest {
// ShulkerBullet.finalTarget is the guest's entity: the
// bullet homes on it while the projectiles tick, where
@@ -649,6 +670,12 @@ impl Game<'_> {
}
self.mobs.append(&mut mobs);
self.died = died;
+ // ... and entity event 60 goes out as it is: the poof.
+ for (id, at, width, height) in gone {
+ let at = [at.x, at.y, at.z];
+ self.lan_entity_event(id as i32, 60, at);
+ self.death_poof(at, width, height);
+ }
self.sync_riders();
self.tick_skeleton_traps();
self.tick_apparition();
@@ -675,6 +702,22 @@ impl Game<'_> {
self.handle_mob_events(queued)?;
Ok(())
}
+ /// `LivingEntity.makePoofParticles` (entity event 60) about a mob's box.
+ pub(super) fn death_poof(&mut self, at: [f64; 3], width: f64, height: f64) {
+ let options = horizon_client::particles::ParticleOptions::simple(
+ horizon_client::particles::ParticleType::Poof,
+ );
+ for _ in 0..20 {
+ let r = self.particles.level_random();
+ let xa = r.next_gaussian() * 0.02;
+ let ya = r.next_gaussian() * 0.02;
+ let za = r.next_gaussian() * 0.02;
+ let x = at[0] + width * (2.0 * r.next_double() - 1.0) - xa * 10.0;
+ let y = at[1] + height * r.next_double() - ya * 10.0;
+ let z = at[2] + width * (2.0 * r.next_double() - 1.0) - za * 10.0;
+ self.particles.add(&options, [x, y, z], [xa, ya, za]);
+ }
+ }
/// LivingEntity.die / dropAllDeathLoot.
fn mob_died(&mut self, m: &Mob) {
let killer = self.last_hurt_by_player.remove(&m.id);
@@ -775,7 +818,17 @@ impl Game<'_> {
.mobs
.iter()
.find(|o| o.id == id)
- .map(|o| drops::loot_entity(o, None)),
+ .map(|o| drops::loot_entity(o, None))
+ // A charged creeper's blast kills after the creeper left the list.
+ .or_else(|| {
+ self.combat
+ .charged_exploders
+ .contains(&id)
+ .then(|| LootEntity {
+ powered: true,
+ ..LootEntity::new("minecraft:creeper")
+ })
+ }),
None => None,
};
let direct = match d.kind {
@@ -811,12 +864,12 @@ impl Game<'_> {
world_seed: self.level.seed,
};
let (items, skulls) = drops::die(m, &death, &mut self.rand_sequences);
- if skulls
- && let Some(Who::Mob(id)) = m.last_damage.and_then(|(d, _)| d.attacker)
- && let Some(creeper) = self.mobs.iter_mut().find(|o| o.id == id)
- {
+ if skulls && let Some(Who::Mob(id)) = m.last_damage.and_then(|(d, _)| d.attacker) {
// Creeper.droppedSkulls: one head per charged explosion.
- creeper.extra.charged = false;
+ self.combat.charged_exploders.retain(|c| *c != id);
+ if let Some(creeper) = self.mobs.iter_mut().find(|o| o.id == id) {
+ creeper.extra.charged = false;
+ }
}
let raider = horizon_client::mobs::raider::is_raider(m.species());
for d in items {
@@ -834,9 +887,51 @@ impl Game<'_> {
}
}
}
+ /// `LivingEntity.dropFromGiftLootTable`: the gift table from its random
+ /// sequence with the mob as `this` (a chicken's egg depends on its
+ /// variant); the loot data of the game's resources decides, and without it
+ /// the items' table engine (no entity) rolls it.
+ fn drop_gift_loot(&mut self, mob: u32, table: &'static str, at: [f64; 3]) {
+ use horizon_client::mobs::drops;
+ use horizon_world::loot::EntityLootParams;
+ let loot = horizon_client::structure_blocks::loot_data(&self.options.resources);
+ let this = self
+ .mobs
+ .iter()
+ .find(|m| m.id == mob)
+ .map(|m| drops::loot_entity(m, None));
+ let stacks = match (loot, this) {
+ (Some(loot), Some(this)) if loot.has_table(table) => {
+ let params = EntityLootParams {
+ this,
+ ..EntityLootParams::default()
+ };
+ let seed = self.level.seed;
+ match loot.random_sequence(table) {
+ Some(id) => {
+ let random = self.rand_sequences.get(id, seed);
+ loot.roll_entity(table, random, ¶ms)
+ .iter()
+ .filter(|s| !s.is_empty())
+ .map(from_loot)
+ .collect()
+ }
+ None => Vec::new(),
+ }
+ }
+ _ => self
+ .res
+ .items()
+ .loot_table(table, false, None, &mut self.world.random),
+ };
+ for d in stacks {
+ self.spawn_item(d, at, [0.0, 0.2, 0.0], 10);
+ }
+ }
pub(super) fn handle_mob_events(&mut self, events: Vec) -> Result<()> {
for e in events {
match e {
+ MobEvent::SquidCycle { mob, at } => self.lan_entity_event(mob as i32, 19, at),
MobEvent::RabbitHop { mob, at } => self.lan_entity_event(mob as i32, 1, at),
MobEvent::Sound(name, at, volume, pitch)
| MobEvent::LocalSound(name, at, volume, pitch) => {
@@ -898,16 +993,24 @@ impl Game<'_> {
owner,
} => self.add_fangs(at, yaw, delay, owner),
MobEvent::Shoot(..) => {}
+ MobEvent::ExplosionSource { mob, charged } => {
+ self.combat.explosion_source = Some(mob);
+ if charged {
+ self.combat.charged_exploders.push(mob);
+ }
+ }
MobEvent::Explode(at, radius) => {
// The exploding mob causes the damage (Creeper.explodeCreeper).
- let source_mob = self
- .mobs
- .iter()
- .filter(|m| {
- (m.position.x - at[0]).powi(2) + (m.position.z - at[2]).powi(2) < 1.0
- })
- .map(|m| m.id)
- .next();
+ let source_mob = self.combat.explosion_source.or_else(|| {
+ self.mobs
+ .iter()
+ .filter(|m| {
+ (m.position.x - at[0]).powi(2) + (m.position.z - at[2]).powi(2)
+ < 1.0
+ })
+ .map(|m| m.id)
+ .next()
+ });
if let Some(id) = source_mob {
self.note_attacker("minecraft:explosion", id);
}
@@ -938,6 +1041,9 @@ impl Game<'_> {
volume,
pitch,
);
+ } else {
+ // Left for the end of the tick.
+ t.outbox.push(event);
}
}
}
@@ -1008,6 +1114,11 @@ impl Game<'_> {
self.next_entity += 1;
p.id = self.next_entity;
let (owner, at) = (p.owner, [p.position.x, p.position.y, p.position.z]);
+ // LlamaSpit.recreateFromPacket: the spit's burst on the client.
+ if p.kind == ProjectileKind::LlamaSpit {
+ let v = p.velocity;
+ self.particles.llama_spit_burst(at, [v.x, v.y, v.z]);
+ }
self.creatures.projectiles.push(p);
self.projectile_event("minecraft:projectile_shoot", owner, at);
}
@@ -1040,6 +1151,40 @@ impl Game<'_> {
self.with_level(|b, level, ticks| b.set_door_open(level, ticks, pos, open));
self.process_level_events()?;
}
+ MobEvent::BreakDoor { pos } => {
+ // BreakDoorGoal.tick: removeBlock, then level events 1021
+ // and 2001 with the state that is there now.
+ let air = self.world.air;
+ let at = BlockPos::new(pos[0], pos[1], pos[2]);
+ self.with_level(|b, level, ticks| b.set_block(level, ticks, at, air, 3));
+ self.process_level_events()?;
+ self.level_event_at(1021, pos, 0);
+ let left = self.world.block(pos[0], pos[1], pos[2]);
+ self.level_event_at(2001, pos, left.0 as i32);
+ }
+ MobEvent::DestroyProgress { mob, pos, progress } => {
+ self.destroy_block_progress(mob as i32, pos, progress);
+ // ServerLevel.destroyBlockProgress: every player nearby sees it.
+ if let Some(host) = self.lan.as_ref() {
+ host.hub.broadcast_near(
+ [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])],
+ 64.0,
+ &horizon_protocol::packets::play::Clientbound::BlockDestruction(
+ horizon_protocol::packets::play::BlockDestruction {
+ id: mob as i32,
+ pos,
+ progress: if (0..10).contains(&progress) {
+ progress as u8
+ } else {
+ 255
+ },
+ },
+ ),
+ None,
+ );
+ }
+ }
+ MobEvent::LevelEvent { id, pos, data } => self.level_event_at(id, pos, data),
MobEvent::SetBlockName { pos, name, effect } => {
if effect {
let old = self.world.block(pos[0], pos[1], pos[2]);
@@ -1062,7 +1207,10 @@ impl Game<'_> {
}
MobEvent::BreakBlock { pos, drop } => {
let old = self.world.block(pos[0], pos[1], pos[2]);
- self.destroy_particles(pos, old);
+ // Block.spawnDestroyParticles: fire breaks leave nothing.
+ if !self.res.facts().get(old).has_class("BaseFireBlock") {
+ self.destroy_particles(pos, old);
+ }
if drop {
let drops = self.res.items().block_drops_in(
self.pack.assets.registry,
@@ -1084,6 +1232,9 @@ impl Game<'_> {
self.ensure_item_particle_sprites();
}
let options = horizon_client::particles::ParticleOptions::simple(ty);
+ if ty == horizon_client::particles::ParticleType::SonicBoom {
+ self.lan_sonic_boom(&options, at);
+ }
// Count 0: one particle exactly there, at rest.
if count == 0 {
self.particles.add(&options, at, [0.0; 3]);
@@ -1117,7 +1268,7 @@ impl Game<'_> {
self.particles.add(&options, at, velocity);
}
}
- MobEvent::Experience { at, amount } => self.spawn_orbs(at, amount),
+ MobEvent::Experience { at, amount } => self.spawn_breeding_orb(at, amount),
MobEvent::AxolotlSupportPlayer => {
let previous = self
.potions
@@ -1179,6 +1330,10 @@ impl Game<'_> {
self.mob_vibration_particle(from, to, ticks)
}
MobEvent::DigParticles { at } => self.warden_dig_particles(at),
+ MobEvent::BlockBreakEffect { pos, block } => {
+ let state = self.world.block(block[0], block[1], block[2]);
+ self.destroy_particles(pos, state);
+ }
MobEvent::Darkness { at, radius } => self.apply_darkness(at, radius),
MobEvent::CreakingHurt {
home,
@@ -1189,12 +1344,14 @@ impl Game<'_> {
self.creaking_tear_down(center, spread)
}
MobEvent::CureZombieVillager { mob } => self.cure_zombie_villager(mob),
+ MobEvent::Reinforcements { mob, target } => self.call_reinforcements(mob, target),
MobEvent::VillagerMeet { mob, other } => self.villager_meet(mob, other),
MobEvent::VillagerBirth {
parent,
partner,
child,
} => self.villager_birth(parent, partner, child),
+ MobEvent::WorkAtComposter { mob, pos } => self.villager_work_at_composter(mob, pos),
MobEvent::GolemCheck { mob, needed } => self.villager_golem_check(mob, needed),
MobEvent::Firework { at, color, flight } => {
self.villager_firework(at, color, flight)
@@ -1215,19 +1372,51 @@ impl Game<'_> {
m.ai.aggressive |= aggressive;
}
}
- MobEvent::GiftLoot { table, at } => {
- let drops =
- self.res
- .items()
- .loot_table(table, false, None, &mut self.world.random);
- for d in drops {
- self.spawn_item(d, at, [0.0, 0.2, 0.0], 10);
+ MobEvent::GiftLoot { mob, table, at } => {
+ // Turtle.ageBoundaryReached: only with mob loot on.
+ if table == "minecraft:gameplay/turtle_grow" && !self.ui.rules.bool("mob_drops")
+ {
+ continue;
}
+ self.drop_gift_loot(mob, table, at);
}
}
}
Ok(())
}
+ /// `TurtleEggBlock.randomTick` at the last hatch stage: one baby turtle
+ /// per egg, a day from grown, with the egg as its home (the sound, the
+ /// crumbs and the block's removal came from the level).
+ pub(super) fn hatch_turtles(
+ &mut self,
+ pos: [i32; 3],
+ state: horizon_world::registry::BlockStateId,
+ ) {
+ let eggs = self
+ .pack
+ .assets
+ .registry
+ .state(state)
+ .and_then(|s| s.properties.get("eggs"))
+ .and_then(|v| v.parse::().ok())
+ .unwrap_or(1);
+ for i in 0..eggs {
+ let at = [
+ f64::from(pos[0]) + 0.3 + f64::from(i) * 0.2,
+ f64::from(pos[1]),
+ f64::from(pos[2]) + 0.3,
+ ];
+ if let Some(id) = self.spawn_mob("minecraft:turtle", at, true)
+ && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
+ {
+ m.extra.age = -24000;
+ m.extra.home = Some(pos);
+ m.yaw = 0.0;
+ m.body_yaw = 0.0;
+ m.head_yaw = 0.0;
+ }
+ }
+ }
fn apply_setup(&mut self, id: u32, setup: &SpawnSetup) {
let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) else {
return;
@@ -1261,6 +1450,13 @@ impl Game<'_> {
m.extra.egg_time = life;
}
}
+ /// `Animal.finalizeSpawnChildFromBreeding`'s experience orb: only when the
+ /// `mob_drops` game rule is on.
+ fn spawn_breeding_orb(&mut self, at: [f64; 3], amount: u32) {
+ if self.ui.rules.bool("mob_drops") {
+ self.spawn_orbs(at, amount);
+ }
+ }
/// Animal.spawnChildFromBreeding
fn breed(
&mut self,
@@ -1283,6 +1479,8 @@ impl Game<'_> {
.unwrap_or_else(|| parent.clone());
let mut child = parent.clone();
child.baby = true;
+ // TurtleBreedGoal.breed triggers it without a child.
+ let turtle = p.species() == Species::Turtle;
if matches!(
(
p.species(),
@@ -1295,7 +1493,7 @@ impl Game<'_> {
) {
child.kind = "minecraft:mule".into();
}
- self.trigger_bred(&parent, &partner_view, Some(&child));
+ self.trigger_bred(&parent, &partner_view, (!turtle).then_some(&child));
}
if let Some(q) = self.mobs.iter_mut().find(|m| m.id == partner) {
q.extra.age = 6000;
@@ -1307,6 +1505,19 @@ impl Game<'_> {
self.lay_sniffer_egg(&p);
return;
}
+ // TurtleBreedGoal.breed: the goal gave the mother her egg; only the
+ // experience is left, and only with mob loot on.
+ if p.species() == Species::Turtle {
+ // One `new ExperienceOrb` of 1 to 7 from the mother's random (not
+ // split up as `ExperienceOrb.award` does).
+ if self.ui.rules.bool("mob_drops")
+ && let Some(m) = self.mobs.iter_mut().find(|m| m.id == parent)
+ {
+ let xp = 1 + m.random.next_int_bound(7).unwrap_or(0) as u32;
+ self.add_orb([p.position.x, p.position.y, p.position.z], xp);
+ }
+ return;
+ }
let coin = self.world.random.next_int_bound(2).unwrap_or(0) == 0;
let coin2 = self.world.random.next_int_bound(2).unwrap_or(0) == 0;
// A horse and a donkey have a mule.
@@ -1354,7 +1565,7 @@ impl Game<'_> {
}
self.world.random = r;
let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32;
- self.spawn_orbs([p.position.x, p.position.y, p.position.z], xp);
+ self.spawn_breeding_orb([p.position.x, p.position.y, p.position.z], xp);
return;
}
if p.species() == Species::Cat {
@@ -1375,7 +1586,7 @@ impl Game<'_> {
};
}
let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32;
- self.spawn_orbs([p.position.x, p.position.y, p.position.z], xp);
+ self.spawn_breeding_orb([p.position.x, p.position.y, p.position.z], xp);
return;
}
if p.species() == Species::Wolf {
@@ -1397,7 +1608,7 @@ impl Game<'_> {
};
}
let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32;
- self.spawn_orbs([p.position.x, p.position.y, p.position.z], xp);
+ self.spawn_breeding_orb([p.position.x, p.position.y, p.position.z], xp);
return;
}
// Nautilus.getBreedOffspring: a tame parent's baby is tame too.
@@ -1413,7 +1624,7 @@ impl Game<'_> {
}
}
let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32;
- self.spawn_orbs([p.position.x, p.position.y, p.position.z], xp);
+ self.spawn_breeding_orb([p.position.x, p.position.y, p.position.z], xp);
}
/// `MobEffectUtil.addEffectToPlayersAround` for an elder guardian:
/// mining fatigue III for five minutes unless a stronger or longer one
@@ -1470,11 +1681,34 @@ impl Game<'_> {
pub(super) fn mob_hits_player_kind(&mut self, amount: f32, from: [f64; 3], kind: &str) {
self.mob_hits_player(amount, from, kind);
}
+ /// Damage whose causing mob is known (`cause`, or none): not guessed
+ /// from the mob nearest to `from`.
+ pub(super) fn mob_hits_player_caused(
+ &mut self,
+ amount: f32,
+ from: [f64; 3],
+ kind: &str,
+ cause: Option,
+ ) {
+ self.hurt_player_from(amount, Some(from), kind, Some(cause));
+ }
pub(super) fn mob_hits_player(
&mut self,
amount: f32,
from: [f64; 3],
damage_type: &str,
+ ) -> bool {
+ self.hurt_player_from(amount, Some(from), damage_type, None)
+ }
+ /// `hurtServer` on the player. `from` is the source's position (none: no
+ /// direction), `known`: the causing mob when it is given (`/damage`),
+ /// else the melee attacker is the mob nearest to `from`.
+ pub(super) fn hurt_player_from(
+ &mut self,
+ amount: f32,
+ from: Option<[f64; 3]>,
+ damage_type: &str,
+ known: Option>,
) -> bool {
// ServerPlayer.canHarmPlayer refused another player's projectile.
if self.creative || self.combat.refuse_player_hit {
@@ -1487,37 +1721,44 @@ impl Game<'_> {
.damage_tags
.get("minecraft:is_projectile")
.is_some_and(|t| t.contains(damage_type));
- let blocking = self.player_blocking(Some(from), damage_type, false);
+ let blocking = self.player_blocking(from, damage_type, false);
let raised = blocking.is_some();
// Melee: the attacker stands at `from` (another player's hit has no mob behind it).
- let attacker = (!projectile && damage_type != "minecraft:player_attack")
- .then(|| {
- self.mobs
- .iter()
- .filter(|m| m.alive())
- .min_by(|a, b| {
- let d = |m: &horizon_client::mobs::Mob| {
- (m.position.x - from[0]).powi(2) + (m.position.z - from[2]).powi(2)
- };
- d(a).total_cmp(&d(b))
- })
- .map(|m| m.id)
- })
- .flatten();
+ let attacker = match known {
+ Some(known) => known,
+ None => from
+ .filter(|_| !projectile && damage_type != "minecraft:player_attack")
+ .and_then(|from| {
+ self.mobs
+ .iter()
+ .filter(|m| m.alive())
+ .min_by(|a, b| {
+ let d = |m: &horizon_client::mobs::Mob| {
+ (m.position.x - from[0]).powi(2) + (m.position.z - from[2]).powi(2)
+ };
+ d(a).total_cmp(&d(b))
+ })
+ .map(|m| m.id)
+ }),
+ };
// The causing entity for the death message.
let owner = self.combat.projectile_owner.take();
if let Some(a) = attacker.or(owner) {
self.note_attacker(damage_type, a);
}
+ // DamageSource.scalesWithDifficulty: a mob (or its projectile's
+ // owner) caused the hit, not a player.
+ let living_cause = attacker.or(owner).is_some();
let mut outcome = horizon_client::health::BlockOutcome::default();
if let Some(player) = self.player.as_mut()
&& let Some(id) = self.motion.health.damage.id(damage_type)
- && let Ok(o) = player.hurt_blocking(
+ && let Ok(o) = player.hurt_caused_by(
&self.motion.health,
self.world.health_rules,
id,
amount,
blocking,
+ living_cause,
)
&& {
outcome = o;
@@ -1527,7 +1768,10 @@ impl Game<'_> {
// LivingEntity.hurtServer's dealDefaultKnockback: not inside the
// hurt cooldown (a stronger hit there only adds its difference).
if o.knockback {
- let (xd, zd) = (from[0] - player.position.x, from[2] - player.position.z);
+ // No source position: a random direction.
+ let (xd, zd) = from.map_or((0.0, 0.0), |from| {
+ (from[0] - player.position.x, from[2] - player.position.z)
+ });
self.knock_back_player(f64::from(0.4_f32), xd, zd);
if let Some(p) = self.player.as_mut()
&& let Some(r) = p.hurt_log.last_mut()
@@ -1535,8 +1779,10 @@ impl Game<'_> {
r.knockback = Some([p.velocity.x, p.velocity.y, p.velocity.z]);
}
}
- self.hurt_armor(amount);
- self.thorns(from);
+ // The thorns hurt the entity that caused the hit, if there is one.
+ if let Some(a) = attacker.or(owner) {
+ self.thorns(a);
+ }
}
if raised {
self.after_block(outcome, amount, attacker, projectile);
@@ -1863,6 +2109,33 @@ impl Game<'_> {
None => self.projectile_hit(p, hit),
}
}
+ /// What an arrow or a thrown trident hits an entity of type `victim`
+ /// for (`AbstractArrow.onHitEntity`, `ThrownTrident.onHitEntity`): a
+ /// trident's 8 through `EnchantmentHelper.modifyDamage` of the trident
+ /// (Impaling's `minecraft:damage` on `#sensitive_to_impaling`).
+ fn shot_damage(&mut self, shot: &mut Projectile, victim: Option<&str>) -> f32 {
+ if !matches!(shot.kind, ProjectileKind::Trident) {
+ return arrow_damage(shot, &mut self.world.random) + shot.bonus.damage;
+ }
+ let Some(trident) = shot.arrow.as_ref().map(|a| a.pickup_item.clone()) else {
+ return 8.0;
+ };
+ let ctx = horizon_client::enchant::EffectContext {
+ this: victim,
+ attacker: (shot.owner == Some(Who::Player)).then_some("minecraft:player"),
+ direct_attacker: Some("minecraft:trident"),
+ damage_type: Some("minecraft:trident"),
+ items: Some(self.res.items()),
+ ..Default::default()
+ };
+ self.res.stations().enchantments.modify_value(
+ Some(&trident),
+ "minecraft:damage",
+ &ctx,
+ &mut self.world.random,
+ 8.0,
+ )
+ }
/// What an arrow's tick asked for: its particles and sounds.
fn arrow_event(&mut self, at: Vec3, event: horizon_client::arrows::ArrowEvent) {
use horizon_client::arrows::{ArrowEvent, ArrowParticle, ArrowSound, BlockReaction};
@@ -1891,6 +2164,8 @@ impl Game<'_> {
ArrowSound::Splash => "minecraft:entity.generic.splash",
ArrowSound::HitGround => "minecraft:entity.arrow.hit",
ArrowSound::Extinguish => "minecraft:entity.generic.extinguish_fire",
+ ArrowSound::TridentHitGround => "minecraft:item.trident.hit_ground",
+ ArrowSound::TridentHit => "minecraft:item.trident.hit",
};
self.audio
.play(name, Some([at.x, at.y, at.z]), volume, pitch);
@@ -1987,6 +2262,23 @@ impl Game<'_> {
self.creatures.projectiles.push(arrow);
}
}
+ /// `TargetBlock.onProjectileHit`: a target block takes its power from
+ /// where the projectile landed and resets after 20 ticks for an arrow, 8
+ /// for any other projectile. A player's shot counts as a target hit.
+ fn target_block_hit(&mut self, p: &Projectile, pos: [i32; 3], at: Vec3, face: [i32; 3]) {
+ let block = BlockPos::new(pos[0], pos[1], pos[2]);
+ let arrow = p.arrow.is_some();
+ let location = [at.x, at.y, at.z];
+ let hit = self.with_level(|b, level, ticks| {
+ b.target_projectile_hit(level, ticks, block, location, face, arrow)
+ });
+ if hit.is_some() {
+ let _ = self.process_level_events();
+ if p.owner == Some(Who::Player) {
+ self.stats.custom("target_hit", 1);
+ }
+ }
+ }
pub(super) fn projectile_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> {
self.combat.projectile_owner = match p.owner {
Some(Who::Mob(id)) => Some(id),
@@ -1996,6 +2288,13 @@ impl Game<'_> {
Hit::Entity { at, .. } | Hit::Block { at, .. } => at,
Hit::None => return Ok(()),
};
+ // Projectile.onHitBlock: BlockState.onProjectileHit, for every
+ // projectile (a wind charge out of the world's top has no face).
+ if let Hit::Block { pos, face, .. } = hit
+ && face != [0; 3]
+ {
+ self.target_block_hit(p, pos, at, face);
+ }
if let Hit::Entity {
who: Who::Mob(id),
at,
@@ -2016,11 +2315,11 @@ impl Game<'_> {
&& id >= super::dragon::SPECIAL
{
let by_player = p.owner == Some(Who::Player);
- if let ProjectileKind::Arrow { .. } = p.kind {
+ if p.arrow.is_some() {
// AbstractArrow.onHitEntity: spent if the part or crystal took
// it, else turned back (a perched dragon sets it alight first).
let mut arrow = p.clone();
- let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage;
+ let amount = self.shot_damage(&mut arrow, None);
let outcome = match self.hit_special(id, amount, by_player, true) {
super::dragon::Hurt::Landed { .. } => EntityHit::Hurt,
super::dragon::Hurt::Refused => EntityHit::Refused,
@@ -2041,17 +2340,15 @@ impl Game<'_> {
self.hit_special(id, amount, by_player, false);
return Ok(());
}
- if let (
- ProjectileKind::Arrow { .. },
- Hit::Entity {
+ if p.arrow.is_some()
+ && let Hit::Entity {
who: Who::Mob(id), ..
- },
- ) = (&p.kind, hit)
+ } = hit
&& let Some(i) = self.carts.iter().position(|c| c.id == id)
{
// AbstractArrow.onHitEntity on a minecart.
let mut arrow = p.clone();
- let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage;
+ let amount = self.shot_damage(&mut arrow, None);
let burning = p.arrow.as_ref().is_some_and(|a| a.on_fire());
let creative = p.owner == Some(Who::Player) && self.creative;
self.arrow_hits_cart(i, amount, p.velocity, burning, creative);
@@ -2062,7 +2359,7 @@ impl Game<'_> {
// Projectile.onHit: the landing is heard.
self.projectile_event("minecraft:projectile_land", p.owner, atp);
let source_kind = match p.kind {
- ProjectileKind::Arrow { .. } => DamageKind::Arrow,
+ ProjectileKind::Arrow { .. } | ProjectileKind::Trident => DamageKind::Arrow,
ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } => {
DamageKind::Fireball
}
@@ -2074,6 +2371,40 @@ impl Game<'_> {
from: Some([p.previous.x, p.previous.y, p.previous.z]),
};
match (&p.kind, hit) {
+ // ThrownTrident.onHitEntity: 8 damage (Impaling on aquatic mobs),
+ // dealt whether or not the hurt lands, then it bounces off.
+ (ProjectileKind::Trident, Hit::Entity { who, .. }) => {
+ let mut trident = p.clone();
+ let victim = match who {
+ Who::Mob(id) => self
+ .mobs
+ .iter()
+ .find(|m| m.id == id)
+ .map(|m| m.kind.id.clone()),
+ Who::Player => Some("minecraft:player".to_owned()),
+ };
+ let amount = self.shot_damage(&mut trident, victim.as_deref());
+ let hurt = match who {
+ Who::Player => self.mob_hits_player(
+ amount,
+ [p.previous.x, p.previous.y, p.previous.z],
+ "minecraft:trident",
+ ),
+ Who::Mob(id) => self
+ .mobs
+ .iter_mut()
+ .find(|m| m.id == id)
+ .is_some_and(|m| m.damage(amount, source)),
+ };
+ let outcome = if hurt {
+ EntityHit::Hurt
+ } else {
+ EntityHit::Refused
+ };
+ self.finish_arrow_hit(trident, outcome);
+ }
+ // AbstractArrow.onHitBlock plays its sound itself (ArrowEvent).
+ (ProjectileKind::Trident, Hit::Block { .. }) => {}
(ProjectileKind::Arrow { effect, .. }, Hit::Entity { who, .. }) => {
let mut arrow = p.clone();
let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage;
@@ -2295,14 +2626,30 @@ impl Game<'_> {
if d2 < 16.0 && !self.creative {
let scale = 1.0 - d2.sqrt() / 4.0;
let t = (f64::from(*ticks) * scale + 0.5) as i32;
- if let Some(owner) = self.combat.projectile_owner {
- self.note_attacker("minecraft:indirect_magic", owner);
- }
match *effect {
- "minecraft:instant_damage" => self.hurt_player_by(
- "minecraft:indirect_magic",
- 6.0 * (1 << *amplifier) as f32 * scale as f32,
- ),
+ "minecraft:instant_damage" => {
+ // indirectMagic(potion, owner), built where the
+ // hurt happens: the thrower, or the potion
+ // itself when it has none. A status effect
+ // deals no damage, so it records no source.
+ let owner = self
+ .combat
+ .projectile_owner
+ .filter(|id| self.mob_display_name(*id).is_some());
+ match owner {
+ Some(owner) => {
+ self.note_attacker("minecraft:indirect_magic", owner)
+ }
+ None => self.note_direct_entity(
+ "minecraft:indirect_magic",
+ Text::translate("entity.minecraft.splash_potion", &[]),
+ ),
+ }
+ self.hurt_player_by(
+ "minecraft:indirect_magic",
+ 6.0 * (1 << *amplifier) as f32 * scale as f32,
+ )
+ }
e if t > 20 => self.give_player_effect(e, t, *amplifier),
_ => {}
}
@@ -2358,12 +2705,14 @@ impl Game<'_> {
// ShulkerBullet.onHitEntity: 4 damage, then levitation for 10 s.
(ProjectileKind::ShulkerBullet { .. }, Hit::Entity { who, .. }) => match who {
Who::Player => {
- if !self.creative {
- self.mob_hits_player(
+ // Only a hit that hurt (`wasHurt`) brings the levitation.
+ if !self.creative
+ && self.mob_hits_player(
4.0,
[p.previous.x, p.previous.y, p.previous.z],
"minecraft:mob_projectile",
- );
+ )
+ {
self.give_player_effect("minecraft:levitation", 200, 0);
}
}
@@ -2372,6 +2721,8 @@ impl Game<'_> {
&& m.damage(4.0, source)
{
m.extra.levitation = 200;
+ // Shulker.hurtServer: a shulker hit by a bullet.
+ horizon_client::mobs::shulker::hit_by_bullet(m);
}
}
},
@@ -2453,21 +2804,22 @@ impl Game<'_> {
.as_ref()
.map(|h| h.item.to_string())
.unwrap_or_default();
+ // Bucketable.bucketMobPickup: a water bucket scoops up a fish, a
+ // tadpole or an axolotl, with the data its bucket carries.
if item == "minecraft:water_bucket"
- && self.mobs[index].species() == Species::Axolotl
&& self.mobs[index].alive()
+ && let Some((bucket, sound)) = bucketable(self.mobs[index].species())
{
- let mut filled = ItemStack::new("minecraft:axolotl_bucket", 1);
+ let mut filled = ItemStack::new(bucket, 1);
filled.extra = Some(Box::new(horizon_client::entity_nbt::bucket_components(
&self.mobs[index],
)));
- self.audio.play(
- "minecraft:item.bucket.fill_axolotl",
- Some(self.mobs[index].center()),
- 1.0,
- 1.0,
- );
+ self.audio
+ .play(sound, Some(self.mobs[index].center()), 1.0, 1.0);
self.trigger_item("minecraft:filled_bucket", &filled);
+ // Leashable.dropLeash, then discard.
+ let id = self.mobs[index].id;
+ self.break_leash(id, true, false);
self.mobs[index].removed = true;
if self.creative {
if let Some(rest) = self.give(filled) {
@@ -2521,6 +2873,19 @@ impl Game<'_> {
}
return Ok(true);
}
+ // Creeper.mobInteract: any item in #creeper_igniters, damaged when it
+ // is damageable and used up otherwise.
+ let creeper_igniter = self
+ .res
+ .items()
+ .item_tags
+ .get("minecraft:creeper_igniters")
+ .is_some_and(|t| t.contains(&*item));
+ let damageable = self
+ .res
+ .items()
+ .get(&item)
+ .is_some_and(|i| i.max_damage > 0);
let m = &mut self.mobs[index];
if !m.alive() {
return Ok(false);
@@ -2536,6 +2901,7 @@ impl Game<'_> {
let mut handled = true;
let mut drops: Vec<(String, u32)> = Vec::new();
let is_food = m.kind.food.contains(&item);
+ let baby_turtle = species == Species::Turtle && m.is_baby();
match species {
Species::Cow | Species::Mooshroom if item == "minecraft:bucket" && !m.is_baby() => {
give = Some("minecraft:milk_bucket");
@@ -2761,10 +3127,21 @@ impl Game<'_> {
consume = true;
sound = Some("entity.iron_golem.repair");
}
- Species::Creeper if item == "minecraft:flint_and_steel" => {
+ Species::Creeper if creeper_igniter => {
m.extra.flag = true;
- sound = Some("item.flintandsteel.use");
- self.damage_held_tool();
+ // FIRECHARGE_USE for a fire charge, else FLINTANDSTEEL_USE,
+ // at the creeper's feet with a pitch from its own random.
+ let event = if item == "minecraft:fire_charge" {
+ "item.firecharge.use"
+ } else {
+ "item.flintandsteel.use"
+ };
+ eat = Some((event, 1.0, m.random.next_float() * 0.4 + 0.8));
+ if damageable {
+ self.damage_held_tool();
+ } else {
+ consume = true;
+ }
}
// Parrot.mobInteract: parrot food may tame a wild one (one time in
// ten); a parrot never takes it as Animal food (isFood is false).
@@ -2814,6 +3191,14 @@ impl Game<'_> {
if !handled {
return Ok(false);
}
+ // Turtle.ageBoundaryReached: food that finishes a baby's growth.
+ if baby_turtle && !self.mobs[index].is_baby() {
+ self.handle_mob_events(vec![MobEvent::GiftLoot {
+ mob: self.mobs[index].id,
+ table: "minecraft:gameplay/turtle_grow",
+ at: feet,
+ }])?;
+ }
self.swing_arm();
if let Some(s) = sound {
let pitch =
@@ -3173,6 +3558,30 @@ impl Game<'_> {
}
continue;
}
+ // ThrownTridentRenderer.
+ if matches!(a.kind, ProjectileKind::Trident) {
+ let Some(model) = self.trident_model.as_ref() else {
+ continue;
+ };
+ let Some(r) = atlas.sprites.get("entity/trident/trident").copied() else {
+ continue;
+ };
+ let m = glam::Mat4::from_translation(c)
+ * glam::Mat4::from_rotation_y((a.yaw - 90.0).to_radians())
+ * glam::Mat4::from_rotation_z((a.pitch + 90.0).to_radians());
+ let poses = horizon_client::mobs::anim::Poses::new(model);
+ horizon_client::mobs::render::draw(
+ model,
+ m,
+ &poses,
+ [r.u0, r.v0, r.u1, r.v1],
+ 0xFFFF_FFFF,
+ packed,
+ 0,
+ out,
+ );
+ continue;
+ }
// WindChargeRenderer.
if matches!(
a.kind,
@@ -3247,6 +3656,26 @@ impl Game<'_> {
}
}
}
+/// `Bucketable.getBucketItemStack` and `getPickupSound` of a mob that a water
+/// bucket picks up.
+fn bucketable(species: Species) -> Option<(&'static str, &'static str)> {
+ let fish = "minecraft:item.bucket.fill_fish";
+ Some(match species {
+ Species::Cod => ("minecraft:cod_bucket", fish),
+ Species::Salmon => ("minecraft:salmon_bucket", fish),
+ Species::Pufferfish => ("minecraft:pufferfish_bucket", fish),
+ Species::TropicalFish => ("minecraft:tropical_fish_bucket", fish),
+ Species::Tadpole => (
+ "minecraft:tadpole_bucket",
+ "minecraft:item.bucket.fill_tadpole",
+ ),
+ Species::Axolotl => (
+ "minecraft:axolotl_bucket",
+ "minecraft:item.bucket.fill_axolotl",
+ ),
+ _ => return None,
+ })
+}
/// Mob.getBaseExperienceReward
/// The damage type id of a Horizon damage kind.
pub(super) fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static str {
@@ -3266,6 +3695,7 @@ pub(super) fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool)
K::InFire => "minecraft:in_fire",
K::Lava => "minecraft:lava",
K::Drown => "minecraft:drown",
+ K::DryOut => "minecraft:dry_out",
K::Magic => "minecraft:magic",
K::Sting => "minecraft:sting",
K::Cactus => "minecraft:cactus",
@@ -3291,6 +3721,7 @@ fn to_loot(stack: &ItemStack) -> horizon_world::loot::LootStack {
map: false,
exploration: None,
ominous_amplifier: None,
+ stew_effects: Vec::new(),
}
}
/// A generated loot stack as a Horizon item stack.
diff --git a/crates/horizon-client/src/game/crossbow.rs b/crates/horizon-client/src/game/crossbow.rs
index 70ccba8d3..bc49c4b90 100644
--- a/crates/horizon-client/src/game/crossbow.rs
+++ b/crates/horizon-client/src/game/crossbow.rs
@@ -6,6 +6,7 @@
//! finds the ammo for bows and crossbows.
use super::{Game, shield::OFFHAND_SLOT, view_vector};
use horizon_client::{
+ enchant::EffectContext,
items::ItemStack,
mobs::Who,
projectiles::{Projectile, ProjectileKind},
@@ -152,6 +153,20 @@ impl Game<'_> {
};
let charged = std::mem::take(&mut bow.data_mut().charged);
bow.tidy();
+ let weapon = bow.clone();
+ // AbstractArrow's constructor: `getPiercingCount` of the weapon.
+ let pierce = self
+ .res
+ .stations()
+ .enchantments
+ .modify_value(
+ Some(&weapon),
+ "minecraft:projectile_piercing",
+ &EffectContext::default(),
+ &mut self.world.random,
+ 0.0,
+ )
+ .clamp(0.0, 127.0) as u8;
let count = charged.len();
// getShootingPower: a rocket among them slows every shot.
let power = if charged.iter().any(|s| &*s.item == FIREWORK_ROCKET) {
@@ -204,6 +219,7 @@ impl Game<'_> {
if let Some(a) = arrow.arrow.as_mut() {
a.set_item(ammo);
a.set_owner(Some(Who::Player));
+ a.pierce = pierce;
}
arrow.shoot(&mut self.world.random, dir.to_array(), power, 1.0);
self.creatures.projectiles.push(arrow);
diff --git a/crates/horizon-client/src/game/cushions.rs b/crates/horizon-client/src/game/cushions.rs
new file mode 100644
index 000000000..0847321d6
--- /dev/null
+++ b/crates/horizon-client/src/game/cushions.rs
@@ -0,0 +1,494 @@
+//! Cushions: `CushionItem.useOn` placement on the top face of a block,
+//! `Cushion.canBePlacedAt`/`survives`, `Cushion.interact` (sit),
+//! `BlockAttachedEntity.hurtServer` (break, dropping the matching colour),
+//! `BlockAttachedEntity.tick` and `CushionRenderer`.
+//!
+//! A cushion is a `BlockAttachedEntity`, not a block: it has no block state,
+//! only an entity whose `Pos` is the click point's height. Placement uses
+//! outline bounds, collision shapes and suffocation predicates.
+use super::{Game, Hit, view_vector};
+use horizon_client::entities::{Cushion, dye_index};
+use horizon_client::items::ItemStack;
+use horizon_client::mobs::anim::Poses;
+use horizon_core::geometry::{Aabb, Vec3};
+use winit::keyboard::KeyCode;
+
+/// `Direction.fromYRot(yaw).toYRot()`: the nearest 90 degree step.
+pub(crate) fn snap_yaw(yaw: f32) -> f32 {
+ (((f64::from(yaw) / 90.0 + 0.5).floor() as i64) & 3) as f32 * 90.0
+}
+
+fn aabb(bounds: ([f64; 3], [f64; 3])) -> Aabb {
+ Aabb::new(
+ Vec3::new(bounds.0[0], bounds.0[1], bounds.0[2]),
+ Vec3::new(bounds.1[0], bounds.1[1], bounds.1[2]),
+ )
+}
+
+fn overlaps(a: Aabb, b: Aabb) -> bool {
+ a.intersects(b)
+}
+use horizon_client::cushion::blocks_in;
+
+struct PlacementWorld<'a, 'r>(&'a Game<'r>);
+impl horizon_client::cushion::World for PlacementWorld<'_, '_> {
+ fn outline_bounds(&self, p: [i32; 3]) -> Option {
+ let boxes = self.0.outline_boxes(p);
+ let mut shape = *boxes.first()?;
+ for b in &boxes[1..] {
+ for k in 0..3 {
+ shape[k] = shape[k].min(b[k]);
+ shape[k + 3] = shape[k + 3].max(b[k + 3]);
+ }
+ }
+ Some(Aabb::new(
+ Vec3::new(shape[0], shape[1], shape[2]),
+ Vec3::new(shape[3], shape[4], shape[5]),
+ ))
+ }
+
+ fn collision_shapes(&self, bounds: Aabb) -> Vec {
+ let binding = self.0.res.collision();
+ let mut world = horizon_client::collisions::SceneCollisions {
+ world: &self.0.world,
+ binding,
+ subject: None,
+ };
+ // Include neighbour blocks whose collision shape can reach outside their cell.
+ blocks_in(bounds.inflate(Vec3::new(1.0, 1.0, 1.0)))
+ .filter_map(|p| {
+ let state = self.0.world.block(p[0], p[1], p[2]);
+ binding
+ .collision_shape(&mut world, state, p)
+ .ok()
+ .map(|s| s.moved(Vec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2]))))
+ })
+ .collect()
+ }
+ fn suffocating(&self, p: [i32; 3]) -> bool {
+ let state = self.0.world.block(p[0], p[1], p[2]);
+ let facts = self.0.res.facts().get(state);
+ let name = facts.name.as_ref();
+ // Blocks' explicit predicates, then the default causes_suffocation/full-shape rule.
+ match name {
+ "minecraft:dirt_path"
+ | "minecraft:farmland"
+ | "minecraft:mud"
+ | "minecraft:soul_sand" => true,
+ "minecraft:piston" | "minecraft:sticky_piston" => self
+ .0
+ .pack
+ .assets
+ .registry
+ .state(state)
+ .is_some_and(|s| s.properties.get("extended").is_some_and(|p| p == "false")),
+ "minecraft:mangrove_roots" | "minecraft:moving_piston" => false,
+ _ if name.ends_with("_leaves")
+ || name.ends_with("glass")
+ || name.ends_with("copper_grate") =>
+ {
+ false
+ }
+ // ShulkerBoxBlock: suffocating while closed; a box seen open
+ // here is rare enough to count as closed.
+ _ if name.ends_with("shulker_box") => true,
+ _ => {
+ facts.full_collision
+ && self
+ .0
+ .res
+ .items()
+ .block_in_tag("minecraft:causes_suffocation", name)
+ }
+ }
+ }
+}
+
+impl Game<'_> {
+ /// The cushion under the crosshair, its distance and the hit point.
+ pub(super) fn cushion_hit(&self) -> Option<(usize, f64, [f64; 3])> {
+ let eye = self.eye_position()?;
+ let dir = view_vector(self.yaw, self.pitch);
+ let reach: f64 = if self.creative { 5.0 } else { 3.0 };
+ let mut best: Option<(usize, f64, [f64; 3])> = None;
+ for (i, c) in self.cushions.iter().enumerate() {
+ let Some(d) = super::ray_box(eye, dir, reach, aabb(c.bounds())) else {
+ continue;
+ };
+ if best.is_none_or(|b| d < b.1) {
+ best = Some((i, d, std::array::from_fn(|k| eye[k] + dir[k] * d)));
+ }
+ }
+ best
+ }
+
+ pub(super) fn cushion_survives(&self, c: &Cushion) -> bool {
+ horizon_client::cushion::survives(&PlacementWorld(self), aabb(c.bounds()))
+ }
+
+ /// `Cushion.destroyIfInFire`: a fire-tagged block inside the deflated box.
+ fn cushion_in_fire(&self, c: &Cushion) -> bool {
+ let bounds = aabb(c.bounds()).next_deflated();
+ blocks_in(bounds).any(|p| {
+ let facts = self.res.facts().get(self.world.block(p[0], p[1], p[2]));
+ self.res.items().block_in_tag("minecraft:fire", &facts.name)
+ })
+ }
+
+ /// `CushionItem.useOn`: on the top face only, spawning at the click's
+ /// height above the clicked block (or the replaceable block itself).
+ pub(super) fn place_cushion(&mut self, hit: &Hit, stack: &ItemStack) -> bool {
+ let Some(info) = self.res.items().get(&stack.item).cloned() else {
+ return false;
+ };
+ let Some(default_color) = info.cushion_color.as_deref() else {
+ return false;
+ };
+ let color_override = stack
+ .data()
+ .and_then(|d| d.other("minecraft:cushion/color"))
+ .and_then(|tag| match tag {
+ horizon_world::nbt::Tag::String(s) => Some(s.to_string_lossy()),
+ _ => None,
+ });
+ let color = dye_index(color_override.as_deref().unwrap_or(default_color));
+ // CushionItem.recalculateContextForSpecialCollisionShapes: open containers
+ // (cauldrons, hoppers and composters) use the collision ray's actual height.
+ let mut adjusted = Hit {
+ pos: hit.pos,
+ face: hit.face,
+ point: hit.point,
+ };
+ let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
+ if self.res.items().block_in_tag(
+ "minecraft:cushion_uses_collision_shape",
+ &self.res.facts().get(state).name,
+ ) && let Some(eye) = self.eye_position()
+ {
+ let start = Vec3::new(eye[0], eye[1], eye[2]);
+ let point = Vec3::new(hit.point[0], hit.point[1], hit.point[2]);
+ let end = point.add_vector(point.subtract(start).normalize().scale(0.001));
+ let binding = self.res.collision();
+ let mut world = horizon_client::collisions::SceneCollisions {
+ world: &self.world,
+ binding,
+ subject: None,
+ };
+ if let Ok(shape) = binding.collision_shape(&mut world, state, hit.pos)
+ && let Some(result) = shape.clip(
+ start,
+ end,
+ horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]),
+ )
+ {
+ adjusted.face = result.direction.normal();
+ adjusted.point = [result.location.x, result.location.y, result.location.z];
+ }
+ }
+ let hit = &adjusted;
+ if hit.face != [0, 1, 0] {
+ return false;
+ }
+ // BlockPlaceContext: a replaceable clicked block is replaced.
+ let clicked = self
+ .res
+ .facts()
+ .get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]));
+ let pos = if clicked.replaceable {
+ hit.pos
+ } else {
+ std::array::from_fn(|i| hit.pos[i] + hit.face[i])
+ };
+ // `Vec3.atCenterOfWithY(clickedPos, clickLocation.y)`.
+ let y = hit.point[1];
+ let position = Vec3::new(f64::from(pos[0]) + 0.5, y, f64::from(pos[2]) + 0.5);
+ let bounds = aabb((
+ [position.x - 0.5, position.y, position.z - 0.5],
+ [position.x + 0.5, position.y + 0.25, position.z + 0.5],
+ ));
+ if !horizon_client::cushion::can_place(&PlacementWorld(self), bounds) {
+ return false;
+ }
+ // `getEntitiesOfClass(Cushion.class, spawnAABB).isEmpty()`.
+ if self
+ .cushions
+ .iter()
+ .any(|c| overlaps(aabb(c.bounds()), bounds))
+ {
+ return false;
+ }
+ self.next_entity += 1;
+ let id = self.next_entity;
+ // `BlockAttachedEntity.setPos`: `BlockPos.containing(position)`.
+ let attached = [
+ position.x.floor() as i32,
+ position.y.floor() as i32,
+ position.z.floor() as i32,
+ ];
+ self.cushions.push(Cushion {
+ id,
+ position,
+ pos: attached,
+ yaw: snap_yaw(self.yaw),
+ color,
+ check_interval: 0,
+ });
+ self.world
+ .modified
+ .insert((attached[0] >> 4, attached[2] >> 4));
+ // `destroyIfInFire`: placed into fire, it breaks at once.
+ let placed = self.cushions.len() - 1;
+ if self.cushion_in_fire(&self.cushions[placed]) {
+ self.break_cushion(placed, false);
+ }
+ self.audio.play(
+ "minecraft:entity.cushion.place",
+ Some([position.x, position.y, position.z]),
+ 0.75,
+ 0.8,
+ );
+ let ctx = self.who_context(Some(horizon_client::mobs::Who::Player), None);
+ self.post_game_event(
+ "minecraft:entity_place",
+ [position.x, position.y, position.z],
+ ctx,
+ );
+ if !self.creative {
+ self.consume_held();
+ }
+ true
+ }
+
+ /// `Cushion.interact`: sit down unless sneaking or already occupied.
+ pub(super) fn interact_cushion(&mut self) -> bool {
+ let Some((i, d, _)) = self.cushion_hit() else {
+ return false;
+ };
+ if !self.before_block(d) {
+ return false;
+ }
+ // isSecondaryUseActive.
+ if self.keys.contains(&KeyCode::ShiftLeft) {
+ return false;
+ }
+ let id = self.cushions[i].id;
+ let occupied = self.riding == Some(id)
+ || self
+ .lan
+ .as_ref()
+ .is_some_and(|h| h.hub.guests.iter().any(|g| g.vehicle == Some(id)));
+ // `Cushion.interact`: an occupied cushion (`isVehicle`) passes.
+ if occupied {
+ return false;
+ }
+ // `Player.startRiding` gives up the vehicle it already has; the
+ // client never sends that click, so pass instead.
+ if self.riding.is_some() {
+ return false;
+ }
+ self.riding = Some(id);
+ let p = self.cushions[i].position;
+ self.audio.play(
+ "minecraft:entity.cushion.sit",
+ Some([p.x, p.y, p.z]),
+ 1.0,
+ 1.0,
+ );
+ self.swing_arm();
+ true
+ }
+
+ /// `Cushion.hurtServer` from a player: killed, then the item dropped.
+ pub(super) fn attack_cushion(&mut self) -> bool {
+ let Some((i, d, _)) = self.cushion_hit() else {
+ return false;
+ };
+ if !self.before_block(d) || self.mob_hit().is_some_and(|m| m.1 < d) {
+ return false;
+ }
+ // `skipAttackInteraction` when `mayInteract` is false.
+ if !self.may_build() {
+ return true;
+ }
+ self.break_cushion(i, true);
+ true
+ }
+
+ /// `Cushion.dropItem`: the break sound and particles, then the coloured
+ /// item unless drops are off or the breaker has infinite materials.
+ pub(super) fn break_cushion(&mut self, index: usize, by_player: bool) {
+ let c = self.cushions.remove(index);
+ let p = c.position;
+ self.world.modified.insert((c.pos[0] >> 4, c.pos[2] >> 4));
+ if self.riding == Some(c.id) {
+ self.riding = None;
+ }
+ self.audio.play(
+ "minecraft:entity.cushion.break",
+ Some([p.x, p.y, p.z]),
+ 1.0,
+ 1.0,
+ );
+ self.cushion_break_particles(&c);
+ if !self.ui.rules.bool("entity_drops") || (by_player && self.creative) {
+ return;
+ }
+ let stack = ItemStack {
+ item: std::sync::Arc::from(c.item()),
+ count: 1,
+ damage: 0,
+ extra: None,
+ };
+ self.spawn_item(stack, [p.x, p.y, p.z], [0.0; 3], 10);
+ }
+
+ /// `Cushion.showBreakingParticles`: ten of the matching wool block.
+ fn cushion_break_particles(&mut self, c: &Cushion) {
+ let name = format!("minecraft:{}_wool", c.color_name());
+ let Some(state) = self.pack.assets.registry.default_state(&name) else {
+ return;
+ };
+ let at = [
+ c.position.x.floor() as i32,
+ c.position.y.floor() as i32,
+ c.position.z.floor() as i32,
+ ];
+ let Some((sprite, tint)) = self.particle_sprite(state, at) else {
+ return;
+ };
+ let options = horizon_client::particles::ParticleOptions::block(
+ horizon_client::particles::ParticleType::Block,
+ sprite,
+ tint,
+ );
+ let p = c.position;
+ self.particles.send_particles(
+ &options,
+ [p.x, p.y + 0.666_666_7, p.z],
+ [0.25, 0.0625, 0.25],
+ 0.05,
+ 10,
+ );
+ }
+
+ /// `BlockAttachedEntity.tick`: survive and burn checks after the post-increment reaches 100.
+ pub(super) fn tick_cushions(&mut self) {
+ let ticking = self.entity_ticking_area();
+ let mut i = 0;
+ while i < self.cushions.len() {
+ let p = self.cushions[i].position;
+ if !ticking(p.x.floor() as i32, p.z.floor() as i32) {
+ i += 1;
+ continue;
+ }
+ let previous = self.cushions[i].check_interval;
+ self.cushions[i].check_interval += 1;
+ if previous < 100 {
+ i += 1;
+ continue;
+ }
+ self.cushions[i].check_interval = 0;
+ let c = self.cushions[i].clone();
+ if self.cushion_in_fire(&c) || !self.cushion_survives(&c) {
+ self.break_cushion(i, false);
+ continue;
+ }
+ i += 1;
+ }
+ }
+
+ /// `Player.rideTick` on a cushion: hold the seat, and get up on sneak.
+ pub(super) fn tick_cushion_riding(&mut self, keys: super::Keys) -> bool {
+ let Some(c) = self
+ .cushions
+ .iter()
+ .find(|c| Some(c.id) == self.riding)
+ .cloned()
+ else {
+ return false;
+ };
+ if keys.shift {
+ let at = c.dismount();
+ self.riding = None;
+ if let Some(p) = self.player.as_mut() {
+ self.previous_position = p.position;
+ p.position = at;
+ p.velocity = Vec3::ZERO;
+ p.fall_distance = 0.0;
+ }
+ // `Cushion.removePassenger`: the get-up sound for a rider that
+ // left rather than one whose cushion was killed.
+ self.audio.play(
+ "minecraft:entity.cushion.get_up",
+ Some([c.position.x, c.position.y, c.position.z]),
+ 1.0,
+ 1.0,
+ );
+ return true;
+ }
+ let seat = c.seat();
+ if let Some(p) = self.player.as_mut() {
+ self.previous_position = p.position;
+ p.position = seat;
+ p.velocity = Vec3::ZERO;
+ p.fall_distance = 0.0;
+ }
+ true
+ }
+
+ /// `CushionRenderer`: the coloured model, rotated to the nearest
+ /// direction, with its bottom on the cushion's position.
+ pub(super) fn cushion_geometry(
+ &self,
+ camera: glam::DVec3,
+ out: &mut Vec,
+ ) {
+ let Some(model) = self.cushion_model.as_ref() else {
+ return;
+ };
+ let sprites = &self.gui.atlas.sprites;
+ for c in &self.cushions {
+ let entity_start = out.len();
+ let a = aabb(c.bounds());
+ let (lo, hi) = (a.min_position(), a.max_position());
+ let (lo, hi) = (
+ glam::DVec3::new(lo.x, lo.y, lo.z),
+ glam::DVec3::new(hi.x, hi.y, hi.z),
+ );
+ let range =
+ super::entity_culling::default_range(hi - lo, self.settings.entity_distance);
+ if !self.entity_in_view(camera, (lo + hi) / 2.0, range, lo, hi) {
+ continue;
+ }
+ let Some(uv) = sprites
+ .get(&format!("entity/cushion/{}_cushion", c.color_name()))
+ .map(|r| [r.u0, r.v0, r.u1, r.v1])
+ else {
+ continue;
+ };
+ let p = glam::DVec3::new(c.position.x, c.position.y, c.position.z) - camera;
+ let base = glam::Mat4::from_translation(p.as_vec3())
+ * glam::Mat4::from_rotation_y((180.0 - snap_yaw(c.yaw)).to_radians())
+ * glam::Mat4::from_rotation_x(std::f32::consts::PI)
+ * glam::Mat4::from_translation(glam::Vec3::new(0.0, -0.25, 0.0));
+ // `EntityRenderer.getPackedLightCoords` probes at the eye height.
+ let l = self.world.light(
+ c.position.x.floor() as i32,
+ (c.position.y + 0.2125).floor() as i32,
+ c.position.z.floor() as i32,
+ );
+ let packed = (u32::from(l >> 4) * 16) | ((u32::from(l & 15) * 16) << 8);
+ horizon_client::mobs::render::draw(
+ model,
+ base,
+ &Poses::new(model),
+ uv,
+ 0xFFFF_FFFF,
+ packed,
+ 0,
+ out,
+ );
+ self.cull_entity_vertices(out, entity_start);
+ }
+ }
+}
diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs
index fa5365195..49b653ae1 100644
--- a/crates/horizon-client/src/game/dedicated.rs
+++ b/crates/horizon-client/src/game/dedicated.rs
@@ -654,6 +654,9 @@ impl Game<'_> {
// DedicatedServer.initServer ends with saveEverything(false, true, true).
self.save_game()?;
self.log_saved_levels();
+ if let Some(host) = self.lan.as_mut() {
+ host.hub.entity_range_percent = props.entity_broadcast_range_percentage;
+ }
let mut state = ServerState {
lists,
console,
diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs
index 267f323c3..33da8b5ce 100644
--- a/crates/horizon-client/src/game/dispense_fixture.rs
+++ b/crates/horizon-client/src/game/dispense_fixture.rs
@@ -725,6 +725,11 @@ impl Game<'_> {
match self.world.block_entities.get_mut(&p) {
Some(BlockEntity::Jukebox(j)) => j.record = stack,
Some(BlockEntity::Lectern(l)) => l.book = stack,
+ Some(BlockEntity::Campfire(c)) => {
+ if let Some(cell) = c.items.get_mut(slot) {
+ *cell = stack;
+ }
+ }
Some(e) => {
if let Some(cell) = e.slots_mut().get_mut(slot) {
*cell = stack;
@@ -1126,14 +1131,18 @@ impl Game<'_> {
let (p, v) = (b.position, b.velocity);
out.push(line(&kind, [p.x, p.y, p.z], [v.x, v.y, v.z], ""));
}
+ // A merged orb prints once per count, as the oracle does: whether orbs
+ // merge depends on entity ids, which differ from vanilla's.
for o in &self.orbs {
let (p, v) = (o.position, o.velocity);
- out.push(line(
- "minecraft:experience_orb",
- [p.x, p.y, p.z],
- [v.x, v.y, v.z],
- "",
- ));
+ for _ in 0..o.count.max(1) {
+ out.push(line(
+ "minecraft:experience_orb",
+ [p.x, p.y, p.z],
+ [v.x, v.y, v.z],
+ "",
+ ));
+ }
}
for c in &self.carts {
let (p, v) = (c.position, c.velocity);
diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs
index 61725c6ab..f902f1c05 100644
--- a/crates/horizon-client/src/game/dispenser.rs
+++ b/crates/horizon-client/src/game/dispenser.rs
@@ -982,7 +982,7 @@ impl Game<'_> {
| "minecraft:lingering_potion" => {
let mut shot = Projectile::new(ProjectileKind::Snowball, at, None);
shot.shoot(&mut own, dir, power, uncertainty);
- self.launch_thrown(one, at, shot.velocity);
+ self.launch_thrown(one, at, shot.velocity, None);
}
"minecraft:firework_rocket" => {
let mut shot = Projectile::new(ProjectileKind::Snowball, at, None);
diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs
index c83018c82..e063b913c 100644
--- a/crates/horizon-client/src/game/dragon.rs
+++ b/crates/horizon-client/src/game/dragon.rs
@@ -12,11 +12,13 @@ use horizon_client::{
hud_layout, hud_overlays,
mesher::Vertex,
particles::{ParticleOptions, ParticleType},
+ text::Text,
};
use horizon_core::{
geometry::{Aabb, Vec3},
random::{LegacyRandom, RandomSource},
};
+use horizon_protocol::entity_data::Value;
use horizon_world::nbt::Tag;
/// Mob ids from here on are dragon parts (`SPECIAL + part`) and crystals
@@ -1558,6 +1560,7 @@ impl Game<'_> {
y -= 1.0;
}
self.breath_clouds.push(Breath {
+ id: 0,
at: [x, y.floor() + 1.0, z],
radius: 5.0,
age: 0,
@@ -1684,32 +1687,17 @@ impl Game<'_> {
.play("minecraft:entity.ender_dragon.growl", Some(at), 2.5, pitch);
}
}
- // checkCrystals: heal 1 every 10 ticks from the nearest crystal within 32.
+ // checkCrystals: heal 1 every 10 ticks from the nearest crystal, found
+ // among those touching the dragon's box grown by 32.
let d = self.dragon.as_mut().expect("dragon");
if d.nearest_crystal.is_some() && d.ticks % 10 == 0 && d.health < MAX_HEALTH {
- d.health += 1.0;
+ // LivingEntity.setHealth clamps to the maximum.
+ d.health = (d.health + 1.0).min(MAX_HEALTH);
}
if d.random.next_int_bound(10).unwrap_or(1) == 0 {
let p = d.position;
- d.nearest_crystal = self
- .crystals
- .iter()
- .enumerate()
- .filter(|(_, c)| {
- (c.position.x - p.x).abs() <= 32.0
- && (c.position.y - p.y).abs() <= 32.0
- && (c.position.z - p.z).abs() <= 32.0
- })
- .min_by(|a, b| {
- let da = (a.1.position.x - p.x).powi(2)
- + (a.1.position.y - p.y).powi(2)
- + (a.1.position.z - p.z).powi(2);
- let db = (b.1.position.x - p.x).powi(2)
- + (b.1.position.y - p.y).powi(2)
- + (b.1.position.z - p.z).powi(2);
- da.total_cmp(&db)
- })
- .map(|(i, _)| i);
+ let nearest = self.nearest_crystal_to(p);
+ self.dragon.as_mut().expect("dragon").nearest_crystal = nearest;
}
let d = self.dragon.as_mut().expect("dragon");
d.yaw = wrap(d.yaw);
@@ -1870,7 +1858,7 @@ impl Game<'_> {
pl.velocity.z += zd / dd * 4.0;
}
if !sitting {
- g.hurt_player_by("minecraft:mob_attack", 5.0);
+ g.dragon_hurts_player("minecraft:mob_attack", 5.0);
}
});
}
@@ -1879,7 +1867,7 @@ impl Game<'_> {
for h in heads {
if h.inflate(Vec3::new(1.0, 1.0, 1.0)).intersects(p.bounds) {
self.as_fight_player(p.who, |g| {
- g.hurt_player_by("minecraft:mob_attack", 10.0);
+ g.dragon_hurts_player("minecraft:mob_attack", 10.0);
});
}
}
@@ -2037,6 +2025,7 @@ impl Game<'_> {
// assignDirectionalMovement: the direction times the acceleration power 0.1.
let velocity = Vec3::new(v.x * 0.1, v.y * 0.1, v.z * 0.1);
self.dragon_fireballs.push(DragonFireball {
+ id: 0,
position: at,
previous: at,
velocity,
@@ -2083,6 +2072,7 @@ impl Game<'_> {
});
if hit_block || hit_player || b.age > 600 {
self.breath_clouds.push(Breath {
+ id: 0,
at: [next.x, next.y, next.z],
radius: 3.0,
age: 0,
@@ -2166,10 +2156,23 @@ impl Game<'_> {
self.breath_clouds.append(&mut clouds);
for (who, amount) in harmed {
self.as_fight_player(who, |g| {
- g.hurt_player_by("minecraft:indirect_magic", amount);
+ g.dragon_hurts_player("minecraft:indirect_magic", amount);
});
}
}
+ /// Damage from the dragon, which is its causing entity
+ /// (`DamageSources.mobAttack(dragon)`, `indirectMagic(cloud, dragon)`): the
+ /// death message names it, or the cloud once the dragon is gone.
+ fn dragon_hurts_player(&mut self, damage_type: &str, amount: f32) {
+ if let Some(id) = self.dragon.as_ref().map(|d| d.id) {
+ let name = Text::translate("entity.minecraft.ender_dragon", &[]);
+ self.note_named_attacker(damage_type, id, name);
+ } else if damage_type == "minecraft:indirect_magic" {
+ let name = Text::translate("entity.minecraft.area_effect_cloud", &[]);
+ self.note_direct_entity(damage_type, name);
+ }
+ self.hurt_player_by(damage_type, amount);
+ }
/// `BossHealthOverlay.extractRenderState`: whatever `publish_boss_bars`
/// (or a server's packets) put on this client's overlay.
pub(super) fn draw_boss_bars(&self, batch: &mut HudBatch) {
@@ -2207,15 +2210,58 @@ impl Game<'_> {
}
}
pub(super) struct DragonFireball {
- position: Vec3,
- previous: Vec3,
- velocity: Vec3,
+ /// Its entity id once a server's players track it (0 until then).
+ pub(super) id: u32,
+ pub(super) position: Vec3,
+ pub(super) previous: Vec3,
+ pub(super) velocity: Vec3,
age: i32,
}
+impl DragonFireball {
+ /// One a server sent (`handleAddEntity`).
+ pub(super) fn remote(id: u32, at: Vec3, velocity: Vec3) -> Self {
+ Self {
+ id,
+ position: at,
+ previous: at,
+ velocity,
+ age: 0,
+ }
+ }
+ /// `AbstractHurtingProjectile.tick` on a server's client: `applyInertia`
+ /// first (power 0.1, inertia 0.95 or 0.8 in water), then the move; only
+ /// the server decides what it hits.
+ pub(super) fn remote_step(&mut self, water: bool) {
+ self.previous = self.position;
+ self.age += 1;
+ let v = self.velocity;
+ // Vec3.normalize: a vector shorter than 1e-5 stays zero.
+ let l = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt();
+ let n = if l < 1.0e-5 {
+ Vec3::new(0.0, 0.0, 0.0)
+ } else {
+ Vec3::new(v.x / l, v.y / l, v.z / l)
+ };
+ let inertia = f64::from(if water { 0.8f32 } else { 0.95f32 });
+ let v = Vec3::new(
+ (v.x + n.x * 0.1) * inertia,
+ (v.y + n.y * 0.1) * inertia,
+ (v.z + n.z * 0.1) * inertia,
+ );
+ self.velocity = v;
+ self.position = Vec3::new(
+ self.position.x + v.x,
+ self.position.y + v.y,
+ self.position.z + v.z,
+ );
+ }
+}
pub(super) struct Breath {
- at: [f64; 3],
- radius: f32,
- age: i32,
+ /// Its entity id once a server's players track it (0 until then).
+ pub(super) id: u32,
+ pub(super) at: [f64; 3],
+ pub(super) radius: f32,
+ pub(super) age: i32,
duration: i32,
from_dragon: bool,
}
@@ -2560,7 +2606,9 @@ impl Game<'_> {
}
pub(super) fn fight_ready(&mut self) -> bool {
self.load_fight();
- self.fight.loaded
+ // spawnExitPortal runs from scanState and the dragon's death, both
+ // only with players in the fight.
+ self.fight.loaded && self.fight.players
}
pub(super) fn exit_portal(&self) -> Option<[i32; 3]> {
self.fight.exit_portal
@@ -3137,6 +3185,212 @@ impl Game<'_> {
let _ = self.activate_exit_portal();
self.fight.dirty = true;
}
+ /// `EnderDragon.checkCrystals`' search: the nearest crystal whose box
+ /// meets the dragon's box grown by 32.
+ fn nearest_crystal_to(&self, p: Vec3) -> Option {
+ // The dragon's 16 by 8 box.
+ let reach = Aabb::new(
+ Vec3::new(p.x - 8.0, p.y, p.z - 8.0),
+ Vec3::new(p.x + 8.0, p.y + 8.0, p.z + 8.0),
+ )
+ .inflate(Vec3::new(32.0, 32.0, 32.0));
+ self.crystals
+ .iter()
+ .enumerate()
+ .filter(|(_, c)| {
+ // An end crystal's 2 by 2 box.
+ reach.intersects(Aabb::new(
+ Vec3::new(c.position.x - 1.0, c.position.y, c.position.z - 1.0),
+ Vec3::new(c.position.x + 1.0, c.position.y + 2.0, c.position.z + 1.0),
+ ))
+ })
+ .min_by(|a, b| {
+ let da = (a.1.position.x - p.x).powi(2)
+ + (a.1.position.y - p.y).powi(2)
+ + (a.1.position.z - p.z).powi(2);
+ let db = (b.1.position.x - p.x).powi(2)
+ + (b.1.position.y - p.y).powi(2)
+ + (b.1.position.z - p.z).powi(2);
+ da.total_cmp(&db)
+ })
+ .map(|(i, _)| i)
+ }
+}
+
+/// The dragon on a server's client (`ClientPacketListener.handleAddEntity`
+/// and the client side of `EnderDragon.aiStep`): the server flies it and
+/// sends its moves, health and phase; the client flaps its wings, keeps
+/// its flight history and places its parts, so it can be drawn and hit.
+impl Game<'_> {
+ /// `handleAddEntity` for `minecraft:ender_dragon`. Its constructor
+ /// sets the full health and the hovering phase until the server's
+ /// synched data says otherwise.
+ pub(super) fn spawn_remote_dragon(&mut self, id: i32, position: [f64; 3], yaw: f32) {
+ let at = Vec3::new(position[0], position[1], position[2]);
+ let mut d = Dragon::new(at, yaw, i64::from(id));
+ d.id = id as u32;
+ d.phase = Phase::from_id(10);
+ self.dragon = Some(d);
+ self.place_dragon_parts();
+ if let Some(d) = self.dragon.as_mut() {
+ for part in &mut d.parts {
+ part.1 = part.0;
+ }
+ }
+ }
+ /// The remote dragon, if `id` is it.
+ fn remote_dragon_mut(&mut self, id: i32) -> Option<&mut Dragon> {
+ self.dragon.as_mut().filter(|d| d.id as i32 == id)
+ }
+ /// `handleSetEntityData`: LivingEntity.DATA_HEALTH_ID and
+ /// EnderDragon.DATA_PHASE (`onSyncedDataUpdated` sets the phase).
+ pub(super) fn remote_dragon_data(&mut self, id: i32, values: &[(u8, i32, Value)]) {
+ let Some(d) = self.remote_dragon_mut(id) else {
+ return;
+ };
+ for (index, _, value) in values {
+ match (index, value) {
+ (9, Value::Float(health)) => d.health = *health,
+ (16, Value::Int(phase)) => d.set_phase(Phase::from_id(*phase)),
+ _ => {}
+ }
+ }
+ }
+ /// `handleSetEntityMotion`: the velocity its wings flap by.
+ pub(super) fn remote_dragon_motion(&mut self, id: i32, velocity: [f64; 3]) {
+ if let Some(d) = self.remote_dragon_mut(id) {
+ d.velocity = Vec3::new(velocity[0], velocity[1], velocity[2]);
+ }
+ }
+ /// `handleHurtAnimation` and `handleDamageEvent`: the red flash.
+ pub(super) fn remote_dragon_hurt(&mut self, id: i32) {
+ if let Some(d) = self.remote_dragon_mut(id) {
+ d.hurt_time = 10;
+ }
+ }
+ /// `handleRemoveEntities`, or a crystal removed: the healing beam
+ /// keeps pointing at the same crystal.
+ pub(super) fn remove_remote_dragon(&mut self, id: i32) {
+ if self.remote_dragon_mut(id).is_some() {
+ self.dragon = None;
+ return;
+ }
+ let Some(index) = self.crystals.iter().position(|c| c.id as i32 == id) else {
+ return;
+ };
+ if let Some(d) = self.dragon.as_mut() {
+ match d.nearest_crystal {
+ Some(n) if n == index => d.nearest_crystal = None,
+ Some(n) if n > index => d.nearest_crystal = Some(n - 1),
+ _ => {}
+ }
+ }
+ }
+ /// One client tick of the dragon. `lerp`: the step toward its last
+ /// sent position and yaw (LivingEntity's interpolation), and the
+ /// steps left including this one.
+ pub(super) fn tick_remote_dragon(&mut self, lerp: Option<([f64; 3], Option, u32)>) {
+ let Some(d) = self.dragon.as_mut() else {
+ return;
+ };
+ d.previous = d.position;
+ d.previous_yaw = d.yaw;
+ d.old_flap = d.flap;
+ d.ticks += 1;
+ d.hurt_time = (d.hurt_time - 1).max(0);
+ for part in &mut d.parts {
+ part.1 = part.0;
+ }
+ if let Some((target, yaw, steps)) = lerp {
+ let n = f64::from(steps.max(1));
+ d.position = Vec3::new(
+ d.position.x + (target[0] - d.position.x) / n,
+ d.position.y + (target[1] - d.position.y) / n,
+ d.position.z + (target[2] - d.position.z) / n,
+ );
+ if let Some(yaw) = yaw {
+ d.yaw += wrap(yaw - d.yaw) / steps.max(1) as f32;
+ }
+ }
+ if !d.alive() {
+ // EnderDragon.tickDeath on a client: it rises, and bursts
+ // from tick 180 to 200; the server removes it.
+ d.death_time += 1;
+ let (t, p) = (d.death_time, d.position);
+ if (180..=200).contains(&t) {
+ let r = &mut d.random;
+ let o = [
+ f64::from((r.next_float() - 0.5) * 8.0),
+ f64::from((r.next_float() - 0.5) * 4.0),
+ f64::from((r.next_float() - 0.5) * 8.0),
+ ];
+ self.particles.add(
+ &ParticleOptions::simple(ParticleType::ExplosionEmitter),
+ [p.x + o[0], p.y + 2.0 + o[1], p.z + o[2]],
+ [0.0; 3],
+ );
+ }
+ if let Some(d) = self.dragon.as_mut() {
+ d.position.y += 0.1;
+ for part in &mut d.parts {
+ part.0.y += 0.1;
+ }
+ }
+ return;
+ }
+ // processFlappingMovement and onFlap: its wing beats, and their sound.
+ let flap_was = (d.old_flap * std::f32::consts::TAU).cos();
+ let v = d.velocity;
+ let mut flap_speed = 0.2 / ((v.x.hypot(v.z) as f32) * 10.0 + 1.0);
+ flap_speed *= 2f32.powf(v.y as f32);
+ d.flap += if d.phase.sitting() { 0.1 } else { flap_speed };
+ let flap_now = (d.flap * std::f32::consts::TAU).cos();
+ let at = [d.position.x, d.position.y, d.position.z];
+ if flap_was <= -0.3 && flap_now >= -0.3 {
+ let pitch = 0.8 + self.world.random.next_float() * 0.3;
+ self.audio
+ .play("minecraft:entity.ender_dragon.flap", Some(at), 5.0, pitch);
+ }
+ let d = self.dragon.as_mut().expect("dragon");
+ if !d.phase.sitting() {
+ d.growl -= 1;
+ if d.growl < 0 {
+ d.growl = 200 + d.random.next_int_bound(200).unwrap_or(0);
+ let pitch = 0.8 + self.world.random.next_float() * 0.3;
+ self.audio
+ .play("minecraft:entity.ender_dragon.growl", Some(at), 2.5, pitch);
+ }
+ }
+ // checkCrystals' search runs on a client too (the healing beam).
+ let d = self.dragon.as_mut().expect("dragon");
+ if d.random.next_int_bound(10).unwrap_or(1) == 0 {
+ let p = d.position;
+ let nearest = self.nearest_crystal_to(p);
+ self.dragon.as_mut().expect("dragon").nearest_crystal = nearest;
+ }
+ let d = self.dragon.as_mut().expect("dragon");
+ d.yaw = wrap(d.yaw);
+ d.record();
+ self.place_dragon_parts();
+ }
+ /// The dragon's parts as a server's client attacks them: the server's
+ /// ids for `EnderDragonPart`s follow the dragon's.
+ pub(super) fn remote_dragon_part_hit(
+ &self,
+ eye: [f64; 3],
+ dir: [f64; 3],
+ reach: f64,
+ ) -> Option<(i32, f64, [f64; 3])> {
+ let d = self.dragon.as_ref().filter(|d| d.alive() && d.id != 0)?;
+ (0..8)
+ .filter_map(|i| {
+ let b = d.part_box(i);
+ let p = d.parts[i].0;
+ super::ray_box(eye, dir, reach, b)
+ .map(|t| ((d.id + 1 + i as u32) as i32, t, [p.x, p.y, p.z]))
+ })
+ .min_by(|a, b| a.1.total_cmp(&b.1))
+ }
}
#[cfg(test)]
diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs
index aa9f75e06..b24a62520 100644
--- a/crates/horizon-client/src/game/enchant_effects.rs
+++ b/crates/horizon-client/src/game/enchant_effects.rs
@@ -3,10 +3,14 @@
//! unbreaking (`minecraft:item_damage`), sharpness/smite/bane and power
//! (`minecraft:damage`), knockback, fire aspect, infinity (`minecraft:ammo_use`),
//! thorns (`minecraft:post_attack`), mending (`minecraft:repair_with_xp`) and
-//! the armor attribute effects (respiration, depth strider, ...).
+//! the armor attribute effects (respiration, depth strider, ...) and Soul
+//! Speed's `location_changed` and `tick` effects.
use super::Game;
-use horizon_client::{enchant::EffectContext, items::ItemStack};
-use horizon_core::random::RandomSource;
+use horizon_client::{
+ enchant::{EffectContext, Enchantments, level_value},
+ items::ItemStack,
+};
+use horizon_core::{position::BlockPos, random::RandomSource};
/// Where Mending found a damaged item (`EnchantedItemInUse.inSlot`).
#[derive(Clone, Copy)]
@@ -255,23 +259,26 @@ impl Game<'_> {
let _ = self.wind_burst(feet, radius, knockback, false, false);
}
}
- /// Thorns on worn armor when a mob at `from` hits the player.
- pub(super) fn thorns(&mut self, from: [f64; 3]) {
- let attacker = self
- .mobs
- .iter()
- .enumerate()
- .filter(|(_, m)| m.alive())
- .min_by(|a, b| {
- let d = |m: &horizon_client::mobs::Mob| {
- (m.position.x - from[0]).powi(2)
- + (m.position.y - from[1]).powi(2)
- + (m.position.z - from[2]).powi(2)
- };
- d(a.1).total_cmp(&d(b.1))
- })
- .map(|(i, _)| i);
- let Some(attacker) = attacker else { return };
+ /// Thorns on worn armor when the mob `attacker` hits the player: the
+ /// `affected: attacker` effect of `Enchantment.doPostAttack` hurts the
+ /// entity that caused the hit.
+ pub(super) fn thorns(&mut self, attacker: u32) {
+ let Some(index) = self.mobs.iter().position(|m| m.id == attacker && m.alive()) else {
+ return;
+ };
+ for damage in self.thorns_damage() {
+ let m = &mut self.mobs[index];
+ m.hurt(damage, None, &mut self.world.random);
+ let center = [m.position.x, m.position.y, m.position.z];
+ self.audio
+ .play("minecraft:enchant.thorns.hit", Some(center), 1.0, 1.0);
+ }
+ }
+ /// The victim's side of thorns: for each worn piece whose chance comes up,
+ /// the damage to deal the attacker (`DamageEntity` min 1, max 5) and the
+ /// piece's wear (`ChangeItemDamage` 2).
+ pub(super) fn thorns_damage(&mut self) -> Vec {
+ let mut hits = Vec::new();
for slot in 0..4 {
let Some(stack) = self.armor[slot].clone() else {
continue;
@@ -299,15 +306,7 @@ impl Game<'_> {
if !ok {
continue;
}
- // DamageEntity(min 1, max 5) and ChangeItemDamage(2).
- let damage = 1.0 + self.world.random.next_float() * 4.0;
- let center = {
- let m = &mut self.mobs[attacker];
- m.hurt(damage, None, &mut self.world.random);
- [m.position.x, m.position.y, m.position.z]
- };
- self.audio
- .play("minecraft:enchant.thorns.hit", Some(center), 1.0, 1.0);
+ hits.push(1.0 + self.world.random.next_float() * 4.0);
if let Some(s) = self.armor[slot].as_mut() {
s.damage += 2;
if self
@@ -320,6 +319,7 @@ impl Game<'_> {
}
}
}
+ hits
}
/// `ExperienceOrb.repairPlayerItems`: returns the experience left over.
pub(super) fn mending(&mut self, amount: u32) -> u32 {
@@ -388,7 +388,9 @@ impl Game<'_> {
}
}
/// Bow enchantments at release: (extra base damage, infinity keeps the arrow).
- pub(super) fn bow_enchantments(&mut self) -> (f64, bool) {
+ /// `ammo` is the item being fired: `Enchantment.itemContext` hands it to the
+ /// `ammo_use` conditions as the tool, so Infinity only frees plain arrows.
+ pub(super) fn bow_enchantments(&mut self, ammo: &str) -> (f64, bool) {
let Some(bow) = self.inventory[self.selected].clone() else {
return (0.0, false);
};
@@ -407,7 +409,7 @@ impl Game<'_> {
0.0,
);
let ammo_ctx = EffectContext {
- tool: Some("minecraft:arrow"),
+ tool: Some(ammo),
items: Some(self.res.items()),
..Default::default()
};
@@ -460,6 +462,134 @@ impl Game<'_> {
}
ignite
}
+ /// Soul Speed (`data/minecraft/enchantment/soul_speed.json`), the parts of
+ /// `Enchantment.runLocationChangedEffects` and `tick` that file uses. The
+ /// `location_changed` effects run when the player enters a new block, lands,
+ /// or its boots change:
+ /// - the speed and movement efficiency modifiers turn on over a soul speed
+ /// block (not flying, not riding) and stay on while airborne, then off
+ /// (`enchantment_active_check`);
+ /// - the boots lose 1 durability with a 4% chance when on such a block.
+ ///
+ /// Every fifth tick the player walking on one also gets a soul particle
+ /// (returned as its position and velocity, for the caller to show or send
+ /// to the players around) and sometimes a sound. Runs for the window's own
+ /// player and for each guest on the server (`guest_server_tick`); a remote
+ /// client leaves it to its server.
+ pub(super) fn tick_soul_speed(&mut self) -> Option<([f64; 3], [f64; 3])> {
+ const ID: &str = "minecraft:soul_speed";
+ let player = self.player.as_mut()?;
+ if player.client_side {
+ return None;
+ }
+ let level = self.armor[3]
+ .as_ref()
+ .map_or(0, |s| s.enchantment_level(ID));
+ let position = player.position;
+ let (on_ground, flying) = (player.ground.on_ground, player.flying);
+ let moved = position.subtract(player.old_position);
+ let (tick, width) = (player.health.tick_count, player.dimensions.width);
+ let fx = &mut player.location_effects;
+ let on_soul = fx.on_soul_speed_block;
+ let block = BlockPos::containing(position);
+ let changed_block = fx.block.replace(block) != Some(block);
+ let landed = std::mem::take(&mut fx.landed);
+ // Changed boots: `stopLocationBasedEffects`, then the effects run again.
+ let equipped = std::mem::replace(&mut fx.boots_level, level) != level;
+ let was_active = fx.applied_level;
+ let mut active = was_active > 0 && !equipped;
+ let mut wear = false;
+ if level > 0 && (changed_block || landed || equipped) {
+ let riding = self.riding.is_some();
+ let wanted = !riding && !flying && (on_soul || (active && !on_ground));
+ active = wanted;
+ // `random_chance` is the first term of the wear's `all_of`: it
+ // draws from the level random before the block is looked at.
+ let roll = self.world.random.next_float() < 0.04;
+ wear = roll && on_ground && on_soul;
+ }
+ fx.applied_level = if active { level } else { 0 };
+ // `Entity.getKnownMovement` horizontal speed of at least 1.0E-5.
+ let walking = moved.x * moved.x + moved.z * moved.z >= 1.0e-10;
+ let tick_effects = level > 0 && !flying && on_ground && walking && on_soul && tick % 5 == 0;
+ // The attribute effects were applied to the player before: swap them.
+ if was_active > 0 && (!active || equipped) {
+ for (attribute, id, _, op) in
+ soul_speed_modifiers(&self.res.stations().enchantments, was_active)
+ {
+ let _ = player.set_modifier(&attribute, &id, 0.0, &op, false);
+ }
+ }
+ if active && (was_active == 0 || equipped) {
+ for (attribute, id, amount, op) in
+ soul_speed_modifiers(&self.res.stations().enchantments, level)
+ {
+ let _ = player.set_modifier(&attribute, &id, amount, &op, true);
+ }
+ }
+ if wear && !self.creative {
+ self.wear_boots(1);
+ }
+ if level == 0 {
+ return None;
+ }
+ let r = &mut self.world.random;
+ // `spawn_particles`: in the bounding box, 0.1 above the feet, thrown
+ // back against the movement (-0.2) and up (0.1).
+ let particle = tick_effects.then(|| {
+ let x = position.x + (r.next_double() - 0.5) * f64::from(width);
+ let z = position.z + (r.next_double() - 0.5) * f64::from(width);
+ (
+ [x, position.y + 0.1, z],
+ [moved.x * -0.2, 0.1, moved.z * -0.2],
+ )
+ });
+ // `play_sound`: its `random_chance` (35%) comes first in its `all_of`,
+ // so the level random is drawn every tick the boots are worn; volume
+ // 0.6, pitch 0.6 to 1.0.
+ if r.next_float() < 0.35 && tick_effects {
+ let pitch = r.next_float() * 0.4 + 0.6;
+ self.audio.play(
+ "minecraft:particle.soul_escape",
+ Some([position.x, position.y, position.z]),
+ 0.6,
+ pitch,
+ );
+ }
+ particle
+ }
+ /// `ItemStack.hurtAndBreak` on the worn boots (`change_item_damage`):
+ /// Unbreaking applies, and they break when worn out.
+ fn wear_boots(&mut self, amount: u32) {
+ let Some(stack) = self.armor[3].clone() else {
+ return;
+ };
+ let loss = self.durability_loss(&stack, amount);
+ let max = self
+ .res
+ .items()
+ .get(&stack.item)
+ .map_or(0, |info| info.max_damage);
+ if max == 0 {
+ return;
+ }
+ let Some(boots) = self.armor[3].as_mut() else {
+ return;
+ };
+ boots.damage += loss;
+ if boots.damage >= max {
+ self.armor[3] = None;
+ if let Some(eye) = self.eye_position() {
+ self.audio.play(
+ "minecraft:entity.item.break",
+ Some(eye),
+ 0.8,
+ 0.8 + self.world.random.next_float() * 0.4,
+ );
+ }
+ self.apply_equipment();
+ }
+ }
/// Enchantment attribute modifiers of worn armor (respiration, depth strider...).
/// Each piece's modifier id ends with its slot (`EnchantmentAttributeEffect.idForSlot`),
/// so the same enchantment on two pieces stacks instead of replacing itself.
@@ -483,3 +613,28 @@ impl Game<'_> {
self.potions.enchant_modifiers = wanted;
}
}
+
+/// Soul Speed's `attribute` effects at `level` (attribute, id, amount, operation),
+/// the id taking the boots slot like `EnchantmentAttributeEffect.idForSlot`.
+fn soul_speed_modifiers(
+ enchantments: &Enchantments,
+ level: u32,
+) -> Vec<(String, String, f64, String)> {
+ let Some(e) = enchantments.get("minecraft:soul_speed") else {
+ return Vec::new();
+ };
+ e.effects["minecraft:location_changed"][0]["effect"]["effects"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter(|a| a["type"] == "minecraft:attribute")
+ .map(|a| {
+ (
+ a["attribute"].as_str().unwrap_or("").to_owned(),
+ format!("{}/feet", a["id"].as_str().unwrap_or("")),
+ f64::from(level_value(&a["amount"], level)),
+ a["operation"].as_str().unwrap_or("add_value").to_owned(),
+ )
+ })
+ .collect()
+}
diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs
index 904c035c5..32d5113b0 100644
--- a/crates/horizon-client/src/game/end.rs
+++ b/crates/horizon-client/src/game/end.rs
@@ -129,15 +129,32 @@ impl EndState {
survive: false,
});
}
- /// One tick of a server's client: `step` moves each toward where the
- /// server put it.
- pub(super) fn step_remote_eyes(&mut self, mut step: impl FnMut(u32, [f64; 3]) -> [f64; 3]) {
+ /// `EyeOfEnder.tick` on a server's client: it moves by its last known
+ /// motion; only the server steers it.
+ pub(super) fn step_remote_eyes(&mut self) {
for e in &mut self.eyes {
e.previous = e.position;
e.life += 1;
- e.position = glam::DVec3::from_array(step(e.id, e.position.to_array()));
+ e.position += e.velocity;
}
}
+ /// A server's move: an eye has no interpolation handler, so
+ /// `moveOrInterpolateTo` puts it there at once. False when `id` isn't one.
+ pub(super) fn move_remote_eye(&mut self, id: u32, at: [f64; 3]) -> bool {
+ let Some(e) = self.eyes.iter_mut().find(|e| e.id == id) else {
+ return false;
+ };
+ e.position = glam::DVec3::from_array(at);
+ true
+ }
+ /// `handleSetEntityMotion` for an eye. False when `id` isn't one.
+ pub(super) fn remote_eye_motion(&mut self, id: u32, velocity: [f64; 3]) -> bool {
+ let Some(e) = self.eyes.iter_mut().find(|e| e.id == id) else {
+ return false;
+ };
+ e.velocity = glam::DVec3::from_array(velocity);
+ true
+ }
pub(super) fn remove_remote_eye(&mut self, id: u32) {
self.eyes.retain(|e| e.id != id);
}
@@ -1099,6 +1116,7 @@ impl Game<'_> {
/// EyeOfEnder.tick: fly, then drop (4 in 5) or shatter after 80 ticks.
fn tick_eyes(&mut self) {
let mut eyes = std::mem::take(&mut self.end.eyes);
+ let mut shattered = Vec::new();
eyes.retain_mut(|eye| {
eye.previous = eye.position;
let next = eye.position + eye.velocity;
@@ -1122,10 +1140,44 @@ impl Game<'_> {
extra: None,
};
self.spawn_item(stack, at, [vx, 0.2, vz], 0);
+ } else {
+ shattered.push(at.map(|v| v.floor() as i32));
}
false
});
self.end.eyes = eyes;
+ for pos in shattered {
+ self.level_event_at(2003, pos, 0);
+ }
+ }
+
+ /// `LevelEventHandler` 2003: a shattered eye's item crumbs and two rings
+ /// of portal particles drawn in towards it.
+ pub(super) fn eye_break_particles(&mut self, pos: [i32; 3]) {
+ let (x, y, z) = (
+ f64::from(pos[0]) + 0.5,
+ f64::from(pos[1]),
+ f64::from(pos[2]) + 0.5,
+ );
+ let crumbs = self.item_particle(&ItemStack::new("minecraft:ender_eye", 1));
+ for _ in 0..8 {
+ let r = self.particles.random();
+ let v = [
+ r.next_gaussian() * 0.15,
+ r.next_double() * 0.2,
+ r.next_gaussian() * 0.15,
+ ];
+ self.particles.add(&crumbs, [x, y, z], v);
+ }
+ let portal = ParticleOptions::simple(ParticleType::Portal);
+ let mut angle = 0.0f64;
+ while angle < std::f64::consts::PI * 2.0 {
+ let (c, s) = (angle.cos(), angle.sin());
+ let at = [x + c * 5.0, y - 0.4, z + s * 5.0];
+ self.particles.add(&portal, at, [c * -5.0, 0.0, s * -5.0]);
+ self.particles.add(&portal, at, [c * -7.0, 0.0, s * -7.0]);
+ angle += std::f64::consts::PI / 20.0;
+ }
}
/// `EyeOfEnder.tick` on a client: behind each eye (a quarter of its last
diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs
index 6ecba3a54..b2191aa9f 100644
--- a/crates/horizon-client/src/game/explosion.rs
+++ b/crates/horizon-client/src/game/explosion.rs
@@ -296,12 +296,14 @@ impl Game<'_> {
if !creative
&& !spectator
&& hurtable
- && let Ok(o) = p.hurt_blocking(
+ && let Ok(o) = p.hurt_caused_by(
&self.motion.health,
self.world.health_rules,
id,
amount,
blocking,
+ // The exploding mob is the causing entity.
+ exploding.is_some(),
)
{
outcome = o;
@@ -314,9 +316,6 @@ impl Game<'_> {
);
}
}
- if outcome.hurt && !creative {
- self.hurt_armor(amount);
- }
if raised {
self.after_block(outcome, amount, None, false);
}
@@ -391,9 +390,11 @@ impl Game<'_> {
[feet[0] - w, feet[1], feet[2] - w],
[feet[0] + w, feet[1] + h, feet[2] + w],
);
+ // The exploding mob is the damage source's entity, so victims
+ // it kills drop its charged-creeper loot (`Creeper.killedEntity`).
let source = horizon_client::mobs::Damage {
kind: horizon_client::mobs::DamageKind::Explosion,
- attacker: None,
+ attacker: exploding.map(horizon_client::mobs::Who::Mob),
from: Some(center),
};
if hurtable && !m.damage(damage(dist, exposure), source) {
@@ -571,16 +572,16 @@ impl Game<'_> {
let pitch = (1.0 + (client_float() - client_float()) * 0.2) * 0.7;
self.audio
.play("minecraft:entity.generic.explode", Some(center), 4.0, pitch);
- let block_count = if interaction == BlockInteraction::Keep {
- 0
- } else {
- targets.len()
- };
+ // ServerLevel.explode sends toBlow.size() whatever the interaction, and
+ // `ServerExplosion.isSmall` also covers an explosion that keeps blocks.
+ let block_count = targets.len();
+ let small = radius < 2.0 || interaction == BlockInteraction::Keep;
let (world, facts) = (&self.world, self.res.facts());
- self.particles.explosion(center, radius, block_count, &|b| {
- facts.is_air(world.block(b[0], b[1], b[2]))
- });
- self.lan_explode(center, radius, block_count);
+ self.particles
+ .explosion(center, small, block_count, radius, &|b| {
+ facts.is_air(world.block(b[0], b[1], b[2]))
+ });
+ self.lan_explode(center, small, radius, block_count);
Ok(())
}
/// `BlockBehaviour.onExplosionHit` (TNT: `wasExploded` primes a short fuse).
@@ -597,6 +598,11 @@ impl Game<'_> {
}
let name = self.res.facts().get(state).name.clone();
let is_tnt = &*name == "minecraft:tnt";
+ // CreakingHeartBlock.onExplosionHit: its creaking dies (no
+ // experience, as Horizon does not track a TNT's owner).
+ if &*name == "minecraft:creaking_heart" {
+ self.creaking_heart_broken(pos, false);
+ }
// Block.onExplosionHit: the drops copy from the block entity, which
// then spills its contents as the block turns to air.
let key = (pos[0], pos[1], pos[2]);
@@ -620,6 +626,7 @@ impl Game<'_> {
&mut self.world.random,
Some((&mut self.rand_sequences, self.level.seed)),
decay,
+ false,
);
for mut stack in drops {
if &*stack.item == "minecraft:air" || stack.count == 0 {
diff --git a/crates/horizon-client/src/game/falling_damage.rs b/crates/horizon-client/src/game/falling_damage.rs
index 8eec28d1d..41c714561 100644
--- a/crates/horizon-client/src/game/falling_damage.rs
+++ b/crates/horizon-client/src/game/falling_damage.rs
@@ -64,6 +64,25 @@ impl Game<'_> {
pos: BlockPos::new(pos[0], pos[1], pos[2]),
data: 0,
});
+ } else if self
+ .res
+ .facts()
+ .get(block.state)
+ .name
+ .starts_with("minecraft:suspicious_")
+ {
+ // BrushableBlock.onBrokenAfterFall.
+ let at = BlockPos::new(pos[0], pos[1], pos[2]);
+ self.level_events.push(LevelEvent::LevelEvent {
+ id: 2001,
+ pos: at,
+ data: block.state.0 as i32,
+ });
+ self.level_events.push(LevelEvent::GameEvent {
+ pos: at,
+ event: "minecraft:block_destroy",
+ state: None,
+ });
}
return;
}
@@ -108,16 +127,10 @@ impl Game<'_> {
} else {
amount
};
- let hurt = if let Some(p) = self.player.as_mut()
+ if let Some(p) = self.player.as_mut()
&& let Some(id) = self.motion.health.damage.id(kind)
{
- p.hurt(&self.motion.health, self.world.health_rules, id, amount)
- .unwrap_or(false)
- } else {
- false
- };
- if hurt {
- self.hurt_armor(amount);
+ let _ = p.hurt(&self.motion.health, self.world.health_rules, id, amount);
}
}
}
diff --git a/crates/horizon-client/src/game/fangs.rs b/crates/horizon-client/src/game/fangs.rs
index cdf2d17a5..6c20ccf93 100644
--- a/crates/horizon-client/src/game/fangs.rs
+++ b/crates/horizon-client/src/game/fangs.rs
@@ -7,12 +7,13 @@ use std::sync::Arc;
#[derive(Clone, Debug)]
pub(super) struct Fangs {
- pos: [f64; 3],
- yaw: f32,
+ pub id: u32,
+ pub pos: [f64; 3],
+ pub yaw: f32,
warmup: i32,
- life: i32,
+ pub life: i32,
owner: u32,
- started: bool,
+ pub started: bool,
}
#[derive(Default)]
pub(super) struct FangState {
@@ -21,6 +22,11 @@ pub(super) struct FangState {
}
impl Game<'_> {
pub(super) fn add_fangs(&mut self, at: [f64; 3], yaw: f32, delay: i32, owner: u32) {
+ self.next_entity += 1;
+ self.insert_fangs(self.next_entity, at, yaw, delay, owner);
+ }
+
+ pub(super) fn insert_fangs(&mut self, id: u32, at: [f64; 3], yaw: f32, delay: i32, owner: u32) {
if self.fangs.model.is_none() {
self.fangs.model = horizon_client::mobs::load_model(
&self.options.resources,
@@ -29,6 +35,7 @@ impl Game<'_> {
.map(Arc::new);
}
self.fangs.list.push(Fangs {
+ id,
pos: at,
yaw,
warmup: delay,
@@ -37,6 +44,30 @@ impl Game<'_> {
started: false,
});
}
+ /// `EvokerFangs.handleEntityEvent`: only event 4 starts a client attack.
+ pub(super) fn remote_fangs_event(&mut self, id: u32, event: i8) {
+ if event == 4
+ && let Some(f) = self.fangs.list.iter_mut().find(|f| f.id == id)
+ {
+ f.started = true;
+ self.audio.play_unshared(
+ "minecraft:entity.evoker_fangs.attack",
+ Some(f.pos),
+ 1.0,
+ 1.0,
+ );
+ }
+ }
+
+ /// `EvokerFangs.tick`: clients only advance animation, never damage or discard.
+ pub(super) fn tick_remote_fangs(&mut self) {
+ for f in &mut self.fangs.list {
+ if f.started {
+ f.life -= 1;
+ }
+ }
+ }
+
/// `EvokerFangs.tick`.
pub(super) fn tick_fangs(&mut self) {
let mut list = std::mem::take(&mut self.fangs.list);
@@ -50,7 +81,8 @@ impl Game<'_> {
}
if !f.started {
f.started = true;
- self.audio.play(
+ self.lan_entity_event(f.id as i32, 4, f.pos);
+ self.audio.play_unshared(
"minecraft:entity.evoker_fangs.attack",
Some(f.pos),
1.0,
@@ -71,26 +103,49 @@ impl Game<'_> {
let b = horizon_core::geometry::Aabb::new(lo, hi);
// Every player in the box, the server's players too.
let pos = f.pos;
+ // `EvokerFangs.dealDamageTo`: indirectMagic(fangs, owner) while the
+ // owner lives, plain magic (nobody to name) once it is gone.
+ let owner = self
+ .mobs
+ .iter()
+ .any(|m| m.id == f.owner && m.alive())
+ .then_some(f.owner);
let bite = move |g: &mut Self| {
if let Some(p) = g.player_view()
&& p.alive
&& p.bounds.intersects(b)
{
- g.mob_hits_player_kind(6.0, pos, "minecraft:indirect_magic");
+ let kind = match owner {
+ Some(_) => "minecraft:indirect_magic",
+ None => "minecraft:magic",
+ };
+ g.mob_hits_player_caused(6.0, pos, kind, owner);
}
};
bite(self);
self.each_guest_hit(bite);
+ // `AbstractIllager.considersEntityAsAlly`: with no teams, the illager
+ // tag is allied; `Evoker.considersEntityAsAlly` adds a vex whose
+ // owner is allied (itself or another illager). Teams are not modelled.
+ let illager = |s: Species| {
+ matches!(
+ s,
+ Species::Evoker | Species::Illusioner | Species::Pillager | Species::Vindicator
+ )
+ };
+ let illagers: Vec = self
+ .mobs
+ .iter()
+ .filter(|m| illager(m.species()))
+ .map(|m| m.id)
+ .collect();
+ // A missing owner hurts everyone (`currentOwner == null`).
+ let owner_known = illagers.contains(&f.owner);
for m in &mut self.mobs {
- let ally = matches!(
- m.species(),
- Species::Evoker
- | Species::Illusioner
- | Species::Vex
- | Species::Pillager
- | Species::Vindicator
- | Species::Witch
- );
+ let ally = owner_known
+ && (illager(m.species())
+ || m.species() == Species::Vex
+ && illagers.contains(&(m.extra.counter2 as u32)));
if m.id != f.owner && !ally && m.alive() && m.bounds().intersects(b) {
m.damage(
6.0,
diff --git a/crates/horizon-client/src/game/fireworks.rs b/crates/horizon-client/src/game/fireworks.rs
index e6b4eb136..38fd74ed8 100644
--- a/crates/horizon-client/src/game/fireworks.rs
+++ b/crates/horizon-client/src/game/fireworks.rs
@@ -17,6 +17,8 @@ use horizon_core::{
random::RandomSource,
};
+pub(super) const FIREWORK_EXPLODE_EVENT: i8 = 17;
+
pub(super) struct Rocket {
/// The entity id a server tracks it by (0 until it is tracked).
pub id: u32,
@@ -261,6 +263,14 @@ impl Game<'_> {
/// `FireworkRocketEntity.explode` and `dealExplosionDamage`.
fn explode_rocket(&mut self, r: &Rocket) {
let at = [r.position.x, r.position.y, r.position.z];
+ // FireworkRocketEntity.explode broadcasts before discard. Send now:
+ // tick_lan removes missing tracked entities before flushing effects.
+ if r.id != 0
+ && let Some(host) = &self.lan
+ {
+ host.hub
+ .entity_event(r.id as i32, FIREWORK_EXPLODE_EVENT, at);
+ }
if !r.explosions.is_empty() {
let damage = 5.0 + r.explosions.len() as f32 * 2.0;
let from = r.position;
@@ -322,6 +332,16 @@ impl Game<'_> {
self.particles
.fireworks(at, v, r.explosions.clone(), camera);
}
+ /// FireworkRocketEntity.handleEntityEvent: use the synchronized item data.
+ pub(super) fn remote_firework_explosion(&mut self, id: i32) {
+ let camera = self.eye_position();
+ if let Some(r) = self.rockets.iter().find(|r| r.id == id as u32) {
+ let at = [r.position.x, r.position.y, r.position.z];
+ let v = [r.velocity.x, r.velocity.y, r.velocity.z];
+ self.particles
+ .fireworks(at, v, r.explosions.clone(), camera.unwrap_or(at));
+ }
+ }
/// `dealExplosionDamage` on a player that is not the rocket's
/// `attachedToEntity`: within 5 blocks, when the rocket sees its feet or
/// its middle (`ClipContext.Block.COLLIDER`, no fluids).
@@ -352,17 +372,11 @@ impl Game<'_> {
if self.creative || self.spectator() {
return;
}
- let hurt = if let Some(p) = self.player.as_mut()
+ if let Some(p) = self.player.as_mut()
&& !p.health.dead_or_dying()
&& let Some(id) = self.motion.health.damage.id("minecraft:fireworks")
{
- p.hurt(&self.motion.health, self.world.health_rules, id, amount)
- .unwrap_or(false)
- } else {
- false
- };
- if hurt {
- self.hurt_armor(amount);
+ let _ = p.hurt(&self.motion.health, self.world.health_rules, id, amount);
}
}
/// `FireworkEntityRenderer.submit`: the item (GROUND) facing the camera,
diff --git a/crates/horizon-client/src/game/fishing.rs b/crates/horizon-client/src/game/fishing.rs
index d454df406..39f9e5ffe 100644
--- a/crates/horizon-client/src/game/fishing.rs
+++ b/crates/horizon-client/src/game/fishing.rs
@@ -154,37 +154,54 @@ impl Game<'_> {
let mut damage = 0;
if let State::Hooked(id) = hook.state {
// pullEntity: 0.1 of the way to the owner.
+ let d = Vec3::new(
+ owner.x - hook.position.x,
+ owner.y - hook.position.y,
+ owner.z - hook.position.z,
+ );
+ let pulled = |v: Vec3| Vec3::new(v.x + d.x * 0.1, v.y + d.y * 0.1, v.z + d.z * 0.1);
+ let mut hooked_item = false;
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
- let d = Vec3::new(
- owner.x - hook.position.x,
- owner.y - hook.position.y,
- owner.z - hook.position.z,
- );
- m.velocity = Vec3::new(
- m.velocity.x + d.x * 0.1,
- m.velocity.y + d.y * 0.1,
- m.velocity.z + d.z * 0.1,
- );
+ m.velocity = pulled(m.velocity);
+ } else if let Some(item) = self.dropped.iter_mut().find(|i| i.id == id) {
+ item.velocity = pulled(item.velocity);
+ hooked_item = true;
}
- damage = 5;
+ // `hookedIn instanceof ItemEntity ? 3 : 5`.
+ damage = if hooked_item { 3 } else { 5 };
} else if hook.nibble > 0 {
let biome = self.biome_name_at(hook.position);
let Some(loot) = horizon_client::structure_blocks::loot_data(&self.options.resources)
else {
return damage;
};
+ // `withLuck(this.luck + owner.getLuck())`: the rod's Luck of the Sea
+ // plus the owner's luck attribute (the Luck and Bad Luck effects).
+ let owner_luck = self
+ .player
+ .as_mut()
+ .and_then(|p| p.attribute("minecraft:luck").ok())
+ .unwrap_or(0.0) as f32;
let mut random = self.world.random.clone();
let items = loot.roll(
"minecraft:gameplay/fishing",
&mut random,
- hook.luck as f32,
+ hook.luck as f32 + owner_luck,
biome.as_deref(),
Some(hook.open_water),
);
self.world.random = random;
- // FishingHook.retrieve: fish_caught for a catch.
- self.stats.custom("fish_caught", 1);
for stack in items {
+ // FishingHook.retrieve: fish_caught for each catch in #minecraft:fishes.
+ if self
+ .res
+ .items()
+ .item_tags
+ .get("minecraft:fishes")
+ .is_some_and(|t| t.contains(stack.item.as_str()))
+ {
+ self.stats.custom("fish_caught", 1);
+ }
let mut item = ItemStack {
item: Arc::from(stack.item.as_str()),
count: stack.count.max(1) as u32,
@@ -231,7 +248,7 @@ impl Game<'_> {
}
damage
}
- fn biome_name_at(&self, p: Vec3) -> Option {
+ pub(super) fn biome_name_at(&self, p: Vec3) -> Option {
let (x, y, z) = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32);
let c = self.world.chunks.get(&(x >> 4, z >> 4))?;
Some(
@@ -457,35 +474,47 @@ impl Game<'_> {
self.hook = Some(h);
return;
}
- // checkCollision: hook the first living mob it touches.
+ // checkCollision: hook the first living mob it touches, or (via
+ // `canHitEntity`) a dropped item.
let bb = bounds(h.position);
let (lo, hi) = (bb.min_position(), bb.max_position());
- if let Some(m) = self.mobs.iter().find(|m| {
- let mb = m.bounds();
- let (a, z) = (mb.min_position(), mb.max_position());
- m.alive()
- && a.x < hi.x
- && lo.x < z.x
- && a.y < hi.y
- && lo.y < z.y
- && a.z < hi.z
- && lo.z < z.z
- }) {
- h.state = State::Hooked(m.id);
+ let touches = |b: Aabb| {
+ let (a, z) = (b.min_position(), b.max_position());
+ a.x < hi.x && lo.x < z.x && a.y < hi.y && lo.y < z.y && a.z < hi.z && lo.z < z.z
+ };
+ let hit = self
+ .mobs
+ .iter()
+ .find(|m| m.alive() && touches(m.bounds()))
+ .map(|m| m.id)
+ .or_else(|| {
+ self.dropped
+ .iter()
+ .find(|i| touches(i.bounds()))
+ .map(|i| i.id)
+ });
+ if let Some(id) = hit {
+ h.state = State::Hooked(id);
h.velocity = Vec3::ZERO;
self.hook = Some(h);
return;
}
}
State::Hooked(id) => {
- match self.mobs.iter().find(|m| m.id == id && m.alive()) {
- Some(m) => {
- h.position = Vec3::new(
- m.position.x,
- m.position.y + f64::from(m.height()) * 0.8,
- m.position.z,
- )
- }
+ // updateHookedEntity: ride the hooked mob or item at 0.8 of its height.
+ let hooked = self
+ .mobs
+ .iter()
+ .find(|m| m.id == id && m.alive())
+ .map(|m| (m.position, f64::from(m.height())))
+ .or_else(|| {
+ self.dropped
+ .iter()
+ .find(|i| i.id == id)
+ .map(|i| (i.position, horizon_client::entities::ItemEntity::WIDTH))
+ });
+ match hooked {
+ Some((at, height)) => h.position = Vec3::new(at.x, at.y + height * 0.8, at.z),
None => h.state = State::Flying,
}
self.hook = Some(h);
diff --git a/crates/horizon-client/src/game/frames.rs b/crates/horizon-client/src/game/frames.rs
index 7f5e6c26a..d08c5f283 100644
--- a/crates/horizon-client/src/game/frames.rs
+++ b/crates/horizon-client/src/game/frames.rs
@@ -355,12 +355,23 @@ impl Game<'_> {
* glam::DMat4::from_rotation_y(y_rot.to_radians());
let light = self.world.light(f.pos[0], f.pos[1], f.pos[2]);
let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8);
+ // ItemFrameRenderer.getBlockLightLevel: a glow frame's model is at least 5 bright.
+ let frame_light = if f.glow {
+ (light & 0xF0) | (light & 15).max(5)
+ } else {
+ light
+ };
+ let frame_packed =
+ (u32::from(frame_light >> 4) * 16) | ((u32::from(frame_light & 15) * 16) << 8);
let mut quad =
|m: &glam::DMat4, corners: [[f64; 3]; 4], uv: [[f32; 2]; 4], light: u32| {
- for (c, uv) in corners.iter().zip(uv) {
- let p = m.transform_point3(glam::DVec3::from_array(*c));
+ // The frame model is drawn with the entity shader, lit by its face normal.
+ let at = corners.map(|c| m.transform_point3(glam::DVec3::from_array(c)));
+ let n = (at[1] - at[0]).cross(at[2] - at[0]).normalize_or_zero();
+ let normal = [0, 1, 2].map(|k| (n[k].clamp(-1.0, 1.0) * 127.0) as i8);
+ for (p, uv) in at.into_iter().zip(uv) {
out.push(Vertex {
- normal: [0; 4],
+ normal: [normal[0], normal[1], normal[2], -127],
pos: p.as_vec3().to_array(),
uv,
layer: 0,
@@ -393,7 +404,7 @@ impl Game<'_> {
]
}),
map_uv(r, *uv),
- packed,
+ frame_packed,
);
}
}
diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs
index a7218ff3c..d91d3b979 100644
--- a/crates/horizon-client/src/game/hand.rs
+++ b/crates/horizon-client/src/game/hand.rs
@@ -151,6 +151,7 @@ impl Game<'_> {
before(self.painting_hit().map(|h| h.1))
|| before(self.frame_hit().map(|h| h.1))
|| before(self.armor_stand_hit().map(|h| h.1))
+ || before(self.cushion_hit().map(|h| h.1))
|| before(self.boat_hit().map(|h| h.1))
|| before(self.cart_hit().map(|h| h.1))
|| before(self.dragon_hit().map(|h| h.1))
diff --git a/crates/horizon-client/src/game/initial_spawn.rs b/crates/horizon-client/src/game/initial_spawn.rs
index 3f7a071bb..c1149b26a 100644
--- a/crates/horizon-client/src/game/initial_spawn.rs
+++ b/crates/horizon-client/src/game/initial_spawn.rs
@@ -20,7 +20,8 @@ use horizon_core::{
};
use horizon_world::{
block_collision::BlockCollisionRegistry, collision_context::CollisionContext,
- heightmap::HeightmapType, worldgen::terrain::TerrainBlockStates,
+ heightmap::HeightmapType, level::flags::UPDATE_CLIENTS, registry::BlockStateId,
+ worldgen::terrain::TerrainBlockStates,
};
/// The loaded world as the spawn searches query it.
@@ -121,33 +122,102 @@ impl Game<'_> {
}
Ok(Some([ox * 16 + 8, height, oz * 16 + 8]))
}
+ /// MinecraftServer.setInitialSpawn's bonus chest: BonusChestFeature.place
+ /// in the spawn chunk, a chest with the spawn bonus loot and a torch on
+ /// each side that can hold one, on the first free column of a shuffled
+ /// walk over the chunk. Skipped while the chunk is not loaded.
+ pub(super) fn place_bonus_chest(&mut self, origin: [i32; 3]) -> Result<()> {
+ use horizon_client::containers::BlockEntity;
+ let (cx, cz) = (origin[0] >> 4, origin[2] >> 4);
+ let registry = &self.pack.assets.registry;
+ let (Some(chest), Some(torch)) = (
+ registry.default_state("minecraft:chest"),
+ registry.default_state("minecraft:torch"),
+ ) else {
+ return Ok(());
+ };
+ if !self.streaming.is_lit(cx, cz) {
+ return Ok(());
+ }
+ // `level.getRandom()`. Util.toShuffledList of the chunk's x and z.
+ let random = &mut self.world.random;
+ let mut shuffled = |min: i32| -> [i32; 16] {
+ let mut values: [i32; 16] = std::array::from_fn(|i| min + i as i32);
+ for end in (2..=16usize).rev() {
+ let other = random.next_int_bound(end as i32).unwrap_or(0) as usize;
+ values.swap(end - 1, other);
+ }
+ values
+ };
+ let (xs, zs) = (shuffled(cx * 16), shuffled(cz * 16));
+ for x in xs {
+ for z in zs {
+ let y = self
+ .spawn_columns()
+ .height(HeightmapType::MotionBlockingNoLeaves, x, z);
+ if self.world.block(x, y, z) != self.world.air && !self.collision_empty([x, y, z]) {
+ continue;
+ }
+ self.set_block_clients([x, y, z], chest)?;
+ let seed = self.world.random.next_long();
+ self.world
+ .block_entities
+ .insert((x, y, z), BlockEntity::Chest(Vec::new()));
+ self.load_block_entity_nbt(
+ [x, y, z],
+ &format!(
+ "{{LootTable:\"minecraft:chests/spawn_bonus_chest\",LootTableSeed:{seed}L}}"
+ ),
+ );
+ for [dx, dz] in [[0, -1], [1, 0], [0, 1], [-1, 0]] {
+ let at = [x + dx, y, z + dz];
+ let survives = self.with_level(|b, level, ticks| {
+ b.can_survive(level, ticks, BlockPos::new(at[0], at[1], at[2]), torch)
+ });
+ if survives {
+ self.set_block_clients(at, torch)?;
+ }
+ }
+ return Ok(());
+ }
+ }
+ Ok(())
+ }
+ /// `Level.setBlock(pos, state, UPDATE_CLIENTS)`: no neighbour updates.
+ fn set_block_clients(&mut self, pos: [i32; 3], state: BlockStateId) -> Result<()> {
+ self.with_level(|b, level, ticks| {
+ b.set_block(
+ level,
+ ticks,
+ BlockPos::new(pos[0], pos[1], pos[2]),
+ state,
+ UPDATE_CLIENTS,
+ );
+ });
+ self.process_level_events()
+ }
+ /// The block at `pos` has no collision shape.
+ fn collision_empty(&self, pos: [i32; 3]) -> bool {
+ let mut scene = SceneCollisions {
+ world: &self.world,
+ binding: self.collision,
+ subject: None,
+ };
+ self.collision
+ .collision_shape_with_context(
+ &mut scene,
+ self.world.block(pos[0], pos[1], pos[2]),
+ BlockPos::new(pos[0], pos[1], pos[2]),
+ &CollisionContext::empty(false),
+ )
+ .is_ok_and(|shape| shape.is_empty())
+ }
/// PlayerSpawnFinder.findSpawn around the world spawn: the feet of a
/// player who has no position yet. None while a candidate's chunk loads.
pub(super) fn find_player_spawn(&mut self, suggestion: [i32; 3]) -> Result> {
let mut finder = match self.player_spawn {
Some(finder) => finder,
- None if self.level.game_mode == 2 => {
- // Adventure mode: the suggestion itself.
- let mut finder = PlayerSpawnFinder::new(suggestion, 0, |_| 0);
- finder.next_candidate();
- finder
- }
- None => {
- let mut radius = self.ui.rules.int("respawn_radius").max(0);
- let to_border = self
- .border
- .distance(f64::from(suggestion[0]), f64::from(suggestion[2]))
- .floor() as i32;
- if to_border < radius {
- radius = to_border;
- }
- if to_border <= 1 {
- radius = 1;
- }
- PlayerSpawnFinder::new(suggestion, radius, |n| {
- entity_random().next_int_bound(n).unwrap_or(0)
- })
- }
+ None => self.spawn_finder(suggestion),
};
let found = loop {
let Some(candidate) = finder.next_candidate() else {
@@ -176,6 +246,58 @@ impl Game<'_> {
self.player_spawn = found.is_none().then_some(finder);
Ok(found)
}
+ /// A new PlayerSpawnFinder around `suggestion`: the respawn radius, cut
+ /// by the world border; the suggestion itself in adventure mode.
+ fn spawn_finder(&self, suggestion: [i32; 3]) -> PlayerSpawnFinder {
+ if self.level.game_mode == 2 {
+ let mut finder = PlayerSpawnFinder::new(suggestion, 0, |_| 0);
+ finder.next_candidate();
+ return finder;
+ }
+ let mut radius = self.ui.rules.int("respawn_radius").max(0);
+ let to_border = self
+ .border
+ .distance(f64::from(suggestion[0]), f64::from(suggestion[2]))
+ .floor() as i32;
+ if to_border < radius {
+ radius = to_border;
+ }
+ if to_border <= 1 {
+ radius = 1;
+ }
+ PlayerSpawnFinder::new(suggestion, radius, |n| {
+ entity_random().next_int_bound(n).unwrap_or(0)
+ })
+ }
+ /// ServerPlayer.adjustSpawnLocation for a server's new player: where
+ /// PlayerSpawnFinder.findSpawn puts their feet around the world spawn
+ /// (`spawn`, the feet there), so that players new to a world don't all
+ /// stand in one spot. Vanilla waits for each candidate's chunk; a server
+ /// tick can't, so a candidate in a chunk not loaded yet is passed over,
+ /// and `spawn` stays when the search never reaches a loaded column.
+ pub(super) fn server_player_spawn(&self, spawn: [f64; 3]) -> [f64; 3] {
+ let suggestion = spawn.map(|v| v.floor() as i32);
+ let mut finder = self.spawn_finder(suggestion);
+ while let Some(candidate) = finder.next_candidate() {
+ let (x, z) = match candidate {
+ SpawnCandidate::Column(x, z) => (x, z),
+ SpawnCandidate::Suggestion => (suggestion[0], suggestion[2]),
+ };
+ if !self.streaming.is_lit(x >> 4, z >> 4) {
+ continue;
+ }
+ let feet = match candidate {
+ SpawnCandidate::Column(x, z) => level_respawn_pos(&self.spawn_columns(), x, z)
+ .filter(|&pos| self.player_fits(pos))
+ .map(bottom_center),
+ SpawnCandidate::Suggestion => Some(self.fixup_spawn_height(suggestion)),
+ };
+ if let Some(feet) = feet {
+ return [feet.x, feet.y, feet.z];
+ }
+ }
+ spawn
+ }
/// PlayerSpawnFinder.noCollisionNoLiquid: a player's box standing at the
/// block's bottom centre touches no block or liquid.
fn player_fits(&self, pos: [i32; 3]) -> bool {
diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs
index 14a18caa6..7d81c971d 100644
--- a/crates/horizon-client/src/game/integrated.rs
+++ b/crates/horizon-client/src/game/integrated.rs
@@ -52,6 +52,8 @@ struct Flags {
/// server follows while it runs (IntegratedServer.tickServer).
render_distance: AtomicI32,
simulation_distance: AtomicI32,
+ /// `MinecraftServer.isCurrentlySaving`: the server is autosaving.
+ saving: AtomicBool,
}
/// Work the window hands its server thread (`MinecraftServer.execute`).
@@ -69,6 +71,10 @@ impl Integrated {
pub fn smoothed_tick_ms(&self) -> f32 {
f32::from_bits(self.flags.smoothed_tick_ms.load(Ordering::Relaxed))
}
+ /// `MinecraftServer.isCurrentlySaving`.
+ pub fn is_saving(&self) -> bool {
+ self.flags.saving.load(Ordering::Relaxed)
+ }
/// `IntegratedServer.tickServer` skips the world while the game is paused.
pub fn set_paused(&self, paused: bool) {
self.flags.paused.store(paused, Ordering::Relaxed);
@@ -148,6 +154,12 @@ pub(super) struct Serving {
/// is out of its place: applied after the tick.
pending: Option,
}
+impl Serving {
+ /// The window reads this as `MinecraftServer.isCurrentlySaving`.
+ pub(super) fn set_saving(&self, saving: bool) {
+ self.flags.saving.store(saving, Ordering::Relaxed);
+ }
+}
enum Publish {
Open(TcpListener, LanSettings),
Close,
@@ -222,7 +234,6 @@ impl Game<'_> {
options.report = None;
options.server = None;
options.world = None;
- options.dev_mods.clear();
self.join_world_rest()?;
let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone());
let flags = Arc::new(Flags::default());
@@ -292,6 +303,9 @@ impl Game<'_> {
launch.create.as_ref(),
)?)?;
let saved = Box::new(self.level.clone());
+ // IntegratedServer runs the server mods; the window the client mods.
+ self.mods.dev = self.options.dev_mods.clone();
+ self.start_mods();
// Math.max(2, options.renderDistance): past vanilla's 32 when the
// window's render distance is (Horizon's options go to 64).
let view_distance = self.settings.render_distance.max(2);
diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs
index 1d79f077d..b6b7e2fb7 100644
--- a/crates/horizon-client/src/game/item_draw.rs
+++ b/crates/horizon-client/src/game/item_draw.rs
@@ -196,13 +196,31 @@ impl Game<'_> {
skins: &self.skin_downloads,
}
}
- /// The client level as item models read it.
+ /// The client level as item models read it: worked out once a frame (a
+ /// screen of items read the same level, its sky sampled once).
pub(super) fn item_level(&self) -> LevelState {
let dimension = match self.dim {
Dim::Overworld => "minecraft:overworld",
Dim::Nether => "minecraft:the_nether",
Dim::End => "minecraft:the_end",
};
+ let key = (
+ self.frames,
+ self.world.game_time,
+ self.world.day_time,
+ dimension,
+ );
+ let mut cached = self.item_level_cache.borrow_mut();
+ if let Some((at, level)) = cached.as_ref()
+ && *at == key
+ {
+ return level.clone();
+ }
+ let level = self.level_state_now(dimension);
+ *cached = Some((key, level.clone()));
+ level
+ }
+ fn level_state_now(&self, dimension: &'static str) -> LevelState {
let sky = self
.dim_environment()
.sample(self.world.day_time, None, None);
diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs
index 50fa222e6..28ec3fe8a 100644
--- a/crates/horizon-client/src/game/lan.rs
+++ b/crates/horizon-client/src/game/lan.rs
@@ -11,10 +11,10 @@ use horizon_client::{
chunks::ChunkEncoder,
data::SyncData,
entity::{EntityState, States},
- hub::{HostEvent, HostState, Hub, HubConfig, TickCtx},
+ hub::{BodyFlags, HostEvent, HostState, Hub, HubConfig, TickCtx},
playerdata,
},
- mobs::{Mob, leash::Holder},
+ mobs::{Mob, Who, leash::Holder},
text::Text,
};
use horizon_core::geometry::Vec3;
@@ -24,11 +24,24 @@ use horizon_protocol::{
};
use std::{
collections::HashMap,
- sync::{Arc, OnceLock},
+ sync::{Arc, Mutex},
};
/// The registries and tags are the same for every world: load them once.
-static SYNC: OnceLock, String>> = OnceLock::new();
+static SYNC: Mutex, String>>> = Mutex::new(None);
+
+/// The registries and tags a server sends, loaded from `root` the first time.
+pub(super) fn sync_data(root: &std::path::Path) -> std::result::Result, String> {
+ let mut sync = SYNC.lock().unwrap_or_else(|e| e.into_inner());
+ sync.get_or_insert_with(|| SyncData::load(root).map(Arc::new))
+ .clone()
+}
+
+/// Let go of what `sync_data` loaded: for a preload no world used
+/// (game/world_loading.rs).
+pub(super) fn forget_sync_data() {
+ *SYNC.lock().unwrap_or_else(|e| e.into_inner()) = None;
+}
/// The settings of the open world (WorldOptionsScreen's multiplayer section).
#[derive(Clone, Copy, Debug)]
@@ -71,6 +84,8 @@ pub(super) struct LanHost {
/// Guests' commands waiting for the hub to be back in `self.lan`, where
/// a command can reach every player (game/lan_actions.rs).
pub commands: Vec,
+ /// Mods' quiet commands waiting to run a few a tick (game/lan_quiet.rs).
+ pub quiet: std::collections::VecDeque,
/// The entities the guests track, described again every tick
/// (`lan_entities`) over last tick's states.
states: lan::entity::States,
@@ -145,6 +160,7 @@ pub(super) fn baby_index(kind: &str) -> Option {
fn mob_meta(
m: &Mob,
hub: &Hub,
+ player_entity: Option,
meta: &mut Vec<(u8, i32, Value)>,
defaults: &mut Vec<(u8, i32, Value)>,
) {
@@ -175,6 +191,17 @@ fn mob_meta(
meta.push((9, serializer::FLOAT, Value::Float(health)));
}
defaults.push((9, serializer::FLOAT, Value::Float(1.0)));
+ // LivingEntity.DATA_EFFECT_PARTICLES and DATA_EFFECT_AMBIENCE_ID: the
+ // swirls of its effects (the ones a mob has are visible, not ambient).
+ meta.extend(
+ hub.effect_meta(
+ (m.extra.effects.iter())
+ .filter(|e| !m.extra.hidden_effects.contains(&e.0))
+ .map(|e| (e.0, false)),
+ ),
+ );
+ defaults.push((10, serializer::PARTICLES, Value::Particles(Vec::new())));
+ defaults.push((11, serializer::BOOLEAN, Value::Bool(false)));
// Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2, aggressive 4 (what
// draws a vindicator's axe, a skeleton's drawn bow, a piglin's raised
// weapon).
@@ -194,6 +221,53 @@ fn mob_meta(
let e = &m.extra;
let id = |registry: &str, name: &str| hub.registry_id(registry, &format!("minecraft:{name}"));
match kind {
+ "minecraft:guardian" | "minecraft:elder_guardian" => {
+ // Guardian.DATA_ID_MOVING and DATA_ID_ATTACK_TARGET.
+ if e.flag2 {
+ meta.push((16, serializer::BOOLEAN, Value::Bool(true)));
+ }
+ let target = if e.flag {
+ m.ai.target.and_then(|who| match who {
+ Who::Player => player_entity,
+ Who::Mob(id) => Some(id as i32),
+ })
+ } else {
+ None
+ };
+ if let Some(target) = target {
+ meta.push((17, serializer::INT, Value::Int(target)));
+ }
+ defaults.push((16, serializer::BOOLEAN, Value::Bool(false)));
+ defaults.push((17, serializer::INT, Value::Int(0)));
+ }
+ // Bat.DATA_ID_FLAGS: resting in bit 0, flying by default.
+ "minecraft:bat" => {
+ if e.flag {
+ meta.push((16, serializer::BYTE, Value::Byte(1)));
+ }
+ defaults.push((16, serializer::BYTE, Value::Byte(0)));
+ }
+ // SnowGolem.DATA_PUMPKIN_ID: 16 while the pumpkin is on (the default).
+ "minecraft:snow_golem" => {
+ if e.sheared {
+ meta.push((16, serializer::BYTE, Value::Byte(0)));
+ }
+ defaults.push((16, serializer::BYTE, Value::Byte(16)));
+ }
+ // MushroomCow.DATA_TYPE: 0 red, 1 brown.
+ "minecraft:mooshroom" => {
+ if e.variant == 1 {
+ meta.push((17, serializer::INT, Value::Int(1)));
+ }
+ defaults.push((17, serializer::INT, Value::Int(0)));
+ }
+ // Piglin.DATA_IS_DANCING (after the baby flag and the crossbow charge).
+ "minecraft:piglin" => {
+ if e.scratch[0] > 0 {
+ meta.push((19, serializer::BOOLEAN, Value::Bool(true)));
+ }
+ defaults.push((19, serializer::BOOLEAN, Value::Bool(false)));
+ }
// Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 when sheared.
"minecraft:sheep" => {
let value = (e.color & 15) | if e.sheared { 16 } else { 0 };
@@ -308,6 +382,14 @@ fn mob_meta(
}
defaults.push((17, serializer::BOOLEAN, Value::Bool(false)));
}
+ // PolarBear.DATA_STANDING_ID (after AgeableMob's two): the bear
+ // rears up; the client animates it.
+ "minecraft:polar_bear" => {
+ if e.flag {
+ meta.push((18, serializer::BOOLEAN, Value::Bool(true)));
+ }
+ defaults.push((18, serializer::BOOLEAN, Value::Bool(false)));
+ }
// SpellcasterIllager.DATA_SPELL_CASTING_ID: the casting pose.
"minecraft:evoker" | "minecraft:illusioner" => {
if e.variant2 != 0 {
@@ -533,10 +615,7 @@ impl Game<'_> {
config: HubConfig,
host: Option,
) -> Result<()> {
- let root = self.options.resources.clone();
- let sync = SYNC
- .get_or_init(|| SyncData::load(&root).map(Arc::new))
- .clone()?;
+ let sync = sync_data(&self.options.resources)?;
let biome_names: Vec = self
.res
.biomes()
@@ -596,6 +675,7 @@ impl Game<'_> {
waypoint_dead: Default::default(),
border_sent: None,
commands: Vec::new(),
+ quiet: std::collections::VecDeque::new(),
states: Default::default(),
});
self.audio.capture = Some(Vec::new());
@@ -634,6 +714,7 @@ impl Game<'_> {
self.world.light_log = None;
self.audio.capture = None;
self.lan_events.clear();
+ self.lan_critical_hits.clear();
self.streaming.extra.clear();
if announce {
self.system_message(Text::translate(
@@ -804,6 +885,16 @@ impl Game<'_> {
living_flags: living_flags(self.using)
| if p.auto_spin_attack_ticks > 0 { 4 } else { 0 },
bed: self.sleeping,
+ body: BodyFlags {
+ gliding: p.fall_flying,
+ swimming: p.swimming,
+ crawling: p.pose == horizon_client::pose::Pose::Swimming && !p.swimming,
+ crouching: p.pose == horizon_client::pose::Pose::Crouching,
+ spin_attack: p.auto_spin_attack_ticks > 0,
+ on_fire: p.fire_ticks > 0,
+ invisible: self.potions.effects.get("invisibility").is_some(),
+ glowing: self.potions.effects.get("glowing").is_some(),
+ },
})
}
@@ -820,12 +911,13 @@ impl Game<'_> {
for m in self.mobs.iter().filter(|m| !m.removed) {
// The lead's holder: the player the mob sees (a guest, else the
// host) or another mob. A fence knot isn't an entity here.
+ let player_entity = mob_players
+ .get(&m.id)
+ .and_then(|conn| hub.guest(*conn))
+ .map(|g| g.entity_id)
+ .or(host_entity);
let leash = m.extra.leash.and_then(|h| match h {
- Holder::Player => mob_players
- .get(&m.id)
- .and_then(|conn| hub.guest(*conn))
- .map(|g| g.entity_id)
- .or(host_entity),
+ Holder::Player => player_entity,
Holder::Mob(id) => Some(id as i32),
Holder::Knot(_) => None,
});
@@ -835,7 +927,7 @@ impl Game<'_> {
e.on_ground = m.on_ground;
e.velocity = [m.velocity.x, m.velocity.y, m.velocity.z];
e.needs_sync = m.needs_sync;
- mob_meta(m, hub, &mut e.meta, &mut e.defaults);
+ mob_meta(m, hub, player_entity, &mut e.meta, &mut e.defaults);
mob_equipment(m, hub, &mut e.equipment);
self.mob_attributes(m, &mut e.attributes);
e.leash = leash;
@@ -912,7 +1004,24 @@ impl Game<'_> {
for m in &mut self.mobs {
m.needs_sync = false;
}
+ // `runBlockEvents`' broadcast precedes the tick's block changes
+ // (`ChunkHolder.broadcastChanges` in `tick_level` below): the
+ // guest re-runs a piston's `triggerEvent` while its level still
+ // has the blocks as they were before the move.
+ for (pos, b0, b1, state) in std::mem::take(&mut self.lan_block_events) {
+ host.hub.block_event(pos, b0, b1, state);
+ }
let entities = states.as_slice();
+ // An entity that left the level since the last tick (a snowball
+ // that hit) is dropped by the tracker below: its event goes out
+ // first, as `Level.broadcastEntityEvent` precedes the discard.
+ let (gone, later): (Vec<_>, Vec<_>) = std::mem::take(&mut self.lan_entity_events)
+ .into_iter()
+ .partition(|(id, ..)| !entities.iter().any(|e| e.id == *id));
+ self.lan_entity_events = later;
+ for (id, event, at) in gone {
+ host.hub.entity_event(id, event, at);
+ }
let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]);
let events = {
let clock_rate = self.network_clock_rate();
@@ -960,6 +1069,9 @@ impl Game<'_> {
event @ (HostEvent::Chat { .. } | HostEvent::Warn(_) | HostEvent::Error(_)) => {
self.lan_log_event(event);
}
+ HostEvent::PlayerChat { sender, text } => {
+ self.mod_player_chat(super::server_mods::Who::Uuid(sender), &text);
+ }
HostEvent::Joined(conn) => {
self.lan_guest_joined(&mut host, conn, state.as_ref(), entities, spawn);
if self.options.dedicated.is_some()
@@ -1029,6 +1141,14 @@ impl Game<'_> {
}
host.states = states;
}
+ if !host.quiet.is_empty() {
+ self.lan = Some(host);
+ self.run_quiet_commands();
+ host = self
+ .lan
+ .take()
+ .expect("the hub is back after the quiet commands");
+ }
self.lan_flush_effects(&mut host);
if !paused {
self.tick_guests(&mut host);
@@ -1078,8 +1198,17 @@ impl Game<'_> {
g.game_mode = default_mode;
}
if !known {
- g.position = spawn;
- g.previous_position = spawn;
+ // ServerPlayer.adjustSpawnLocation: a player new to the world
+ // stands where PlayerSpawnFinder puts them, not all on one spot
+ // (it reads the loaded level, which holds the spawn when it is
+ // the overworld).
+ let feet = if self.dim == super::Dim::Overworld {
+ self.server_player_spawn(spawn)
+ } else {
+ spawn
+ };
+ g.position = feet;
+ g.previous_position = feet;
g.health = 20.0;
g.food = 20;
g.dimension = super::Dim::Overworld.id().to_owned();
@@ -1134,17 +1263,29 @@ impl Game<'_> {
return;
}
for e in events {
- if let horizon_world::level::LevelEvent::LevelEvent { id, pos, data } = e {
- // The acting guest does not predict the egg's teleport
- // particles, bone meal's growth, or anvil result sounds
- // (these levelEvent calls name no excluded player).
- let except = if matches!(*id, 2015 | 1505 | 1029 | 1030) {
- None
- } else {
- self.lan_acting
- };
- self.lan_events
- .push((*id, [pos.x, pos.y, pos.z], *data, except));
+ match e {
+ horizon_world::level::LevelEvent::LevelEvent { id, pos, data } => {
+ // The acting guest does not predict the egg's teleport
+ // particles, bone meal's growth, or anvil result sounds
+ // (these levelEvent calls name no excluded player).
+ let except = if matches!(*id, 2015 | 1505 | 1029 | 1030) {
+ None
+ } else {
+ self.lan_acting
+ };
+ self.lan_events
+ .push((*id, [pos.x, pos.y, pos.z], *data, except));
+ }
+ // `ServerLevel.runBlockEvents` broadcasts a handled block
+ // event (`ClientboundBlockEventPacket`): the guest re-runs
+ // the block's `triggerEvent` — a piston's `moveBlocks` is
+ // what animates the move there. `state` is the block the
+ // event named, read before it ran (the packet's `block`).
+ horizon_world::level::LevelEvent::BlockEntityEvent { pos, state, a, b } => {
+ self.lan_block_events
+ .push(([pos.x, pos.y, pos.z], *a, *b, state.0));
+ }
+ _ => {}
}
}
}
@@ -1162,8 +1303,33 @@ impl Game<'_> {
self.lan_entity_events.push((id, event, at));
}
}
+ /// `ServerPlayer.crit` (or `magicCrit` when `magic`): this window's
+ /// emitter, and an animation for the attacker's client and observers once
+ /// the hub is back in place.
+ pub(super) fn critical_hit(
+ &mut self,
+ attacker: Option,
+ id: i32,
+ feet: [f64; 3],
+ width: f64,
+ height: f64,
+ magic: bool,
+ ) {
+ use horizon_client::particles::{ParticleOptions, ParticleType};
+ let particle = if magic {
+ ParticleType::EnchantedHit
+ } else {
+ ParticleType::Crit
+ };
+ self.particles
+ .tracking_emitter(ParticleOptions::simple(particle), feet, width, height);
+ if self.audio.capture.is_some() {
+ self.lan_critical_hits.push((attacker, id, magic));
+ }
+ }
/// Send the tick's level events, sounds and mob animations.
fn lan_flush_effects(&mut self, host: &mut LanHost) {
+ let critical_hits = std::mem::take(&mut self.lan_critical_hits);
for (kind, pos, data, acting) in std::mem::take(&mut self.lan_events) {
if kind == 2001 {
host.broken
@@ -1236,6 +1402,14 @@ impl Game<'_> {
seen.insert(m.id, (m.hurt_time, dead, swing));
}
host.mob_state.insert(self.dim, seen);
+ for (attacker, target, magic) in critical_hits {
+ let Some(attacker) = attacker.map_or(Some(host.host_entity), |conn| {
+ host.hub.guest(conn).map(|g| g.entity_id)
+ }) else {
+ continue;
+ };
+ host.hub.critical_hit(attacker, target, magic);
+ }
}
/// Keep the chunks around every guest loaded.
@@ -1317,6 +1491,13 @@ impl Game<'_> {
.each_ref()
.map(|s| s.as_ref().map(|s| s.item.clone()));
m.extra.crouching = g.sneaking;
+ m.extra.sprinting = g.sprinting;
+ // LivingEntity.DATA_EFFECT_PARTICLES: the swirls of its visible effects.
+ let visible = || g.effects.list.iter().filter(|e| e.visible);
+ m.extra.effect_particles = visible()
+ .filter_map(|e| super::client_ambient::effect_particle(e.id, e.ambient))
+ .collect();
+ m.extra.effect_ambient = visible().all(|e| e.ambient);
// Lying in its bed (LivingEntity.getBedOrientation).
m.extra.ints[1] = g.bed.map_or(0, |b| self.bed_facing(b));
// LivingEntity.updateSwingTime: the arm swing lan_swings started.
@@ -1403,7 +1584,11 @@ impl Game<'_> {
let tag = if secure { "" } else { "[Not Secure] " };
super::dedicated::log("INFO", &format!("{tag}{line}"));
}
- HostEvent::Chat { line, .. } => self.system_message(Text::literal(line)),
+ // Player chat (and `/say`'s or `/me`'s, which are chat messages
+ // too): the host's Chat option decides, as `ChatListener` does
+ // for the guests' packets. Command feedback is a system message
+ // and takes the system-message permission instead.
+ HostEvent::Chat { line, .. } => self.player_message(Text::literal(line)),
HostEvent::Warn(line) if dedicated => super::dedicated::log("WARN", &line),
HostEvent::Warn(line) => log::warn!("{line}"),
HostEvent::Error(line) if dedicated => super::dedicated::log("ERROR", &line),
diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs
index bbb0c37c0..8c51a3f2a 100644
--- a/crates/horizon-client/src/game/lan_actions.rs
+++ b/crates/horizon-client/src/game/lan_actions.rs
@@ -77,6 +77,10 @@ pub(super) struct GuestPlay {
last_inventory: u64,
/// `Entity.portalProcess` and `portalCooldown` (game/server_travel.rs).
pub(super) portal: horizon_client::nether_portal::PortalState,
+ /// `ServerPlayer.wonGame`: the End poem is showing, the player waits for
+ /// its client's PERFORM_RESPAWN (`respawn_requested`).
+ pub(super) won_game: bool,
+ pub(super) respawn_requested: bool,
/// `Player.takeXpDelay`: ticks until the next orb can be taken.
xp_delay: u32,
/// What last killed the guest outright (`/kill`): the death message's key.
@@ -94,11 +98,14 @@ pub(super) struct GuestPlay {
/// A guest's command waiting for the hub (`LanHost::commands`).
pub(super) struct GuestCommand {
- conn: u32,
- command: String,
- permission: u8,
+ pub(super) conn: u32,
+ pub(super) command: String,
+ pub(super) permission: u8,
/// An integrated server's: no level teleports (yet).
- integrated: bool,
+ pub(super) integrated: bool,
+ /// A mod's quiet command (game/lan_quiet.rs): its output suppressed, as
+ /// `CommandSourceStack.withSuppressedOutput` does.
+ pub(super) quiet: bool,
}
/// The game's own state while a guest's is swapped in (`enter_guest`), and
@@ -872,7 +879,11 @@ impl Game<'_> {
.filter(|g| host.hub.here(g))
.filter(|g| {
g.menu.as_ref().is_some_and(|m| {
- m.slots.valid(&self.world) && !m.slots.still_valid(&self.world, g, m.pos)
+ (m.slots.valid(&self.world) && !m.slots.still_valid(&self.world, g, m.pos))
+ || m.pos.is_some_and(|k| {
+ k.1 == super::minecarts::CART_KEY_Y
+ && !self.chest_vehicle_still_valid(k.2, g)
+ })
})
})
.map(|g| g.conn)
@@ -886,6 +897,35 @@ impl Game<'_> {
}
}
+ /// `ContainerEntity.isChestVehicleStillValid`: the chest minecart or chest
+ /// boat is still there and within the guest's entity interaction range
+ /// plus 4 of its box.
+ fn chest_vehicle_still_valid(&self, id: i32, g: &horizon_client::lan::guest::Guest) -> bool {
+ let bounds = self
+ .carts
+ .iter()
+ .find(|c| c.id as i32 == id)
+ .map(|c| c.bounds())
+ .or_else(|| {
+ self.boats
+ .iter()
+ .find(|b| b.id as i32 == id)
+ .map(|b| b.bounds())
+ });
+ let Some(b) = bounds else {
+ return false;
+ };
+ let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]];
+ let (lo, hi) = (b.min_position(), b.max_position());
+ let d = [
+ eye[0] - eye[0].clamp(lo.x, hi.x),
+ eye[1] - eye[1].clamp(lo.y, hi.y),
+ eye[2] - eye[2].clamp(lo.z, hi.z),
+ ];
+ let range = if g.creative() { 5.0 } else { 3.0 } + 4.0;
+ d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < range * range
+ }
+
/// A packet from a guest that the hub does not handle itself.
pub(super) fn lan_guest_packet(&mut self, host: &mut LanHost, conn: u32, packet: S) {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
@@ -1176,6 +1216,12 @@ impl Game<'_> {
{
self.guest_carried_back(host, gi);
}
+ S::SelectBundleItem(p) => {
+ if !spectator && let Ok(slot) = usize::try_from(p.slot) {
+ host.hub
+ .select_bundle_item(conn, slot, p.index, &mut self.world);
+ }
+ }
S::ContainerClick(p) => {
let rules = ItemRules(self.res.items());
let slots = host.hub.guests[gi]
@@ -1210,6 +1256,9 @@ impl Game<'_> {
self.guest_carried_back(host, gi);
}
S::ChatCommand(c) => self.guest_chat_command(host, conn, &c.command),
+ S::CustomPayload(p) if p.channel == horizon_protocol::quiet::CHANNEL => {
+ self.guest_quiet_commands(host, conn, &p.data)
+ }
S::ChatCommandSigned(p) => self.guest_signed_command(host, conn, p),
S::ChangeDifficulty(p) if host.hub.guests[gi].permission >= 2 => {
if !self.level.difficulty_locked && (0..=3).contains(&p.difficulty) {
@@ -1308,6 +1357,13 @@ impl Game<'_> {
self.guest_suggestions(host, conn, &payload);
}
S::PlaceRecipe(p) => self.lan_place_recipe(host, conn, &p),
+ // handleClientCommand: PERFORM_RESPAWN after the poem leaves the End
+ // (the next server tick sends the player on).
+ S::ClientCommand(c)
+ if c.action == 0 && host.play.get(&conn).is_some_and(|p| p.won_game) =>
+ {
+ host.play.entry(conn).or_default().respawn_requested = true;
+ }
S::ClientCommand(c) if c.action == 0 => self.guest_respawn(host, conn),
// ServerStatsCounter.sendStats.
S::ClientCommand(c) if c.action == 1 => {
@@ -1533,6 +1589,10 @@ impl Game<'_> {
);
return;
}
+ // A server mod's command, for every player whatever their level.
+ if self.guest_server_mod_command(host, conn, command.trim_start_matches('/')) {
+ return;
+ }
// An integrated server runs every player's commands at their own
// permission level (`CommandSourceStack.permissions`); a LAN world
// follows its Allow Commands, and a dedicated server leaves it to
@@ -1559,6 +1619,7 @@ impl Game<'_> {
command: command.trim_start_matches('/').to_owned(),
permission,
integrated,
+ quiet: false,
});
}
@@ -1573,41 +1634,54 @@ impl Game<'_> {
return;
}
let c = host.commands.remove(0);
- let mut host = self.lan.take().expect("checked above");
- let Some(swap) = self.enter_guest(&mut host, c.conn) else {
- self.lan = Some(host);
- continue;
- };
- self.lan = Some(host);
- self.chat_capture = Some(Vec::new());
- let level = std::mem::replace(&mut self.ui.registries.permission, c.permission);
- self.run_command(&c.command);
- self.ui.registries.permission = level;
- let lines = self.chat_capture.take().unwrap_or_default();
- let mut host = self.lan.take().expect("a command puts the hub back");
- self.leave_guest(&mut host, swap);
- host.hub.sync_all_effects();
- if !c.integrated {
- // A teleport into another level happens before its feedback is sent.
- self.run_level_teleports(&mut host);
- }
- // What the command earned is announced before its feedback.
- self.announce_guest_advancements(&mut host);
- for line in lines {
- host.hub.send_to(
- c.conn,
- &C::SystemChat(play::SystemChat {
- content: horizon_client::lan::data::component_nbt(&line.component()),
- overlay: false,
- }),
- );
- }
- // The other operators hear of it; never the player whose command it was.
- self.send_admin_feedback(&mut host, Some(c.conn));
- self.lan = Some(host);
+ self.run_guest_command(c);
}
}
+ /// One guest's command as that guest, its feedback sent to them; false
+ /// when it failed (or the guest is gone).
+ pub(super) fn run_guest_command(&mut self, c: GuestCommand) -> bool {
+ let Some(mut host) = self.lan.take() else {
+ return false;
+ };
+ let Some(swap) = self.enter_guest(&mut host, c.conn) else {
+ self.lan = Some(host);
+ return false;
+ };
+ self.lan = Some(host);
+ self.chat_capture = Some(Vec::new());
+ let level = std::mem::replace(&mut self.ui.registries.permission, c.permission);
+ let ok = if c.quiet {
+ self.run_command_quietly(&c.command)
+ } else {
+ self.run_command(&c.command)
+ };
+ self.ui.registries.permission = level;
+ let lines = self.chat_capture.take().unwrap_or_default();
+ let mut host = self.lan.take().expect("a command puts the hub back");
+ self.leave_guest(&mut host, swap);
+ host.hub.sync_all_effects();
+ if !c.integrated {
+ // A teleport into another level happens before its feedback is sent.
+ self.run_level_teleports(&mut host);
+ }
+ // What the command earned is announced before its feedback.
+ self.announce_guest_advancements(&mut host);
+ for line in lines {
+ host.hub.send_to(
+ c.conn,
+ &C::SystemChat(play::SystemChat {
+ content: horizon_client::lan::data::component_nbt(&line.component()),
+ overlay: false,
+ }),
+ );
+ }
+ // The other operators hear of it; never the player whose command it was.
+ self.send_admin_feedback(&mut host, Some(c.conn));
+ self.lan = Some(host);
+ ok
+ }
+
/// The `broadcastToAdmins` lines a command queued (`source`: the guest
/// whose it was; none for the host's or the console's): every other
/// operator gets them, and the console logs them as the server's own
@@ -2115,6 +2189,7 @@ impl Game<'_> {
let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height());
let at = g.position;
let sneaking = g.sneaking;
+ let mut soul = None;
let events = self.as_guest(host, conn, |game| {
let (rules, motion) = (game.world.health_rules, game.motion);
let health = &motion.health;
@@ -2184,6 +2259,7 @@ impl Game<'_> {
w.player.shift_key_down = sneaking;
w.player.freeze_immune = freeze_immune;
let _ = w.server_block_damage(start);
+ let _ = w.update_soul_speed_block();
let _ = w.tick_environment_damage();
let _ = w.apply_fire_contact();
let _ = w.server_hazards_tick(in_wall);
@@ -2211,6 +2287,9 @@ impl Game<'_> {
// LivingEntity.baseTick: outside the world border, then tickEffects.
game.border_damage();
game.tick_mob_effects();
+ // Soul Speed's effects (LivingEntity.baseTick's location_changed
+ // and tick effects); its particle goes to the players around.
+ soul = game.tick_soul_speed();
let Some(player) = game.player.as_mut() else {
return (Vec::new(), None);
};
@@ -2233,16 +2312,48 @@ impl Game<'_> {
let marked = std::mem::take(&mut player.health.sync_velocity);
let velocity = marked.then_some(player.velocity);
game.record_combat(&events);
+ game.wear_armor(&events);
(events, velocity)
});
let Some((events, marked)) = events else {
return;
};
+ if let Some((at, velocity)) = soul {
+ super::lan_particles::send_soul_particle(host, at, velocity);
+ }
self.as_guest(host, conn, |game| game.tick_player_sculk_events());
for event in events {
match event {
MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, at),
+ // LivingEntity.checkFallDamage: the crumbs reach every player.
+ MotionEvent::Fall(horizon_client::landing::FallEvent::Particles {
+ state,
+ position,
+ count,
+ speed,
+ }) => self.landing_dust(Some(host), state, position, count, speed),
MotionEvent::Fall(event) => self.landing_block_updates(&event),
+ // HoneyBlock.maybeDoSlideEffects: the sound reaches the
+ // others (Player.playSound excludes the player, whose client
+ // plays it), the entity event 53 everyone around.
+ MotionEvent::HoneySlide {
+ sound, particles, ..
+ } => {
+ let Some((id, at)) = host.hub.guest(conn).map(|g| (g.entity_id, g.position))
+ else {
+ continue;
+ };
+ if sound {
+ let name = "minecraft:block.honey_block.slide";
+ let source = horizon_client::settings::sound_source(name) as i32;
+ self.audio.play_unshared(name, Some(at), 1.0, 1.0);
+ host.hub.sound(name, at, 1.0, 1.0, source, Some(conn));
+ }
+ if particles {
+ self.honey_slide_particles(at);
+ host.hub.entity_event(id, 53, at);
+ }
+ }
_ => {}
}
}
@@ -2326,9 +2437,13 @@ impl Game<'_> {
}
if (next / 10) % 2 == 0
&& !creative
- && let Some(elytra) = game.armor[1].as_mut()
+ && let Some(stack) = game.armor[1].clone()
{
- elytra.damage += 1;
+ // `ItemStack.hurtAndBreak`: Unbreaking can save the wear.
+ let loss = game.durability_loss(&stack, 1);
+ if let Some(elytra) = game.armor[1].as_mut() {
+ elytra.damage += loss;
+ }
}
let ctx = game.player_context(None);
game.post_game_event("minecraft:elytra_glide", at, ctx);
@@ -2591,7 +2706,13 @@ impl Game<'_> {
.random
.next_int_bound(touching.len() as i32)
.unwrap_or(0) as usize;
- let orb = self.orbs.remove(touching[pick]);
+ // A merged orb gives its value once per count and goes at zero.
+ let orb = self.orbs[touching[pick]].clone();
+ if orb.count <= 1 {
+ self.orbs.remove(touching[pick]);
+ } else {
+ self.orbs[touching[pick]].count -= 1;
+ }
play.xp_delay = 2;
host.hub.take_item(orb.id as i32, id, 1, at);
// ClientPacketListener.handleTakeItemEntity's sound, at the orb.
diff --git a/crates/horizon-client/src/game/lan_chat.rs b/crates/horizon-client/src/game/lan_chat.rs
index f678480ab..621955967 100644
--- a/crates/horizon-client/src/game/lan_chat.rs
+++ b/crates/horizon-client/src/game/lan_chat.rs
@@ -28,7 +28,11 @@ impl Game<'_> {
/// SignableCommand.of: the command's message arguments, by name, with
/// their text, not past a redirect to the root (`execute ... run`).
- fn signable_arguments(&mut self, permission: u8, command: &str) -> Vec<(String, String)> {
+ pub(super) fn signable_arguments(
+ &mut self,
+ permission: u8,
+ command: &str,
+ ) -> Vec<(String, String)> {
let parse = self.parse_as(permission, command);
let nodes = &vanilla::game_dispatcher().nodes;
let root = parse.context.root;
diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs
index cd4ba2fb8..665710be2 100644
--- a/crates/horizon-client/src/game/lan_entities.rs
+++ b/crates/horizon-client/src/game/lan_entities.rs
@@ -245,6 +245,16 @@ impl Game<'_> {
}
out.push(e);
}
+ for c in &self.cushions {
+ let p = c.position;
+ let mut e = state(c.id, "minecraft:cushion", [p.x, p.y, p.z], c.yaw, false);
+ // Cushion.DATA_COLOR, set unless it is the default white.
+ if c.color != 0 {
+ e.meta
+ .push((8, serializer::DYE_COLOR, Value::Id(i32::from(c.color))));
+ }
+ out.push(e);
+ }
self.lan_projectile_states(host_entity, hub, out);
for o in &self.others {
let p = o.position;
@@ -279,6 +289,10 @@ impl Game<'_> {
self.bolts.iter_mut().for_each(|b| give(&mut b.id));
self.potions.thrown_ids().for_each(&mut give);
self.end.eye_ids().for_each(&mut give);
+ self.breath_clouds.iter_mut().for_each(|b| give(&mut b.id));
+ self.dragon_fireballs
+ .iter_mut()
+ .for_each(|b| give(&mut b.id));
}
/// Primed TNT, falling blocks, projectiles, tridents, firework rockets and
@@ -290,6 +304,9 @@ impl Game<'_> {
None => 0,
};
let at = |p: horizon_core::geometry::Vec3| [p.x, p.y, p.z];
+ for f in &self.fangs.list {
+ out.push(state(f.id, "minecraft:evoker_fangs", f.pos, f.yaw, false));
+ }
// LightningBolt: each client draws and flashes its own.
for b in self.bolts.iter().filter(|b| b.id != 0) {
out.push(state(b.id, "minecraft:lightning_bolt", b.at, 0.0, false));
@@ -340,6 +357,20 @@ impl Game<'_> {
a.is_some_and(|a| a.in_ground) || p.stuck,
));
}
+ // ThrownTrident.ID_LOYALTY (none for a mob's) and ID_FOIL, on
+ // AbstractArrow's flags.
+ K::Trident => {
+ let a = p.arrow.as_deref();
+ e.meta.extend(arrow_meta(
+ false,
+ a.is_some_and(|a| a.no_physics),
+ 0,
+ a.is_some_and(|a| a.in_ground) || p.stuck,
+ ));
+ if a.is_some_and(|a| a.pickup_item.has_any_enchantments()) {
+ e.meta.push((12, serializer::BOOLEAN, Value::Bool(true)));
+ }
+ }
// WitherSkull.DATA_DANGEROUS.
K::WitherSkull { dangerous: true } => {
e.meta.push((8, serializer::BOOLEAN, Value::Bool(true)));
@@ -435,6 +466,35 @@ impl Game<'_> {
}
out.push(e);
}
+ // The dragon's breath clouds (AreaEffectCloud's DATA_RADIUS,
+ // DATA_WAITING for its 20-tick wait, and DATA_PARTICLE): the
+ // client draws them from these (`tick_remote_clouds`).
+ let breath = self.network_particle(
+ &horizon_client::particles::ParticleOptions::simple(
+ horizon_client::particles::ParticleType::DragonBreath,
+ ),
+ None,
+ );
+ for b in self.dragon_fireballs.iter().filter(|b| b.id != 0) {
+ let p = b.position;
+ let mut e = state(b.id, "minecraft:dragon_fireball", at(p), 0.0, false);
+ e.velocity = [b.velocity.x, b.velocity.y, b.velocity.z];
+ out.push(e);
+ }
+ for b in self.breath_clouds.iter().filter(|b| b.id != 0) {
+ let mut e = state(b.id, "minecraft:area_effect_cloud", b.at, 0.0, false);
+ e.meta.push((8, serializer::FLOAT, Value::Float(b.radius)));
+ if b.age < 20 {
+ e.meta.push((9, serializer::BOOLEAN, Value::Bool(true)));
+ }
+ if let Some(p) = &breath {
+ e.meta
+ .push((10, serializer::PARTICLE, Value::Particle(p.clone())));
+ }
+ e.defaults
+ .push((9, serializer::BOOLEAN, Value::Bool(false)));
+ out.push(e);
+ }
out.extend(self.lan_dragon_state());
}
}
diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs
index 4f53cec60..6527f1015 100644
--- a/crates/horizon-client/src/game/lan_mobs.rs
+++ b/crates/horizon-client/src/game/lan_mobs.rs
@@ -370,6 +370,7 @@ mod tests {
velocity: Vec3::ZERO,
yaw: 0.0,
hero: false,
+ effects: Vec::new(),
uuid: [0; 4],
allies: Default::default(),
remote: false,
diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs
index 0e35392bf..648cef962 100644
--- a/crates/horizon-client/src/game/lan_particles.rs
+++ b/crates/horizon-client/src/game/lan_particles.rs
@@ -1,7 +1,8 @@
//! Particles a server sends its players and its clients draw:
//! `ClientboundLevelParticlesPacket` (`ServerLevel.sendParticles`, which
//! `/particle` uses) and `ClientboundExplodePacket` (`ServerLevel.explode`).
-use super::Game;
+use super::{Game, lan::LanHost};
+use horizon_client::lan::hub::Hub;
use horizon_client::particles::{ParticleOptions, ParticleType};
use horizon_core::{geometry::Vec3, random::RandomSource};
use horizon_protocol::{
@@ -24,7 +25,123 @@ fn rgb(c: [f32; 4]) -> [f32; 3] {
[c[0], c[1], c[2]]
}
+/// `ServerLevel.sendParticles` of one soul particle moving by `velocity`
+/// (Soul Speed's `spawn_particles`): sent to the players within 32 blocks.
+pub(super) fn send_soul_particle(host: &super::lan::LanHost, at: [f64; 3], velocity: [f64; 3]) {
+ let Some(id) = host
+ .hub
+ .registry_id("minecraft:particle_type", "minecraft:soul")
+ else {
+ return;
+ };
+ let packet = C::LevelParticles(play::LevelParticles {
+ particle: Particle { id, data: None },
+ override_limiter: false,
+ always_show: false,
+ pos: at,
+ dist: velocity.map(|v| v as f32),
+ max_speed: [1.0; 3],
+ count: 0,
+ randomization: 0,
+ });
+ for g in host.hub.guests.iter().filter(|g| host.hub.here(g)) {
+ let distance: f64 = (0..3)
+ .map(|k| (g.position[k].floor() + 0.5 - at[k]).powi(2))
+ .sum();
+ if distance < 32.0 * 32.0 {
+ g.send(&packet);
+ }
+ }
+}
+
impl Game<'_> {
+ /// `SonicBoom.tick` uses `ServerLevel.sendParticles` for each ray point.
+ /// Keep the local event's rendering; connected players receive one at rest.
+ pub(super) fn lan_sonic_boom(&self, options: &ParticleOptions, at: [f64; 3]) {
+ let (Some(host), Some(particle)) = (&self.lan, self.network_particle(options, None)) else {
+ return;
+ };
+ let packet = C::LevelParticles(play::LevelParticles {
+ particle,
+ override_limiter: false,
+ always_show: false,
+ pos: at,
+ dist: [0.0; 3],
+ max_speed: [0.0; 3],
+ count: 0,
+ randomization: 0,
+ });
+ for g in host.hub.guests.iter().filter(|g| host.hub.here(g)) {
+ // ServerLevel compares the player's block centre, strictly within 32.
+ let distance: f64 = (0..3)
+ .map(|k| (g.position[k].floor() + 0.5 - at[k]).powi(2))
+ .sum();
+ if distance < 32.0 * 32.0 {
+ g.send(&packet);
+ }
+ }
+ }
+
+ /// `LivingEntity.checkFallDamage`'s `ServerLevel.sendParticles` of the
+ /// landing block's crumbs: drawn in this window, when it has one, and
+ /// sent to each player within 32 blocks. `host` is the hub of a guest's
+ /// turn, which is out of `self.lan` meanwhile.
+ pub(super) fn landing_dust(
+ &mut self,
+ host: Option<&LanHost>,
+ state: BlockStateId,
+ at: Vec3,
+ count: i32,
+ speed: f64,
+ ) {
+ let at = [at.x, at.y, at.z];
+ if self.serving.is_none() && self.options.dedicated.is_none() {
+ let block = [
+ at[0].floor() as i32,
+ (at[1] - 0.2).floor() as i32,
+ at[2].floor() as i32,
+ ];
+ if let Some((sprite, tint)) = self.particle_sprite(state, block) {
+ self.particles.send_particles(
+ &ParticleOptions::block(ParticleType::Block, sprite, tint),
+ at,
+ [0.0; 3],
+ speed,
+ count as u32,
+ );
+ }
+ }
+ let Some(hub) = host.or(self.lan.as_ref()).map(|h| &h.hub) else {
+ return;
+ };
+ let Some(particle) = Self::hub_particle(
+ hub,
+ &ParticleOptions::simple(ParticleType::Block),
+ Some(state),
+ ) else {
+ return;
+ };
+ let packet = C::LevelParticles(play::LevelParticles {
+ particle,
+ override_limiter: false,
+ always_show: false,
+ pos: at,
+ dist: [0.0; 3],
+ max_speed: [speed as f32; 3],
+ count,
+ randomization: 0,
+ });
+ for g in hub.guests.iter().filter(|g| hub.here(g)) {
+ // ServerLevel compares the player's block centre, strictly within 32.
+ let distance: f64 = (0..3)
+ .map(|k| (g.position[k].floor() + 0.5 - at[k]).powi(2))
+ .sum();
+ if distance < 32.0 * 32.0 {
+ g.send(&packet);
+ }
+ }
+ }
+
/// `ParticleTypes.STREAM_CODEC`'s value for `options`: the type's
/// network id and the data it carries (`state` for the block particles).
/// None while not serving, or for a particle whose data isn't sent from
@@ -33,13 +150,19 @@ impl Game<'_> {
&self,
options: &ParticleOptions,
state: Option,
+ ) -> Option {
+ Self::hub_particle(&self.lan.as_ref()?.hub, options, state)
+ }
+
+ /// `network_particle` for a hub that is out of `self.lan` meanwhile (a
+ /// guest's turn).
+ fn hub_particle(
+ hub: &Hub,
+ options: &ParticleOptions,
+ state: Option,
) -> Option {
let name = format!("minecraft:{}", options.ty.name());
- let id = self
- .lan
- .as_ref()?
- .hub
- .registry_id("minecraft:particle_type", &name)?;
+ let id = hub.registry_id("minecraft:particle_type", &name)?;
use ParticleType as T;
let c = options.color;
let data = match options.ty {
@@ -68,7 +191,11 @@ impl Game<'_> {
/// The options a server's particle stands for (None for a type or data
/// this client doesn't draw).
- fn received_particle(&mut self, p: &Particle, at: [f64; 3]) -> Option {
+ pub(super) fn received_particle(
+ &mut self,
+ p: &Particle,
+ at: [f64; 3],
+ ) -> Option {
let name = self
.remote
.as_ref()?
@@ -194,8 +321,14 @@ impl Game<'_> {
/// `ServerLevel.explode`'s packet to each player within 64 blocks. The
/// sound and the push reach them on their own (the level's sounds, the
/// motion a hurt player is sent), so the packet carries neither.
- pub(super) fn lan_explode(&self, center: [f64; 3], radius: f32, block_count: usize) {
- let emitter = if radius < 2.0 {
+ pub(super) fn lan_explode(
+ &self,
+ center: [f64; 3],
+ small: bool,
+ radius: f32,
+ block_count: usize,
+ ) {
+ let emitter = if small {
"minecraft:explosion"
} else {
"minecraft:explosion_emitter"
diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs
index 467c4537c..65520221a 100644
--- a/crates/horizon-client/src/game/lan_pvp.rs
+++ b/crates/horizon-client/src/game/lan_pvp.rs
@@ -32,9 +32,13 @@ pub(super) enum Victim {
/// The attacker's side of the hit.
pub(super) struct Strike {
+ /// The attacking guest, kept after their turn through `as_guest` ends.
+ attacker: Option,
amount: f32,
scale: f32,
crit: bool,
+ /// `Player.attack`'s `magicBoost > 0`: the enchantments added damage.
+ magic: bool,
from: [f64; 3],
sweep: Option<[f64; 3]>,
/// `causeExtraKnockback`: its strength and direction (the attacker's
@@ -107,7 +111,7 @@ impl Game<'_> {
pub(super) fn pvp_strike(&mut self) -> Option {
let p = self.player.as_ref()?;
let from = [p.position.x, p.position.y, p.position.z];
- let (amount, scale, crit) = self.melee_damage("minecraft:player");
+ let (amount, scale, crit, magic) = self.melee_damage("minecraft:player");
let sweep = self.sweep_attack_position(scale, crit);
let (strength, knockback_attack) = self.extra_knockback("minecraft:player", scale);
let (xd, zd) = self.extra_knockback_direction();
@@ -119,9 +123,11 @@ impl Game<'_> {
}
self.swing_arm();
Some(Strike {
+ attacker: self.lan_acting,
amount,
scale,
crit,
+ magic,
from,
sweep,
knockback: (strength, xd, zd),
@@ -242,14 +248,50 @@ impl Game<'_> {
if hurt && strength > 0.0 {
g.knock_back_player(f64::from(strength), xd, zd);
}
- hurt
+ // The victim's thorns, dealt to the attacker below.
+ let thorns = if hurt { g.thorns_damage() } else { Vec::new() };
+ (hurt, thorns)
};
- let hurt = self.ui.rules.bool("pvp")
- && harm
- && match victim {
+ let (hurt, thorns) = if self.ui.rules.bool("pvp") && harm {
+ match victim {
Victim::Host => land(self),
- Victim::Guest(conn) => self.guest_struck_by(host, conn, land).unwrap_or(false),
+ Victim::Guest(conn) => self.guest_struck_by(host, conn, land).unwrap_or_default(),
+ }
+ } else {
+ Default::default()
+ };
+ if hurt && (s.crit || s.magic) {
+ let target = match victim {
+ Victim::Host => self.player.as_ref().map(|p| (host.host_entity, p)),
+ Victim::Guest(conn) => host
+ .hub
+ .guest(conn)
+ .and_then(|g| g.motion.as_deref().map(|p| (g.entity_id, p))),
};
+ if let Some((id, p)) = target {
+ let d = p.dimensions;
+ let (feet, width, height) = (
+ [p.position.x, p.position.y, p.position.z],
+ f64::from(d.width),
+ f64::from(d.height),
+ );
+ if s.crit {
+ self.critical_hit(s.attacker, id, feet, width, height, false);
+ }
+ if s.magic {
+ self.critical_hit(s.attacker, id, feet, width, height, true);
+ }
+ }
+ }
+ // `Enchantment.doPostAttack`: thorns hurt the attacking player.
+ for damage in thorns {
+ match s.attacker {
+ None => self.hurt_player_by("minecraft:thorns", damage),
+ Some(conn) => {
+ self.guest_hit_by(host, conn, |g| g.hurt_player_by("minecraft:thorns", damage));
+ }
+ }
+ }
let sound = match (hurt, s.crit, s.scale > 0.9) {
(false, ..) => "minecraft:entity.player.attack.nodamage",
(true, true, _) => "minecraft:entity.player.attack.crit",
diff --git a/crates/horizon-client/src/game/lan_quiet.rs b/crates/horizon-client/src/game/lan_quiet.rs
new file mode 100644
index 000000000..63d382c02
--- /dev/null
+++ b/crates/horizon-client/src/game/lan_quiet.rs
@@ -0,0 +1,165 @@
+//! Quiet commands (`horizon_protocol::quiet`): a Horizon client's mod sends a
+//! batch of command lines in one payload, and the server runs each exactly as
+//! that player typing it would (`guest_command`'s checks, the player's own
+//! permission level, at the time it runs) with its output suppressed, as
+//! vanilla's functions run (`CommandSourceStack.withSuppressedOutput`): no
+//! feedback and no failure in anyone's chat. A batch waits in a queue and runs
+//! [`PER_TICK`] lines a player a tick, so a mod can't flood a server; each
+//! finished batch is one line in the server's log.
+use super::{Game, lan::LanHost, lan_actions::GuestCommand};
+use horizon_protocol::quiet;
+use std::collections::{HashMap, VecDeque};
+
+/// Lines a player may have waiting at most; a batch past it loses the rest.
+pub(super) const PENDING: usize = 4096;
+/// Lines run a player a tick at most.
+pub(super) const PER_TICK: usize = 64;
+
+/// A batch waiting to run.
+pub(super) struct QuietBatch {
+ conn: u32,
+ mod_id: String,
+ lines: VecDeque,
+ ran: usize,
+ failed: usize,
+ /// Lines past [`PENDING`], never run.
+ dropped: usize,
+}
+
+impl Game<'_> {
+ /// A `horizon:quiet_commands` payload from `conn`: queued (or logged as
+ /// refused when it breaks the payload's caps).
+ pub(super) fn guest_quiet_commands(&mut self, host: &mut LanHost, conn: u32, data: &[u8]) {
+ let Some(name) = host.hub.guest(conn).map(|g| g.name.clone()) else {
+ return;
+ };
+ let batch = match quiet::decode(data) {
+ Ok(b) => b,
+ Err(e) => {
+ super::dedicated::log(
+ "WARN",
+ &format!("{name} sent quiet commands that were refused: {e}"),
+ );
+ return;
+ }
+ };
+ let waiting: usize = host
+ .quiet
+ .iter()
+ .filter(|b| b.conn == conn)
+ .map(|b| b.lines.len())
+ .sum();
+ let room = PENDING.saturating_sub(waiting);
+ let dropped = batch.lines.len().saturating_sub(room);
+ host.quiet.push_back(QuietBatch {
+ conn,
+ mod_id: batch.mod_id,
+ lines: batch.lines.into_iter().take(room).collect(),
+ ran: 0,
+ failed: 0,
+ dropped,
+ });
+ }
+
+ /// The waiting batches, [`PER_TICK`] lines a player this tick, in order.
+ pub(super) fn run_quiet_commands(&mut self) {
+ let mut left: HashMap = HashMap::new();
+ let mut i = 0;
+ loop {
+ let Some(host) = self.lan.as_mut() else {
+ return;
+ };
+ let Some(batch) = host.quiet.get_mut(i) else {
+ return;
+ };
+ let conn = batch.conn;
+ let budget = left.entry(conn).or_insert(PER_TICK);
+ let gone = host.hub.guest(conn).is_none();
+ if gone || batch.lines.is_empty() {
+ let batch = host.quiet.remove(i).expect("got it above");
+ if !gone {
+ let name = host
+ .hub
+ .guest(conn)
+ .map_or(String::new(), |g| g.name.clone());
+ super::dedicated::log("INFO", &summary(&name, &batch));
+ }
+ continue;
+ }
+ if *budget == 0 {
+ i += 1;
+ continue;
+ }
+ *budget -= 1;
+ let line = batch.lines.pop_front().expect("not empty");
+ let ok = self.run_quiet_line(conn, &line);
+ if let Some(batch) = self.lan.as_mut().and_then(|h| h.quiet.get_mut(i)) {
+ batch.ran += 1;
+ batch.failed += usize::from(!ok);
+ }
+ }
+ }
+
+ /// One line as `guest_command` would run it for `conn`, quietly. False
+ /// when it is refused or fails. A command that carries a chat message
+ /// (`say`, `msg`...) is refused: it would need the player's signature.
+ fn run_quiet_line(&mut self, conn: u32, line: &str) -> bool {
+ let allowed = self.options.dedicated.is_some() || self.allow_commands();
+ let Some(host) = self.lan.as_ref() else {
+ return false;
+ };
+ let integrated = host.hub.config.integrated;
+ if !integrated && (!host.settings.guest_commands || !allowed) {
+ return false;
+ }
+ let Some(permission) = host.hub.guest(conn).map(|g| g.permission) else {
+ return false;
+ };
+ let command = line.trim_start_matches('/');
+ if !self.signable_arguments(permission, command).is_empty() {
+ return false;
+ }
+ self.run_guest_command(GuestCommand {
+ conn,
+ command: command.to_owned(),
+ permission,
+ integrated,
+ quiet: true,
+ })
+ }
+}
+
+/// The batch's line in the server's log.
+fn summary(name: &str, b: &QuietBatch) -> String {
+ let mut line = format!(
+ "{name} ran {} quiet command(s) from mod {}: {} failed",
+ b.ran, b.mod_id, b.failed
+ );
+ if b.dropped > 0 {
+ line += &format!(", {} dropped (more than {PENDING} waiting)", b.dropped);
+ }
+ line
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_log_line_counts_the_batch() {
+ let b = QuietBatch {
+ conn: 1,
+ mod_id: "orbital".into(),
+ lines: VecDeque::new(),
+ ran: 12,
+ failed: 3,
+ dropped: 0,
+ };
+ assert_eq!(
+ summary("Alex", &b),
+ "Alex ran 12 quiet command(s) from mod orbital: 3 failed"
+ );
+ let b = QuietBatch { dropped: 5, ..b };
+ assert!(summary("Alex", &b).ends_with(", 5 dropped (more than 4096 waiting)"));
+ }
+}
diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs
index 1bec9809d..7beeeba2f 100644
--- a/crates/horizon-client/src/game/lan_trading.rs
+++ b/crates/horizon-client/src/game/lan_trading.rs
@@ -144,15 +144,16 @@ impl Game<'_> {
.offers
.iter()
.filter_map(|o| {
- let cost =
- |st: &ItemStack, hub: &mut horizon_client::lan::hub::Hub| play::NetCost {
- item: hub.item_id(&st.item),
- count: st.count as i32,
- };
+ let cost = |st: &ItemStack, hub: &mut horizon_client::lan::hub::Hub| {
+ hub.stack(&Some(st.clone())).map(play::NetCost::from)
+ };
Some(play::NetOffer {
- cost_a: cost(&o.base_cost_a.stack, &mut host.hub),
+ cost_a: cost(&o.base_cost_a.stack, &mut host.hub)?,
result: host.hub.stack(&Some(o.result.clone()))?,
- cost_b: o.cost_b.as_ref().map(|b| cost(&b.stack, &mut host.hub)),
+ cost_b: match &o.cost_b {
+ Some(b) => Some(cost(&b.stack, &mut host.hub)?),
+ None => None,
+ },
out_of_stock: o.out_of_stock(),
uses: o.uses,
max_uses: o.max_uses,
diff --git a/crates/horizon-client/src/game/lan_vehicles.rs b/crates/horizon-client/src/game/lan_vehicles.rs
index f16a1e37d..00795aa62 100644
--- a/crates/horizon-client/src/game/lan_vehicles.rs
+++ b/crates/horizon-client/src/game/lan_vehicles.rs
@@ -56,6 +56,13 @@ impl Game<'_> {
let (lo, hi) = corners(a.bounds());
return Some((lo, hi, at(a.position)));
}
+ if let Some(c) = self.cushions.iter().find(|c| c.id == id) {
+ let (lo, hi) = corners(Aabb::new(
+ Vec3::new(c.position.x - 0.5, c.position.y, c.position.z - 0.5),
+ Vec3::new(c.position.x + 0.5, c.position.y + 0.25, c.position.z + 0.5),
+ ));
+ return Some((lo, hi, at(c.position)));
+ }
if let Some(f) = self.item_frames.iter().find(|f| f.id == id) {
let (lo, hi) = f.bounds();
return Some((lo, hi, centre(f.pos)));
@@ -98,9 +105,10 @@ impl Game<'_> {
let boat = self.boats.iter().position(|b| b.id == vehicle);
let cart = self.carts.iter().any(|c| c.id == vehicle);
let mount = self.mobs.iter().any(|m| m.id == vehicle);
+ let cushion = self.cushions.iter().any(|c| c.id == vehicle);
// The vehicle is gone (broken, in another level) or the rider died:
// its client drops it with the entity or the death screen.
- if dead || (boat.is_none() && !cart && !mount) {
+ if dead || (boat.is_none() && !cart && !mount && !cushion) {
let g = &mut host.hub.guests[gi];
(g.vehicle, g.vehicle_good) = (None, None);
return;
@@ -115,6 +123,17 @@ impl Game<'_> {
// Getting out goes through leave_guest, which tells the client and
// teleports it (ServerPlayer.dismountTo).
let seat = self.as_guest(host, conn, |game| {
+ // A cushion does not move: the rider sits on it until it sneaks
+ // (`Cushion.removePassenger` plays the get-up sound).
+ if game.cushions.iter().any(|c| Some(c.id) == game.riding) {
+ if keys.shift {
+ game.tick_cushion_riding(keys);
+ return None;
+ }
+ let c = game.cushions.iter().find(|c| Some(c.id) == game.riding)?;
+ let p = c.seat();
+ return Some([p.x, p.y, p.z]);
+ }
if let Some(i) = game.boats.iter().position(|b| Some(b.id) == game.riding) {
if keys.shift {
game.dismount(i);
@@ -168,6 +187,12 @@ impl Game<'_> {
.iter()
.find(|c| c.id == vehicle)
.map(|c| (c.position, c.position.add_vector(Vec3::new(0.0, SEAT, 0.0))))
+ })
+ .or_else(|| {
+ self.cushions
+ .iter()
+ .find(|c| c.id == vehicle)
+ .map(|c| (c.position, c.seat()))
});
if let Some((p, seat)) = at {
let g = &mut host.hub.guests[gi];
diff --git a/crates/horizon-client/src/game/leads.rs b/crates/horizon-client/src/game/leads.rs
index 8867157ee..ca70351c6 100644
--- a/crates/horizon-client/src/game/leads.rs
+++ b/crates/horizon-client/src/game/leads.rs
@@ -104,6 +104,9 @@ impl Game<'_> {
};
let m = &mut self.mobs[i];
if let Some(h) = holder {
+ if h == Holder::Player {
+ m.extra.leash_player = Some(player_uuid);
+ }
m.extra.leash = Some(h);
m.extra.leash_pending = None;
} else if m.age > 100 {
@@ -201,7 +204,9 @@ impl Game<'_> {
if self.mobs[index].extra.leash.is_some() {
self.break_leash(id, true, false);
}
+ let holder = self.acting_player_uuid();
self.mobs[index].extra.leash = Some(Holder::Player);
+ self.mobs[index].extra.leash_player = Some(holder);
self.lead_sound("tied", at);
// The lead is always used up.
if let Some(stack) = self.held_mut().as_mut() {
diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs
index e6593e7b9..e73cfdb01 100644
--- a/crates/horizon-client/src/game/level_particles.rs
+++ b/crates/horizon-client/src/game/level_particles.rs
@@ -4,6 +4,7 @@
//! off (3004) and scraping (3005), plus the smoke, drips, egg and dragon
//! fireball particles of 1501, 1502, 1504, 2006, 2009, 2012 and 3009.
use super::Game;
+use horizon_client::items::ItemStack;
use horizon_client::particles::{self, ParticleOptions, ParticleType};
use horizon_core::{geometry::trig, position::BlockPos, random::RandomSource};
use horizon_world::level::LevelEvent;
@@ -309,6 +310,68 @@ impl Game<'_> {
// Each guest plays it from the global packet.
self.audio.play_unshared(sound, at, volume, 1.0);
}
+ /// `LevelEventHandler.potionSplashParticles` (2002 with `Effect`, 2007
+ /// with `InstantEffect`): eight splash potion crumbs, and a hundred
+ /// spell particles in the potion's colour `data`, flung out in a disc.
+ pub(super) fn potion_splash_particles(&mut self, pos: BlockPos, data: i32, instant: bool) {
+ let ty = if instant {
+ ParticleType::InstantEffect
+ } else {
+ ParticleType::Effect
+ };
+ // Vec3.atBottomCenterOf.
+ let at = [
+ f64::from(pos.x) + 0.5,
+ f64::from(pos.y),
+ f64::from(pos.z) + 0.5,
+ ];
+ let crumb = self.item_particle(&ItemStack::new("minecraft:splash_potion", 1));
+ let r = self.particles.level_random();
+ let crumbs: Vec<[f64; 3]> = (0..8)
+ .map(|_| {
+ [
+ r.next_gaussian() * 0.15,
+ r.next_double() * 0.2,
+ r.next_gaussian() * 0.15,
+ ]
+ })
+ .collect();
+ for v in crumbs {
+ self.particles.add(&crumb, at, v);
+ }
+ let channel = |shift: i32| ((data >> shift) & 0xFF) as f32 / 255.0;
+ let color = [channel(16), channel(8), channel(0)];
+ for _ in 0..100 {
+ let r = self.particles.level_random();
+ let dist = r.next_double() * 4.0;
+ let angle = r.next_double() * std::f64::consts::PI * 2.0;
+ let velocity = [
+ angle.cos() * dist,
+ 0.01 + r.next_double() * 0.5,
+ angle.sin() * dist,
+ ];
+ let brightness = 0.75 + r.next_float() * 0.25;
+ let options = ParticleOptions {
+ color: [
+ color[0] * brightness,
+ color[1] * brightness,
+ color[2] * brightness,
+ 1.0,
+ ],
+ scale: dist as f32,
+ ..ParticleOptions::simple(ty)
+ };
+ self.particles.add(
+ &options,
+ [
+ at[0] + velocity[0] * 0.1,
+ at[1] + 0.3,
+ at[2] + velocity[2] * 0.1,
+ ],
+ velocity,
+ );
+ }
+ }
/// Queue and play level event `id` at `pos` (`Level.levelEvent`).
pub(super) fn level_event_at(&mut self, id: i32, pos: [i32; 3], data: i32) {
self.level_events.push(LevelEvent::LevelEvent {
diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs
index e8a8cfb59..5f0286d02 100644
--- a/crates/horizon-client/src/game/levels.rs
+++ b/crates/horizon-client/src/game/levels.rs
@@ -3,8 +3,8 @@
//! The game's tick code reads one level: the one in place, held in `Game`'s
//! own fields (the world, its streaming and save, block ticks, entities).
//! A server (the dedicated server and single player's server thread) keeps
-//! the other dimensions' levels here and ticks each one that has players by
-//! swapping it into place (`enter_level`), the way `as_guest` swaps a player
+//! the other dimensions' levels here and ticks each one with players or forced
+//! chunks by swapping it into place (`enter_level`), the way `as_guest` swaps a player
//! in, so the tick code runs unchanged, one level at a time. The in-frame
//! game holds one level, which follows its player (`enter_dimension`).
//!
@@ -50,6 +50,7 @@ pub(super) struct Parked {
paintings: Vec,
item_frames: Vec,
armor_stands: Vec,
+ cushions: Vec,
others: Vec,
boats: Vec,
carts: Vec,
@@ -74,6 +75,7 @@ pub(super) struct Parked {
lan_events: Vec<(i32, [i32; 3], i32, Option)>,
lan_block_events: Vec<([i32; 3], i32, i32, u32)>,
lan_entity_events: Vec<(i32, i8, [f64; 3])>,
+ lan_critical_hits: Vec<(Option, i32, bool)>,
/// Only the per-level parts of these are used (`swap_level`).
anims: BlockEntityAnims,
raiding: Raiding,
@@ -107,6 +109,19 @@ pub(super) struct Levels {
parked: HashMap,
}
+impl Levels {
+ /// The chunks of each level not in place (capability `world` lends
+ /// them to server mods for a call).
+ #[cfg_attr(not(feature = "mods"), allow(dead_code))]
+ pub(super) fn parked_chunks(
+ &mut self,
+ ) -> impl Iterator- {
+ self.parked
+ .iter_mut()
+ .map(|(d, p)| (*d, &mut p.world.chunks))
+ }
+}
+
impl Game<'_> {
/// A new level for `dim`, opened from the save (`MinecraftServer.createLevels`).
fn open_level(&self, dim: Dim) -> Result
{
@@ -135,6 +150,7 @@ impl Game<'_> {
paintings: Vec::new(),
item_frames: Vec::new(),
armor_stands: Vec::new(),
+ cushions: Vec::new(),
others: Vec::new(),
boats: Vec::new(),
carts: Vec::new(),
@@ -159,6 +175,7 @@ impl Game<'_> {
lan_events: Vec::new(),
lan_block_events: Vec::new(),
lan_entity_events: Vec::new(),
+ lan_critical_hits: Vec::new(),
anims: Default::default(),
raiding: Default::default(),
sculk: Default::default(),
@@ -175,6 +192,7 @@ impl Game<'_> {
let mut locator = self.end.locator();
swap(&mut locator, &mut p.locator);
self.end.set_locator(locator);
+ self.share_spawn_conditions();
swap(&mut self.save, &mut p.save);
swap(&mut self.block_ticks, &mut p.block_ticks);
swap(&mut self.tick_chunks, &mut p.tick_chunks);
@@ -185,6 +203,7 @@ impl Game<'_> {
swap(&mut self.paintings, &mut p.paintings);
swap(&mut self.item_frames, &mut p.item_frames);
swap(&mut self.armor_stands, &mut p.armor_stands);
+ swap(&mut self.cushions, &mut p.cushions);
swap(&mut self.others, &mut p.others);
swap(&mut self.boats, &mut p.boats);
swap(&mut self.carts, &mut p.carts);
@@ -209,6 +228,7 @@ impl Game<'_> {
swap(&mut self.lan_events, &mut p.lan_events);
swap(&mut self.lan_block_events, &mut p.lan_block_events);
swap(&mut self.lan_entity_events, &mut p.lan_entity_events);
+ swap(&mut self.lan_critical_hits, &mut p.lan_critical_hits);
let (a, b) = (&mut self.be_anims, &mut p.anims);
swap(&mut a.chests, &mut b.chests);
swap(&mut a.books, &mut b.books);
@@ -219,6 +239,7 @@ impl Game<'_> {
swap(&mut a.pots, &mut b.pots);
swap(&mut a.gateways, &mut b.gateways);
swap(&mut a.gateway_servers, &mut b.gateway_servers);
+ swap(&mut a.conduit_servers, &mut b.conduit_servers);
self.raiding.swap_level(&mut p.raiding);
self.sculk.swap_level(&mut p.sculk);
self.creaking.swap_level(&mut p.creaking);
@@ -287,8 +308,8 @@ impl Game<'_> {
}
/// One server tick (`MinecraftServer.tickServer`): each level with
- /// players in turn (`tickChildren`), its chunks streamed and loaded and
- /// its world ticked. The first pass reads the network and runs the
+ /// players or forced chunks in turn (`tickChildren`), its chunks streamed
+ /// and loaded and its world ticked. The first pass reads the network and runs the
/// tick's shared parts (the clock, the weather, functions, the autosave);
/// the next ones only their level. While `paused`, only the connections
/// run.
@@ -307,6 +328,8 @@ impl Game<'_> {
};
self.update_dedicated_streaming();
self.update_world();
+ // What server mods set in this level since its last tick.
+ self.apply_mod_block_writes();
result = if paused {
self.tick_lan(true);
Ok(())
@@ -377,7 +400,8 @@ impl Game<'_> {
}
*next += self.clock.tick_duration();
if *next > now {
- // A `/pregen` task keeps the workers fed until the next tick.
+ // A `/pregen` task or force-loaded chunks keep the workers fed
+ // until the next tick.
self.pump_pregen(*next);
let now = Instant::now();
if *next > now {
@@ -390,7 +414,7 @@ impl Game<'_> {
/// The levels this server tick runs, in `MinecraftServer.levels` order
/// (the Overworld, the Nether, the End): every level with a player in
- /// it or a `/pregen` task, or the Overworld while nobody is online.
+ /// it, forced chunks or a `/pregen` task, or the Overworld while idle.
pub(super) fn levels_to_tick(&self) -> Vec {
let guests = self
.lan
@@ -399,7 +423,17 @@ impl Game<'_> {
let mut dims: Vec = [Dim::Overworld, Dim::Nether, Dim::End]
.into_iter()
.filter(|d| {
- guests.iter().any(|g| g.dimension == d.id()) || self.pregen_level() == Some(*d)
+ let forced = if *d == self.dim {
+ !self.streaming.forced.is_empty()
+ } else {
+ self.levels
+ .parked
+ .get(d)
+ .is_some_and(|p| !p.streaming.forced.is_empty())
+ };
+ guests.iter().any(|g| g.dimension == d.id())
+ || forced
+ || self.pregen_level() == Some(*d)
})
.collect();
if dims.is_empty() {
diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs
index 916bd2a0a..8a3ac2745 100644
--- a/crates/horizon-client/src/game/lightning.rs
+++ b/crates/horizon-client/src/game/lightning.rs
@@ -74,14 +74,74 @@ impl Game<'_> {
self.spawn_bolt(at, trap);
}
}
- /// `findLightningTargetAround`: a living entity under open sky in the
- /// column (3 blocks around), else the top of the column.
+ /// `ServerLevel.findLightningRod`: `PoiManager.findClosest` over the
+ /// lightning rod points of interest within 128 blocks of `center` whose
+ /// block is the top (`WORLD_SURFACE`) of its column; the strike lands one
+ /// above it. Horizon keeps no point-of-interest index, so this scans the
+ /// loaded chunks the way `/locate poi` does.
+ fn find_lightning_rod(&self, center: [i32; 3]) -> Option<[i32; 3]> {
+ const RANGE: i32 = 128;
+ let facts = self.res.facts();
+ let mut is_rod: std::collections::HashMap = std::collections::HashMap::new();
+ let mut best: Option<(i64, [i32; 3])> = None;
+ let (cx0, cz0) = ((center[0] - RANGE) >> 4, (center[2] - RANGE) >> 4);
+ let (cx1, cz1) = ((center[0] + RANGE) >> 4, (center[2] + RANGE) >> 4);
+ for cx in cx0..=cx1 {
+ for cz in cz0..=cz1 {
+ let Some(chunk) = self.world.chunks.get(&(cx, cz)) else {
+ continue;
+ };
+ for (i, section) in chunk.sections.iter().enumerate() {
+ let mut rod = |state: u32| {
+ *is_rod.entry(state).or_insert_with(|| {
+ facts
+ .get(horizon_world::registry::BlockStateId(state))
+ .name
+ .ends_with("lightning_rod")
+ })
+ };
+ if !section.blocks.maybe_has(&mut rod) {
+ continue;
+ }
+ let base_y = horizon_client::chunk::MIN_Y + 16 * i as i32;
+ for j in 0..4096 {
+ if !rod(section.get(j)) {
+ continue;
+ }
+ let p = [
+ cx * 16 + (j & 15) as i32,
+ base_y + (j >> 8) as i32,
+ cz * 16 + ((j >> 4) & 15) as i32,
+ ];
+ let d = [p[0] - center[0], p[1] - center[1], p[2] - center[2]]
+ .map(|d| i64::from(d) * i64::from(d))
+ .iter()
+ .sum::();
+ if d > i64::from(RANGE * RANGE) || best.is_some_and(|(b, _)| d >= b) {
+ continue;
+ }
+ let surface = self.world.world_surface(p[0], p[2], |s| facts.is_air(s));
+ if p[1] == surface - 1 {
+ best = Some((d, p));
+ }
+ }
+ }
+ }
+ }
+ best.map(|(_, p)| [p[0], p[1] + 1, p[2]])
+ }
+ /// `findLightningTargetAround`: the closest lightning rod, else a living
+ /// entity under open sky in the column (3 blocks around), else the top of
+ /// the column.
fn lightning_target(&mut self, x: i32, z: i32) -> Option<[i32; 3]> {
if !self.world.loaded(x, z) {
return None;
}
let top =
self.with_level(|b, level, _| b.motion_blocking_top(level, BlockPos::new(x, 0, z)));
+ if let Some(rod) = self.find_lightning_rod([x, top.y, z]) {
+ return Some(rod);
+ }
let sees_sky = |g: &Self, p: [i32; 3]| g.world.light(p[0], p[1], p[2]) >> 4 == 15;
let mut candidates: Vec<[i32; 3]> = self
.mobs
@@ -162,11 +222,9 @@ impl Game<'_> {
converted: Vec::new(),
});
}
- /// `spawnFire`: fire at the strike point and `extra` random neighbours.
+ /// `spawnFire`: fire at the strike point and `extra` random neighbours,
+ /// wherever `BaseFireBlock.getState` fire can survive.
fn bolt_fire(&mut self, at: [f64; 3], extra: i32) {
- if self.ui.difficulty < 2 {
- return;
- }
let base = [
at[0].floor() as i32,
at[1].floor() as i32,
@@ -183,18 +241,13 @@ impl Game<'_> {
if !self.res.facts().is_air(state) {
continue;
}
- // BaseFireBlock.getState: soul fire on soul soil and sand.
- let below = self.res.facts().get(self.world.block(p[0], p[1] - 1, p[2]));
- let name = if matches!(&*below.name, "minecraft:soul_soil" | "minecraft:soul_sand") {
- "minecraft:soul_fire"
- } else {
- "minecraft:fire"
- };
- // FireBlock.canSurvive: a sturdy floor (flammable neighbours aside).
- if below.sturdy_full >> 1 & 1 == 0 {
- continue;
- }
- if let Some(fire) = self.pack.assets.registry.default_state(name) {
+ // BaseFireBlock.getState and FireBlock/SoulFireBlock.canSurvive.
+ let at = BlockPos::new(p[0], p[1], p[2]);
+ let fire = self.with_level(|b, level, ticks| {
+ let fire = b.fire_state_for(level, ticks, at);
+ b.can_survive(level, ticks, at, fire).then_some(fire)
+ });
+ if let Some(fire) = fire {
let _ = self.level_set(p, fire);
}
}
@@ -219,7 +272,10 @@ impl Game<'_> {
pitch,
);
if !b.visual_only {
- self.bolt_fire(b.at, 4);
+ // Only Normal and Hard start fires with the strike itself.
+ if self.ui.difficulty >= 2 {
+ self.bolt_fire(b.at, 4);
+ }
self.strike_rod(b.at);
}
}
diff --git a/crates/horizon-client/src/game/mace.rs b/crates/horizon-client/src/game/mace.rs
index 8ad5e76c3..34c968980 100644
--- a/crates/horizon-client/src/game/mace.rs
+++ b/crates/horizon-client/src/game/mace.rs
@@ -24,7 +24,7 @@ const KNOCKBACK_POWER: f32 = 0.7;
/// `Entity.isAlliedTo` between the player (`player` its UUID) and a mob
/// without teams: `TamableAnimal.considersEntityAsAlly` (a pet it tamed) and
/// `Allay.considersEntityAsAlly` (an allay that likes it).
-fn ally_of_player(m: &Mob, player: Option<[i32; 4]>) -> bool {
+pub(super) fn ally_of_player(m: &Mob, player: Option<[i32; 4]>) -> bool {
let tamable = matches!(
m.species(),
Species::Wolf
diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs
index 8742962e9..bb936744b 100644
--- a/crates/horizon-client/src/game/machines.rs
+++ b/crates/horizon-client/src/game/machines.rs
@@ -159,8 +159,10 @@ impl Containers<'_> {
});
}
let entity = self.world.block_entities.get(&pos)?;
- // A beehive keeps bees, not items: it is no `Container`.
- if matches!(entity, BlockEntity::Beehive(_)) {
+ // A beehive keeps bees, not items, and a campfire cooks its own: neither
+ // is a `Container` (HopperBlockEntity.getContainerAt), so a dropper drops
+ // in front of them and a hopper leaves them alone.
+ if matches!(entity, BlockEntity::Beehive(_) | BlockEntity::Campfire(_)) {
return None;
}
let kind = match (entity, name) {
diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs
index a19b6df73..072059e49 100644
--- a/crates/horizon-client/src/game/minecarts.rs
+++ b/crates/horizon-client/src/game/minecarts.rs
@@ -87,9 +87,12 @@ pub(super) struct Minecart {
pub fuse: i32,
/// Hopper minecarts: an unpowered activator rail enables them.
pub enabled: bool,
+ /// Chest minecarts: the loot table rolled into `items` on load, saved
+ /// again while the items are still that roll.
+ pub loot: Option