diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 39ea920da..b2fd9fa48 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -144,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 70fb33796..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: 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 e1fa9e7fe..4d2a258ec 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,7 +34,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` | @@ -118,16 +120,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/Cargo.lock b/Cargo.lock index 809df3a5a..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,6 +1372,8 @@ dependencies = [ "glam", "horizon-assets", "horizon-bench", + "horizon-client-core", + "horizon-command", "horizon-core", "horizon-dualsense", "horizon-friends", @@ -1396,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" @@ -2971,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 59bfe5e33..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-hdr", "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/crates/cargo-horizon-mod/src/check.rs b/crates/cargo-horizon-mod/src/check.rs index 33095a115..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 { @@ -266,8 +266,17 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> { 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-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 99% rename from crates/horizon-client/src/block_entity_nbt.rs rename to crates/horizon-client-core/src/block_entity_nbt.rs index a4c02ba3b..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(), 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 f1011c534..5611edbc9 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -9,6 +9,8 @@ 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" } diff --git a/crates/horizon-client/examples/probe/entity_anim_fixture.rs b/crates/horizon-client/examples/probe/entity_anim_fixture.rs index 4aceb9f6f..4582033fe 100644 --- a/crates/horizon-client/examples/probe/entity_anim_fixture.rs +++ b/crates/horizon-client/examples/probe/entity_anim_fixture.rs @@ -592,6 +592,7 @@ pub fn main() -> horizon_client::Result<()> { pose, num("maxCrossbowChageDuration"), num("ticksUsingItem"), + false, ); } Species::Evoker | Species::Illusioner | Species::Pillager | Species::Vindicator => { diff --git a/crates/horizon-client/examples/probe/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs index ecdf02901..5b6c26d2f 100644 --- a/crates/horizon-client/examples/probe/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -1057,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, 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/src/biome.rs b/crates/horizon-client/src/biome.rs index c8c15e44e..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}; @@ -33,6 +33,8 @@ pub struct BiomeInfo { 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, @@ -45,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, @@ -135,6 +157,7 @@ impl Biomes { .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/entities.rs b/crates/horizon-client/src/entities.rs index 69e053411..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 { diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 7f3565067..c49af48c9 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -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; @@ -1913,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), @@ -1922,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); } } @@ -1992,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), @@ -2027,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) { @@ -2077,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/game.rs b/crates/horizon-client/src/game.rs index a51bdcbcb..bbb40921b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -102,7 +102,12 @@ mod maps; mod minecarts; mod mob_blocks; mod mob_gear; +mod mod_browser; +#[cfg(feature = "mods")] +mod mod_browser_recipes; mod mod_input; +#[cfg(feature = "mods")] +mod mod_recipes; mod mod_render; mod mods; mod mount_menu; @@ -186,6 +191,7 @@ mod win; mod wind; mod wither; mod world_loading; +mod zombie_reinforcements; mod zombie_villagers; use horizon_client::{ Result, @@ -369,7 +375,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); @@ -424,6 +430,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() { @@ -434,7 +450,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()), @@ -2237,8 +2253,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], @@ -2252,9 +2269,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, @@ -2298,11 +2315,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(), @@ -2316,7 +2335,7 @@ 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() { + if thrown_from_hand && self.lan_acting.is_none() { let uuid = self.level.ensure_player_uuid(); self.dropped.last_mut().unwrap().thrower = Some(uuid); } @@ -2925,6 +2944,17 @@ impl Game<'_> { 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, @@ -2950,6 +2980,9 @@ impl Game<'_> { 1501 => Some(("minecraft:block.lava.extinguish", 0.5)), 1009 => Some(("minecraft:block.fire.extinguish", 0.5)), 1502 => Some(("minecraft:block.redstone_torch.burnout", 0.5)), + // LevelEvent.SOUND_ZOMBIE_WOODEN_DOOR (attack, break). + 1019 => Some(("minecraft:entity.zombie.attack_wooden_door", 2.0)), + 1021 => Some(("minecraft:entity.zombie.break_wooden_door", 2.0)), 1030 => Some(("minecraft:block.anvil.use", 1.0)), 1029 => Some(("minecraft:block.anvil.destroy", 1.0)), 1031 => Some(("minecraft:block.anvil.land", 0.3)), @@ -2957,6 +2990,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 { @@ -2966,12 +3001,17 @@ impl Game<'_> { - self.world.random.next_float()) * 0.8 } - 1029 | 1030 | 1042 | 1043 | 1044 => { + 1029 | 1030 | 1042 | 1043 | 1044 | 1053 | 1054 => { self.world.random.next_float() * 0.1 + 0.9 } + 1019 | 1021 => { + (self.world.random.next_float() - self.world.random.next_float()) + * 0.2 + + 1.0 + } _ => 1.0, }; - if matches!(id, 1029 | 1030) { + if matches!(id, 1019 | 1021 | 1029 | 1030 | 1053 | 1054) { // Clients play the anvil sound from its level event; // capturing it also sends a duplicate sound packet. self.audio.play_unshared(name, c, volume, pitch); @@ -3020,11 +3060,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, }); } @@ -3101,6 +3139,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", @@ -3138,6 +3181,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; @@ -4484,12 +4531,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; @@ -4500,9 +4541,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), @@ -4675,7 +4743,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) @@ -4683,6 +4751,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 @@ -4995,7 +5064,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); @@ -5085,7 +5154,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, @@ -5212,12 +5281,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); } } } @@ -5378,6 +5447,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); @@ -5770,6 +5840,7 @@ impl Game<'_> { 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(); @@ -5783,7 +5854,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; @@ -6496,6 +6568,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; } @@ -6679,24 +6754,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 { @@ -6710,6 +6769,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`). @@ -6870,7 +6949,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) { @@ -7917,6 +7996,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); @@ -8039,6 +8121,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), @@ -8104,6 +8187,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(); @@ -8242,6 +8326,7 @@ impl Game<'_> { seed, )?; self.end.set_locator(locator); + self.share_spawn_conditions(); Ok((streaming, save)) } /// Change dimension through a portal (Entity.changeDimension with @@ -8591,15 +8676,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) { @@ -8696,7 +8820,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); } } } @@ -9039,7 +9164,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 }); @@ -9189,8 +9315,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 @@ -9212,6 +9359,8 @@ impl Game<'_> { value, age: 0, on_ground: false, + count: 1, + ticks: 0, }); } fn can_place_used_fire(&mut self, target: [i32; 3]) -> bool { @@ -9288,18 +9437,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) @@ -9311,12 +9473,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] @@ -9324,11 +9496,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 }); @@ -9404,7 +9578,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, @@ -9418,9 +9595,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, @@ -11998,6 +12172,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 @@ -12539,7 +12721,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(), @@ -12906,6 +13095,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(); } 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/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/client_ambient.rs b/crates/horizon-client/src/game/client_ambient.rs index 3ea8f922a..1cf59733d 100644 --- a/crates/horizon-client/src/game/client_ambient.rs +++ b/crates/horizon-client/src/game/client_ambient.rs @@ -4,8 +4,11 @@ //! 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::motion::{LAVA, WATER}; use horizon_client::particles::{ParticleEngine, ParticleOptions, ParticleType}; +use horizon_client::pose::Pose; use horizon_core::{geometry::Vec3, random::RandomSource}; impl Game<'_> { @@ -34,9 +37,96 @@ 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 diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index 106e0e1a1..6e1d5d82b 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -31,6 +31,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, diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 8f934ad8a..22041c3b2 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1697,6 +1697,8 @@ impl Game<'_> { value: 0, age: 0, on_ground: false, + count: 1, + ticks: 0, }); name = Text::translate("entity.minecraft.experience_orb", &[]); } diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index 3f7e4c2a0..d715ce0ab 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 }) }) 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/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 687eb3f88..1ce11755b 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -115,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, 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/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 86a7954e9..319305199 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -193,6 +193,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, @@ -429,6 +430,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; @@ -497,6 +504,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(); @@ -779,7 +788,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 { @@ -815,12 +834,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 { @@ -838,6 +857,47 @@ 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 { @@ -903,16 +963,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); } @@ -943,6 +1011,9 @@ impl Game<'_> { volume, pitch, ); + } else { + // Left for the end of the tick. + t.outbox.push(event); } } } @@ -1045,6 +1116,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]); @@ -1190,6 +1295,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, @@ -1200,6 +1309,7 @@ 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, @@ -1227,19 +1337,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; @@ -1302,6 +1444,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(), @@ -1314,7 +1458,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; @@ -1326,6 +1470,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. @@ -1558,7 +1715,6 @@ impl Game<'_> { r.knockback = Some([p.velocity.x, p.velocity.y, p.velocity.z]); } } - self.hurt_armor(amount); // The thorns hurt the entity that caused the hit, if there is one. if let Some(a) = attacker.or(owner) { self.thorns(a); @@ -2408,12 +2564,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); } } @@ -2422,6 +2580,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); } } }, @@ -2503,21 +2663,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) { @@ -2599,6 +2760,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"); @@ -2888,6 +3050,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 = @@ -3321,6 +3491,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 { @@ -3340,6 +3530,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", diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index 43f41d201..33da8b5ce 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -1131,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/dragon.rs b/crates/horizon-client/src/game/dragon.rs index fff03ef1c..a2602fb96 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -2598,7 +2598,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 diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index 7cdb3e526..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)] @@ -384,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); }; @@ -403,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() }; @@ -456,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. @@ -479,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/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 8800e29d8..687884519 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -316,9 +316,6 @@ impl Game<'_> { ); } } - if outcome.hurt && !creative { - self.hurt_armor(amount); - } if raised { self.after_block(outcome, amount, None, false); } @@ -393,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) { @@ -622,6 +621,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..1f2d932d4 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, @@ -81,16 +113,28 @@ impl Game<'_> { }; 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 fd160a920..38fd74ed8 100644 --- a/crates/horizon-client/src/game/fireworks.rs +++ b/crates/horizon-client/src/game/fireworks.rs @@ -372,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/initial_spawn.rs b/crates/horizon-client/src/game/initial_spawn.rs index 3f7a071bb..7ddb9cb90 100644 --- a/crates/horizon-client/src/game/initial_spawn.rs +++ b/crates/horizon-client/src/game/initial_spawn.rs @@ -126,28 +126,7 @@ impl Game<'_> { 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 +155,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/lan.rs b/crates/horizon-client/src/game/lan.rs index f1298e589..dc1d12a4b 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -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)] @@ -573,10 +586,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() @@ -1139,8 +1149,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(); @@ -1420,6 +1439,7 @@ 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() diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 43bb573dc..dc1e74f0b 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -2183,6 +2183,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; @@ -2252,6 +2253,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); @@ -2279,6 +2281,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); }; @@ -2301,11 +2306,15 @@ 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 { @@ -2394,9 +2403,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); @@ -2659,7 +2672,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_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 529666590..1d9140041 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -304,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)); 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 c41fdf1ad..599a3f637 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -24,6 +24,35 @@ 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. diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index f12aedc5b..9fa53eb25 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -3,6 +3,7 @@ //! consumable's teleport (2017), electric sparks (3002), waxing (3003), wax //! off (3004) and scraping (3005). use super::Game; +use horizon_client::items::ItemStack; use horizon_client::particles::{self, ParticleOptions, ParticleType}; use horizon_core::{position::BlockPos, random::RandomSource}; use horizon_world::level::LevelEvent; @@ -134,6 +135,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 8d2e0a4a2..533b1c3a9 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -109,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 { @@ -179,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); @@ -225,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); @@ -313,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(()) @@ -383,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 { diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 297f372c5..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 diff --git a/crates/horizon-client/src/game/mod_browser.rs b/crates/horizon-client/src/game/mod_browser.rs new file mode 100644 index 000000000..645415ccb --- /dev/null +++ b/crates/horizon-client/src/game/mod_browser.rs @@ -0,0 +1,485 @@ +//! Capability `ui`'s panel beside container screens (WIT `interface +//! browser`, docs/mods.md): the items a recipe viewer mod lists, drawn as +//! the game's own item slots in pages right of the screen's window, with a +//! search box under them. The mod says what the panel holds; the game pages +//! it and tells the mod what the player clicked, typed, and which of the +//! mod's keys went down over an item. With no mod showing a panel, each +//! hook here returns after one check. +use super::Game; +#[cfg(feature = "mods")] +use { + super::Screen, + horizon_client::{ + hud::{HudBatch, rgba}, + items::ItemStack, + ui::EditBox, + }, + horizon_mods::{BrowserClick, BrowserEvent, BrowserStack}, +}; + +#[cfg(not(feature = "mods"))] +impl Game<'_> { + pub(super) fn draw_mod_browser(&mut self, _batch: &mut horizon_client::hud::HudBatch) {} + pub(super) fn mod_browser_press(&mut self, _right: bool) -> bool { + false + } + pub(super) fn mod_browser_typing(&self) -> bool { + false + } + pub(super) fn mod_browser_key(&mut self, _event: &winit::event::KeyEvent) {} + pub(super) fn mod_browser_text(&mut self, _text: Option<&str>, _backspace: bool) {} + pub(super) fn mod_browser_closed(&mut self) {} +} + +/// One slot of the panel, in GUI pixels. +#[cfg(feature = "mods")] +const SLOT: f32 = 18.0; +/// The most columns the panel takes, and the fewest it shows with. +#[cfg(feature = "mods")] +const COLUMNS: (usize, usize) = (12, 2); +/// The gap between the window and the panel, and the screen's edges. +#[cfg(feature = "mods")] +const MARGIN: f32 = 8.0; + +/// The panel's state in the game. +#[cfg(feature = "mods")] +#[derive(Default)] +pub(super) struct Browser { + /// The items' owner and version they were made from. + of: Option<(usize, u64)>, + /// The mod's items as stacks; `None` for an item the game doesn't have. + stacks: Vec>, + page: usize, + search: Option, + /// The search text the mod last heard. + sent: String, + /// `set-recipes`' recipes, shown instead of the items. + pub(super) recipes: Option, +} + +/// Where the panel's parts are this frame. +#[cfg(feature = "mods")] +pub(super) struct Layout { + /// The panel's whole area, for clicks that hit none of its parts. + pub(super) area: [f32; 4], + /// The grid's top left corner, its columns and rows. + pub(super) grid: (f32, f32), + pub(super) columns: usize, + pub(super) rows: usize, + /// The page arrows' row. + pub(super) arrows_y: f32, + pub(super) search: [f32; 4], +} +#[cfg(feature = "mods")] +impl Layout { + fn per_page(&self) -> usize { + self.columns * self.rows + } + pub(super) fn width(&self) -> f32 { + self.columns as f32 * SLOT + } + fn slot(&self, n: usize) -> (f32, f32) { + ( + self.grid.0 + (n % self.columns) as f32 * SLOT, + self.grid.1 + (n / self.columns) as f32 * SLOT, + ) + } + /// The page arrows: backward, then forward. + pub(super) fn arrows(&self) -> [(f32, f32); 2] { + [ + (self.grid.0, self.arrows_y), + (self.grid.0 + self.width() - 12.0, self.arrows_y), + ] + } +} + +#[cfg(feature = "mods")] +pub(super) fn inside(p: (f32, f32), [x, y, w, h]: [f32; 4]) -> bool { + p.0 >= x && p.1 >= y && p.0 < x + w && p.1 < y + h +} + +#[cfg(feature = "mods")] +impl Game<'_> { + fn browser_batch(&self) -> Option { + let r = self.renderer.as_ref()?; + Some(HudBatch::new([r.config.width, r.config.height])) + } + /// The mod showing a panel, with its items made into stacks once per + /// `set-items`; none while no mod shows one or no container screen is up. + fn browser_sync(&mut self) -> Option { + if self.screen != Screen::Inventory || self.title.is_some() { + return None; + } + let Some((owner, version)) = self.mods.mods.browser_items().map(|(o, v, _)| (o, v)) else { + self.mods.browser.of = None; + self.mods.browser.stacks.clear(); + return None; + }; + if self.mods.browser.of != Some((owner, version)) { + let items = self.res.items(); + let stacks = self + .mods + .mods + .browser_items() + .map_or_else(Vec::new, |(_, _, list)| { + list.iter().map(|s| browser_stack(items, s)).collect() + }); + self.mods.browser.stacks = stacks; + // The same title again (the mod updating its buttons) keeps the page. + let old = self.mods.browser.recipes.take(); + self.mods.browser.recipes = self + .mods + .mods + .browser_recipes(owner) + .map(|shown| super::mod_browser_recipes::Pages::new(items, shown, old)); + self.mods.browser.of = Some((owner, version)); + } + Some(owner) + } + /// The panel's parts: right of the window, from the top of the screen to + /// the search box at its foot. None when the screen has no room for it. + fn browser_layout(&self, batch: &HudBatch) -> Option { + let image = self.container_image(batch); + let left = (image.left + image.width) as f32 + MARGIN; + let right = batch.width - MARGIN; + let columns = (((right - left) / SLOT).floor().max(0.0) as usize).min(COLUMNS.0); + if columns < COLUMNS.1 { + return None; + } + let x = (left + (right - left - columns as f32 * SLOT) / 2.0).floor(); + let arrows_y = MARGIN; + let top = arrows_y + 17.0 + 4.0; + let search = [x, batch.height - MARGIN - 16.0, columns as f32 * SLOT, 16.0]; + let rows = ((search[1] - 4.0 - top) / SLOT).floor().max(0.0) as usize; + (rows > 0).then_some(Layout { + area: [left, 0.0, right - left, batch.height], + grid: (x, top), + columns, + rows, + arrows_y, + search, + }) + } + fn browser_pages(&self, layout: &Layout) -> usize { + self.mods + .browser + .stacks + .len() + .div_ceil(layout.per_page()) + .max(1) + } + /// The stack under the pointer on the panel, an item's or a recipe's, + /// as the mod sent it and as a stack. + fn browser_pointed_stack(&self, layout: &Layout) -> Option<(BrowserStack, ItemStack)> { + if self.mods.browser.recipes.is_some() { + if let Some((_, sent, stack)) = self.recipe_tab_hovered(layout) { + return Some((sent, stack)); + } + let (_, _, sent, stack) = self.recipe_slot_hovered(layout)?; + return Some((sent, stack)); + } + let (index, stack) = self.browser_hovered(layout)?; + let (_, _, items) = self.mods.mods.browser_items()?; + Some((items.get(index)?.clone(), stack)) + } + /// The panel's item under the pointer: its index and stack. + fn browser_hovered(&self, layout: &Layout) -> Option<(usize, ItemStack)> { + if self.mods.browser.recipes.is_some() { + return None; + } + let first = self.mods.browser.page * layout.per_page(); + (0..layout.per_page()).find_map(|n| { + let (x, y) = layout.slot(n); + if !inside(self.cursor, [x, y, SLOT, SLOT]) { + return None; + } + let stack = self.mods.browser.stacks.get(first + n)?.clone()?; + Some((first + n, stack)) + }) + } + fn browser_search(&mut self, layout: &Layout) -> &mut EditBox { + let search = self.mods.browser.search.get_or_insert_with(|| { + let mut edit = EditBox::new(0.0, 0.0, 0.0, 0.0); + edit.max_length = 50; + edit.focused = false; + edit + }); + [search.x, search.y, search.width, search.height] = layout.search; + search + } + + /// The items' page arrows and grid. + fn draw_browser_items(&mut self, batch: &mut HudBatch, layout: &Layout) { + let pages = self.browser_pages(layout); + self.mods.browser.page = self.mods.browser.page.min(pages - 1); + let page = self.mods.browser.page; + let cursor = self.cursor; + if pages > 1 { + let labels = [ + self.translate("gui.recipebook.previous_page", "Previous Page"), + self.translate("gui.recipebook.next_page", "Next Page"), + ]; + let shown = [page > 0, page + 1 < pages]; + let atlas = &self.gui.atlas; + for (((x, y), name), (label, shown)) in layout + .arrows() + .into_iter() + .zip(["page_backward", "page_forward"]) + .zip(labels.iter().zip(shown)) + { + if !shown { + continue; + } + let hover = inside(cursor, [x, y, 12.0, 17.0]); + let suffix = if hover { "_highlighted" } else { "" }; + batch.sprite( + atlas, + &format!("gui/sprites/recipe_book/{name}{suffix}"), + x, + y, + ); + horizon_client::widgets::record(label, [x, y, 12.0, 17.0], true); + } + let text = format!("{}/{pages}", page + 1); + let w = HudBatch::text_width(atlas, &text); + let x = (layout.grid.0 + (layout.width() - w) / 2.0).floor(); + batch.text(atlas, &text, x, layout.arrows_y + 5.0, u32::MAX, true); + } + let first = page * layout.per_page(); + for n in 0..layout.per_page() { + let Some(stack) = self.mods.browser.stacks.get(first + n) else { + break; + }; + let Some(stack) = stack.clone() else { + continue; + }; + let (x, y) = layout.slot(n); + self.draw_item(batch, &stack, x + 1.0, y + 1.0); + let rect = [x + 1.0, y + 1.0, 16.0, 16.0]; + if inside(cursor, [x, y, SLOT, SLOT]) { + batch.fill( + &self.gui.atlas, + x + 1.0, + y + 1.0, + 16.0, + 16.0, + rgba(255, 255, 255, 128), + ); + } + let name = self.pack.names.display_item(&stack.item); + horizon_client::widgets::record_as( + &name, + rect, + true, + horizon_client::widgets::Kind::Button, + ); + } + } + /// Draws the panel over the open container screen, then the carried + /// stack or the tooltip again so they stay on top of it. + pub(super) fn draw_mod_browser(&mut self, batch: &mut HudBatch) { + if self.browser_sync().is_none() { + return; + } + let Some(layout) = self.browser_layout(batch) else { + return; + }; + let cursor = self.cursor; + if self.mods.browser.recipes.is_some() { + self.draw_browser_recipes(batch, &layout); + } else { + self.draw_browser_items(batch, &layout); + } + let hint = self.translate("gui.recipebook.search_hint", "Search..."); + let search = self.browser_search(&layout); + // The hint shows in an empty box without focus, as the recipe book's. + search.suggestion = (search.value.is_empty() && !search.focused).then_some(hint); + let mut search = search.clone(); + search.draw(batch, &self.gui.atlas, None); + self.mods.browser.search = Some(search); + if self.carried.is_some() { + self.draw_carried(batch); + } else if let Some(stack) = self.browser_pointed_stack(&layout) { + let lines = self.stack_tooltip(&stack.1); + self.draw_tooltip_lines(batch, &lines, cursor.0, cursor.1); + } else { + self.draw_slot_tooltip(batch); + } + } + + /// A mouse press on a container screen: true when the panel took it + /// (its search box, page arrows, items or empty space; a click there + /// never throws the carried stack). + pub(super) fn mod_browser_press(&mut self, right: bool) -> bool { + let Some(owner) = self.browser_sync() else { + return false; + }; + let Some(batch) = self.browser_batch() else { + return false; + }; + let Some(layout) = self.browser_layout(&batch) else { + return false; + }; + let cursor = self.cursor; + let shift = self.has_shift_down(); + let atlas = &self.gui.atlas; + let search = self.mods.browser.search.get_or_insert_with(|| { + let mut edit = EditBox::new(0.0, 0.0, 0.0, 0.0); + edit.max_length = 50; + edit + }); + [search.x, search.y, search.width, search.height] = layout.search; + if inside(cursor, layout.search) { + search.focused = true; + search.click(atlas, cursor.0, shift, false); + search.reset_blink(); + return true; + } + search.focused = false; + if self.mods.browser.recipes.is_some() { + return self.browser_recipes_press(&layout, owner, right) + || inside(cursor, layout.area); + } + let pages = self.browser_pages(&layout); + let page = self.mods.browser.page; + let [back, forward] = layout.arrows(); + let step = if pages > 1 && page > 0 && inside(cursor, [back.0, back.1, 12.0, 17.0]) { + Some(page - 1) + } else if pages > 1 + && page + 1 < pages + && inside(cursor, [forward.0, forward.1, 12.0, 17.0]) + { + Some(page + 1) + } else { + None + }; + if let Some(to) = step { + self.mods.browser.page = to; + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); + return true; + } + if let Some((index, _)) = self.browser_hovered(&layout) { + let event = BrowserEvent::Clicked(BrowserClick { + index: index as u32, + right, + }); + self.mods.mods.browser_event(owner, event); + return true; + } + inside(cursor, layout.area) + } + + /// Whether keys go to the panel's search box. + pub(super) fn mod_browser_typing(&self) -> bool { + self.screen == Screen::Inventory + && self.mods.browser.of.is_some() + && self.mods.browser.search.as_ref().is_some_and(|s| s.focused) + } + /// A key press while the search box has focus. + pub(super) fn mod_browser_key(&mut self, event: &winit::event::KeyEvent) { + use winit::keyboard::PhysicalKey; + let shortcut = self.edit_shortcut(event); + let ctrl = self.has_control_down(); + let shift = self.has_shift_down(); + let Some(search) = self.mods.browser.search.as_mut() else { + return; + }; + if let Some(shortcut) = shortcut { + search.shortcut(shortcut, &mut self.clipboard); + } else { + let handled = match event.physical_key { + PhysicalKey::Code(code) => search.key(code, ctrl, shift), + _ => false, + }; + if !handled + && !ctrl + && let Some(text) = &event.text + { + let text: String = text.chars().filter(|c| !c.is_control()).collect(); + search.insert_text(&text); + } + } + search.reset_blink(); + self.browser_searched(); + } + /// Text typed (or one backspace) into the search box (`horizon-ctl type`). + pub(super) fn mod_browser_text(&mut self, text: Option<&str>, backspace: bool) { + let Some(search) = self.mods.browser.search.as_mut() else { + return; + }; + if backspace { + search.delete_chars(-1); + } else if let Some(text) = text { + search.insert_text(text); + } + self.browser_searched(); + } + /// The mod hears the search text when it changed. + fn browser_searched(&mut self) { + let (Some((owner, _)), Some(search)) = (self.mods.browser.of, &self.mods.browser.search) + else { + return; + }; + if search.value != self.mods.browser.sent { + let value = search.value.clone(); + self.mods.browser.sent.clone_from(&value); + self.mods.browser.page = 0; + self.mods + .mods + .browser_event(owner, BrowserEvent::Search(value)); + } + } + /// The container screen closed: the search box lets go of the keys. + pub(super) fn mod_browser_closed(&mut self) { + if let Some(search) = self.mods.browser.search.as_mut() { + search.focused = false; + } + } + /// The item under the pointer on a container screen, for the mods' keys + /// (`browser`'s `key` event): the panel's, else a slot's. + pub(super) fn mod_browser_pointed(&mut self) -> Option { + let batch = self.browser_batch()?; + let stack = match self + .browser_sync() + .and_then(|_| self.browser_layout(&batch)) + { + // The panel's stacks as the mod sent them. + Some(layout) if inside(self.cursor, layout.area) => { + return Some(self.browser_pointed_stack(&layout)?.0); + } + _ => { + let slot = self.slot_at(&batch, self.cursor.0, self.cursor.1)?; + self.slot_view(slot)? + } + }; + Some(BrowserStack { + item: stack.item.to_string(), + count: stack.count, + components: super::mod_recipes::components(&stack), + }) + } +} + +/// A mod's item as a stack: an item the game has, its components read as +/// `/give` reads them (ones it can't read are left out). +#[cfg(feature = "mods")] +pub(super) fn browser_stack( + items: &horizon_client::items::Items, + s: &BrowserStack, +) -> Option { + items.get(&s.item)?; + let (damage, extra) = if s.components.is_empty() { + (0, None) + } else { + horizon_client::item_data::command_components(&s.components).map_or((0, None), |tag| { + horizon_client::item_data::decode_components(Some(&tag)) + }) + }; + Some(ItemStack { + item: s.item.as_str().into(), + count: s.count.clamp(1, 99), + damage, + extra, + }) +} diff --git a/crates/horizon-client/src/game/mod_browser_recipes.rs b/crates/horizon-client/src/game/mod_browser_recipes.rs new file mode 100644 index 000000000..557ae9029 --- /dev/null +++ b/crates/horizon-client/src/game/mod_browser_recipes.rs @@ -0,0 +1,523 @@ +//! `browser.set-recipes` (docs/mods.md): a mod's recipes shown in its item +//! panel's place, laid out by the game with its own slots, arrows and +//! buttons, paged to the panel's height, under a title and a back button. +//! The mod hears clicks on their slots, their action buttons, the back +//! button and page turns. +use super::{ + Game, + mod_browser::{Layout, browser_stack, inside}, +}; +use horizon_client::{ + hud::{HudBatch, rgba}, + items::ItemStack, +}; +use horizon_mods::{BrowserEvent, BrowserLayout, BrowserSlotClick, BrowserStack, RecipePage}; +use std::time::Instant; + +const SLOT: f32 = 18.0; +/// The title row's height, and the gap under each recipe. +const TITLE: f32 = 18.0; +/// A tab's step: an 18 px slot and a gap. +const TAB: f32 = 20.0; +const GAP: f32 = 6.0; + +/// One recipe as the game draws it. +pub(super) struct Shown { + layout: BrowserLayout, + width: usize, + height: usize, + /// Each slot's stacks (the result last), as the mod sent them and as + /// stacks; a stack the game doesn't have is left out of the cycle. + slots: Vec>, + note: String, + action: Option, +} + +/// The recipes a panel shows, and its page. +pub(super) struct Pages { + title: String, + /// The tabs' icons and the selected one. + tabs: Vec<(BrowserStack, Option)>, + tab: usize, + recipes: Vec, + page: usize, + since: Instant, +} + +impl Pages { + pub(super) fn new( + items: &horizon_client::items::Items, + shown: &RecipePage, + old: Option, + ) -> Self { + let (title, list, tab) = (&shown.title, &shown.recipes, shown.tab as usize); + let kept = old.filter(|o| o.title == *title && o.tab == tab); + let cycle = |stacks: &[BrowserStack]| -> Vec<(BrowserStack, ItemStack)> { + stacks + .iter() + .filter_map(|s| Some((s.clone(), browser_stack(items, s)?))) + .collect() + }; + let recipes = list + .iter() + .map(|r| { + let mut slots: Vec<_> = r.slots.iter().map(|s| cycle(s)).collect(); + slots.push(cycle(&r.results)); + Shown { + layout: r.layout, + width: r.width as usize, + height: r.height as usize, + slots, + note: r.note.clone(), + action: r.action, + } + }) + .collect(); + Self { + title: title.clone(), + tabs: shown + .tabs + .iter() + .map(|t| (t.clone(), browser_stack(items, t))) + .collect(), + tab, + recipes, + page: kept.as_ref().map_or(0, |o| o.page), + since: kept.map_or_else(Instant::now, |o| o.since), + } + } +} + +impl Shown { + /// The inputs' block: its size and each input slot's place in it. + fn inputs(&self) -> ((f32, f32), Vec<(f32, f32)>) { + let row = |n: usize| (0..n).map(|i| (i as f32 * SLOT, 0.0)).collect(); + match self.layout { + BrowserLayout::Grid => { + let (w, h) = (self.width.max(1), self.height.max(1)); + let at = (0..w * h) + .map(|i| ((i % w) as f32 * SLOT, (i / w) as f32 * SLOT)) + .collect(); + ((w as f32 * SLOT, h as f32 * SLOT), at) + } + // The input over the flame. + BrowserLayout::Cooking => ((SLOT, 2.0 * SLOT), vec![(0.0, 0.0)]), + BrowserLayout::Single => ((SLOT, SLOT), row(1)), + BrowserLayout::Smithing => ((3.0 * SLOT, SLOT), row(3)), + BrowserLayout::Brewing => ((2.0 * SLOT, SLOT), row(2)), + } + } + /// The height of its slots, arrow and button, `room` wide. + fn block(&self, room: f32) -> f32 { + let h = self.inputs().0.1; + let (_, _, action) = self.places(room); + match self.action { + Some(_) => h.max(action.1 + 12.0), + None => h, + } + } + fn height(&self, room: f32) -> f32 { + let note = if self.note.is_empty() { 0.0 } else { 11.0 }; + self.block(room) + note + GAP + } + /// Every slot's place from the recipe's corner (the result last), the + /// arrow's and the action button's: beside the result, or under it + /// when the panel is `room` wide and that doesn't fit. + fn places(&self, room: f32) -> (Vec<(f32, f32)>, (f32, f32), (f32, f32)) { + let ((w, h), mut at) = self.inputs(); + // The mod's slots beyond the layout's are not shown. + at.truncate(self.slots.len() - 1); + let arrow = (w + 4.0, ((h - 16.0) / 2.0).floor()); + let result = (w + 32.0, ((h - SLOT) / 2.0).floor()); + let action = if result.0 + SLOT + 16.0 <= room { + (result.0 + SLOT + 4.0, ((h - 12.0) / 2.0).floor()) + } else { + (result.0 + 3.0, result.1 + SLOT + 2.0) + }; + while at.len() < self.slots.len() - 1 { + at.push((f32::NAN, f32::NAN)); + } + at.push(result); + (at, arrow, action) + } +} + +/// The tabs' places, in rows under the title row. +fn tab_places(pages: &Pages, layout: &Layout) -> Vec<(f32, f32)> { + let per_row = ((layout.width() / TAB).floor() as usize).max(1); + (0..pages.tabs.len()) + .map(|i| { + ( + layout.grid.0 + (i % per_row) as f32 * TAB, + layout.grid.1 + TITLE + 3.0 + (i / per_row) as f32 * TAB, + ) + }) + .collect() +} +/// Where the recipes start: under the title row and the tabs. +fn recipes_top(pages: &Pages, layout: &Layout) -> f32 { + let tabs = tab_places(pages, layout); + tabs.last() + .map_or(layout.grid.1 + TITLE, |&(_, y)| y + TAB + 3.0) +} + +impl Game<'_> { + /// The first recipe of each page, filling the panel from the tabs to + /// the search box. + fn recipe_pages(pages: &Pages, layout: &Layout) -> Vec { + let room = layout.search[1] - 4.0 - recipes_top(pages, layout); + let mut starts = vec![0]; + let mut used = 0.0; + for (i, r) in pages.recipes.iter().enumerate() { + let h = r.height(layout.width()); + if used > 0.0 && used + h > room { + starts.push(i); + used = 0.0; + } + used += h; + } + starts + } + /// The recipes on the open page, each with its corner. + fn recipes_shown(&self, layout: &Layout) -> Vec<(usize, (f32, f32))> { + let Some(pages) = &self.mods.browser.recipes else { + return Vec::new(); + }; + let starts = Self::recipe_pages(pages, layout); + let page = pages.page.min(starts.len() - 1); + let end = starts.get(page + 1).copied().unwrap_or(pages.recipes.len()); + let mut y = recipes_top(pages, layout); + (starts[page]..end) + .map(|i| { + let at = (layout.grid.0, y); + y += pages.recipes[i].height(layout.width()); + (i, at) + }) + .collect() + } + fn back_button(&self, layout: &Layout) -> ([f32; 4], String) { + let label = self.translate("gui.back", "Back"); + let w = HudBatch::text_width(&self.gui.atlas, &label) + 8.0; + ([layout.grid.0, layout.grid.1, w, 14.0], label) + } + /// What a slot of a shown recipe holds now: its stacks cycle once a second. + fn recipe_slot_now(&self, recipe: usize, slot: usize) -> Option<&(BrowserStack, ItemStack)> { + let pages = self.mods.browser.recipes.as_ref()?; + let stacks = pages.recipes.get(recipe)?.slots.get(slot)?; + let n = pages.since.elapsed().as_secs() as usize; + stacks.get(n % stacks.len().max(1)) + } + /// The tab under the pointer: its index and icon. + pub(super) fn recipe_tab_hovered( + &self, + layout: &Layout, + ) -> Option<(usize, BrowserStack, ItemStack)> { + let pages = self.mods.browser.recipes.as_ref()?; + let places = tab_places(pages, layout); + places.iter().enumerate().find_map(|(i, &(x, y))| { + if !inside(self.cursor, [x, y, SLOT, SLOT]) { + return None; + } + let (sent, stack) = pages.tabs.get(i)?; + Some((i, sent.clone(), stack.clone()?)) + }) + } + /// The recipe slot under the pointer: recipe, slot, and its stack now. + pub(super) fn recipe_slot_hovered( + &self, + layout: &Layout, + ) -> Option<(usize, usize, BrowserStack, ItemStack)> { + let pages = self.mods.browser.recipes.as_ref()?; + self.recipes_shown(layout) + .into_iter() + .find_map(|(i, (x, y))| { + let (at, _, _) = pages.recipes[i].places(layout.width()); + at.iter().enumerate().find_map(|(k, &(sx, sy))| { + if !inside(self.cursor, [x + sx, y + sy, SLOT, SLOT]) { + return None; + } + let (mod_stack, stack) = self.recipe_slot_now(i, k)?.clone(); + Some((i, k, mod_stack, stack)) + }) + }) + } + + /// Draws the title row, the page's recipes and the page arrows. + pub(super) fn draw_browser_recipes(&mut self, batch: &mut HudBatch, layout: &Layout) { + let Some(pages) = &self.mods.browser.recipes else { + return; + }; + let cursor = self.cursor; + let starts = Self::recipe_pages(pages, layout); + let page = pages.page.min(starts.len() - 1); + let (title, pages_n) = (pages.title.clone(), starts.len()); + let (back, label) = self.back_button(layout); + let atlas = &self.gui.atlas; + let hover = inside(cursor, back); + let sprite = if hover { + "gui/sprites/widget/button_highlighted" + } else { + "gui/sprites/widget/button" + }; + horizon_client::ui::nine_slice( + batch, + atlas, + sprite, + back[0], + back[1], + back[2], + back[3], + u32::MAX, + ); + batch.text(atlas, &label, back[0] + 4.0, back[1] + 3.0, u32::MAX, true); + horizon_client::widgets::record(&label, back, true); + let room = layout.width() - back[2] - 4.0; + // Cut to the panel with vanilla's ellipsis (CommonComponents.ELLIPSIS). + let shown = if atlas.font.fit(&title, room) >= title.chars().count() { + title + } else { + let fit = atlas.font.fit(&title, room - atlas.font.width("...")); + let kept: String = title.chars().take(fit).collect(); + format!("{}...", kept.trim_end()) + }; + batch.text( + atlas, + &shown, + back[0] + back[2] + 4.0, + back[1] + 3.0, + u32::MAX, + true, + ); + self.draw_recipe_tabs(batch, layout); + if pages_n > 1 { + let labels = [ + self.translate("gui.recipebook.previous_page", "Previous Page"), + self.translate("gui.recipebook.next_page", "Next Page"), + ]; + let visible = [page > 0, page + 1 < pages_n]; + let atlas = &self.gui.atlas; + for (((x, y), name), (label, visible)) in layout + .arrows() + .into_iter() + .zip(["page_backward", "page_forward"]) + .zip(labels.iter().zip(visible)) + { + if !visible { + continue; + } + let suffix = if inside(cursor, [x, y, 12.0, 17.0]) { + "_highlighted" + } else { + "" + }; + batch.sprite( + atlas, + &format!("gui/sprites/recipe_book/{name}{suffix}"), + x, + y, + ); + horizon_client::widgets::record(label, [x, y, 12.0, 17.0], true); + } + let text = format!("{}/{pages_n}", page + 1); + let w = HudBatch::text_width(atlas, &text); + let x = (layout.grid.0 + (layout.width() - w) / 2.0).floor(); + batch.text(atlas, &text, x, layout.arrows_y + 5.0, u32::MAX, true); + } + for (i, (x, y)) in self.recipes_shown(layout) { + let Some(r) = self.mods.browser.recipes.as_ref().map(|p| &p.recipes[i]) else { + break; + }; + let (at, arrow, action) = r.places(layout.width()); + let h = r.block(layout.width()); + let (cooking, note, button) = + (r.layout == BrowserLayout::Cooking, r.note.clone(), r.action); + let atlas = &self.gui.atlas; + for &(sx, sy) in at.iter().filter(|p| p.0.is_finite()) { + batch.sprite(atlas, "gui/sprites/container/slot", x + sx, y + sy); + } + if cooking { + batch.sprite( + atlas, + "gui/sprites/container/furnace/lit_progress", + x + 2.0, + y + SLOT + 2.0, + ); + } + batch.sprite( + atlas, + "gui/sprites/container/furnace/burn_progress", + x + arrow.0, + y + arrow.1, + ); + if let Some(enabled) = button { + let rect = [x + action.0, y + action.1, 12.0, 12.0]; + let sprite = match (enabled, inside(cursor, rect)) { + (false, _) => "gui/sprites/widget/button_disabled", + (true, true) => "gui/sprites/widget/button_highlighted", + (true, false) => "gui/sprites/widget/button", + }; + horizon_client::ui::nine_slice( + batch, + atlas, + sprite, + rect[0], + rect[1], + 12.0, + 12.0, + u32::MAX, + ); + let color = if enabled { + u32::MAX + } else { + rgba(160, 160, 160, 255) + }; + batch.text(atlas, "+", rect[0] + 3.0, rect[1] + 2.0, color, true); + horizon_client::widgets::record(&format!("+ {i}"), rect, enabled); + } + if !note.is_empty() { + batch.text(atlas, ¬e, x, y + h + 2.0, rgba(224, 224, 224, 255), true); + } + for (k, &(sx, sy)) in at.iter().enumerate().filter(|(_, p)| p.0.is_finite()) { + let Some((_, stack)) = self.recipe_slot_now(i, k).cloned() else { + continue; + }; + self.draw_item(batch, &stack, x + sx + 1.0, y + sy + 1.0); + if inside(cursor, [x + sx, y + sy, SLOT, SLOT]) { + batch.fill( + &self.gui.atlas, + x + sx + 1.0, + y + sy + 1.0, + 16.0, + 16.0, + rgba(255, 255, 255, 128), + ); + } + let name = self.pack.names.display_item(&stack.item); + horizon_client::widgets::record_as( + &format!("{name} {i}:{k}"), + [x + sx + 1.0, y + sy + 1.0, 16.0, 16.0], + true, + horizon_client::widgets::Kind::Button, + ); + } + } + } + + /// The tabs, on slots; the selected one framed. + fn draw_recipe_tabs(&mut self, batch: &mut HudBatch, layout: &Layout) { + let Some(pages) = &self.mods.browser.recipes else { + return; + }; + let places = tab_places(pages, layout); + let tabs: Vec> = pages.tabs.iter().map(|t| t.1.clone()).collect(); + let selected = pages.tab; + for (i, (&(x, y), stack)) in places.iter().zip(tabs).enumerate() { + let atlas = &self.gui.atlas; + batch.sprite(atlas, "gui/sprites/container/slot", x, y); + let Some(stack) = stack else { + continue; + }; + self.draw_item(batch, &stack, x + 1.0, y + 1.0); + // The selected tab: a white frame around its slot. + if i == selected { + let white = rgba(255, 255, 255, 255); + let atlas = &self.gui.atlas; + batch.fill(atlas, x - 1.0, y - 1.0, SLOT + 2.0, 1.0, white); + batch.fill(atlas, x - 1.0, y + SLOT, SLOT + 2.0, 1.0, white); + batch.fill(atlas, x - 1.0, y, 1.0, SLOT, white); + batch.fill(atlas, x + SLOT, y, 1.0, SLOT, white); + } + if inside(self.cursor, [x, y, SLOT, SLOT]) { + batch.fill( + &self.gui.atlas, + x + 1.0, + y + 1.0, + 16.0, + 16.0, + rgba(255, 255, 255, 128), + ); + } + let name = self.pack.names.display_item(&stack.item); + horizon_client::widgets::record_as( + &format!("{name} tab"), + [x + 1.0, y + 1.0, 16.0, 16.0], + true, + horizon_client::widgets::Kind::Tab(i == selected), + ); + } + } + + /// A press on the recipes: true when it hit one of their parts. + pub(super) fn browser_recipes_press( + &mut self, + layout: &Layout, + owner: usize, + right: bool, + ) -> bool { + let Some(pages) = &self.mods.browser.recipes else { + return false; + }; + let cursor = self.cursor; + let starts = Self::recipe_pages(pages, layout); + let page = pages.page.min(starts.len() - 1); + let [back_arrow, forward] = layout.arrows(); + let turn = if page > 0 && inside(cursor, [back_arrow.0, back_arrow.1, 12.0, 17.0]) { + Some(page - 1) + } else if page + 1 < starts.len() && inside(cursor, [forward.0, forward.1, 12.0, 17.0]) { + Some(page + 1) + } else { + None + }; + if let Some(to) = turn { + if let Some(p) = self.mods.browser.recipes.as_mut() { + p.page = to; + } + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); + self.mods + .mods + .browser_event(owner, BrowserEvent::Page(starts[to] as u32)); + return true; + } + if let Some((tab, _, _)) = self.recipe_tab_hovered(layout) { + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); + self.mods + .mods + .browser_event(owner, BrowserEvent::Tab(tab as u32)); + return true; + } + if inside(cursor, self.back_button(layout).0) { + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); + self.mods.mods.browser_event(owner, BrowserEvent::Back); + return true; + } + if let Some((recipe, slot, stack, _)) = self.recipe_slot_hovered(layout) { + let event = BrowserEvent::SlotClicked(BrowserSlotClick { + recipe: recipe as u32, + slot: slot as u32, + stack, + right, + }); + self.mods.mods.browser_event(owner, event); + return true; + } + let action = self.recipes_shown(layout).into_iter().find(|&(i, (x, y))| { + let r = &pages.recipes[i]; + let (_, _, (ax, ay)) = r.places(layout.width()); + r.action.is_some() && inside(cursor, [x + ax, y + ay, 12.0, 12.0]) + }); + if let Some((i, _)) = action { + if pages.recipes[i].action == Some(true) { + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); + self.mods + .mods + .browser_event(owner, BrowserEvent::Action(i as u32)); + } + return true; + } + false + } +} diff --git a/crates/horizon-client/src/game/mod_input.rs b/crates/horizon-client/src/game/mod_input.rs index 10faf6a81..3df62c3d4 100644 --- a/crates/horizon-client/src/game/mod_input.rs +++ b/crates/horizon-client/src/game/mod_input.rs @@ -111,6 +111,18 @@ impl Game<'_> { if repeat || !self.mods.mods.has_keys() { return; } + // Over an item on a container screen, the mods' keys are `browser` + // events (a recipe viewer's R and U). + if pressed + && self.screen == Screen::Inventory + && self.title.is_none() + && !self.mod_browser_typing() + && let Some(name) = horizon_client::keybinds::key_name(key) + && let Some(stack) = self.mod_browser_pointed() + { + self.mods.mods.browser_key(name, &stack); + return; + } if pressed && (self.screen != Screen::Playing || self.title.is_some()) { return; } diff --git a/crates/horizon-client/src/game/mod_recipes.rs b/crates/horizon-client/src/game/mod_recipes.rs new file mode 100644 index 000000000..b97944e39 --- /dev/null +++ b/crates/horizon-client/src/game/mod_recipes.rs @@ -0,0 +1,274 @@ +//! Capability `recipes` (docs/mods.md): every item and recipe the game +//! knows, made once for the mods that read them, and the recipe book's +//! known displays. The recipes are the window's own data: the world's in +//! single player, vanilla's on a server (a client is sent no others), while +//! the known displays follow the server's book as the recipe book does. +use super::Game; +use horizon_client::{ + crafting::Ingredient, + items::ItemStack, + recipe_book::{Category, Display}, + stations::Smithing, +}; +use horizon_mods::{Recipe, RecipeItem, RecipeKind, RecipeStack, Recipes}; +use std::{collections::HashMap, sync::Arc}; + +/// Item id -> its index in [`Recipes::items`]. +struct Index(HashMap, u32>); +impl Index { + fn stack(&self, item: &str, count: u32, components: String) -> Option { + Some(RecipeStack { + item: *self.0.get(item)?, + count, + components, + }) + } + fn of(&self, s: &ItemStack) -> Option { + self.stack(&s.item, s.count, components(s)) + } + fn any(&self, i: &Ingredient) -> Vec { + i.1.iter() + .filter_map(|id| self.stack(id, 1, String::new())) + .collect() + } +} + +/// A stack's components beyond its item's, as vanilla's item syntax writes +/// them (`[minecraft:potion_contents={potion:"minecraft:swiftness"}]`), or "". +pub(super) fn components(s: &ItemStack) -> String { + use horizon_world::nbt::Tag; + let Some(Tag::Compound(entries)) = horizon_client::item_data::encode_components(s) else { + return String::new(); + }; + let parts: Vec = entries + .iter() + .map(|(k, v)| { + format!( + "{}={}", + k.to_string_lossy(), + horizon_client::snbt::to_snbt(v) + ) + }) + .collect(); + format!("[{}]", parts.join(",")) +} + +fn recipe(id: String, kind: RecipeKind) -> Recipe { + Recipe { + id, + kind, + category: String::new(), + group: String::new(), + width: 0, + height: 0, + slots: Vec::new(), + results: Vec::new(), + cooking_time: 0, + experience: 0.0, + book_id: -1, + } +} + +impl Game<'_> { + /// `recipes.give`: a creative player takes the stack as from the + /// creative inventory; a server hears it as `SetCreativeModeSlot` + /// through the inventory's sync, and refuses it unless creative. + pub(super) fn mod_give(&mut self, item: &str, count: u32, components: &str) { + let Some(max) = self.res.items().get(item).map(|i| i.max_stack) else { + return; + }; + if !self.creative { + return; + } + let (damage, extra) = horizon_client::item_data::command_components(components) + .map_or((0, None), |tag| { + horizon_client::item_data::decode_components(Some(&tag)) + }); + let _ = self.give(ItemStack { + item: item.into(), + // One stack at most, as the creative inventory hands out. + count: count.min(max), + damage, + extra, + }); + } + /// Capability `recipes`'s tables and known displays for this tick's + /// snapshot; nothing while no running mod reads them. + pub(super) fn mod_recipes(&mut self) -> (Option>, Arc<[i32]>) { + if !self.mods.mods.wants_recipes() { + return (None, Arc::from([])); + } + if self.mods.recipes.is_none() { + self.mods.recipes = Some(Arc::new(self.make_mod_recipes())); + } + let (version, known) = self.recipe_book_displays(); + if self.mods.known_recipes.0 != Some(version) { + self.mods.known_recipes = (Some(version), known.into()); + } + (self.mods.recipes.clone(), self.mods.known_recipes.1.clone()) + } + + fn make_mod_recipes(&mut self) -> Recipes { + let names = &self.pack.names; + let items = self.res.items(); + let mut tags: HashMap<&str, Vec> = HashMap::new(); + for (tag, members) in &items.item_tags { + for m in members { + tags.entry(m).or_default().push(tag.clone()); + } + } + let table: Vec = items + .registry_order + .iter() + .map(|id| RecipeItem { + id: id.to_string(), + name: names.display_item(id), + tags: tags.remove(&**id).map_or_else(Vec::new, |mut t| { + t.sort(); + t + }), + }) + .collect(); + let index = Index( + items + .registry_order + .iter() + .enumerate() + .map(|(i, id)| (id.clone(), i as u32)) + .collect(), + ); + let mut out = Vec::new(); + let cooking: HashMap = self + .res + .recipes() + .cooking + .iter() + .map(|c| (format!("minecraft:{}", c.id), (c.time, c.experience))) + .collect(); + for e in self.recipe_book_entries() { + let furnace = |c: Category| match c.name().split('_').next() { + Some("blast") => RecipeKind::Blasting, + Some("smoker") => RecipeKind::Smoking, + _ => RecipeKind::Smelting, + }; + let kind = match &e.display { + Display::Shaped { .. } => RecipeKind::CraftingShaped, + Display::Shapeless(_) => RecipeKind::CraftingShapeless, + Display::Furnace(_) => furnace(e.category), + }; + let mut r = recipe(e.id.clone(), kind); + r.category = e.category.name().to_owned(); + r.group = e.group.clone().unwrap_or_default(); + r.book_id = e.display_id; + r.slots = match &e.display { + Display::Shaped { + width, + height, + cells, + } => { + (r.width, r.height) = (*width as u32, *height as u32); + cells + .iter() + .map(|c| c.as_ref().map_or_else(Vec::new, |i| index.any(i))) + .collect() + } + Display::Shapeless(list) => list.iter().map(|i| index.any(i)).collect(), + Display::Furnace(i) => vec![index.any(i)], + }; + // Requirements shown as other stacks (an arrow's potions): the + // requirement's index counts the filled slots only. + let filled: Vec = (0..r.slots.len()) + .filter( + |&k| !matches!(&e.display, Display::Shaped { cells, .. } if cells[k].is_none()), + ) + .collect(); + for (req, stacks) in &e.stacks { + if let Some(&k) = filled.get(*req) { + r.slots[k] = stacks.iter().filter_map(|s| index.of(s)).collect(); + } + } + r.results = e.results().iter().filter_map(|s| index.of(s)).collect(); + if let Some(&(time, xp)) = cooking.get(&e.id) { + (r.cooking_time, r.experience) = (time, xp); + } + out.push(r); + } + for c in &self.res.recipes().cooking { + if c.kind == "minecraft:campfire_cooking" { + let mut r = recipe(format!("minecraft:{}", c.id), RecipeKind::Campfire); + r.group = c.group.clone(); + r.slots = vec![index.any(&c.ingredient)]; + r.results = index.of(&c.result).into_iter().collect(); + (r.cooking_time, r.experience) = (c.time, c.experience); + out.push(r); + } + } + let stations = self.res.stations(); + for s in &stations.recipes.stonecutting { + let mut r = recipe(s.id.clone(), RecipeKind::Stonecutting); + r.slots = vec![index.any(&s.input)]; + r.results = index.of(&s.result).into_iter().collect(); + out.push(r); + } + for s in &stations.recipes.smithing { + let (id, template, base, addition, results) = match s { + Smithing::Transform { + id, + template, + base, + addition, + result, + } => ( + id, + template, + base, + addition, + index.stack(result, 1, String::new()).into_iter().collect(), + ), + Smithing::Trim { + id, + template, + base, + addition, + .. + } => (id, template, base, addition, index.any(base)), + }; + let mut r = recipe(id.clone(), RecipeKind::Smithing); + r.slots = vec![index.any(template), index.any(base), index.any(addition)]; + r.results = results; + out.push(r); + } + for b in &stations.brewing.recipes { + let potion = |p: &horizon_client::brewing::PotionIngredient| -> Vec { + let mut item_ids: Vec<&String> = p.items.iter().collect(); + item_ids.sort(); + let mut potions: Vec<&String> = p.potions.iter().flatten().collect(); + potions.sort(); + item_ids + .into_iter() + .flat_map(|item| { + let one = |c: String| index.stack(item, 1, c); + if potions.is_empty() { + one(String::new()).into_iter().collect::>() + } else { + potions + .iter() + .filter_map(|p| { + one(format!("[minecraft:potion_contents={{potion:\"{p}\"}}]")) + }) + .collect() + } + }) + .collect() + }; + let mut r = recipe(b.id.clone(), RecipeKind::Brewing); + r.slots = vec![potion(&b.input), potion(&b.reagent)]; + r.results = index.of(&b.output).into_iter().collect(); + out.push(r); + } + Recipes { + items: table, + recipes: out, + } + } +} diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index d6e38dbbf..52dc46fe0 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -63,6 +63,14 @@ pub(super) struct ModsState { /// What players did this tick, for server mods at its end. #[cfg(feature = "mods")] pub(super) events: Vec, + /// A running server mod has capability `world`: its calls get the + /// levels' chunks to read. + #[cfg(feature = "mods")] + pub(super) world: bool, + /// Blocks server mods set, by dimension, made before that level's next + /// tick. + #[cfg(feature = "mods")] + pub(super) block_writes: Vec<(String, horizon_mods::BlockChange)>, /// `command.run` lines for this window's own world, run on the next tick: /// run at once, their chat lines would reach the mods while their output /// is still being shown, and a mod answering its own lines would recurse. @@ -81,6 +89,15 @@ pub(super) struct ModsState { /// The HUD font's advances for `render.text-width`, made once. #[cfg(feature = "mods")] font_widths: std::sync::Arc<[f32]>, + /// Capability `recipes`'s tables, made once a mod reads them. + #[cfg(feature = "mods")] + pub(super) recipes: Option>, + /// The recipe book's known displays, and the book's version they are of. + #[cfg(feature = "mods")] + pub(super) known_recipes: (Option, std::sync::Arc<[i32]>), + /// Capability `ui`'s item panel beside container screens. + #[cfg(feature = "mods")] + pub(super) browser: super::mod_browser::Browser, /// Extras that are official mods now, being installed. #[cfg(feature = "mods")] pub(super) moved: super::moved_extras::MovedState, @@ -293,6 +310,8 @@ impl Game<'_> { self.mods.mods.set_bindings(|id| chosen.keys_of(id)); // Entries were replaced wholesale: a screen's owner index is stale. self.mods.screen = None; + // Content mods may have changed the items: remade on the next read. + self.mods.recipes = None; self.list_mods(); self.sync_mod_commands(); self.show_mod_output(); @@ -309,6 +328,7 @@ impl Game<'_> { /// The Mods page's rows, from what loaded. fn list_mods(&mut self) { self.mods.server = self.mods.mods.runs_server(); + self.mods.world = self.mods.mods.wants_world(); let dev = &self.mods.dev; self.settings.mods.installed = self .mods @@ -351,7 +371,10 @@ impl Game<'_> { } /// The chat's tree after the running mods changed. fn sync_mod_commands(&mut self) { - let mut names = self.mods.mods.commands().peekable(); + // In-frame, the window runs server mods too: their names, free text + // here (the server parses their arguments). + let server = self.mods.mods.server_commands().map(|c| c.name.as_str()); + let mut names = self.mods.mods.commands().chain(server).peekable(); self.mods.tree = names .peek() .is_some() @@ -440,6 +463,7 @@ impl Game<'_> { .map(|c| char::from_u32(c).map_or(6.0, |c| atlas.glyph_cell(c).1)) .collect(); } + let (recipes, known_recipes) = self.mod_recipes(); Snapshot { player, clock, @@ -451,6 +475,10 @@ impl Game<'_> { font_widths: self.mods.font_widths.clone(), players, view_hit: self.mod_view_hit(), + recipes, + known_recipes, + placing: self.mod_recipe_screen(), + creative: self.creative, } } /// The first block along the player's view within @@ -673,8 +701,10 @@ impl Game<'_> { } Text::literal(line).with_color(text::RED) } - server - @ (Output::Tell { .. } | Output::Broadcast { .. } | Output::Reply { .. }) => { + server @ (Output::Tell { .. } + | Output::Broadcast { .. } + | Output::Reply { .. } + | Output::SetBlocks { .. }) => { self.route_server_output(host.as_deref_mut(), server); continue; } @@ -686,6 +716,18 @@ impl Game<'_> { self.mods.shake.add(strength, seconds); continue; } + Output::PlaceRecipe { book_id, all } => { + self.mod_place_recipe(book_id, all); + continue; + } + Output::Give { + item, + count, + components, + } => { + self.mod_give(&item, count, &components); + continue; + } Output::CloseScreen { owner } => { if self.mods.screen.as_ref().is_some_and(|s| s.owner == owner) { self.close_mod_screen(false); diff --git a/crates/horizon-client/src/game/music.rs b/crates/horizon-client/src/game/music.rs index 6f8b5e7ae..97ca3763e 100644 --- a/crates/horizon-client/src/game/music.rs +++ b/crates/horizon-client/src/game/music.rs @@ -3,7 +3,7 @@ use super::Game; use horizon_client::{ blocks::Fluid, - music::{BackgroundMusic, Music, Situation}, + music::{BackgroundMusic, Music, MusicFrequency, Situation}, sound_engine::TickContext, }; @@ -11,6 +11,11 @@ impl Game<'_> { /// `Minecraft.tick` -> `MusicManager.tick`, once per client tick. pub(super) fn tick_music(&mut self) { let (music, volume) = self.situational_music(); + // Options.musicFrequency's listener: MusicManager.setMinutesBetweenSongs. + let frequency = MusicFrequency::parse(&self.settings.file.name("musicFrequency")); + if frequency != self.music.frequency { + self.music.set_frequency(frequency, music.as_ref()); + } // LevelLoadingScreen: no new track before the player is in the world. let loading = self.title.is_none() && self.player.is_none() && self.win.is_none(); self.music @@ -91,7 +96,7 @@ impl Game<'_> { }) } /// `isEyeInFluid(WATER)`: the eye inside the water of its block column. - fn eye_in_water(&self, x: f64, eye_y: f64, z: f64) -> bool { + pub(super) fn eye_in_water(&self, x: f64, eye_y: f64, z: f64) -> bool { let (bx, by, bz) = (x.floor() as i32, eye_y.floor() as i32, z.floor() as i32); let f = self.res.facts().get(self.world.block(bx, by, bz)); if f.fluid != Fluid::Water { diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index b5e650e70..9e727d35d 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -357,7 +357,8 @@ impl Game<'_> { pub(super) fn load_mob(&mut self, tag: Tag, mount: Option) -> Option { self.next_entity += 1; let uuid = entity_nbt::uuid(&tag); - // Structure entities placed with finalizeEntities. + // Structure mobs that generation left to finish: saves from before + // they were finalized at placement, or a placement that could not. let mut tag = tag; let mut finalize = false; if let Tag::Compound(c) = &mut tag { @@ -449,7 +450,8 @@ impl Game<'_> { } } /// An entity of a type Horizon does not simulate, kept as its compound. - fn load_other(&mut self, tag: Tag, kind: &str) -> Option { + fn load_other(&mut self, mut tag: Tag, kind: &str) -> Option { + strip_finalize(&mut tag); let position = entity_nbt::position(&tag)?; let rotation = match tag.get("Rotation") { Some(Tag::List(l)) => { @@ -1014,3 +1016,9 @@ impl Game<'_> { self.save.save_entities(chunks) } } +/// Only a mob is finalized; another entity drops the request. +fn strip_finalize(tag: &mut Tag) { + if let Tag::Compound(c) = tag { + c.remove(&"horizon:finalize".into()); + } +} diff --git a/crates/horizon-client/src/game/pickups.rs b/crates/horizon-client/src/game/pickups.rs index 1e19bcfc3..040a6f01b 100644 --- a/crates/horizon-client/src/game/pickups.rs +++ b/crates/horizon-client/src/game/pickups.rs @@ -155,6 +155,8 @@ mod tests { value: 1, age: 0, on_ground: false, + count: 1, + ticks: 0, })) } diff --git a/crates/horizon-client/src/game/piglins.rs b/crates/horizon-client/src/game/piglins.rs index bcf9e6ab5..edfd9a3a0 100644 --- a/crates/horizon-client/src/game/piglins.rs +++ b/crates/horizon-client/src/game/piglins.rs @@ -4,18 +4,172 @@ use super::Game; use horizon_client::{ items::ItemStack, - mobs::{Species, Who, piglin::ADMIRE}, + mobs::{ + Mob, Species, Who, + finalize::{ + SLOT_NAMES, set_drop_chance, set_item, set_slot_enchantments, slot_enchantments, + stored_drop_chance, + }, + piglin::{ADMIRE, ATE_RECENTLY}, + }, }; use horizon_core::{geometry::Vec3, random::RandomSource}; impl Game<'_> { - fn piglin_loved(&self, item: &str) -> bool { + fn item_in_tag(&self, tag: &str, item: &str) -> bool { self.res .items() .item_tags - .get("minecraft:piglin_loved") + .get(tag) .is_some_and(|t| t.contains(item)) } + fn piglin_loved(&self, item: &str) -> bool { + self.item_in_tag("minecraft:piglin_loved", item) + } + /// `PiglinAi.isLovedItem` or a preferred weapon (`Piglin.canReplaceCurrentItem`). + fn piglin_wanted(&self, item: &str) -> bool { + self.piglin_loved(item) || self.item_in_tag("minecraft:piglin_preferred_weapons", item) + } + /// The `SLOT_NAMES` index `getEquipmentSlotForItem` picks: armour goes + /// to its slot, anything else to the main hand. + fn piglin_slot(&self, item: &str) -> usize { + let slot = self + .res + .items() + .get(item) + .and_then(|i| i.equip_slot.as_deref()) + .filter(|s| matches!(*s, "head" | "chest" | "legs" | "feet")) + .unwrap_or("mainhand"); + SLOT_NAMES.iter().position(|n| *n == slot).unwrap_or(0) + } + /// `Piglin.canReplaceCurrentItem`: an empty slot takes anything, a wanted + /// item replaces an unwanted one and never the other way round. Vanilla's + /// armour and weapon comparison for two equal-interest items is left out + /// (the piglin keeps what it has). + fn piglin_can_replace(&self, m: &Mob, item: &str, slot: usize) -> bool { + let Some(current) = horizon_client::mobs::finalize::item(m, slot) else { + return true; + }; + self.piglin_wanted(item) && !self.piglin_wanted(¤t) + } + /// `SimpleContainer.canAddItem` on the piglin's eight slots. + fn piglin_can_add(&self, m: &Mob, stack: &ItemStack) -> bool { + m.extra.inventory.len() < 8 + || m.extra.inventory.iter().any(|s| { + s.same_item_same_components(stack) && s.count < self.piglin_max_stack(&s.item) + }) + } + fn piglin_max_stack(&self, item: &str) -> u32 { + self.res.items().get(item).map_or(64, |i| i.max_stack) + } + /// `PiglinAi.wantsToPickup` (an adult that is not hurt-shy), without + /// the baby rule, which babies skip entirely here. + fn piglin_wants(&self, m: &Mob, stack: &ItemStack) -> bool { + let item = &*stack.item; + if self.item_in_tag("minecraft:piglin_repellents", item) { + return false; + } + let holds_loved = m + .extra + .off_hand + .as_deref() + .is_some_and(|o| self.piglin_loved(o)); + if item == "minecraft:gold_ingot" { + return !holds_loved; + } + let space = self.piglin_can_add(m, stack); + if item == "minecraft:gold_nugget" { + space + } else if self.item_in_tag("minecraft:piglin_food", item) { + m.extra.ints[0] <= 0 && space + } else if !self.piglin_loved(item) { + self.piglin_can_replace(m, item, self.piglin_slot(item)) + } else { + !holds_loved && space + } + } + /// `Mob.equipItemIfPossible` for a piglin: put it in its slot when that + /// slot takes it (an armour piece that cannot replace what is worn goes + /// to an empty main hand), dropping what it replaces by drop chance. + fn piglin_equip(&mut self, index: usize, stack: &ItemStack) -> bool { + let item = &*stack.item; + let mut slot = self.piglin_slot(item); + let m = &self.mobs[index]; + let mut replace = self.piglin_can_replace(m, item, slot); + if slot > 1 && !replace { + slot = 0; + replace = m.extra.main_hand.is_none(); + } + if !replace { + return false; + } + let m = &mut self.mobs[index]; + let old = horizon_client::mobs::finalize::item(m, slot); + let chance = stored_drop_chance(m, slot); + let drop_old = old.is_some() && (m.random.next_float() - 0.1).max(0.0) < chance; + let old_enchantments = slot_enchantments(m, slot); + set_item(m, slot, item); + // The piglin keeps what the stack carried (Protection IV stays on). + set_slot_enchantments(m, slot, stack.enchantments().to_vec()); + // setItemSlotAndDropWhenKilled, then persistenceRequired. + set_drop_chance(m, slot, 2.0); + m.persistent = true; + let at = [m.position.x, m.position.y, m.position.z]; + if let (true, Some(old)) = (drop_old, old) { + let mut dropped = ItemStack::new(&old, 1); + dropped.set_crafting_enchantments(old_enchantments); + self.spawn_item(dropped, at, super::dispenser::new_item_motion(), 10); + } + true + } + /// `PiglinAi.putInInventory`: what does not fit is thrown at a random + /// spot nearby. + fn piglin_stash(&mut self, index: usize, mut stack: ItemStack) { + let max = self.piglin_max_stack(&stack.item); + let m = &mut self.mobs[index]; + for s in &mut m.extra.inventory { + if stack.count > 0 && s.same_item_same_components(&stack) && s.count < max { + let n = (max - s.count).min(stack.count); + s.count += n; + stack.count -= n; + } + } + while stack.count > 0 && m.extra.inventory.len() < 8 { + let n = stack.count.min(max); + m.extra.inventory.push(ItemStack { + count: n, + ..stack.clone() + }); + stack.count -= n; + } + if stack.count == 0 { + return; + } + let from = [m.position.x, m.position.y + 1.3, m.position.z]; + let r = &mut self.world.random; + let to = [ + from[0] + f64::from(r.next_float() * 8.0 - 4.0), + from[1], + from[2] + f64::from(r.next_float() * 8.0 - 4.0), + ]; + self.piglin_throw(from, to, stack); + } + /// `PiglinAi.stopHoldingOffHandItem` for something that is not + /// bartering currency: wear it if it can, else keep it in the inventory. + fn piglin_keep(&mut self, index: usize, stack: ItemStack) { + // Nuggets keep their whole stack in the inventory (a hand slot here + // holds one item id only). + if &*stack.item == "minecraft:gold_nugget" || !self.piglin_equip(index, &stack) { + self.piglin_stash(index, stack); + } + } + /// `BehaviorUtils.throwItem`: toss a stack from a point toward another. + fn piglin_throw(&mut self, from: [f64; 3], to: [f64; 3], stack: ItemStack) { + let d = [to[0] - from[0], to[1] - from[1], to[2] - from[2]]; + let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1e-6); + let v = [d[0] / len * 0.3, d[1] / len * 0.3 + 0.1, d[2] / len * 0.3]; + self.spawn_item(stack, from, v, 40); + } /// `PiglinAi.isWearingSafeArmor`. pub(super) fn wearing_gold(&self) -> bool { let tag = self @@ -28,15 +182,13 @@ impl Game<'_> { .flatten() .any(|s| tag.is_some_and(|t| t.contains(&*s.item))) } - /// Piglins notice gold on the ground within 9 blocks, walk to it and - /// take it (`GoToWantedItem`, `Piglin.pickUpItem`). + /// Piglins notice wanted items on the ground within 9 blocks (`PiglinAi.wantsToPickup`: + /// gold and other loved items, nuggets, food, gear), walk to them and + /// take them (`GoToWantedItem`, `Piglin.pickUpItem`). pub(super) fn piglin_pickups(&mut self) { if !self.ui.rules.bool("mob_griefing") { return; } - // Whether each item is piglin-loved, kept until an item is added or - // removed (added ones are pushed at the end under a new id). - let mut loved: (Option<(usize, Option)>, Vec) = (None, Vec::new()); for i in 0..self.mobs.len() { let m = &self.mobs[i]; if m.species() != Species::Piglin @@ -44,27 +196,17 @@ impl Game<'_> { || m.is_baby() || m.extra.using_item > 0 || m.extra.egg_time > 0 - || m.extra.off_hand.is_some() { continue; } let pos = m.position; - let key = (self.dropped.len(), self.dropped.last().map(|e| e.id)); - if loved.0 != Some(key) { - loved.0 = Some(key); - loved.1 = self - .dropped - .iter() - .map(|e| self.piglin_loved(&e.stack.item)) - .collect(); - } let best = self .dropped .iter() .enumerate() - .filter(|&(j, _)| loved.1[j]) .map(|(j, e)| (j, e.position.distance_squared(pos))) .filter(|(_, d)| *d <= 81.0) + .filter(|&(j, _)| self.piglin_wants(m, &self.dropped[j].stack)) .min_by(|a, b| a.1.total_cmp(&b.1)); let Some((j, _)) = best else { self.mobs[i].extra.point = None; @@ -79,24 +221,38 @@ impl Game<'_> { continue; } // Nuggets come whole, anything else one at a time. - let item = e.stack.item.clone(); let (taken_item, id) = (e.clone(), self.mobs[i].id); + let item = e.stack.item.clone(); self.add_pickup( super::pickups::Taken::Item(Box::new(taken_item)), super::pickups::Collector::Mob(id), ); - let taken = if &*item == "minecraft:gold_nugget" { - self.dropped.remove(j).stack.count + let stack = if &*item == "minecraft:gold_nugget" { + self.dropped.remove(j).stack } else { let e = &mut self.dropped[j]; e.stack.count -= 1; + let one = ItemStack { + count: 1, + ..e.stack.clone() + }; if e.stack.count == 0 { self.dropped.remove(j); } - 1 + one }; - let _ = taken; - self.start_admiring(i, item); + if self.piglin_loved(&item) { + self.start_admiring(i, item); + } else if self.item_in_tag("minecraft:piglin_food", &item) + && self.mobs[i].extra.ints[0] <= 0 + { + // PiglinAi.eat: the food is gone and it will not eat for a while. + self.mobs[i].extra.ints[0] = ATE_RECENTLY; + self.mobs[i].nav_stop(); + } else { + self.mobs[i].nav_stop(); + self.piglin_keep(i, stack); + } } } fn start_admiring(&mut self, index: usize, item: std::sync::Arc) { @@ -109,14 +265,15 @@ impl Game<'_> { self.audio .play("minecraft:entity.piglin.admiring_item", Some(at), 1.0, 1.0); } - /// `PiglinAi.mobInteract`: hand a piglin something it loves. + /// `PiglinAi.mobInteract`: hand a piglin a gold ingot (only piglin + /// currency is accepted from the hand; other loved items are passed over). pub(super) fn give_piglin(&mut self, index: usize, item: &str) -> bool { let m = &self.mobs[index]; if m.species() != Species::Piglin || m.is_baby() || m.extra.using_item > 0 || m.extra.egg_time > 0 - || !self.piglin_loved(item) + || item != "minecraft:gold_ingot" { return false; } @@ -124,7 +281,8 @@ impl Game<'_> { true } /// `PiglinAi.stopHoldingOffHandItem` after admiring: gold ingots buy a - /// roll of the bartering table, thrown toward the player. + /// roll of the bartering table, thrown toward the player; any other loved + /// item it picked up is kept (worn if it can be, else stored). pub(super) fn finish_admiring(&mut self, mob: u32) { let Some(i) = self.mobs.iter().position(|m| m.id == mob) else { return; @@ -132,9 +290,13 @@ impl Game<'_> { let Some(item) = self.mobs[i].extra.off_hand.take() else { return; }; + if &*item != "minecraft:gold_ingot" { + self.piglin_keep(i, ItemStack::new(&item, 1)); + return; + } let m = &self.mobs[i]; let from = [m.position.x, m.position.y + 1.3, m.position.z]; - let items = if &*item == "minecraft:gold_ingot" && !m.is_baby() { + let items = if !m.is_baby() { self.res.items().loot_table( "minecraft:gameplay/piglin_bartering", false, @@ -176,10 +338,7 @@ impl Game<'_> { from[2] + f64::from(r.next_float() * 8.0 - 4.0), ] }); - let d = [to[0] - from[0], to[1] - from[1], to[2] - from[2]]; - let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1e-6); - let v = [d[0] / len * 0.3, d[1] / len * 0.3 + 0.1, d[2] / len * 0.3]; - self.spawn_item(stack, from, v, 40); + self.piglin_throw(from, to, stack); } } /// `PiglinAi.angerNearbyPiglins`. diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 13eae7d3e..3d5390ce3 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -276,7 +276,8 @@ impl Game<'_> { } else if let Some(rest) = self.give(filled) && let Some(eye) = self.eye_position() { - self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40); + // `player.drop(stack, false)`. + self.throw_from_eyes(rest, eye, false); } } /// Drinking a potion while right-click is held; true when handled. @@ -400,8 +401,28 @@ impl Game<'_> { for action in actions { self.apply_effect_action(action); } + self.turtle_helmet_tick(); self.apply_effect_status(); } + /// `Player.tick` -> `turtleHelmetTick`: with a turtle helmet on the head + /// and the eyes out of the water, Water Breathing for 200 ticks (no + /// particles, an icon). + fn turtle_helmet_tick(&mut self) { + let Some(p) = self.player.as_ref() else { + return; + }; + let eye_y = p.position.y + f64::from(p.dimensions.eye_height); + if !p.health.dead_or_dying() + && self.armor[0] + .as_ref() + .is_some_and(|s| &*s.item == "minecraft:turtle_helmet") + && !self.eye_in_water(p.position.x, eye_y, p.position.z) + { + let mut effect = EffectInstance::new("water_breathing", 200, 0); + effect.visible = false; + self.potions.effects.add(effect); + } + } /// A client's own effects (`LivingEntity.tickEffects` on the client, /// `MobEffectInstance.tickClient`): they count down, and the server /// removes them. Their modifiers and flags move the predicted player. @@ -674,62 +695,31 @@ impl Game<'_> { } /// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash). fn splash(&mut self, stack: &ItemStack, at: Vec3) { + let block = [at.x, at.y, at.z].map(|v| v.floor() as i32); if &*stack.item == "minecraft:experience_bottle" { // ThrownExperienceBottle.onHit: the water-coloured splash (level - // event 2002) and 3 to 11 experience. - let pitch = self.world.random.next_float() * 0.1 + 0.9; - self.audio.play( - "minecraft:entity.splash_potion.break", - Some([at.x, at.y, at.z]), - 1.0, - pitch, - ); - for _ in 0..8 { - let v = [ - f64::from(self.world.random.next_float() - 0.5) * 0.3, - 0.2, - f64::from(self.world.random.next_float() - 0.5) * 0.3, - ]; - let p = horizon_client::particles::Particle::terrain( - &mut self.world.random, - [at.x, at.y, at.z], - v, - "item/splash_potion".into(), - 0x38_5DC6, - ); - self.particles.push(p); - } + // event 2002, its sound 1053) and 3 to 11 experience. + self.level_event_at(2002, block, 0xFF38_5DC6u32 as i32); + self.level_event_at(1053, block, 0); let r = &mut self.world.random; let value = 3 + r.next_int_bound(5).unwrap_or(0) + r.next_int_bound(5).unwrap_or(0); self.spawn_orbs([at.x, at.y, at.z], value as u32); return; } let lingering = &*stack.item == "minecraft:lingering_potion"; - let event = if lingering { - "minecraft:entity.lingering_potion.break" - } else { - "minecraft:entity.splash_potion.break" - }; - let pitch = self.world.random.next_float() * 0.1 + 0.9; - self.audio.play(event, Some([at.x, at.y, at.z]), 1.0, pitch); + // AbstractThrownPotion.onHit: level event 2007 and sound 1054 for a + // potion with instant effects, 2002 and 1053 otherwise. + let potion = stack.potion().and_then(brewing::potion); + let instant = potion.is_some_and(|d| { + d.effects + .iter() + .any(|(id, ..)| brewing::effect(id).is_some_and(|e| e.instant)) + }); let color = brewing::potion_color(stack.potion()); - for _ in 0..8 { - let v = [ - f64::from(self.world.random.next_float() - 0.5) * 0.3, - 0.2, - f64::from(self.world.random.next_float() - 0.5) * 0.3, - ]; - let p = horizon_client::particles::Particle::terrain( - &mut self.world.random, - [at.x, at.y, at.z], - v, - "item/splash_potion".into(), - color, - ); - self.particles.push(p); - } + self.level_event_at(if instant { 2007 } else { 2002 }, block, color as i32); + self.level_event_at(if instant { 1054 } else { 1053 }, block, 0); let scale = if lingering { 0.25 } else { 1.0 }; - let Some(def) = stack.potion().and_then(brewing::potion) else { + let Some(def) = potion else { return; }; // Every player in range (`ThrownSplashPotion.applySplash` over diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index bedca5708..da7c79394 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -235,7 +235,7 @@ impl Game<'_> { } out } - fn difficulty_id(&self) -> i32 { + pub(super) fn difficulty_id(&self) -> i32 { use horizon_world::food::Difficulty; match self.world.health_rules.difficulty { Difficulty::Peaceful => 0, @@ -796,6 +796,8 @@ impl Game<'_> { let s = m.extra.raider.get_or_insert_with(Box::default); s.rider = has_rider; s.in_village = in_village; + // Vindicator.customServerAiStep: `ServerLevel.isRaided`. + s.raided = species == Species::Vindicator && raids.nearby(block).is_some(); if s.raid_id.is_some_and(|id| raids.get(id).is_none()) { s.raid_id = None; s.ticks_outside_raid = 0; diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 96e12d79b..024d45734 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -338,6 +338,25 @@ impl Game<'_> { ui.client_known = Some(known.clone()); ui.client_version += 1; } + /// Every entry of the book, in its order (capability `recipes`). + #[cfg(feature = "mods")] + pub(super) fn recipe_book_entries(&mut self) -> Vec { + self.ensure_book(); + self.recipe_ui + .book + .as_ref() + .map_or_else(Vec::new, |b| b.entries.clone()) + } + /// The display ids the player's book holds, and a number that changes + /// whenever they do (capability `recipes`). + #[cfg(feature = "mods")] + pub(super) fn recipe_book_displays(&mut self) -> (u64, Vec) { + self.sync_client_book(); + ( + self.recipe_ui.client_version, + self.recipe_ui.client.displays(), + ) + } fn ensure_book(&mut self) { if self.recipe_ui.book.is_none() { let mut book = Book::build(self.res.recipes(), self.res.items()); @@ -826,6 +845,34 @@ impl Game<'_> { self.recipe_ui.ghost.clear(); self.place_recipe(book_type, entry_index, use_max); } + /// Whether the open screen takes `recipes.place`: a crafting grid's + /// book (the inventory's or a crafting table's). + #[cfg(feature = "mods")] + pub(super) fn mod_recipe_screen(&self) -> bool { + self.screen == Screen::Inventory + && self.active_book() == Some(BookType::Crafting) + && !self.spectator() + } + /// `recipes.place`: the book's click on the recipe with this display + /// id, refused as `handlePlaceRecipe` refuses it (no crafting screen, + /// not in the player's book; an impossible one in `place_recipe`). + #[cfg(feature = "mods")] + pub(super) fn mod_place_recipe(&mut self, display_id: i32, all: bool) { + if !self.mod_recipe_screen() || !self.recipe_ui.client.displays().contains(&display_id) { + return; + } + self.ensure_book(); + let Some(index) = self + .recipe_ui + .book + .as_ref() + .and_then(|b| b.entries.iter().position(|e| e.display_id == display_id)) + else { + return; + }; + self.recipe_ui.ghost.clear(); + self.place_recipe(BookType::Crafting, index, all); + } /// `ServerboundPlaceRecipePacket`: the server places the recipe /// (`ServerPlaceRecipe` on the menu engine) and answers with a ghost /// recipe when the items are missing. diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..671b88d7f 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1283,6 +1283,8 @@ impl Game<'_> { value: 1, age: 0, on_ground: false, + count: 1, + ticks: 0, }); } if let Some(t) = mob_type { @@ -1973,9 +1975,9 @@ impl Game<'_> { } } } - // Entity.DATA_SHARED_FLAGS_ID's crouching bit: another - // player's or a mannequin's crouch (their model and - // Entity.isDiscrete's name tag). + // Entity.DATA_SHARED_FLAGS_ID's crouching and sprinting bits: + // another player's or a mannequin's crouch (their model and + // Entity.isDiscrete's name tag), and the dust a runner raises. if (mannequin || self .remote @@ -1986,6 +1988,7 @@ impl Game<'_> { for (index, _, value) in &p.values { if let (0, Value::Byte(flags)) = (index, value) { m.extra.crouching = flags & 2 != 0; + m.extra.sprinting = flags & 8 != 0; } } } @@ -2064,7 +2067,10 @@ impl Game<'_> { { self.add_pickup(super::pickups::Taken::Orb(Box::new(orb)), collector); } - self.remove_entity(p.item); + // An orb stays: the server may still hold merged ones in it. + if !orb { + self.remove_entity(p.item); + } } // ClientPacketListener.handleSetEntityMotion: knockback on this player. C::SetEntityMotion(p) if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) => { @@ -2106,6 +2112,7 @@ impl Game<'_> { if p.event == super::fireworks::FIREWORK_EXPLODE_EVENT { self.remote_firework_explosion(p.id); } + self.remote_fangs_event(p.id as u32, p.event); // LocalPlayer.setPermissions also refreshes an open World Options screen. if (24..=28).contains(&p.event) && self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) @@ -4051,15 +4058,11 @@ impl Game<'_> { world_border: false, sequence: seq, })); - let target = [ - hit.pos[0] + hit.face[0], - hit.pos[1] + hit.face[1], - hit.pos[2] + hit.face[2], - ]; - let ticks = self.ticks; + // Only a predicted placement (predict_place) marks a cell whose + // resend plays a place sound: an empty hand or a non-block item + // places nothing (BlockItem.place is where the sound comes from). if let Some(r) = self.remote.as_mut() { r.use_target = Some(hit.pos); - r.placing = Some((target, ticks)); } if reacts { self.predict_use(&changes, seq); diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index 897999c6b..eabb89093 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -95,6 +95,7 @@ impl Game<'_> { let (yaw, pitch) = rotation; self.remove_remote_projectile(id); match kind { + "minecraft:evoker_fangs" => self.insert_fangs(id, position, yaw, 0, 0), "minecraft:tnt" => self.tnts.push(super::tnt::PrimedTnt { id, position: at, @@ -296,6 +297,7 @@ impl Game<'_> { /// One tick of interpolation, as `tick_remote_objects`. pub(super) fn tick_remote_projectiles(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) { + self.tick_remote_fangs(); // PrimedTnt.tick runs on a client too: it falls, bounces and burns its // fuse down (the swell and flash follow it) between the server's // updates (every 10 ticks), and a client discards it when the fuse @@ -458,6 +460,7 @@ impl Game<'_> { } pub(super) fn remove_remote_projectile(&mut self, id: u32) { + self.fangs.list.retain(|f| f.id != id); self.tnts.retain(|t| t.id != id); self.falling.retain(|f| f.id != id); self.creatures.projectiles.retain(|p| p.id != id); @@ -473,6 +476,7 @@ impl Game<'_> { /// Every one a server sent (a new connection, level or dimension). pub(super) fn clear_remote_projectiles(&mut self) { + self.fangs.list.clear(); self.tnts.clear(); self.falling.clear(); self.creatures.projectiles.clear(); @@ -493,6 +497,12 @@ impl Game<'_> { use serde_json::json; let at = |p: Vec3| [p.x, p.y, p.z]; let mut out = Vec::new(); + for f in &self.fangs.list { + out.push( + json!({"id": f.id, "kind": "minecraft:evoker_fangs", "position": f.pos, + "yaw": f.yaw, "started": f.started, "life": f.life}), + ); + } for t in &self.tnts { out.push(json!({"id": t.id, "kind": "minecraft:tnt", "position": at(t.position), "fuse": t.fuse})); } diff --git a/crates/horizon-client/src/game/render_control.rs b/crates/horizon-client/src/game/render_control.rs index 0a2f9b715..7c5ff4b2d 100644 --- a/crates/horizon-client/src/game/render_control.rs +++ b/crates/horizon-client/src/game/render_control.rs @@ -19,33 +19,7 @@ pub const HELP: &[&str] = &[ impl Game<'_> { /// Parse `name[k=v,...]` into a registry state (defaults for missing properties). fn parse_state(&self, text: &str) -> Result { - let (name, props) = match text.split_once('[') { - Some((n, rest)) => (n, rest.trim_end_matches(']')), - None => (text, ""), - }; - let name = if name.contains(':') { - name.to_owned() - } else { - format!("minecraft:{name}") - }; - let registry = &self.pack.assets.registry; - let default = registry - .default_state(&name) - .ok_or_else(|| format!("unknown block {name}"))?; - let mut state = registry - .state(default) - .ok_or("missing default state")? - .clone(); - for pair in props.split(',').filter(|p| !p.is_empty()) { - let (k, v) = pair - .split_once('=') - .ok_or_else(|| format!("bad property {pair}"))?; - if !state.properties.contains_key(k) { - return Err(format!("{name} has no property {k}").into()); - } - state.properties.insert(k.to_owned(), v.to_owned()); - } - Ok(registry.resolve(&state)?) + parse_state(self.pack.assets.registry, text) } pub(super) fn render_command(&mut self, words: &[&str]) -> Result> { let int = |i: usize| -> Result { @@ -137,3 +111,36 @@ impl Game<'_> { } } } + +/// Parse `name[k=v,...]` into a registry state (defaults for missing properties). +pub(super) fn parse_state( + registry: &horizon_world::registry::BlockRegistry, + text: &str, +) -> Result { + let (name, props) = match text.split_once('[') { + Some((n, rest)) => (n, rest.trim_end_matches(']')), + None => (text, ""), + }; + let name = if name.contains(':') { + name.to_owned() + } else { + format!("minecraft:{name}") + }; + let default = registry + .default_state(&name) + .ok_or_else(|| format!("unknown block {name}"))?; + let mut state = registry + .state(default) + .ok_or("missing default state")? + .clone(); + for pair in props.split(',').filter(|p| !p.is_empty()) { + let (k, v) = pair + .split_once('=') + .ok_or_else(|| format!("bad property {pair}"))?; + if !state.properties.contains_key(k) { + return Err(format!("{name} has no property {k}").into()); + } + state.properties.insert(k.to_owned(), v.to_owned()); + } + Ok(registry.resolve(&state)?) +} diff --git a/crates/horizon-client/src/game/server_mods.rs b/crates/horizon-client/src/game/server_mods.rs index db88639eb..a5a4b0f3f 100644 --- a/crates/horizon-client/src/game/server_mods.rs +++ b/crates/horizon-client/src/game/server_mods.rs @@ -47,19 +47,129 @@ impl Game<'_> { ) -> bool { false } + pub(super) fn apply_mod_block_writes(&mut self) {} } #[cfg(feature = "mods")] mod run { use super::{Game, LanHost, ModEvent, Who}; + use horizon_client::chunk_map::ChunkMap; use horizon_client::{ command::args::GameMode as Mode, lan::data::component_nbt, text::{self, Text}, }; - use horizon_mods::{BlockPos, GameMode, Output, ServerPlayer}; + use horizon_mods::{ + ArgumentKind, BlockPos, GameMode, Output, ServerCommand, ServerPlayer, WorldView, + }; use horizon_protocol::packets::play::{self, Clientbound as C}; - use horizon_world::registry::BlockStateId; + use horizon_world::registry::{BlockRegistry, BlockStateId}; + use serde_json::{Value, json}; + + /// Blocks queued for levels that don't tick (another dimension, in-frame) + /// are kept up to this many; the oldest go first. + const MAX_QUEUED_WRITES: usize = 1 << 16; + + /// Capability `world`'s view during a call: the levels' chunks, moved out + /// of the game for the call and back after it (no copy). + struct LentWorld { + registry: &'static BlockRegistry, + biomes: std::sync::Arc, + dims: Vec<(&'static str, ChunkMap)>, + } + impl WorldView for LentWorld { + fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option { + let (_, chunks) = self.dims.iter().find(|(d, _)| *d == dimension)?; + let chunk = chunks.get(&(x >> 4, z >> 4))?; + Some(state_string(self.registry, chunk.block(x & 15, y, z & 15))) + } + fn biome(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option { + let (_, chunks) = self.dims.iter().find(|(d, _)| *d == dimension)?; + let chunk = chunks.get(&(x >> 4, z >> 4))?; + Some(self.biomes.get(chunk.biome(x, y, z)).name.clone()) + } + fn has_dimension(&self, dimension: &str) -> bool { + matches!( + dimension, + "minecraft:overworld" | "minecraft:the_nether" | "minecraft:the_end" + ) + } + fn check_state(&self, state: &str) -> Result<(), String> { + crate::game::render_control::parse_state(self.registry, state) + .map(drop) + .map_err(|e| format!("{state}: {e}")) + } + } + + /// Server mods' commands as a root of the commands report + /// (`lan::commands`): a literal per command, then its arguments in a + /// chain, each node runnable where only optional arguments follow. + fn command_tree<'a>(commands: impl Iterator) -> Value { + let mut root = serde_json::Map::new(); + for c in commands { + let mut next: Option<(String, Value)> = None; + for (i, a) in c.arguments.iter().enumerate().rev() { + let executable = c.arguments.get(i + 1).is_none_or(|b| b.optional); + let (parser, properties) = match a.kind { + ArgumentKind::Word => ("brigadier:string", json!({"type": "word"})), + ArgumentKind::Text => ("brigadier:string", json!({"type": "greedy"})), + ArgumentKind::Integer((min, max)) => { + let mut p = serde_json::Map::new(); + if let Some(min) = min { + p.insert("min".into(), min.into()); + } + if let Some(max) = max { + p.insert("max".into(), max.into()); + } + ("brigadier:integer", Value::Object(p)) + } + ArgumentKind::Number => ("brigadier:double", Value::Null), + ArgumentKind::Boolean => ("brigadier:bool", Value::Null), + ArgumentKind::Player => ( + "minecraft:entity", + json!({"amount": "single", "type": "players"}), + ), + ArgumentKind::BlockPos => ("minecraft:block_pos", Value::Null), + }; + let mut node = json!({ + "type": "argument", + "parser": parser, + "properties": properties, + "executable": executable, + }); + if let Some((name, child)) = next.take() { + node["children"] = json!({ name: child }); + } + next = Some((a.name.clone(), node)); + } + let executable = c.arguments.first().is_none_or(|a| a.optional); + let mut literal = json!({"type": "literal", "executable": executable}); + if let Some((name, child)) = next { + literal["children"] = json!({ name: child }); + } + root.insert(c.name.clone(), literal); + } + if root.is_empty() { + return Value::Null; + } + json!({"type": "root", "children": root}) + } + + /// `minecraft:oak_log[axis=y]`. + fn state_string(registry: &BlockRegistry, state: BlockStateId) -> String { + let Some(s) = registry.state(state) else { + return "minecraft:air".into(); + }; + if s.properties.is_empty() { + return s.name.clone(); + } + let props: Vec = s + .properties + .iter() + .map(|(k, v)| format!("{k}={v}")) + .collect(); + format!("{}[{}]", s.name, props.join(",")) + } /// `UUID.toString()`. fn uuid_string(u: u128) -> String { @@ -138,12 +248,14 @@ mod run { // A server has no frames to check its dev mods in. self.reload_dev_mods(); } + self.send_server_mod_commands(); if !self.mods.server { return; } let players = self.server_players(None); let snapshot = self.mod_snapshot_with(players.clone()); self.mods.mods.set_snapshot(snapshot); + self.lend_world(); let before = std::mem::take(&mut self.mods.players); for p in before .iter() @@ -197,8 +309,94 @@ mod run { } } self.mods.mods.server_tick(self.ticks); + self.return_world(); self.mods.players = players; self.show_mod_output(); + self.apply_mod_block_writes(); + } + + /// Players' command trees list the running server mods' commands + /// after vanilla's, whenever they change (or a hub opens). + fn send_server_mod_commands(&mut self) { + let key = self.mods.mods.generation(); + let Some(host) = self.lan.as_mut() else { + return; + }; + if host.hub.mod_commands_key() == Some(key) { + return; + } + let tree = command_tree(self.mods.mods.server_commands()); + host.hub.set_mod_commands(key, tree); + } + + /// Lends the levels' chunks to capability `world` for the calls up to + /// [`Game::return_world`], when a running server mod has it. + fn lend_world(&mut self) { + if !self.mods.world { + return; + } + let mut dims = vec![(self.dim.id(), std::mem::take(&mut self.world.chunks))]; + for (dim, chunks) in self.levels.parked_chunks() { + dims.push((dim.id(), std::mem::take(chunks))); + } + let registry = self.pack.assets.registry; + let biomes = self.res.biomes().clone(); + self.mods.mods.lend_world(Box::new(LentWorld { + registry, + biomes, + dims, + })); + } + + /// Puts back the chunks [`Game::lend_world`] lent. + fn return_world(&mut self) { + let Some(view) = self.mods.mods.take_world() else { + return; + }; + let view: Box = view; + let Ok(lent) = view.downcast::() else { + return; + }; + let mut dims = lent.dims; + if let Some(i) = dims.iter().position(|(d, _)| *d == self.dim.id()) { + self.world.chunks = dims.swap_remove(i).1; + } + for (dim, chunks) in self.levels.parked_chunks() { + if let Some(i) = dims.iter().position(|(d, _)| *d == dim.id()) { + *chunks = dims.swap_remove(i).1; + } + } + } + + /// Makes the blocks server mods set in the level in place, in order, + /// as `/setblock` does. Those of other dimensions wait for their level. + pub(in crate::game) fn apply_mod_block_writes(&mut self) { + if self.mods.block_writes.is_empty() { + return; + } + let dim = self.dim.id(); + let (now, later): (Vec<_>, Vec<_>) = std::mem::take(&mut self.mods.block_writes) + .into_iter() + .partition(|(d, _)| d == dim); + self.mods.block_writes = later; + let registry = self.pack.assets.registry; + for (_, b) in now { + let state = match crate::game::render_control::parse_state(registry, &b.state) { + Ok(state) => state, + Err(e) => { + log::warn!("Horizon: a server mod set {}: {e}", b.state); + continue; + } + }; + if let Err(e) = self.place_state([b.x, b.y, b.z], state, false) { + log::debug!( + "Horizon: a server mod's block at {} {} {}: {e:?}", + b.x, + b.y, + b.z + ); + } + } } /// A player broke (or placed) `state` at `pos`: the player acting now. @@ -240,8 +438,11 @@ mod run { }; let snapshot = self.mod_snapshot_with(players); self.mods.mods.set_snapshot(snapshot); + self.lend_world(); let owned = self.mods.mods.server_command(&me, line); + self.return_world(); self.show_mod_output(); + self.apply_mod_block_writes(); owned } @@ -266,10 +467,14 @@ mod run { }; let snapshot = self.mod_snapshot_with(players); self.mods.mods.set_snapshot(snapshot); - if !self.mods.mods.server_command(&me, line) { + self.lend_world(); + let owned = self.mods.mods.server_command(&me, line); + self.return_world(); + if !owned { return false; } self.route_mod_output(Some(host)); + self.apply_mod_block_writes(); true } @@ -349,6 +554,21 @@ mod run { self.tell_server_player(host.as_deref_mut(), &p.id, line); } } + Output::SetBlocks { + name, + dimension, + blocks, + } => { + let queued = &mut self.mods.block_writes; + queued.extend(blocks.into_iter().map(|b| (dimension.clone(), b))); + if queued.len() > MAX_QUEUED_WRITES { + let over = queued.len() - MAX_QUEUED_WRITES; + queued.drain(..over); + log::warn!( + "Horizon: mod {name} set more blocks than wait for their level: {over} dropped" + ); + } + } _ => {} } } diff --git a/crates/horizon-client/src/game/spill.rs b/crates/horizon-client/src/game/spill.rs index 7f370507f..b1953596b 100644 --- a/crates/horizon-client/src/game/spill.rs +++ b/crates/horizon-client/src/game/spill.rs @@ -171,8 +171,8 @@ pub(super) struct Spawn { pub(super) struct Spill { pub(super) spawns: Vec, /// Experience orbs (`ExperienceOrb.award`): where and how much, each - /// having drawn its merge id from the level random. - pub(super) orbs: Vec<([f64; 3], u32)>, + /// and the merge id it drew from the level random. + pub(super) orbs: Vec<([f64; 3], u32, i32)>, /// Block entities the behaviour removed, for the game's own follow-ups /// (open screens, playing songs). pub(super) removed: Vec<([i32; 3], BlockEntity)>, @@ -342,8 +342,8 @@ impl GameLevel<'_> { while amount > 0 { let value = removal::orb_value(amount); amount -= value; - let _merge_id = self.world.random.next_int_bound(40); - self.spill.orbs.push((at, value)); + let merge_id = self.world.random.next_int_bound(40).unwrap_or(0); + self.spill.orbs.push((at, value, merge_id)); } } /// `BlockEntity.preRemoveSideEffects` and `removeBlockEntity` for the block @@ -583,8 +583,8 @@ impl Game<'_> { let motion = s.motion.unwrap_or_else(new_item_motion); self.spawn_item(s.stack, s.pos, motion, s.delay); } - for (at, value) in spill.orbs { - self.add_orb(at, value); + for (at, value, merge_id) in spill.orbs { + self.award_orb(at, value, merge_id); } for (pos, entity) in spill.removed { let key = (pos[0], pos[1], pos[2]); diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 56b19e393..c5ddcf9a1 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -713,7 +713,8 @@ impl Game<'_> { if let Some(rest) = self.give(stack) && let Some(eye) = self.eye_position() { - self.spawn_item(rest, [eye[0], eye[1] - 0.3, eye[2]], [0.0, 0.1, 0.0], 40); + // Inventory.placeItemBackInInventory: `player.drop(stack, false)`. + self.throw_from_eyes(rest, eye, false); } } /// `Player.giveExperienceLevels`. diff --git a/crates/horizon-client/src/game/storage.rs b/crates/horizon-client/src/game/storage.rs index 1bcb6a524..e5cb0ab26 100644 --- a/crates/horizon-client/src/game/storage.rs +++ b/crates/horizon-client/src/game/storage.rs @@ -33,6 +33,55 @@ impl Game<'_> { self.container = Some(key); self.ender_open = Some(key); } + /// The block above `key` is a redstone conductor. + fn conductor_above(&self, key: (i32, i32, i32)) -> bool { + let above = self.world.block(key.0, key.1 + 1, key.2); + self.res.behaviours().facts(above).flags + & horizon_world::level::data::state_flags::CONDUCTOR + != 0 + } + /// `ChestBlock.isChestBlockedAt`: a redstone conductor above the chest or + /// a cat sitting on it. + fn chest_blocked_at(&self, key: (i32, i32, i32)) -> bool { + if self.conductor_above(key) { + return true; + } + // isCatSittingOnChest: a cat whose box meets the block above. + let area = horizon_core::geometry::Aabb::new( + horizon_core::geometry::Vec3::new( + f64::from(key.0), + f64::from(key.1 + 1), + f64::from(key.2), + ), + horizon_core::geometry::Vec3::new( + f64::from(key.0 + 1), + f64::from(key.1 + 2), + f64::from(key.2 + 1), + ), + ); + self.mobs.iter().any(|m| { + m.species() == horizon_client::mobs::Species::Cat + && m.alive() + && horizon_client::mobs::tame::cat_sitting(m) + && m.bounds().intersects(area) + }) + } + /// `ChestBlock.getMenuProvider` (`combine(.., false)`) and + /// `EnderChestBlock.useWithoutItem`: a blocked chest, or a double chest + /// with either half blocked, opens no menu. + pub(super) fn chest_menu_blocked(&self, key: (i32, i32, i32), name: &str) -> bool { + match name { + "minecraft:chest" | "minecraft:trapped_chest" => { + self.chest_blocked_at(key) + || self + .chest_partner(key) + .is_some_and(|(other, _)| self.chest_blocked_at(other)) + } + // The ender chest only looks at the block above (no cat check). + "minecraft:ender_chest" => self.conductor_above(key), + _ => false, + } + } /// Closing it copies the items back and leaves no block-entity contents. pub(super) fn close_ender_chest(&mut self) { let Some(key) = self.ender_open.take() else { diff --git a/crates/horizon-client/src/game/world_loading.rs b/crates/horizon-client/src/game/world_loading.rs index ef47cc9c0..73f1820f2 100644 --- a/crates/horizon-client/src/game/world_loading.rs +++ b/crates/horizon-client/src/game/world_loading.rs @@ -46,6 +46,10 @@ impl WorldRequest { options: &Options, settings: &Settings, ) -> Result { + // Before any chunk is read: a loaded container with a loot table is rolled as its chunk + // is decoded (`save::roll_loaded_loot`), and the spawn chunks are read while the world + // opens. Every world opens here: in-frame, on the server thread, on a dedicated server. + horizon_client::structure_blocks::loot_data(&options.resources); let Self { save_root, folder, @@ -192,6 +196,82 @@ impl WorldLoader { } } +/// How long the preloaded world data outlives the world screens: a player +/// who goes back to the title or to Multiplayer and opens no world for this +/// long gets the memory back. +const PRELOAD_KEPT: std::time::Duration = std::time::Duration::from_secs(60); + +enum Preload { + Idle, + /// Read, or being read, on the "World data preload" thread. `left`: when + /// the player last left the world screens. + Started { + thread: std::thread::JoinHandle<()>, + left: Option, + }, + /// A world opened: the data is the world's now, and stays. + Used, +} + +static PRELOAD: std::sync::Mutex = std::sync::Mutex::new(Preload::Idle); + +/// Each frame of the title: read what every world opening loads and keeps +/// for the rest of the process (the worldgen bundle, the loot tables and the +/// registries the server sends) on a helper thread while the player is on the +/// world screens (`on_world_screens`: Singleplayer, Create World and their +/// dialogs), so it overlaps the time spent choosing a world. A world opened +/// meanwhile waits for the part being read instead of reading it again. Not +/// at the title screen itself: many players only go to Multiplayer, and +/// small machines need the memory. Dropped after `PRELOAD_KEPT` away from +/// the world screens without a world opening. +pub(super) fn preload_world_data( + on_world_screens: bool, + resources: &std::path::Path, + registry: &'static horizon_world::registry::BlockRegistry, +) { + let mut preload = PRELOAD.lock().unwrap_or_else(|e| e.into_inner()); + match &mut *preload { + Preload::Used => {} + Preload::Idle if on_world_screens => { + let resources = resources.to_owned(); + let spawned = std::thread::Builder::new() + .name("World data preload".into()) + .spawn(move || { + horizon_threads::behind_server(); + // Errors are left for the world opening to report. + let _ = horizon_client::vanillagen::shared_data( + &resources.join("worldgen"), + registry, + ); + let _ = horizon_client::structure_blocks::loot_data(&resources); + let _ = super::lan::sync_data(&resources); + }); + match spawned { + Ok(thread) => *preload = Preload::Started { thread, left: None }, + Err(e) => log::warn!("Horizon: world data preload: {e}"), + } + } + Preload::Idle => {} + Preload::Started { left, .. } if on_world_screens => *left = None, + Preload::Started { thread, left } => { + let left = *left.get_or_insert_with(std::time::Instant::now); + if left.elapsed() >= PRELOAD_KEPT && thread.is_finished() { + horizon_client::vanillagen::forget_shared_data(); + horizon_client::structure_blocks::forget_loot_data(); + super::lan::forget_sync_data(); + horizon_threads::release_free_memory(); + *preload = Preload::Idle; + log::info!("Horizon: preloaded world data dropped, no world opened"); + } + } + } +} + +/// A world opens: what `preload_world_data` read is the world's from now on. +pub(super) fn world_data_used() { + *PRELOAD.lock().unwrap_or_else(|e| e.into_inner()) = Preload::Used; +} + pub(super) fn make_streaming( res: &Resources, pack: &PackResources, diff --git a/crates/horizon-client/src/game/zombie_reinforcements.rs b/crates/horizon-client/src/game/zombie_reinforcements.rs new file mode 100644 index 000000000..4c6100f43 --- /dev/null +++ b/crates/horizon-client/src/game/zombie_reinforcements.rs @@ -0,0 +1,134 @@ +//! `Zombie.hurtServer`'s reinforcements: a hurt zombie on Hard may call +//! another of its kind from 7 to 40 blocks away to fight its target. +use super::Game; +use horizon_client::mobs::{ + MobType, Species, Who, + finalize::{self, Attr, Op}, + spawn_rules::{self, Reason}, + spawn_selection::{self, NaturalLevel}, + spawner::SpawnerLevel, +}; +use horizon_core::random::{LegacyRandom, RandomSource}; +use horizon_world::food::Difficulty; + +/// `Zombie.REINFORCEMENT_ATTEMPTS`. +const ATTEMPTS: usize = 50; +/// `Zombie.REINFORCEMENT_RANGE_MIN` and `REINFORCEMENT_RANGE_MAX`. +const RANGE_MIN: i32 = 7; +const RANGE_MAX: i32 = 40; + +/// One axis of the offset: `Mth.nextInt(random, 7, 40) * Mth.nextInt(random, -1, 1)`. +fn offset(random: &mut LegacyRandom) -> i32 { + let distance = random + .next_int_between_inclusive(RANGE_MIN, RANGE_MAX) + .unwrap_or(RANGE_MIN); + distance * random.next_int_between_inclusive(-1, 1).unwrap_or(0) +} + +impl Game<'_> { + /// `Zombie.hurtServer` after the hit: on Hard, with the zombie's chance + /// and monsters spawning, a copy of it appears out of sight and takes + /// `target`; both then call less often. + pub(super) fn call_reinforcements(&mut self, caller: u32, target: Who) { + let Some(index) = self.mobs.iter().position(|m| m.id == caller) else { + return; + }; + if self.world.health_rules.difficulty != Difficulty::Hard { + return; + } + let zombie = &mut self.mobs[index]; + if f64::from(zombie.random.next_float()) >= zombie.attrs.spawn_reinforcements { + return; + } + // ServerLevel.isSpawningMonsters. + if !self.ui.rules.bool("spawn_mobs") || !self.ui.rules.bool("spawn_monsters") { + return; + } + let kind = zombie.kind.clone(); + let from = [ + zombie.position.x.floor() as i32, + zombie.position.y.floor() as i32, + zombie.position.z.floor() as i32, + ]; + let mut own = std::mem::replace(&mut zombie.random, LegacyRandom::new(0)); + let mut rules = std::mem::replace(&mut self.world.random, LegacyRandom::new(0)); + let spot = self.reinforcement_spot(&kind, from, &mut own, &mut rules); + self.mobs[index].random = own; + self.world.random = rules; + let Some(spot) = spot else { + return; + }; + let Some(id) = self.spawn_mob(&kind.id, spot.map(f64::from), false) else { + return; + }; + if let Some(reinforcement) = self.mobs.iter_mut().find(|m| m.id == id) { + reinforcement.ai.target = Some(target); + // ZOMBIE_REINFORCEMENT_CALLEE_CHARGE. + finalize::add_modifier( + reinforcement, + Attr::SpawnReinforcements, + "minecraft:reinforcement_callee_charge", + -f64::from(0.05f32), + Op::AddValue, + ); + } + // The caller's charge grows by 0.05 each time it calls. + let caller = &mut self.mobs[index]; + let charged = finalize::modifier_amount( + caller, + Attr::SpawnReinforcements, + "minecraft:reinforcement_caller_charge", + ) + .unwrap_or(0.0); + finalize::add_modifier( + caller, + Attr::SpawnReinforcements, + "minecraft:reinforcement_caller_charge", + charged - 0.05, + Op::AddValue, + ); + } + /// The block `Zombie.hurtServer` puts the reinforcement at: the first of + /// 50 random offsets with a valid spawn surface, no alive player within + /// 7 blocks, and room for the zombie standing on the block's corner. + fn reinforcement_spot( + &self, + kind: &MobType, + from: [i32; 3], + own: &mut LegacyRandom, + rules: &mut LegacyRandom, + ) -> Option<[i32; 3]> { + let level = self.natural_level(); + let (width, height) = (kind.width as f32, kind.height as f32); + for _ in 0..ATTEMPTS { + let [x, y, z] = from.map(|v| v + offset(own)); + if !spawn_rules::is_spawn_position_ok(kind.species, &level, x, y, z) + || !spawn_rules::check_spawn_rules( + kind.species, + &level, + Reason::Reinforcement, + rules, + x, + y, + z, + ) + { + continue; + } + // setPos(x, y, z): the box is centred on the block's corner. + let bounds = + spawn_selection::spawn_box(f64::from(x), f64::from(y), f64::from(z), width, height); + // Drowned.canSpawnInLiquids. + let wet_ok = kind.species == Species::Drowned + || !spawn_selection::contains_any_liquid(&level, bounds); + if !level.alive_player_near(f64::from(x), f64::from(y), f64::from(z), 7.0) + && level.unobstructed(bounds) + && level.no_collision(bounds) + && wet_ok + { + return Some([x, y, z]); + } + } + None + } +} diff --git a/crates/horizon-client/src/graphics_style.rs b/crates/horizon-client/src/graphics_style.rs index e02a0e1d9..62979903b 100644 --- a/crates/horizon-client/src/graphics_style.rs +++ b/crates/horizon-client/src/graphics_style.rs @@ -118,8 +118,9 @@ impl Style { (x, y, w): (f32, f32, f32), label: &Text, hover: bool, + active: bool, ) { - ui::button(batch, atlas, x, y, w, 20.0, label, true, hover); + ui::button(batch, atlas, x, y, w, 20.0, label, active, hover); } pub fn slider( &self, diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index 3c7a40e02..d55e44d99 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -468,6 +468,10 @@ fn max_workers() -> u32 { } impl Item { + /// False for a setting whose system is not in Horizon yet (`Opt::available`). + fn available(self) -> bool { + !matches!(self, Item::Vanilla(o) if !o.available()) + } /// On/off settings and their value. pub fn switch(self, s: &Settings) -> Option { let g = &s.horizon; @@ -510,6 +514,9 @@ impl Item { } } pub fn set_slider(self, s: &mut Settings, v: f32) { + if !self.available() { + return; + } match self { Item::Vanilla(o) => o.set_slider(s, v), Item::Horizon(h) => h.set_slider(s, v), @@ -517,6 +524,9 @@ impl Item { self.touched(s); } pub fn cycle(self, s: &mut Settings, back: bool, framebuffer: [i32; 2]) { + if !self.available() { + return; + } match self { Item::Vanilla(o) => o.cycle(s, back, framebuffer), Item::Horizon(h) => h.cycle(s, back), @@ -689,6 +699,7 @@ impl GraphicsUi { }) .collect(); let mut index = 0; + let mut tooltip = None; for wd in &widgets { let hover = ui::hovered(cursor, wd.x, wd.y, wd.w, 20.0) && (!wd.list || (cursor.1 >= top && cursor.1 < bottom)); @@ -700,6 +711,13 @@ impl GraphicsUi { continue; } let label = item.label(s); + let live = item.available(); + if hover && !live { + tooltip = Some(atlas.font.split( + &Text::literal("This feature is not yet available in Horizon."), + 170.0, + )); + } match item.slider(s) { Some(value) => STYLE.slider( batch, @@ -709,7 +727,14 @@ impl GraphicsUi { value, hover || self.dragging == Some(item), ), - None => STYLE.button(batch, atlas, (wd.x, wd.y, wd.w), &label, hover), + None => STYLE.button( + batch, + atlas, + (wd.x, wd.y, wd.w), + &label, + hover && live, + live, + ), } STYLE.description( batch, @@ -732,6 +757,7 @@ impl GraphicsUi { (wd.x, wd.y, wd.w), &Text::literal(label), hover, + true, ); } } @@ -751,6 +777,9 @@ impl GraphicsUi { Level::Advanced => "Graphics: Advanced", }; STYLE.title(batch, atlas, &Text::literal(title)); + if let Some(lines) = tooltip { + ui::tooltip(batch, atlas, &lines, cursor); + } } /// A press (or a drag with `drag`) at `(x, y)`. pub fn click( @@ -788,6 +817,8 @@ impl GraphicsUi { } return match wd.target { Target::Button(action) => vec![Action::ButtonClick, action], + // A disabled control does nothing: no sound, no preset change. + Target::Item(item) if !item.available() => Vec::new(), Target::Item(item) => { if item.slider(s).is_some() { self.dragging = Some(item); diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index 4f7824b25..46821df27 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -111,6 +111,12 @@ pub enum HealthEvent { amount: f32, }, Phase(&'static str), + /// `Player.hurtArmor`: a hit that doesn't bypass armor wears the worn + /// pieces (`LivingEntity.getDamageAfterArmorAbsorb`); the game applies it. + ArmorHurt { + source: DamageTypeId, + amount: f32, + }, /// `ServerLevel.broadcastDamageEvent`: the client's /// `LivingEntity.handleDamageEvent` plays the source's hurt sound. DamageBroadcast { @@ -139,6 +145,7 @@ impl HealthEvent { format!("record-damage {:08x}", amount.to_bits()) } Self::Phase(name) => name.into(), + Self::ArmorHurt { amount, .. } => format!("hurt-armor {:08x}", amount.to_bits()), Self::DamageBroadcast { .. } => "broadcast-damage".into(), Self::Criterion { .. } => "hurt-criterion".into(), } @@ -534,9 +541,14 @@ impl ServerDamageEnvironment for Environment<'_> { fn bypasses(&mut self, kind: Bypass) -> io::Result { Ok(self.source.bypasses(kind)) } - fn hurt_armor(&mut self, _: &mut Attributes, _: f32) -> io::Result<()> { + fn hurt_armor(&mut self, _: &mut Attributes, damage: f32) -> io::Result<()> { + // The worn armor lives in the game, which wears it from this event. + self.event(HealthEvent::ArmorHurt { + source: self.source.type_id(), + amount: damage, + }); Ok(()) - } // empty equipment + } fn has_resistance(&mut self) -> io::Result { Ok(self.status.resistance.is_some()) } diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index b4092a201..905843d23 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -113,6 +113,9 @@ pub struct ItemInfo { pub swappable: bool, /// `equippable.dispensable` (dispensers may put it on an entity). pub equip_dispensable: bool, + /// `equippable.damage_on_hurt`: the item wears when its wearer is hurt + /// (false for the elytra). + pub equip_damage_on_hurt: bool, /// `equippable.allowed_entities` resolved to entity type ids; None allows all. pub equip_allowed: Option>, pub equip_sound: Option, @@ -400,6 +403,36 @@ impl Items { self.get(&stack.item).is_some_and(|i| i.fire_resistant) } + /// `ItemStack.canBeHurtBy` for the cactus damage type: a `damage_resistant` + /// component naming `minecraft:cactus`, or a damage type tag that holds it. + /// (`#minecraft:is_fire`, as on netherite gear, does not.) + pub fn resists_cactus(&self, stack: &ItemStack) -> bool { + const CACTUS_TAGS: [&str; 5] = [ + "#minecraft:bypasses_shield", + "#minecraft:no_knockback", + "#minecraft:panic_environmental_causes", + "#minecraft:panic_causes", + "#minecraft:sulfur_cube_with_block_immune_to", + ]; + let Some((_, v)) = stack.data().and_then(|data| { + data.other + .iter() + .find(|(key, _)| key == "minecraft:damage_resistant") + }) else { + return false; + }; + match v.get("types") { + Some(horizon_world::nbt::Tag::String(id)) => id + .to_string() + .is_ok_and(|id| id == "minecraft:cactus" || CACTUS_TAGS.contains(&id.as_str())), + Some(horizon_world::nbt::Tag::List(ids)) => ids.iter().any(|t| { + matches!(t, horizon_world::nbt::Tag::String(id) + if id.to_string().is_ok_and(|id| id == "minecraft:cactus")) + }), + _ => false, + } + } + pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> Result { let mut block_for_item: HashMap<&str, BlockStateId> = HashMap::new(); for (i, s) in facts.states.iter().enumerate() { @@ -596,6 +629,9 @@ impl Items { equip_dispensable: c["minecraft:equippable"]["dispensable"] .as_bool() .unwrap_or(true), + equip_damage_on_hurt: c["minecraft:equippable"]["damage_on_hurt"] + .as_bool() + .unwrap_or(true), equip_allowed: match &c["minecraft:equippable"]["allowed_entities"] { Value::String(spec) => Some(entity_spec(&entity_tags, spec)), Value::Array(list) => Some( @@ -834,6 +870,7 @@ impl Items { held: None, killed_by_player: false, explosion_radius: None, + this_entity: false, }; ctx.evaluate(table, random) } @@ -898,10 +935,26 @@ impl Items { random: &mut impl RandomSource, sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>, ) -> Vec { - self.block_drops_exploded(registry, state, held, dynamic, random, sequences, None) + self.block_drops_exploded( + registry, state, held, dynamic, random, sequences, None, false, + ) + } + /// `block_drops_with` for a block a player breaks (`Block.playerDestroy`): + /// the player is the loot context's `this` entity, so snow and chorus + /// flower tables see an entity. + pub fn block_drops_by_player( + &self, + registry: &BlockRegistry, + state: BlockStateId, + held: Option<&ItemStack>, + dynamic: &[ItemStack], + random: &mut impl RandomSource, + ) -> Vec { + self.block_drops_exploded(registry, state, held, dynamic, random, None, None, true) } /// `block_drops_full` for a block an explosion destroys: `explosion` - /// is its radius when the explosion decays drops (`DESTROY_WITH_DECAY`). + /// is its radius when the explosion decays drops (`DESTROY_WITH_DECAY`); + /// `breaker` is whether an entity (the player) broke the block. #[allow(clippy::too_many_arguments)] pub fn block_drops_exploded( &self, @@ -912,8 +965,10 @@ impl Items { random: &mut impl RandomSource, sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>, explosion: Option, + breaker: bool, ) -> Vec { - let drops = self.block_drops_raw(registry, state, held, random, sequences, explosion); + let drops = + self.block_drops_raw(registry, state, held, random, sequences, explosion, breaker); if !drops.iter().any(|d| d.item.starts_with(DYNAMIC)) { return drops; } @@ -928,6 +983,7 @@ impl Items { }) .collect() } + #[allow(clippy::too_many_arguments)] fn block_drops_raw( &self, registry: &BlockRegistry, @@ -936,6 +992,7 @@ impl Items { random: &mut impl RandomSource, sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>, explosion_radius: Option, + breaker: bool, ) -> Vec { let Some(block) = registry.state(state) else { return vec![]; @@ -969,6 +1026,7 @@ impl Items { held, killed_by_player: false, explosion_radius, + this_entity: breaker, }; return ctx.evaluate(table, random); } @@ -979,6 +1037,7 @@ impl Items { held, killed_by_player: false, explosion_radius, + this_entity: breaker, }; ctx.evaluate(table, random) } @@ -1002,6 +1061,7 @@ impl Items { held, killed_by_player, explosion_radius: None, + this_entity: false, }; ctx.evaluate(table, random) } @@ -1034,6 +1094,7 @@ impl Items { held: None, killed_by_player: false, explosion_radius: None, + this_entity: false, }; match table.get("random_sequence").and_then(Value::as_str) { Some(sequence) => ctx.evaluate(table, sequences.get(sequence, seed)), @@ -1059,6 +1120,7 @@ impl Items { held, killed_by_player, explosion_radius: None, + this_entity: false, }; ctx.evaluate(table, random) } @@ -1081,6 +1143,7 @@ impl Items { held, killed_by_player, explosion_radius: None, + this_entity: false, }; ctx.evaluate(table, random) } @@ -1122,6 +1185,8 @@ struct LootContext<'a> { killed_by_player: bool, /// `LootContextParams.EXPLOSION_RADIUS`: an explosion that decays drops. explosion_radius: Option, + /// `LootContextParams.THIS_ENTITY` is set (a player broke the block). + this_entity: bool, } impl LootContext<'_> { /// Level of an enchantment on the tool / killer's weapon. @@ -1282,6 +1347,15 @@ impl LootContext<'_> { }; random.next_float() < chance } + // `this` with no checks (snow, chorus flower) holds when an entity + // broke the block (LootItemEntityPropertyCondition needs the entity). + "minecraft:entity_properties" + if self.this_entity + && c["entity"].as_str() == Some("this") + && c["predicate"].as_object().is_none_or(|p| p.is_empty()) => + { + true + } // Entity flags, equipment and damage-source predicates: none hold // for an unenchanted player kill without fire or lightning. "minecraft:entity_properties" | "minecraft:damage_source_properties" => false, @@ -1667,6 +1741,7 @@ mod tests { held, killed_by_player: block.is_empty(), explosion_radius: None, + this_entity: false, } } diff --git a/crates/horizon-client/src/keybinds.rs b/crates/horizon-client/src/keybinds.rs index 7575fb953..2047b9117 100644 --- a/crates/horizon-client/src/keybinds.rs +++ b/crates/horizon-client/src/keybinds.rs @@ -2,7 +2,6 @@ //! defaults, `key_:key.keyboard.x` persistence, display names, and the //! translation of rebound physical keys back to the default keys the game //! logic listens for. -use crate::text::Text; use std::collections::BTreeMap; use winit::{event::MouseButton, keyboard::KeyCode}; @@ -225,40 +224,7 @@ pub fn mouse_button(name: &str) -> Option { _ => return None, }) } -/// InputConstants.Key.getDisplayName: one-character keys as the upper-case -/// character, others by translation. -pub fn display_name(key: &str) -> Text { - if let Some(rest) = key.strip_prefix("key.keyboard.") - && rest.chars().count() == 1 - { - let c = rest.to_uppercase(); - return Text::literal(c); - } - let symbol = match key { - "key.keyboard.minus" => Some("-"), - "key.keyboard.equal" => Some("="), - "key.keyboard.left.bracket" => Some("["), - "key.keyboard.right.bracket" => Some("]"), - "key.keyboard.backslash" => Some("\\"), - "key.keyboard.semicolon" => Some(";"), - "key.keyboard.apostrophe" => Some("'"), - "key.keyboard.grave.accent" => Some("`"), - "key.keyboard.comma" => Some(","), - "key.keyboard.period" => Some("."), - "key.keyboard.slash" => Some("/"), - _ => None, - }; - if let Some(s) = symbol { - return Text::literal(s); - } - if let Some(n) = key.strip_prefix("key.mouse.") - && n.parse::().is_ok() - && !crate::lang::has(key) - { - return Text::translate("key.mouse", &[Text::literal(n)]); - } - Text::translate(key, &[]) -} +pub use horizon_client_core::key_display::display_name; /// Current bindings by mapping name. #[derive(Clone, Debug, PartialEq, Eq)] diff --git a/crates/horizon-client/src/lan/chunks.rs b/crates/horizon-client/src/lan/chunks.rs index 122d37bcd..9ca20b894 100644 --- a/crates/horizon-client/src/lan/chunks.rs +++ b/crates/horizon-client/src/lan/chunks.rs @@ -66,6 +66,7 @@ pub fn block_entity_type(name: &str) -> Option<&'static str> { "sculk_catalyst" => "minecraft:sculk_catalyst", "sculk_shrieker" => "minecraft:sculk_shrieker", "crafter" => "minecraft:crafter", + "potent_sulfur" => "minecraft:potent_sulfur", "chiseled_bookshelf" => "minecraft:chiseled_bookshelf", "trial_spawner" => "minecraft:trial_spawner", "vault" => "minecraft:vault", diff --git a/crates/horizon-client/src/lan/commands.rs b/crates/horizon-client/src/lan/commands.rs index 71b7fa68d..c3e462348 100644 --- a/crates/horizon-client/src/lan/commands.rs +++ b/crates/horizon-client/src/lan/commands.rs @@ -86,6 +86,18 @@ impl CommandTree { /// The ClientboundCommandsPacket for a player with `level` permissions. pub fn packet(&self, level: u8, dedicated: bool, builtin: &Builtin) -> Commands { + self.packet_with(level, dedicated, builtin, &Value::Null) + } + + /// [`CommandTree::packet`] with more commands after vanilla's: `extra` + /// is a root in the report's format (server mods' commands). + pub fn packet_with( + &self, + level: u8, + dedicated: bool, + builtin: &Builtin, + extra: &Value, + ) -> Commands { let mut nodes = vec![Node { name: String::new(), kind: 0, @@ -99,16 +111,18 @@ impl CommandTree { let suggestions: HashMap<&str, &'static str> = SUGGESTIONS.iter().copied().collect(); let mut paths: HashMap, usize> = HashMap::new(); paths.insert(Vec::new(), 0); - fill( - &self.root, - 0, - &mut Vec::new(), - level, - dedicated, - &suggestions, - &mut nodes, - &mut paths, - ); + for root in [&self.root, extra] { + fill( + root, + 0, + &mut Vec::new(), + level, + dedicated, + &suggestions, + &mut nodes, + &mut paths, + ); + } // enumerateNodes: breadth first from the root, each node's children // (in registration order) then its redirect target. let mut ids = vec![None; nodes.len()]; @@ -365,4 +379,33 @@ mod tests { ); assert!(op.nodes[3].restricted); } + + #[test] + fn server_mods_commands_follow_vanillas() { + let report: Value = serde_json::from_str( + r#"{"type":"root","children":{"me":{"type":"literal","children":{"action":{"type":"argument","parser":"minecraft:message","executable":true}}}}}"#, + ) + .unwrap(); + let mods: Value = serde_json::from_str( + r#"{"type":"root","children":{"beacon":{"type":"literal","executable":true,"children":{ + "height":{"type":"argument","parser":"brigadier:integer","properties":{"min":1,"max":64},"executable":true}}}}}"#, + ) + .unwrap(); + let tree = CommandTree { root: report }; + let packet = tree.packet_with(0, true, &Builtin::default(), &mods); + let names: Vec<_> = packet.nodes.iter().map(|n| n.name.as_str()).collect(); + assert_eq!(names, ["", "me", "beacon", "action", "height"]); + let beacon = &packet.nodes[2]; + assert!(beacon.executable && !beacon.restricted); + assert_eq!(beacon.children, [4]); + let height = packet.nodes[4].parser.as_ref().unwrap(); + assert_eq!(height.1, vec![3, 0, 0, 0, 1, 0, 0, 0, 64]); + // No mods: vanilla's tree as it is. + assert_eq!( + tree.packet_with(0, true, &Builtin::default(), &Value::Null) + .nodes + .len(), + 3 + ); + } } diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index c76404291..3d3e5f072 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -177,6 +177,9 @@ pub struct Hub { entities: std::collections::HashMap, /// What one tick of entity tracking sends each guest, kept between ticks. entity_out: Vec>>, + /// Server mods' commands, a root in the commands report's format, sent + /// after vanilla's; the key the game last set them for. + mod_commands: (serde_json::Value, Option), } fn string(s: &str) -> Tag { @@ -341,6 +344,7 @@ impl Hub { entity_types: Default::default(), entities: Default::default(), entity_out: Vec::new(), + mod_commands: (serde_json::Value::Null, None), teams: Vec::new(), } } @@ -849,13 +853,36 @@ impl Hub { } } + /// The key [`Hub::set_mod_commands`] last had: the game compares it + /// with its server mods' each tick. + pub fn mod_commands_key(&self) -> Option { + self.mod_commands.1 + } + /// Server mods' commands changed: every player gets their tree again. + pub fn set_mod_commands(&mut self, key: u64, commands: serde_json::Value) { + let resend = self.mod_commands.0 != commands; + self.mod_commands = (commands, Some(key)); + if resend { + for i in 0..self.guests.len() { + if self.guests[i].placed { + self.send_commands(i); + } + } + } + } + /// Commands.sendCommands: the command tree for this player. fn send_commands(&self, i: usize) { let g = &self.guests[i]; let packet = match &self.sync.commands { Some(tree) => { let dedicated = self.config.dedicated && !self.config.integrated; - tree.packet(g.permission, dedicated, &self.sync.builtin) + tree.packet_with( + g.permission, + dedicated, + &self.sync.builtin, + &self.mod_commands.0, + ) } None => play::Commands { nodes: vec![play::CommandNode { diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index ebfbdea58..fa5ef1c4d 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -19,13 +19,11 @@ pub mod biome; pub mod block_entities; pub mod block_entity_anim; pub mod block_entity_item; -pub mod block_entity_nbt; pub mod block_entity_render; pub mod block_transform; pub mod blocks; pub mod border_render; pub mod boss_overlay; -pub mod bossbar; pub mod breaking; pub mod brewing; pub mod bundle; @@ -38,10 +36,8 @@ pub mod clipboard; pub mod clock; pub mod clouds; pub mod collisions; -pub mod command; pub mod command_block; pub mod command_storage; -pub mod component; pub mod confirm_screen; pub mod container_screen; pub mod containers; @@ -71,7 +67,6 @@ pub mod extras; pub mod extras_hud; pub mod falling_block; pub mod fast_hash; -pub mod fastutil_order; pub mod fire_render; pub mod first_person; pub mod flatgen; @@ -80,7 +75,6 @@ pub mod font; pub mod friends_screen; pub mod game_mode_switcher; pub mod gamepad; -pub mod gamerules; pub mod gfx; pub mod gizmos; pub mod gossip; @@ -109,7 +103,6 @@ pub mod keybinds; pub mod keymapping; pub mod lan; pub mod landing; -pub mod lang; pub mod level_loading; pub mod light; pub mod locator_bar; @@ -131,7 +124,6 @@ pub mod mouse; pub mod moved_extras; pub mod multiplayer; pub mod music; -pub mod nbt_path; pub mod net; pub mod nether_portal; pub mod offline_name; @@ -160,7 +152,6 @@ pub mod recipe_book; pub mod recipe_book_screen; pub mod reconnect; pub mod save; -pub mod scoreboard; pub mod scoreboard_cmd; pub mod screen_draw; pub mod screen_effects; @@ -173,7 +164,6 @@ pub mod shader_pack_list; pub mod shadows; pub mod signs; pub mod skins; -pub mod snbt; pub mod sound_engine; pub mod sound_events; pub mod spans; @@ -186,7 +176,6 @@ pub mod structure_blocks; pub mod tab_list; pub mod telemetry; pub mod testgen; -pub mod text; pub mod text_display; pub mod tick_chunk_membership; pub mod ticket_levels; @@ -206,4 +195,15 @@ pub mod world; pub mod world_spawn; pub mod worldborder; pub mod zip; -pub type Result = std::result::Result>; +pub use horizon_client_core::Result; +pub use horizon_client_core::block_entity_nbt; +pub use horizon_client_core::bossbar; +pub use horizon_client_core::component; +pub use horizon_client_core::fastutil_order; +pub use horizon_client_core::gamerules; +pub use horizon_client_core::lang; +pub use horizon_client_core::nbt_path; +pub use horizon_client_core::scoreboard; +pub use horizon_client_core::snbt; +pub use horizon_client_core::text; +pub use horizon_command as command; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index b02eb111a..6b98a3a68 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -25,6 +25,7 @@ pub mod creaking; pub mod creaking_heart; pub mod cube; pub mod data; +pub mod doors; pub mod drops; pub mod enderman; pub mod equine; @@ -68,6 +69,7 @@ pub mod tame; pub mod trader; pub mod transport_items; pub mod trial_spawner; +pub mod turtle; pub mod undead; pub mod vex; pub mod villager; @@ -515,6 +517,8 @@ pub enum DamageKind { InFire, Lava, Drown, + /// `dry_out`: an axolotl out of water for too long. + DryOut, Magic, Sting, Cactus, @@ -573,7 +577,11 @@ impl Damage { pub fn causes_panic(&self) -> bool { !matches!( self.kind, - DamageKind::Fall | DamageKind::Drown | DamageKind::Generic | DamageKind::InWall + DamageKind::Fall + | DamageKind::Drown + | DamageKind::DryOut + | DamageKind::Generic + | DamageKind::InWall ) } /// DamageTypeTags.BYPASSES_ARMOR @@ -606,6 +614,7 @@ impl Damage { | DamageKind::InFire | DamageKind::Lava | DamageKind::Drown + | DamageKind::DryOut | DamageKind::Magic | DamageKind::Cactus | DamageKind::Generic @@ -636,6 +645,8 @@ pub struct Attrs { pub struct Extra { /// Players: crouching and riding (HumanoidModel's poses). pub crouching: bool, + /// Players: sprinting (`Entity.DATA_SHARED_FLAGS_ID`), for the dust they raise. + pub sprinting: bool, pub passenger: bool, /// AgeableMob.age: negative while a baby (a tadpole counts up to 24000). pub age: i32, @@ -665,6 +676,8 @@ pub struct Extra { pub chested: bool, /// The chest contents of a donkey or mule (15 slots). pub items: Vec>, + /// `Piglin.inventory` (`SimpleContainer(8)`): what it picked up and kept. + pub inventory: Vec, pub tame: bool, pub sitting: bool, /// The owner's UUID (tamed animals). @@ -979,6 +992,14 @@ pub enum MobEvent { owner: u32, }, Shoot([f64; 3], [f64; 3]), + /// The mob the `Explode` right after this comes from + /// (`ServerExplosion.source`), and whether it is a charged creeper: the + /// exploding creeper is already out of the mob list when the game applies + /// the blast, so its victims' loot cannot look it up. + ExplosionSource { + mob: u32, + charged: bool, + }, Explode([f64; 3], f32), /// Melee or ranged damage to another mob. AttackMob { @@ -1015,6 +1036,24 @@ pub enum MobEvent { pos: [i32; 3], open: bool, }, + /// `BreakDoorGoal.tick` at its end: the door is removed (`removeBlock`), + /// then level events 1021 and 2001 with the state that is left there. + BreakDoor { + pos: [i32; 3], + }, + /// `Level.destroyBlockProgress` for a mob's crack on a block (`-1` + /// clears it). + DestroyProgress { + mob: u32, + pos: [i32; 3], + progress: i32, + }, + /// `Level.levelEvent`: the game plays and sends the event. + LevelEvent { + id: i32, + pos: [i32; 3], + data: i32, + }, /// Destroy a block, dropping nothing (sheep eating grass becomes dirt via SetBlock). BreakBlock { pos: [i32; 3], @@ -1147,8 +1186,10 @@ pub enum MobEvent { target: Who, aggressive: bool, }, - /// Drop the loot of a gift table (chicken eggs, armadillo scutes). + /// Drop the loot of a gift table (chicken eggs, sniffer seeds) with the + /// mob as `this` (`LivingEntity.dropFromGiftLootTable`). GiftLoot { + mob: u32, table: &'static str, at: [f64; 3], }, @@ -1172,6 +1213,18 @@ pub enum MobEvent { DigParticles { at: [f64; 3], }, + /// `Zombie.hurtServer`: a zombie hurt with a target in sight (its own, + /// else the attacker) may call a reinforcement against it on Hard. + Reinforcements { + mob: u32, + target: Who, + }, + /// `LevelEvent.PARTICLES_DESTROY_BLOCK` (2001) at `pos` for the block at + /// `block`: a turtle's digging. + BlockBreakEffect { + pos: [i32; 3], + block: [i32; 3], + }, /// `Warden.applyDarknessAround`: darkness for survival players nearby. Darkness { at: [f64; 3], @@ -1268,6 +1321,14 @@ pub struct Seen { pub sitting: bool, /// `Entity.isVehicle` or `isPassenger`. pub ridden: bool, + /// The active effects, without namespace (`slowness`, `poison`...). + pub effects: Vec<&'static str>, +} +impl Seen { + /// `LivingEntity.hasEffect`, by id without namespace. + pub fn has_effect(&self, effect: &str) -> bool { + self.effects.contains(&effect) + } } impl Mob { pub fn burning_time(&self) -> f64 { @@ -1342,6 +1403,12 @@ impl Mob { ], sitting: m.extra.sitting, ridden: m.rider.is_some() || m.extra.rider.is_some() || m.extra.mount.is_some(), + effects: m + .extra + .effects + .iter() + .map(|e| e.0.trim_start_matches("minecraft:")) + .collect(), } } /// `EntityType.getCategory`'s name. @@ -1486,6 +1553,8 @@ pub struct PlayerView { pub yaw: f32, /// The Hero of the Village effect. pub hero: bool, + /// The active effects, without namespace (`slowness`, `poison`...). + pub effects: Vec<&'static str>, /// The player's UUID (villagers' gossip is keyed by it). pub uuid: [i32; 4], /// The mobs on the player's team (`isAlliedTo`): combat targeting @@ -1495,6 +1564,12 @@ pub struct PlayerView { /// (`EntitySelector.pushableBy` on the client). pub remote: bool, } +impl PlayerView { + /// `LivingEntity.hasEffect`, by id without namespace. + pub fn has_effect(&self, effect: &str) -> bool { + self.effects.contains(&effect) + } +} #[derive(Clone)] pub struct MobWorld<'a> { pub world: &'a World, @@ -1820,6 +1895,12 @@ impl Mob { } } } + // Squid.hurtServer: a squid hurt after a living entity hit it squirts ink. + if matches!(self.species(), Species::Squid | Species::GlowSquid) + && self.ai.last_hurt_by.is_some() + { + aquatic::spawn_ink(self); + } true } /// LivingEntity.knockback(power, xd, zd) towards the negative direction. @@ -1870,7 +1951,8 @@ impl Mob { /// Movement speed attribute bonus (baby zombies, sprinting modifiers). /// MOVEMENT_SPEED including effects (speed +20%/level, slowness -15%/level). pub fn movement_speed(&self) -> f64 { - let mut v = strider::movement_speed(self, self.attrs.speed) * self.speed_bonus(); + let mut v = strider::movement_speed(self, witch::speed(self, self.attrs.speed)) + * self.speed_bonus(); for (e, _, amp) in &self.extra.effects { match *e { "minecraft:speed" => v *= 1.0 + 0.2 * f64::from(amp + 1), diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 014032280..ee997a23e 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -183,6 +183,9 @@ pub fn register(m: &mut Mob) { if m.species() == Species::Rabbit { super::rabbit::register(m); } + if m.species() == Species::Turtle { + super::turtle::register(m); + } } Family::Inert => {} Family::Witch => super::witch::register(m), @@ -441,6 +444,34 @@ pub fn tick_swing(m: &mut Mob) { } m.anim.attack_anim = m.ai.swing_time as f32 / 6.0; } +/// `LivingEntity.baseTick` refills a breather's air by 4, then +/// `Axolotl.handleAirSupply` (unless the mob has no AI): water or rain fills +/// it, anywhere else it runs down from the pre-tick value, and at -20 the +/// axolotl dries out. +fn axolotl_air_supply(m: &mut Mob, w: &MobWorld) { + let before = m.air; + m.air = (m.air + 4).min(super::axolotl::MAX_AIR); + if m.no_ai { + return; + } + // Entity.isInRain: rain at the block, or at the top of the box. + let (x, y, z) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + let top = (m.position.y + f64::from(m.height())).floor() as i32; + let in_rain = w.raining_at(x, y, z) || w.raining_at(x, top, z); + if m.fluids.in_water || in_rain { + m.air = super::axolotl::MAX_AIR; + } else { + m.air = before - 1; + if m.air <= -20 { + m.air = 0; + m.damage(2.0, Damage::of(DamageKind::DryOut)); + } + } +} /// Entity.baseTick + LivingEntity.baseTick + Mob.baseTick. fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.was_eye_in_water = m.fluids.eye_in_water; @@ -500,7 +531,9 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.damage(1.0, Damage::of(DamageKind::InWall)); } // Air supply and drowning (WaterAnimal.handleAirSupply for aquatic mobs). - if m.kind.flags.needs_water { + if m.species() == Species::Axolotl { + axolotl_air_supply(m, w); + } else if m.kind.flags.needs_water { if !m.fluids.in_water { m.air -= 1; if m.air == -20 { @@ -712,6 +745,14 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & // setAge at the age boundary: refreshDimensions. if m.extra.age >= 0 { m.fudge_position_after_size_change(w, bw, bh); + // Turtle.ageBoundaryReached: a grown turtle drops a scute. + if m.species() == Species::Turtle { + events.push(MobEvent::GiftLoot { + mob: m.id, + table: "minecraft:gameplay/turtle_grow", + at: [m.position.x, m.position.y, m.position.z], + }); + } } } else if m.extra.age > 0 { m.extra.age -= 1; @@ -746,7 +787,7 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & if m.kind.flags.burns_in_day && m.alive() && sun_burn_tick(m, w) && m.extra.head.is_none() { m.ignite_for_ticks(160); } - species_ai_step(m, w, events); + species_ai_step(m, w, level_random, events); } impl Mob { /// LivingEntity.isPushable (and the push it takes from `Entity.push(Entity)`): @@ -944,6 +985,7 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { | Species::Parched | Species::WitherSkeleton | Species::ZombifiedPiglin => undead::custom_server_ai_step(m, cx), + Species::Vindicator => super::illager::vindicator_server_ai_step(m), Species::Enderman => super::enderman::custom_server_ai_step(m, cx), Species::Blaze => super::nether::blaze_server_ai_step(m, cx), Species::ElderGuardian => super::guardian::elder_server_ai_step(m, cx), @@ -955,7 +997,12 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { _ => {} } } -fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { +fn species_ai_step( + m: &mut Mob, + w: &MobWorld, + level_random: &mut LegacyRandom, + events: &mut Vec, +) { if family(m.species()) == Family::Aquatic { aquatic::ai_step(m, w, events); } @@ -988,7 +1035,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } Species::Shulker => { super::shulker::tick(m, w, events); - super::shulker::ai_step(m, w, events); + super::shulker::ai_step(m, w, level_random, events); } Species::SnowGolem => super::golem::snow_ai_step(m, w, events), Species::CopperGolem => super::copper_golem::ai_step(m, w, events), @@ -999,6 +1046,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } Species::Nautilus | Species::ZombieNautilus => super::nautilus::ai_step(m, w, events), Species::Chicken => farm::chicken_ai_step(m, w, events), + Species::Turtle => super::turtle::ai_step(m, w, events), Species::Sheep if m.extra.anim_ticks > 0 => { m.extra.anim_ticks -= 1; } @@ -1324,6 +1372,11 @@ pub fn after_hurt(m: &mut Mob, source: &Damage) { Species::Warden => super::warden::hurt(m, source), Species::Wolf => super::tame::after_hurt(m, source), Species::Nautilus | Species::ZombieNautilus => super::nautilus::after_hurt(m, source), + Species::Zombie + | Species::Husk + | Species::Drowned + | Species::ZombieVillager + | Species::ZombifiedPiglin => super::undead::after_hurt(m, source), // NeutralMob: an iron golem hit by the player stays angry a while. // PiglinAi.wasHurtBy: drop what is being admired, no admiring for // a while after a player's hit, and anger. diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index b81f224ae..c183aa59d 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -248,18 +248,24 @@ pub enum ArmPose { pub fn humanoid_pub(p: &mut Poses, s: &State, _m: &Mob) { humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty)); } -/// `AnimationUtils.swingWeaponDown` with the right arm as the main arm. -pub(super) fn swing_weapon_down(p: &mut Poses, swing: f32, age: f32) { +/// `AnimationUtils.swingWeaponDown`: the main arm swings down, the other +/// one hangs and bobs. +pub(super) fn swing_weapon_down(p: &mut Poses, swing: f32, age: f32, left_main: bool) { let attack2 = (swing * PI).msin(); let attack = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin(); + let (main, off) = if left_main { + ("left_arm", "right_arm") + } else { + ("right_arm", "left_arm") + }; p.zrot("right_arm", 0.0); p.zrot("left_arm", 0.0); p.yrot("right_arm", PI / 20.0); p.yrot("left_arm", -PI / 20.0); - p.xrot("right_arm", -1.884_955_8 + (age * 0.09).mcos() * 0.15); - p.xrot("left_arm", -0.0 + (age * 0.19).mcos() * 0.5); - p.get("right_arm")[3] += attack2 * 2.2 - attack * 0.4; - p.get("left_arm")[3] += attack2 * 1.2 - attack * 0.4; + p.xrot(main, -1.884_955_8 + (age * 0.09).mcos() * 0.15); + p.xrot(off, -0.0 + (age * 0.19).mcos() * 0.5); + p.get(main)[3] += attack2 * 2.2 - attack * 0.4; + p.get(off)[3] += attack2 * 1.2 - attack * 0.4; bob(p, "right_arm", age, 1.0); bob(p, "left_arm", age, -1.0); } @@ -286,6 +292,8 @@ pub struct Hum { pub using_item: bool, /// The arm the current swing moves (`Some(true)` for the right one). pub swing_right_arm: Option, + /// `mainArm` is the left one (`Mob.isLeftHanded`): a mob's swing uses it. + pub left_main: bool, } impl Hum { pub fn new(right: ArmPose, left: ArmPose) -> Self { @@ -303,6 +311,7 @@ impl Hum { swim: 0.0, using_item: false, swing_right_arm: None, + left_main: false, } } } @@ -315,7 +324,7 @@ impl ArmPose { } } /// `AnimationUtils.animateCrossbowHold`. -fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) { +pub(super) fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) { let (hold, shoot) = if in_right { ("right_arm", "left_arm") } else { @@ -327,7 +336,7 @@ fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) { p.xrot(shoot, -1.5 + hx); } /// `AnimationUtils.animateCrossbowCharge`. -fn crossbow_charge(p: &mut Poses, max: f32, ticks: f32, in_right: bool) { +pub(super) fn crossbow_charge(p: &mut Poses, max: f32, ticks: f32, in_right: bool) { let (hold, pull) = if in_right { ("right_arm", "left_arm") } else { @@ -418,13 +427,17 @@ pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) { pose_arm(p, h.right, true, h); } } - // setupAttackAnimation (WHACK swing with the right arm). + // setupAttackAnimation (WHACK swing with the arm of the swinging hand). let hx = p.get("head")[3]; let swing = s.swing; + let swing_left = h.swing_right_arm.map_or(h.left_main, |right| !right); if swing > 0.0 && h.weapon_swing { - swing_weapon_down(p, swing, s.age); + swing_weapon_down(p, swing, s.age, h.left_main); } else if swing > 0.0 { - let body_y = (swing.sqrt() * PI * 2.0).msin() * 0.2; + let mut body_y = (swing.sqrt() * PI * 2.0).msin() * 0.2; + if swing_left { + body_y = -body_y; + } p.yrot("body", body_y); let age_scale = if s.baby { 0.5 } else { 1.0 }; { @@ -444,7 +457,7 @@ pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) { let eased = 1.0 - (1.0 - swing).powi(4); let aa = (eased * PI).msin(); let bb = (swing * PI).msin() * -(hx - 0.7) * 0.75; - let r = p.get("right_arm"); + let r = p.get(if swing_left { "left_arm" } else { "right_arm" }); r[3] -= aa * 1.2 + bb; r[4] += body_y * 2.0; r[5] += (swing * PI).msin() * -0.4; @@ -652,6 +665,7 @@ pub fn setup( } else { Hum::new(main, ArmPose::Empty) }; + h.left_main = m.main_arm_left(); h.zombie = Some(m.ai.aggressive); h.holding = m.extra.main_hand.is_some(); h.crouching = m.extra.crouching; @@ -715,6 +729,7 @@ pub fn setup( h.swim = m.extra.swim.amount(s.partial); h.using_item = m.extra.using_item > 0; h.swing_right_arm = m.extra.swing_right_arm; + h.left_main = m.main_arm_left(); humanoid(p, s, &h); if m.ai.aggressive && !bow { // SkeletonModel melee pose. diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index 3f86d8edc..f63a42239 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -24,6 +24,58 @@ const Z_BODY_ROT: usize = 3; const TENTACLE_SPEED: usize = 4; const ROTATE_SPEED: usize = 5; +/// `Squid.spawnInk`: the squirt sound and 30 ink particles shot from under +/// the squid, turned by its body rotation. +pub fn spawn_ink(m: &mut Mob) { + let sound = if m.species() == Species::GlowSquid { + "entity.glow_squid.squirt" + } else { + "entity.squid.squirt" + }; + let kind = if m.species() == Species::GlowSquid { + "glow_squid_ink" + } else { + "squid_ink" + }; + // makeSound draws the voice pitch even for a silent squid. + let pitch = m.voice_pitch(); + if !m.silent { + let at = [m.position.x, m.position.y, m.position.z]; + m.outbox.push(MobEvent::Sound( + sound, + at, + super::ai::sound_volume(m), + pitch, + )); + } + // rotateVector: xRot(xBodyRotO), then yRot(-yBodyRotO). + let to_radians = (std::f64::consts::PI / 180.0) as f32; + let (x_rot, y_rot) = ( + m.anim.vo[X_BODY_ROT] * to_radians, + -m.previous_body_yaw * to_radians, + ); + let rotate = |v: Vec3| v.rotate_x(x_rot).rotate_y(y_rot); + let pos = rotate(Vec3::new(0.0, -1.0, 0.0)).add_vector(m.position); + let offset_scale: f32 = if m.is_baby() { 0.1 } else { 0.3 }; + for _ in 0..30 { + let x = f64::from(m.random.next_float()) * 0.6 - 0.3; + let z = f64::from(m.random.next_float()) * 0.6 - 0.3; + let dir = rotate(Vec3::new(x, -1.0, z)); + let d = dir.scale(f64::from(offset_scale + m.random.next_float() * 2.0)); + // ServerLevel.sendParticles with a count of 0 and speed 0.1: one + // particle moving at the float offset times the float speed. + let speed = f64::from(0.1f32); + m.outbox.push(MobEvent::ParticleAt { + kind, + at: [pos.x, pos.y + 0.5, pos.z], + velocity: [ + speed * f64::from(d.x as f32), + speed * f64::from(d.y as f32), + speed * f64::from(d.z as f32), + ], + }); + } +} pub fn register(m: &mut Mob) { use Species as S; match m.species() { @@ -36,6 +88,7 @@ pub fn register(m: &mut Mob) { m.anim.v[TENTACLE_SPEED] = speed; } S::Axolotl => { + m.air = super::axolotl::MAX_AIR; // Native controller scaling is essential: the base speed attribute is 1.0. m.ai.mov.kind = MoveKind::SmoothSwimming { max_turn_x: 85.0, diff --git a/crates/horizon-client/src/mobs/axolotl.rs b/crates/horizon-client/src/mobs/axolotl.rs index 55f15717c..2815418e3 100644 --- a/crates/horizon-client/src/mobs/axolotl.rs +++ b/crates/horizon-client/src/mobs/axolotl.rs @@ -3,6 +3,8 @@ use super::{Mob, MobEvent, MobWorld, Species, Who, animal_brain, keyframes::Anim use horizon_core::random::RandomSource; pub const PLAY_DEAD_TICKS: i32 = 200; pub const HUNTING_COOLDOWN: i64 = 2400; +/// `Axolotl.getMaxAirSupply`. +pub const MAX_AIR: i32 = 6000; /// AxolotlAttackablesSensor: always-hostile targets bypass the hunting cooldown. pub fn prey_eligible( diff --git a/crates/horizon-client/src/mobs/body_anim.rs b/crates/horizon-client/src/mobs/body_anim.rs index 4411d347b..bbb44c5ab 100644 --- a/crates/horizon-client/src/mobs/body_anim.rs +++ b/crates/horizon-client/src/mobs/body_anim.rs @@ -969,8 +969,8 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool { s, &Turtle { on_land: !m.fluids.in_water && m.on_ground, - laying_egg: false, - has_egg: false, + laying_egg: m.extra.flag2, + has_egg: m.extra.flag, }, ), Species::Strider => strider(p, s, m.rider.is_some()), diff --git a/crates/horizon-client/src/mobs/doors.rs b/crates/horizon-client/src/mobs/doors.rs new file mode 100644 index 000000000..a55ab9863 --- /dev/null +++ b/crates/horizon-client/src/mobs/doors.rs @@ -0,0 +1,252 @@ +//! Doors a mob gets through on its own: `DoorInteractGoal` with its two +//! users, `BreakDoorGoal` (zombies that can break doors, vindicators in a +//! raid) and `OpenDoorGoal` (`AbstractIllager.RaiderOpenDoorGoal`). +use super::{ + Mob, MobEvent, MobWorld, Species, + goals::{Cx, Goal, MOVE, goal_clone, reduced}, + nav::NavKind, + raider, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; + +/// `DefaultDoorBreakTime`: `BreakDoorGoal.getDoorBreakTime` is +/// `max(240, doorBreakTime)`, and the vindicator's 6 is below it. +const DOOR_BREAK_TIME: i32 = 240; + +/// `GoalUtils.hasGroundPathNavigation`: ground, wall-climbing and +/// amphibious navigations walk. +pub fn can_navigate_ground(m: &Mob) -> bool { + matches!( + m.ai.nav.kind, + NavKind::Ground | NavKind::WallClimber | NavKind::Amphibious + ) +} +/// `Zombie.setCanBreakDoors`: only a mob that walks can break doors, and +/// then its navigation opens them. +pub fn set_can_break_doors(m: &mut Mob, can_break: bool) { + let can_break = can_break && can_navigate_ground(m); + m.extra.can_break_doors = can_break; + m.ai.nav.can_open_doors = can_break; +} +/// The species that extend `Zombie` (`CanBreakDoors` is theirs to save). +pub fn is_zombie(s: Species) -> bool { + matches!( + s, + Species::Zombie + | Species::Husk + | Species::Drowned + | Species::ZombieVillager + | Species::ZombifiedPiglin + ) +} +/// `DoorBlock.isWoodenDoor`: a door a hand opens, which is any but iron. +fn wooden_door(w: &MobWorld, p: [i32; 3]) -> bool { + let name = w.block_name(p[0], p[1], p[2]); + name.ends_with("_door") && name != "minecraft:iron_door" +} +/// `DoorInteractGoal`'s door: where it is and whether one is there. +#[derive(Clone, Debug, Default)] +struct Interact { + door: [i32; 3], + has_door: bool, +} +impl Interact { + /// `DoorInteractGoal.canUse`: the mob bumped into something and a + /// wooden door is on its path within 1.5 blocks, or at its own head. + fn can_use(&mut self, m: &Mob, w: &MobWorld) -> bool { + if !can_navigate_ground(m) || !m.horizontal_collision { + return false; + } + let Some(path) = m.ai.nav.path.as_ref().filter(|p| !p.is_done()) else { + return false; + }; + for node in path + .nodes + .iter() + .take((path.next + 2).min(path.nodes.len())) + { + self.door = [node.x, node.y + 1, node.z]; + let dx = m.position.x - f64::from(node.x); + let dz = m.position.z - f64::from(node.z); + if dx * dx + dz * dz <= 2.25 { + self.has_door = wooden_door(w, self.door); + if self.has_door { + return true; + } + } + } + let at = m.position; + self.door = [ + at.x.floor() as i32, + at.y.floor() as i32 + 1, + at.z.floor() as i32, + ]; + self.has_door = wooden_door(w, self.door); + self.has_door + } + /// `DoorInteractGoal.isOpen`: the door is still there and open. + fn is_open(&mut self, w: &MobWorld) -> bool { + if !self.has_door { + return false; + } + let d = self.door; + if !w.block_name(d[0], d[1], d[2]).ends_with("_door") { + self.has_door = false; + return false; + } + w.prop(d[0], d[1], d[2], "open") == Some("true") + } + /// `DoorInteractGoal.setOpen`. + fn set_open(&self, cx: &mut Cx, open: bool) { + let d = self.door; + if self.has_door && cx.w.block_name(d[0], d[1], d[2]).ends_with("_door") { + cx.events.push(MobEvent::SetDoorOpen { pos: d, open }); + } + } +} +/// `BlockPos.closerToCenterThan`. +fn closer_to_center(p: [i32; 3], at: Vec3, distance: f64) -> bool { + Vec3::new( + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, + ) + .distance_squared(at) + < distance * distance +} + +/// `BreakDoorGoal`: crack the door in the way for 240 ticks, then remove it. +/// A zombie does it on hard only; `Vindicator.VindicatorBreakDoorGoal` on +/// normal and hard, in a raid, and holds the mob's movement. +#[derive(Clone, Debug)] +pub struct BreakDoor { + interact: Interact, + vindicator: bool, + break_time: i32, + last_break_progress: i32, +} +impl BreakDoor { + /// `Zombie.breakDoorGoal`, added when the zombie can break doors. + pub fn zombie() -> Self { + Self::new(false) + } + /// `Vindicator.VindicatorBreakDoorGoal`. + pub fn vindicator() -> Self { + Self::new(true) + } + fn new(vindicator: bool) -> Self { + Self { + interact: Interact::default(), + vindicator, + break_time: 0, + last_break_progress: -1, + } + } + /// `DOOR_BREAKING_PREDICATE`. + fn valid_difficulty(&self, w: &MobWorld) -> bool { + if self.vindicator { + w.difficulty.normal || w.difficulty.hard + } else { + w.difficulty.hard + } + } + /// `BreakDoorGoal.canUse` after `DoorInteractGoal.canUse`. + fn can_break(&mut self, m: &Mob, w: &MobWorld) -> bool { + self.interact.can_use(m, w) + && w.mob_griefing + && self.valid_difficulty(w) + && !self.interact.is_open(w) + } +} +impl Goal for BreakDoor { + goal_clone!(); + fn flags(&self) -> u8 { + if self.vindicator { MOVE } else { 0 } + } + fn every_tick(&self) -> bool { + true + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if self.vindicator { + return raider::has_active_raid(m) + && m.random.next_int_bound(reduced(10)).unwrap_or(1) == 0 + && self.can_break(m, cx.w); + } + m.extra.can_break_doors && self.can_break(m, cx.w) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + (!self.vindicator || raider::has_active_raid(m)) + && self.break_time <= DOOR_BREAK_TIME + && !self.interact.is_open(cx.w) + && closer_to_center(self.interact.door, m.position, 2.0) + && self.valid_difficulty(cx.w) + } + fn start(&mut self, m: &mut Mob, _cx: &mut Cx) { + self.break_time = 0; + if self.vindicator { + m.ai.no_action_time = 0; + } + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + cx.events.push(MobEvent::DestroyProgress { + mob: m.id, + pos: self.interact.door, + progress: -1, + }); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let door = self.interact.door; + if m.random.next_int_bound(20).unwrap_or(1) == 0 { + cx.events.push(MobEvent::LevelEvent { + id: 1019, + pos: door, + data: 0, + }); + if !m.ai.swinging { + m.swing(); + } + } + self.break_time += 1; + let progress = (self.break_time as f32 / DOOR_BREAK_TIME as f32 * 10.0) as i32; + if progress != self.last_break_progress { + cx.events.push(MobEvent::DestroyProgress { + mob: m.id, + pos: door, + progress, + }); + self.last_break_progress = progress; + } + if self.break_time == DOOR_BREAK_TIME && self.valid_difficulty(cx.w) { + cx.events.push(MobEvent::BreakDoor { pos: door }); + } + } +} + +/// `AbstractIllager.RaiderOpenDoorGoal` (`OpenDoorGoal` that does not wait +/// to close): open the door in the way during a raid. It never continues, so +/// it closes the door again as soon as it stops. +#[derive(Clone, Debug, Default)] +pub struct RaiderOpenDoor { + interact: Interact, +} +impl Goal for RaiderOpenDoor { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn every_tick(&self) -> bool { + true + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.interact.can_use(m, cx.w) && raider::has_active_raid(m) + } + fn can_continue(&mut self, _m: &mut Mob, _cx: &mut Cx) -> bool { + false + } + fn start(&mut self, _m: &mut Mob, cx: &mut Cx) { + self.interact.set_open(cx, true); + } + fn stop(&mut self, _m: &mut Mob, cx: &mut Cx) { + self.interact.set_open(cx, false); + } +} diff --git a/crates/horizon-client/src/mobs/drops.rs b/crates/horizon-client/src/mobs/drops.rs index c7b1c77e1..064cf0583 100644 --- a/crates/horizon-client/src/mobs/drops.rs +++ b/crates/horizon-client/src/mobs/drops.rs @@ -351,6 +351,9 @@ pub fn loot_entity(m: &Mob, vehicle: Option) -> LootEntity { .to_owned(), ); } + if s == S::Chicken { + e.chicken_variant = super::finalize::variant_component(m).map(|(_, id)| id); + } e.powered = s == S::Creeper && m.extra.charged; e.equipment = SLOTS .iter() @@ -456,6 +459,14 @@ pub fn die(m: &mut Mob, d: &Death, sequences: &mut RandomSequences) -> (Vec) { let at = [m.position.x, m.position.y, m.position.z]; events.push(MobEvent::Sound("entity.chicken.egg", at, 1.0, pitch)); events.push(MobEvent::GiftLoot { + mob: m.id, table: "minecraft:gameplay/chicken_lay", at, }); diff --git a/crates/horizon-client/src/mobs/finalize.rs b/crates/horizon-client/src/mobs/finalize.rs index 4eeed885b..6e5daff1f 100644 --- a/crates/horizon-client/src/mobs/finalize.rs +++ b/crates/horizon-client/src/mobs/finalize.rs @@ -590,6 +590,14 @@ pub fn has_modifier(m: &Mob, a: Attr, id: &str) -> bool { .as_ref() .is_some_and(|s| s.modifiers.iter().any(|x| x.attr == a && x.id == id)) } +/// The amount of a permanent modifier, if the mob has it. +pub fn modifier_amount(m: &Mob, a: Attr, id: &str) -> Option { + m.extra + .attributes + .as_ref() + .and_then(|s| s.modifiers.iter().find(|x| x.attr == a && x.id == id)) + .map(|x| x.amount) +} /// `addOrReplacePermanentModifier`. pub fn add_modifier(m: &mut Mob, a: Attr, id: &'static str, amount: f64, op: Op) { let s = m.extra.attributes.get_or_insert_with(Box::default); @@ -605,6 +613,59 @@ pub fn add_modifier(m: &mut Mob, a: Attr, id: &'static str, amount: f64, op: Op) } refresh(m, a); } +/// `Zombie.handleAttributes`, from the zombie's own random. +pub fn zombie_attributes(m: &mut Mob, special: f32, reason: Reason) { + let r = &mut m.random; + let reinforcements = if m.kind.species == Species::ZombifiedPiglin { + 0.0 + } else { + r.next_double() * f64::from(0.1f32) + }; + let knockback = r.next_double() * f64::from(0.05f32); + let follow = r.next_double() * 1.5 * f64::from(special); + let leader = r.next_float() < special * 0.05; + let leader_rolls = leader.then(|| (r.next_double() * 0.25 + 0.5, r.next_double() * 3.0 + 1.0)); + set_base(m, Attr::SpawnReinforcements, reinforcements); + add_modifier( + m, + Attr::KnockbackResistance, + "minecraft:random_spawn_bonus", + knockback, + Op::AddValue, + ); + if follow > 1.0 { + add_modifier( + m, + Attr::FollowRange, + "minecraft:zombie_random_spawn_bonus", + follow, + Op::AddMultipliedTotal, + ); + } + if let Some((reinforce, health)) = leader_rolls { + add_modifier( + m, + Attr::SpawnReinforcements, + "minecraft:leader_zombie_bonus", + reinforce, + Op::AddValue, + ); + add_modifier( + m, + Attr::MaxHealth, + "minecraft:leader_zombie_bonus", + health, + Op::AddMultipliedTotal, + ); + if !matches!( + reason, + Reason::Conversion | Reason::Load | Reason::DimensionTravel + ) { + m.health = max_health(m); + } + super::doors::set_can_break_doors(m, true); + } +} pub fn max_health(m: &Mob) -> f32 { value(m, Attr::MaxHealth) as f32 } @@ -829,6 +890,14 @@ pub fn set_item(m: &mut Mob, slot: usize, id: &str) { } gear::set(m, gear_slot(slot), Vec::new()); } +/// The enchantments on what `m` has in `slot`. +pub fn slot_enchantments(m: &Mob, slot: usize) -> gear::Levels { + gear::gear(m).map_or_else(Vec::new, |g| g.slots[gear_slot(slot)].clone()) +} +/// Replace the enchantments of what `m` has in `slot` (after `set_item`). +pub fn set_slot_enchantments(m: &mut Mob, slot: usize, levels: gear::Levels) { + gear::set(m, gear_slot(slot), levels); +} /// `Mob.setDropChance`. pub fn set_drop_chance(m: &mut Mob, slot: usize, chance: f32) { let c = m @@ -1144,70 +1213,17 @@ impl Ctx<'_, L, R> { } } } - m.extra.can_break_doors = self.float() < special * 0.1; + let can_break_doors = self.float() < special * 0.1; + super::doors::set_can_break_doors(m, can_break_doors); if reason != Reason::Conversion { self.populate(m); self.enchant(m); } } self.halloween(m); - self.zombie_attributes(m, special, reason); + zombie_attributes(m, special, reason); g } - /// `Zombie.handleAttributes`, from the zombie's own random. - fn zombie_attributes(&mut self, m: &mut Mob, special: f32, reason: Reason) { - let r = &mut m.random; - let reinforcements = if m.kind.species == Species::ZombifiedPiglin { - 0.0 - } else { - r.next_double() * f64::from(0.1f32) - }; - let knockback = r.next_double() * f64::from(0.05f32); - let follow = r.next_double() * 1.5 * f64::from(special); - let leader = r.next_float() < special * 0.05; - let leader_rolls = - leader.then(|| (r.next_double() * 0.25 + 0.5, r.next_double() * 3.0 + 1.0)); - set_base(m, Attr::SpawnReinforcements, reinforcements); - add_modifier( - m, - Attr::KnockbackResistance, - "minecraft:random_spawn_bonus", - knockback, - Op::AddValue, - ); - if follow > 1.0 { - add_modifier( - m, - Attr::FollowRange, - "minecraft:zombie_random_spawn_bonus", - follow, - Op::AddMultipliedTotal, - ); - } - if let Some((reinforce, health)) = leader_rolls { - add_modifier( - m, - Attr::SpawnReinforcements, - "minecraft:leader_zombie_bonus", - reinforce, - Op::AddValue, - ); - add_modifier( - m, - Attr::MaxHealth, - "minecraft:leader_zombie_bonus", - health, - Op::AddMultipliedTotal, - ); - if !matches!( - reason, - Reason::Conversion | Reason::Load | Reason::DimensionTravel - ) { - m.health = max_health(m); - } - m.extra.can_break_doors = true; - } - } fn husk(&mut self, m: &mut Mob, g: Option, reason: Reason) -> Option { let mut g = self.zombie(m, g, reason); if reason != Reason::Conversion { diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index a784464d8..541398bc5 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -1210,6 +1210,9 @@ pub struct NearestTarget { pub interval: i32, /// Extra condition on the attacker, checked after the random interval. pub when: Option bool>, + /// Mobs closer than this squared distance are not picked + /// (`GuardianAttackSelector`: `distanceToSqr > 9`). + pub beyond_sqr: Option, /// A condition checked before anything else, by subclasses overriding /// `canUse` (SpiderTargetGoal: only in the dark). pub gate: Option bool>, @@ -1242,6 +1245,7 @@ impl NearestTarget { must_reach: false, interval: reduced(10), when: None, + beyond_sqr: None, gate: None, label: None, found: None, @@ -1274,6 +1278,10 @@ impl NearestTarget { self.when = Some(f); self } + pub fn beyond(mut self, distance_sqr: f64) -> Self { + self.beyond_sqr = Some(distance_sqr); + self + } pub fn gate(mut self, f: fn(&Mob, &MobWorld) -> bool) -> Self { self.gate = Some(f); self @@ -1284,9 +1292,25 @@ impl NearestTarget { self } } +/// `AbstractIllager.canAttack`: a baby `AbstractVillager` is never attacked. +fn illager_spares(attacker: Species, target: &Seen) -> bool { + matches!( + attacker, + Species::Pillager | Species::Vindicator | Species::Evoker | Species::Illusioner + ) && target.baby + && matches!(target.species, Species::Villager | Species::WanderingTrader) +} /// TargetGoal.canContinueToUse pub fn target_continue(st: &mut TargetState, must_see: bool, m: &mut Mob, cx: &mut Cx) -> bool { let Some(who) = m.ai.target else { return false }; + if let Who::Mob(id) = who + && cx + .w + .seen(id) + .is_some_and(|s| illager_spares(m.species(), s)) + { + return false; + } let Some(t) = cx.w.target_info(who) else { return false; }; @@ -1345,10 +1369,12 @@ impl Goal for NearestTarget { prey => { let pos = Vec3::new(m.position.x, m.eye_y(), m.position.z); let id = m.id; + let attacker = m.species(); let candidates: Vec<(u32, Vec3)> = cx.w.nearby(pos, range, move |s| { s.id != id && !s.playing_dead + && !illager_spares(attacker, s) && match prey { Prey::Species(list) => list.contains(&s.species), Prey::Filter(f) => f(s), @@ -1361,6 +1387,9 @@ impl Goal for NearestTarget { if m.distance_sqr(cpos) > range * range { continue; } + if self.beyond_sqr.is_some_and(|d| m.distance_sqr(cpos) <= d) { + continue; + } if !m.sees(cx.w, Who::Mob(cid)) { continue; } @@ -1762,6 +1791,10 @@ impl Goal for Breed { if tamable && (!m.extra.tame || m.extra.sitting) { return false; } + // TurtleBreedGoal.canUse: not while carrying an egg. + if species == Species::Turtle && super::turtle::has_egg(m) { + return false; + } let id = m.id; // Horses and donkeys breed together (AbstractHorse.canParent: tame). // Sniffer.canMate: calm states only. @@ -1840,6 +1873,10 @@ impl Goal for Breed { }); m.extra.in_love = 0; m.extra.age = 6000; + // TurtleBreedGoal.breed: the mother carries an egg, not a baby. + if m.species() == Species::Turtle { + m.extra.flag = true; + } cx.events.push(MobEvent::Breed { parent: m.id, partner: p.id, diff --git a/crates/horizon-client/src/mobs/guardian.rs b/crates/horizon-client/src/mobs/guardian.rs index 9704de044..880655361 100644 --- a/crates/horizon-client/src/mobs/guardian.rs +++ b/crates/horizon-client/src/mobs/guardian.rs @@ -61,7 +61,8 @@ pub fn register(m: &mut Mob) { NearestTarget::species( &[Species::Squid, Species::GlowSquid, Species::Axolotl], true, - ), + ) + .beyond(9.0), ); } /// `GuardianAttackGoal`. @@ -120,9 +121,11 @@ impl Goal for GuardianAttack { 1.0, )); } else if self.attack_time >= attack_duration(m) { - // Indirect magic (1, +2 for the elder; NORMAL difficulty), then + // Indirect magic (1, +2 on Hard, +2 for the elder), then // doHurtTarget. - let magic = if is_elder(m) { 3.0 } else { 1.0 }; + let magic = 1.0 + + if cx.w.difficulty.hard { 2.0 } else { 0.0 } + + if is_elder(m) { 2.0 } else { 0.0 }; let from = [m.position.x, m.position.y, m.position.z]; match who { Who::Player => cx.events.push(MobEvent::DamagePlayer { diff --git a/crates/horizon-client/src/mobs/hostile.rs b/crates/horizon-client/src/mobs/hostile.rs index 0d3feaa6c..f1c990c48 100644 --- a/crates/horizon-client/src/mobs/hostile.rs +++ b/crates/horizon-client/src/mobs/hostile.rs @@ -177,6 +177,10 @@ pub fn creeper_tick(m: &mut Mob, events: &mut Vec) { if m.swell >= 30 { m.swell = 30; let radius = if m.extra.charged { 6.0 } else { 3.0 }; + events.push(MobEvent::ExplosionSource { + mob: m.id, + charged: m.extra.charged, + }); events.push(MobEvent::Explode( [m.position.x, m.position.y, m.position.z], radius, diff --git a/crates/horizon-client/src/mobs/illager.rs b/crates/horizon-client/src/mobs/illager.rs index 45ef076d3..00581d6d3 100644 --- a/crates/horizon-client/src/mobs/illager.rs +++ b/crates/horizon-client/src/mobs/illager.rs @@ -72,6 +72,8 @@ pub fn register_vindicator(m: &mut Mob) { let g = &mut m.ai.goals; g.add(0, Float); g.add(1, avoid_creaking(1.0, 1.2)); + g.add(2, super::doors::BreakDoor::vindicator()); + g.add(3, super::doors::RaiderOpenDoor::default()); g.add(4, super::raider::HoldGroundAttack::new(10.0)); g.add(5, MeleeAttack::new(1.0, false)); g.add(8, Stroll::new(0.6)); @@ -86,6 +88,13 @@ pub fn register_vindicator(m: &mut Mob) { .when(|m, _| m.custom_name.as_deref() == Some("Johnny")), ); } +/// `Vindicator.customServerAiStep`: its navigation opens doors while a raid +/// is at its position. +pub fn vindicator_server_ai_step(m: &mut Mob) { + if super::doors::can_navigate_ground(m) { + m.ai.nav.can_open_doors = super::raider::state(m).is_some_and(|s| s.raided); + } +} // Evoker state: `counter` spellCastingTickCount, `variant2` the spell // being cast (0 none, 1 vexes, 2 fangs, 3 wololo), `counter2` the wololo // sheep's id. @@ -179,8 +188,8 @@ impl Goal for UseSpell { fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { let age = i64::from(m.age); if self.spell == Spell::Wololo { - // EvokerWololoSpellGoal.canUse: a blue sheep within 16 (4 up or - // down), no target, griefing on. + // EvokerWololoSpellGoal.canUse: a blue sheep within the box + // (16 sideways, 4 up or down) and `range(16)`, no target, griefing on. if m.ai.target.is_some() || m.extra.counter > 0 || age < self.next || !cx.w.mob_griefing { return false; @@ -196,6 +205,7 @@ impl Goal for UseSpell { && (s.position.x - p.x).abs() <= 16.0 && (s.position.y - p.y).abs() <= 4.0 && (s.position.z - p.z).abs() <= 16.0 + && s.position.distance_squared(p) <= 16.0 * 16.0 }) .map(|s| s.id) .collect(); @@ -210,7 +220,8 @@ impl Goal for UseSpell { return false; } if self.spell == Spell::Vexes { - // EvokerSummonSpellGoal: fewer vexes nearby than a roll of 1..8. + // EvokerSummonSpellGoal: fewer vexes within `range(16)` than a + // roll of 1..8. let p = m.position; let vexes = cx.w.others @@ -218,7 +229,7 @@ impl Goal for UseSpell { .filter(|s| { s.species == Species::Vex && s.alive - && s.position.distance_squared(p) <= 16.0 * 16.0 * 3.0 + && s.position.distance_squared(p) <= 16.0 * 16.0 }) .count() as i32; return m.random.next_int_bound(8).unwrap_or(0) + 1 > vexes; @@ -670,7 +681,12 @@ pub fn anim_pose(m: &Mob, s: &State, p: &mut Poses, pose: ArmPose) { p.xrot("right_arm", x + a * 1.2 - b * 0.4); p.xrot("left_arm", x + a * 1.2 - b * 0.4); } else { - // swingWeaponDown (right-handed). + // swingWeaponDown: the main arm swings down. + let (main, off) = if m.main_arm_left() { + ("left_arm", "right_arm") + } else { + ("right_arm", "left_arm") + }; let swing = s.swing; let a2 = (swing * PI).msin(); let a = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin(); @@ -679,11 +695,11 @@ pub fn anim_pose(m: &Mob, s: &State, p: &mut Poses, pose: ArmPose) { p.yrot("right_arm", PI / 20.0); p.yrot("left_arm", -PI / 20.0); p.xrot( - "right_arm", + main, -1.884_955_8 + (s.age * 0.09).mcos() * 0.15 + (a2 * 2.2 - a * 0.4), ); p.xrot( - "left_arm", + off, -0.0 + (s.age * 0.19).mcos() * 0.5 + (a2 * 1.2 - a * 0.4), ); } diff --git a/crates/horizon-client/src/mobs/piglin.rs b/crates/horizon-client/src/mobs/piglin.rs index fff536932..a057581e6 100644 --- a/crates/horizon-client/src/mobs/piglin.rs +++ b/crates/horizon-client/src/mobs/piglin.rs @@ -15,6 +15,9 @@ use std::f32::consts::PI; /// `PiglinAi.ADMIRE_DURATION`. pub const ADMIRE: i32 = 119; +/// `PiglinAi.eat`: the `ATE_RECENTLY` memory lasts 200 ticks (kept in +/// `extra.ints[0]` of a piglin). +pub const ATE_RECENTLY: i32 = 200; /// `AbstractPiglin.CONVERSION_TIME` (and the hoglin's). const CONVERSION: i32 = 300; @@ -45,6 +48,7 @@ pub fn register_piglin(m: &mut Mob) { g.add(3, super::illager::crossbow_goal(1.0, 8.0)); } g.add(3, MeleeAttack::new(1.0, true)); + g.add(4, PiglinAvoidRepellent); g.add(4, GoToWantedItem); g.add(5, Stroll::avoiding_water(0.6)); g.add(6, LookAtPlayer::new(8.0)); @@ -176,6 +180,54 @@ impl Goal for BabyPanic { self.0.stop(m, cx) } } +/// `PiglinAi.avoidRepellent`: `SetWalkTargetAwayFrom.pos(NEAREST_REPELLENT, 1.0, 8, false)` +/// of the idle activity. Closer than 8 blocks to a repellent and not walking +/// anywhere, walk away from it. +#[derive(Clone, Debug)] +struct PiglinAvoidRepellent; +impl Goal for PiglinAvoidRepellent { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some(r) = m.extra.repellent else { + return false; + }; + // The idle activity: not fighting or admiring, and no walk target yet. + if m.ai.target.is_some() || m.extra.using_item > 0 || !m.ai.nav.is_done() { + return false; + } + // Vec3.atBottomCenterOf. + let avoid = [ + f64::from(r[0]) + 0.5, + f64::from(r[1]), + f64::from(r[2]) + 0.5, + ]; + if m.distance_sqr(Vec3::new(avoid[0], avoid[1], avoid[2])) >= 64.0 { + return false; + } + for _ in 0..10 { + if let Some(p) = m.land_random_pos_away(cx.w, 16, 7, avoid) { + let at = [ + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ]; + m.ai.pending_path = m.create_path_to(cx.w, at, 0); + return m.ai.pending_path.is_some(); + } + } + false + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + !m.ai.nav.is_done() + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + let path = m.ai.pending_path.take(); + m.nav_move_to_path(path, 1.0); + } +} /// Admiring a gold item held in the off hand: stand and look at it. #[derive(Clone, Debug)] struct Admire; @@ -257,6 +309,9 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.ai.target = None; } } + if m.species() == Species::Piglin && m.extra.ints[0] > 0 { + m.extra.ints[0] -= 1; + } // Admiring disabled after being hit by a player. if m.extra.egg_time > 0 { m.extra.egg_time -= 1; @@ -299,6 +354,26 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } else { m.extra.counter2 = 0; } + // PiglinSpecificSensor (every 20 ticks): the nearest repelling block. + if m.species() == Species::Piglin && m.alive() && m.age.wrapping_add(m.id).is_multiple_of(20) { + m.extra.repellent = find_piglin_repellent(m, w); + } +} +/// `PiglinSpecificSensor.findNearestRepellent`: the nearest `#piglin_repellents` +/// block within 8 blocks sideways and 4 up or down; a soul campfire only +/// counts while lit. +fn find_piglin_repellent(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> { + let tag = w.block_tags.get("minecraft:piglin_repellents")?; + let at = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + w.nearest_block(at, 8, 4, |p, name| { + tag.contains(name) + && (name != "minecraft:soul_campfire" + || w.prop(p[0], p[1], p[2], "lit") == Some("true")) + }) } /// `HoglinBase.hurtAndThrowTarget`. pub fn hoglin_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { @@ -356,7 +431,14 @@ pub fn piglin_anim(m: &Mob, s: &State, p: &mut Poses) { } else { PiglinPose::Default }; - piglin_pose(p, s, pose, 25.0, m.extra.using_item as f32); + piglin_pose( + p, + s, + pose, + 25.0, + m.extra.using_item as f32, + m.main_arm_left(), + ); } /// `PiglinArmPose`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -368,11 +450,19 @@ pub enum PiglinPose { CrossbowCharge, AdmiringItem, } -/// `PiglinModel.setupAnim` for a piglin facing right-handed. -pub fn piglin_pose(p: &mut Poses, s: &State, pose: PiglinPose, max_charge: f32, ticks: f32) { - use super::anim::{ArmPose, Hum, humanoid}; +/// `PiglinModel.setupAnim`; `left` when the piglin's main arm is the left one. +pub fn piglin_pose( + p: &mut Poses, + s: &State, + pose: PiglinPose, + max_charge: f32, + ticks: f32, + left: bool, +) { + use super::anim::{ArmPose, Hum, crossbow_charge, crossbow_hold, humanoid}; let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty); h.weapon_swing = pose == PiglinPose::MeleeWeapon; + h.left_main = left; h.charge = (max_charge, ticks); humanoid(p, s, &h); ears(p, s); @@ -399,27 +489,22 @@ pub fn piglin_pose(p: &mut Poses, s: &State, pose: PiglinPose, max_charge: f32, p.get("left_arm")[1] += (dance * 40.0).msin() * 0.5 + 0.5; p.get("body")[1] += (dance * 40.0).msin() * 0.35; } - PiglinPose::MeleeWeapon if s.swing == 0.0 => p.xrot("right_arm", -1.8), - PiglinPose::CrossbowHold => { - p.yrot("right_arm", -0.3 + hy); - p.yrot("left_arm", 0.6 + hy); - p.xrot("right_arm", -PI / 2.0 + hx + 0.1); - p.xrot("left_arm", -1.5 + hx); - } - PiglinPose::CrossbowCharge => { - p.yrot("right_arm", -0.8); - p.xrot("right_arm", -0.970_796_35); - p.xrot("left_arm", -0.970_796_35); - let alpha = ticks.clamp(0.0, max_charge) / max_charge; - p.yrot("left_arm", 0.4 + alpha * (0.85 - 0.4)); - let x = -0.970_796_35 + alpha * (-PI / 2.0 - -0.970_796_35); - p.xrot("left_arm", x); + // holdWeaponHigh + PiglinPose::MeleeWeapon if s.swing == 0.0 => { + p.xrot(if left { "left_arm" } else { "right_arm" }, -1.8) } + PiglinPose::CrossbowHold => crossbow_hold(p, hx, hy, !left), + PiglinPose::CrossbowCharge => crossbow_charge(p, max_charge, ticks, !left), PiglinPose::AdmiringItem => { p.xrot("head", 0.5); p.yrot("head", 0.0); - p.yrot("left_arm", 0.5); - p.xrot("left_arm", -0.9); + if left { + p.yrot("right_arm", -0.5); + p.xrot("right_arm", -0.9); + } else { + p.yrot("left_arm", 0.5); + p.xrot("left_arm", -0.9); + } } _ => {} } diff --git a/crates/horizon-client/src/mobs/raider.rs b/crates/horizon-client/src/mobs/raider.rs index 6c3ab9b64..d2ed62374 100644 --- a/crates/horizon-client/src/mobs/raider.rs +++ b/crates/horizon-client/src/mobs/raider.rs @@ -30,6 +30,9 @@ pub struct State { pub celebrating: bool, /// The raid is active (`hasActiveRaid`); set by the game every tick. pub active_raid: bool, + /// A raid is active within 96 blocks (`ServerLevel.isRaided`); set by + /// the game every tick for vindicators. + pub raided: bool, /// The raid is won or lost (`Raid.isOver`), lost (`isLoss`). pub raid_over: bool, pub raid_loss: bool, diff --git a/crates/horizon-client/src/mobs/shulker.rs b/crates/horizon-client/src/mobs/shulker.rs index 11ebdadb4..6f0edc2d7 100644 --- a/crates/horizon-client/src/mobs/shulker.rs +++ b/crates/horizon-client/src/mobs/shulker.rs @@ -3,7 +3,7 @@ //! their face is lost or when badly hurt, and shrugging off arrows while //! closed. use super::{ - Damage, DamageKind, Mob, MobEvent, MobWorld, Who, + Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who, anim::{Poses, State}, goals::{ Cx, Goal, HurtByTarget, LOOK, LookAtPlayer, MOVE, NearestTarget, RandomLookAround, @@ -14,7 +14,7 @@ use crate::projectiles::{Projectile, ProjectileWorld, STEPS}; use horizon_core::geometry::trig::Mth; use horizon_core::{ geometry::{Aabb, Vec3}, - random::RandomSource, + random::{LegacyRandom, RandomSource}, }; use std::f32::consts::PI; @@ -164,12 +164,62 @@ pub fn after_hurt(m: &mut Mob) { m.extra.flag = true; } } -/// The deferred teleport of `after_hurt`. -pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { +/// `Shulker.hurtServer` after a shulker bullet's damage: unless the +/// low-health teleport was drawn instead (`else if`), `hitByShulkerBullet` +/// runs on the next tick. Whether the shell is open is read here, at hurt +/// time, so a goal opening it before that tick cannot change the outcome. +pub fn hit_by_bullet(m: &mut Mob) { + if m.species() == Species::Shulker && !m.extra.flag && m.extra.counter != 0 { + m.extra.flag2 = true; + } +} +/// The deferred teleport of `after_hurt` and `hitByShulkerBullet`. +pub fn ai_step( + m: &mut Mob, + w: &MobWorld, + level_random: &mut LegacyRandom, + events: &mut Vec, +) { if m.extra.flag { m.extra.flag = false; teleport(m, w, events); } + if m.extra.flag2 { + m.extra.flag2 = false; + hit_by_shulker_bullet(m, w, level_random, events); + } +} +/// `Shulker.hitByShulkerBullet` (only queued by an open shulker): it +/// teleports, and leaves a new one of its colour behind unless shulkers +/// crowd the place (one in five fewer chances for every other shulker +/// within 8 blocks). +fn hit_by_shulker_bullet( + m: &mut Mob, + w: &MobWorld, + level_random: &mut LegacyRandom, + events: &mut Vec, +) { + let old_position = m.position; + let old_box = m.bounds(); + if !teleport(m, w, events) { + return; + } + let area = old_box.inflate(Vec3::new(8.0, 8.0, 8.0)); + // The shulker itself stands within reach of its old box, so it counts. + let others = w + .others_near(area) + .filter(|s| { + s.alive && s.species == Species::Shulker && s.id != m.id && s.bounds.intersects(area) + }) + .count(); + let failure_chance = others as f32 / 5.0; + // The level's random, not the shulker's. + if level_random.next_float() < failure_chance { + return; + } + let mut baby = Mob::new(0, m.kind.clone(), old_position, 0.0); + baby.extra.color = m.extra.color; + events.push(MobEvent::Spawn(Box::new(baby))); } /// A ProjectileWorld over the mob world, for aiming a new bullet. struct Probe<'a, 'w> { diff --git a/crates/horizon-client/src/mobs/sniffer.rs b/crates/horizon-client/src/mobs/sniffer.rs index 6979171b8..c0c8d8155 100644 --- a/crates/horizon-client/src/mobs/sniffer.rs +++ b/crates/horizon-client/src/mobs/sniffer.rs @@ -94,6 +94,7 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec) { if current == DIGGING && now(m) == m.extra.ints[3] { let h = head_block(m); events.push(MobEvent::GiftLoot { + mob: m.id, table: "minecraft:gameplay/sniffer_digging", at: [f64::from(h[0]), f64::from(h[1]), f64::from(h[2])], }); diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index 93e3fe119..58118d2c2 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -35,6 +35,8 @@ pub fn placement_ok(species: Species, w: &MobWorld, x: i32, y: i32, z: i32) -> b #[derive(Clone, Copy, Debug)] pub struct LocalDifficulty { pub effective: f32, + /// The world difficulty is normal. + pub normal: bool, /// The world difficulty is hard. pub hard: bool, } @@ -45,9 +47,11 @@ impl LocalDifficulty { /// the overworld clock, the chunk's inhabited time and the moon. pub fn new(base: u8, total: i64, inhabited: i64, moon: f32) -> Self { let hard = base == 3; + let normal = base == 2; if base == 0 { return Self { effective: 0.0, + normal, hard, }; } @@ -60,6 +64,7 @@ impl LocalDifficulty { } Self { effective: f32::from(base) * (0.75 + global + local), + normal, hard, } } @@ -148,6 +153,14 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { S::Pig | S::Cow | S::Chicken => m.extra.variant = climate_index, S::Sheep => m.extra.color = super::farm::sheep_color(biome.climate, &mut m.random), S::Mooshroom => m.extra.variant = 0, + // Turtle.finalizeSpawn: home is where it spawned. + S::Turtle => { + m.extra.home = Some([ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]) + } S::Frog => m.extra.variant = biome.frog, S::Wolf => m.extra.variant = biome.wolf, S::Cat => m.extra.variant = super::tame::cat_variant(m, biome.full_moon), @@ -158,6 +171,9 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { if m.random.next_float() < 0.05 { m.extra.age = i32::MIN / 2; } + // setCanBreakDoors(nextFloat() < special * 0.1), before the gear. + let can_break_doors = m.random.next_float() < difficulty.special() * 0.1; + super::doors::set_can_break_doors(m, can_break_doors); if m.species() != S::Drowned { populate_armor(m, difficulty); } @@ -191,6 +207,9 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { // ZombifiedPiglin.populateDefaultEquipmentSlots: a golden sword, or // one time in 20 a golden spear. S::ZombifiedPiglin => { + // Zombie.finalizeSpawn's setCanBreakDoors. + let can_break_doors = m.random.next_float() < difficulty.special() * 0.1; + super::doors::set_can_break_doors(m, can_break_doors); let spear = m.random.next_int_bound(20).unwrap_or(1) == 0; m.extra.main_hand = Some( if spear { @@ -264,6 +283,18 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { S::Slime | S::MagmaCube => super::cube::finalize(m), _ => {} } + // Zombie.finalizeSpawn ends with handleAttributes: the reinforcement + // chance (and a leader's bonus) that `Zombie.hurtServer` reads. + if matches!( + m.species(), + S::Zombie | S::Husk | S::Drowned | S::ZombieVillager | S::ZombifiedPiglin + ) { + super::finalize::zombie_attributes( + m, + difficulty.special(), + super::finalize::Reason::Natural, + ); + } } /// VillagerType.byBiome pub fn villager_type(b: &BiomeFacts) -> u8 { diff --git a/crates/horizon-client/src/mobs/turtle.rs b/crates/horizon-client/src/mobs/turtle.rs new file mode 100644 index 000000000..98dd5b558 --- /dev/null +++ b/crates/horizon-client/src/mobs/turtle.rs @@ -0,0 +1,209 @@ +//! Turtles (`Turtle`): the egg a bred mother carries (`TurtleBreedGoal`), her +//! walk home (`TurtleGoHomeGoal`) and the egg she digs into the sand +//! (`TurtleLayEggGoal`). `extra.flag` is `hasEgg`, `extra.flag2` `isLayingEgg`, +//! `extra.counter` `layEggCounter` and `extra.home` `homePos`. +use super::{ + Mob, MobEvent, MobWorld, + goals::{Breed, Cx, Goal, JUMP, MOVE, MoveToBlock, goal_clone, reduced}, +}; +use horizon_core::random::RandomSource; + +pub fn register(m: &mut Mob) { + let g = &mut m.ai.goals; + g.add(1, Breed::new(1.0)); + g.add(1, LayEgg(MoveToBlock::new(1.0, 16, 1))); + g.add(4, GoHome::default()); +} +/// `Turtle.hasEgg`. +pub fn has_egg(m: &Mob) -> bool { + m.extra.flag +} +/// `Turtle.setLayingEgg`. +fn set_laying_egg(m: &mut Mob, on: bool) { + m.extra.counter = i32::from(on); + m.extra.flag2 = on; +} +/// `homePos.closerToCenterThan(position, distance)`. Spawning, hatching and +/// loading all set a home; one made any other way is at home where it stands. +fn close_to_home(m: &Mob, distance: f64) -> bool { + let home = m.extra.home.unwrap_or([ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]); + let d = [ + f64::from(home[0]) + 0.5 - m.position.x, + f64::from(home[1]) + 0.5 - m.position.y, + f64::from(home[2]) + 0.5 - m.position.z, + ]; + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < distance * distance +} +fn block_of(m: &Mob) -> [i32; 3] { + [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ] +} +/// `TurtleEggBlock.isSand`. +fn is_sand(w: &MobWorld, p: [i32; 3]) -> bool { + w.has_tag("minecraft:sand", w.block_name(p[0], p[1], p[2])) +} +/// `Turtle.aiStep`: while digging, sand crumbs fly every fifth tick. +pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + if m.alive() && m.extra.flag2 && m.extra.counter >= 1 && m.extra.counter % 5 == 0 { + let at = block_of(m); + let below = [at[0], at[1] - 1, at[2]]; + if is_sand(w, below) { + events.push(MobEvent::BlockBreakEffect { + pos: at, + block: below, + }); + } + } +} + +/// `Turtle.TurtleLayEggGoal`: a mother with an egg within 9 blocks of home +/// walks to sand with air above, digs for 200 ticks and lays it. +#[derive(Clone, Debug)] +struct LayEgg(MoveToBlock); +impl LayEgg { + /// `isValidTarget`: sand with air above it. + fn valid(w: &MobWorld, p: [i32; 3]) -> bool { + w.facts.is_air(w.world.block(p[0], p[1] + 1, p[2])) && is_sand(w, p) + } +} +impl Goal for LayEgg { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | JUMP + } + fn name(&self) -> &'static str { + "TurtleLayEggGoal" + } + fn every_tick(&self) -> bool { + true + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !(has_egg(m) && close_to_home(m, 9.0)) { + return false; + } + // MoveToBlockGoal.canUse. + if self.0.next_start > 0 { + self.0.next_start -= 1; + return false; + } + self.0.next_start = reduced(200 + m.random.next_int_bound(200).unwrap_or(0)); + self.0.find_nearest(m, cx.w, Self::valid) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_continue(cx.w, Self::valid) && has_egg(m) && close_to_home(m, 9.0) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.start(m, cx.w); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.tick(m, cx.w); + if m.fluids.in_water || !self.0.reached { + return; + } + if m.extra.counter < 1 { + set_laying_egg(m, true); + } else if m.extra.counter > 200 { + let at = [m.position.x, m.position.y, m.position.z]; + let pitch = 0.9 + m.random.next_float() * 0.2; + cx.events + .push(MobEvent::Sound("entity.turtle.lay_egg", at, 0.3, pitch)); + // Blocks.TURTLE_EGG with EGGS = nextInt(4) + 1 above the sand. + let eggs = m.random.next_int_bound(4).unwrap_or(0) + 1; + let registry = cx.w.registry; + let state = registry + .default_state("minecraft:turtle_egg") + .and_then(|d| registry.state(d).cloned()) + .and_then(|mut s| { + s.properties.insert("eggs".into(), eggs.to_string()); + registry.resolve(&s).ok() + }); + let b = self.0.block; + if let Some(state) = state { + cx.events.push(MobEvent::SetBlock { + pos: [b[0], b[1] + 1, b[2]], + state, + }); + } + m.extra.flag = false; + set_laying_egg(m, false); + m.extra.in_love = 600; + } + if m.extra.flag2 { + m.extra.counter += 1; + } + } +} + +/// `Turtle.TurtleGoHomeGoal`: a mother with an egg heads home; any adult +/// that strayed 64 blocks away does now and then. +#[derive(Clone, Debug, Default)] +struct GoHome { + stuck: bool, + close_to_home_try_ticks: i32, +} +impl Goal for GoHome { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn name(&self) -> &'static str { + "TurtleGoHomeGoal" + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + if m.is_baby() { + false + } else if has_egg(m) { + true + } else { + m.random.next_int_bound(reduced(700)).unwrap_or(1) == 0 && !close_to_home(m, 64.0) + } + } + fn start(&mut self, _m: &mut Mob, _cx: &mut Cx) { + self.stuck = false; + self.close_to_home_try_ticks = 0; + } + fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + !close_to_home(m, 7.0) && !self.stuck && self.close_to_home_try_ticks <= reduced(600) + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let home = m.extra.home.unwrap_or(block_of(m)); + let close = close_to_home(m, 16.0); + if close { + self.close_to_home_try_ticks += 1; + } + if !m.ai.nav.is_done() { + return; + } + let to = [ + f64::from(home[0]) + 0.5, + f64::from(home[1]), + f64::from(home[2]) + 0.5, + ]; + let mut next = m + .default_random_pos_towards(cx.w, 16, 3, to, std::f64::consts::PI / 10.0) + .or_else(|| m.default_random_pos_towards(cx.w, 8, 7, to, std::f64::consts::FRAC_PI_2)); + if let Some(at) = next + && !close + && cx.w.block_name( + at[0].floor() as i32, + at[1].floor() as i32, + at[2].floor() as i32, + ) != "minecraft:water" + { + next = m.default_random_pos_towards(cx.w, 16, 5, to, std::f64::consts::FRAC_PI_2); + } + match next { + Some(at) => { + m.nav_move_to(cx.w, at, 1.0); + } + None => self.stuck = true, + } + } +} diff --git a/crates/horizon-client/src/mobs/undead.rs b/crates/horizon-client/src/mobs/undead.rs index efff2b73e..52efea3c4 100644 --- a/crates/horizon-client/src/mobs/undead.rs +++ b/crates/horizon-client/src/mobs/undead.rs @@ -1,7 +1,8 @@ //! Zombies (zombie, husk, drowned, zombie villager) and skeletons (skeleton, //! stray, bogged, wither skeleton): goals, bow attacks, water conversion. use super::{ - Mob, MobEvent, Species, Who, + Damage, Mob, MobEvent, Species, Who, + doors::BreakDoor, goals::{ Avoid, AvoidEntity, Cx, FleeSun, Goal, HurtByTarget, LOOK, LookAtPlayer, MOVE, MeleeAttack, NearestTarget, RandomLookAround, RestrictSun, Stroll, goal_clone, @@ -10,11 +11,22 @@ use super::{ use crate::projectiles::{Projectile, ProjectileKind}; use horizon_core::{geometry::Vec3, random::RandomSource}; +/// `Zombie.hurtServer`, once the hit landed: a zombie with a target (its own, +/// else a living attacker) asks the game to try calling a reinforcement; the +/// difficulty, chance and spawn tests are the game's (`call_reinforcements`). +pub fn after_hurt(m: &mut Mob, source: &Damage) { + if let Some(target) = m.ai.target.or(source.attacker) { + m.outbox + .push(MobEvent::Reinforcements { mob: m.id, target }); + } +} + pub fn register(m: &mut Mob) { use Species as S; match m.species() { S::Zombie | S::Husk | S::ZombieVillager => { let g = &mut m.ai.goals; + g.add(1, BreakDoor::zombie()); g.add(4, AttackTurtleEgg::default()); g.add(8, LookAtPlayer::new(8.0)); g.add(8, RandomLookAround::default()); @@ -42,6 +54,7 @@ pub fn register(m: &mut Mob) { S::ZombifiedPiglin => { // ZombifiedPiglin.addBehaviourGoals: neutral until provoked. let g = &mut m.ai.goals; + g.add(1, BreakDoor::zombie()); g.add(8, LookAtPlayer::new(8.0)); g.add(8, RandomLookAround::default()); g.add(2, MeleeAttack::new(1.0, false).zombie()); @@ -58,6 +71,7 @@ pub fn register(m: &mut Mob) { S::Drowned => { // Zombie.registerGoals, then Drowned.addBehaviourGoals. let g = &mut m.ai.goals; + g.add(1, BreakDoor::zombie()); g.add(4, AttackTurtleEgg::default()); g.add(8, LookAtPlayer::new(8.0)); g.add(8, RandomLookAround::default()); diff --git a/crates/horizon-client/src/mobs/vex.rs b/crates/horizon-client/src/mobs/vex.rs index de38f6da8..1301d1922 100644 --- a/crates/horizon-client/src/mobs/vex.rs +++ b/crates/horizon-client/src/mobs/vex.rs @@ -29,6 +29,7 @@ pub fn register(m: &mut Mob) { g.add(8, RandomMove); g.add(9, LookAtPlayer::new(3.0).probability(1.0)); g.add(10, LookAtPlayer::mobs(8.0)); + // `HurtByTargetGoal(this, Raider.class)`: raiders are ignored, vexes are not. let mut hurt = HurtByTarget::new().alert(); hurt.ignore = vec![ Species::Pillager, @@ -36,7 +37,7 @@ pub fn register(m: &mut Mob) { Species::Evoker, Species::Illusioner, Species::Witch, - Species::Vex, + Species::Ravager, ]; m.ai.targets.add(1, hurt); m.ai.targets.add(2, CopyOwnerTarget); diff --git a/crates/horizon-client/src/mobs/witch.rs b/crates/horizon-client/src/mobs/witch.rs index 0990ae01d..b0ec7866a 100644 --- a/crates/horizon-client/src/mobs/witch.rs +++ b/crates/horizon-client/src/mobs/witch.rs @@ -193,6 +193,11 @@ fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { } Who::Player => false, }; + // `target.hasEffect`: a target that already has the effect gets the next one. + let has = |effect: &str| match who { + Who::Player => cx.w.player.as_ref().is_some_and(|p| p.has_effect(effect)), + Who::Mob(id) => cx.w.seen(id).is_some_and(|s| s.has_effect(effect)), + }; let (effect, ticks, amplifier) = if heals { m.ai.target = None; if health <= 4.0 { @@ -200,11 +205,11 @@ fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { } else { ("minecraft:regeneration", 900, 0) } - } else if dist >= 8.0 { + } else if dist >= 8.0 && !has("slowness") { ("minecraft:slowness", 1800, 0) - } else if health >= 8.0 { + } else if health >= 8.0 && !has("poison") { ("minecraft:poison", 900, 0) - } else if dist <= 3.0 && m.random.next_float() < 0.25 { + } else if dist <= 3.0 && !has("weakness") && m.random.next_float() < 0.25 { ("minecraft:weakness", 1800, 0) } else { ("minecraft:instant_damage", 1, 0) @@ -236,6 +241,15 @@ fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { pitch, )); } +/// The movement speed of a witch with `SPEED_MODIFIER_DRINKING` (-0.25, +/// `ADD_VALUE`) while it drinks: it stands still for the 32 ticks. +pub fn speed(m: &Mob, base: f64) -> f64 { + if m.species() == Species::Witch && m.extra.flag { + (base - 0.25).max(0.0) + } else { + base + } +} /// Witch.aiStep before `super.aiStep()`: the healing cooldown, then drink /// water breathing, fire resistance, healing or swiftness. pub fn ai_step(m: &mut Mob, cx_events: &mut Vec, target_far: bool) { diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index aa665decc..bce324228 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -206,6 +206,19 @@ impl MobWorld<'_> { } self.world.light(x, y, z) >> 4 == 15 } + /// Level.isRainingAt: raining, open to the sky, nothing motion blocking + /// above, and the biome's precipitation at the position is rain, not snow + /// or none. + pub fn raining_at(&self, x: i32, y: i32, z: i32) -> bool { + if !self.raining || !self.can_see_sky(x, y, z) || self.motion_blocking_height(x, z) > y { + return false; + } + let Some(chunk) = self.world.chunks.get(&(x >> 4, z >> 4)) else { + return false; + }; + let biome = self.biomes.get(chunk.biome(x, y, z)); + biome.precipitation && biome.temperature_at(BlockPos::new(x, y, z), self.sea_level) >= 0.15 + } /// Level.getLightLevelDependentMagicValue: the dimension's brightness curve /// at the raw (sky darkened) light level. pub fn brightness(&self, x: i32, y: i32, z: i32) -> f32 { diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index fcdd32cbd..dfdc3f168 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -50,6 +50,10 @@ pub struct MotionResources { pub attributes: Arc, pub blocks: BoundMovementProperties, pub climbable: BTreeSet, + /// `BlockTags.CAN_GLIDE_THROUGH`: climbable blocks a gliding player passes. + pub glide_through: BTreeSet, + /// `BlockTags.SOUL_SPEED_BLOCKS`: what Soul Speed's effects look for. + pub soul_speed_blocks: BTreeSet, pub fall_reset: BTreeSet, pub landing: BlockLandingRegistry, pub health: crate::health::HealthResources, @@ -108,11 +112,30 @@ impl MotionResources { suppresses_bounce: tag("minecraft:suppresses_bounce")?, })?, climbable: tag("minecraft:climbable")?, + glide_through: tag("minecraft:can_glide_through")?, + soul_speed_blocks: tag("minecraft:soul_speed_blocks")?, fall_reset: tag("minecraft:fall_damage_resetting")?, }) } } +/// What the `location_changed` enchantment effects (Soul Speed) need to know +/// between ticks. +#[derive(Clone, Debug, Default)] +pub struct LocationEffects { + /// `MovementAffectedByPredicate`: the block under the player + /// (`getBlockPosBelowThatAffectsMyMovement`) is in `#minecraft:soul_speed_blocks`. + pub on_soul_speed_block: bool, + /// `LivingEntity.lastPos`: the block the player was in last tick. + pub block: Option, + /// A landing ran `onChangedBlock` (`LivingEntity.checkFallDamage`). + pub landed: bool, + /// The Soul Speed level of the boots seen last tick (0: none). + pub boots_level: u32, + /// The Soul Speed level whose attribute modifiers are on the player (0: none). + pub applied_level: u32, +} + /// Ordered requests and phase records for world/audio/network consumers. Landing /// hurt dispatch updates stored health synchronously before these are drained. #[derive(Clone, Copy, Debug)] @@ -255,6 +278,8 @@ pub struct PlayerMotion { pub glide_ending: bool, /// Glider durability to take this tick (updateFallFlying). pub glider_wear: u32, + /// Soul Speed's `location_changed` bookkeeping. + pub location_effects: LocationEffects, /// `LivingEntity.autoSpinAttackTicks` and `autoSpinAttackDmg`: Riptide's /// spin. The damage stays until the game has dealt the hit. pub auto_spin_attack_ticks: i32, @@ -308,6 +333,9 @@ pub struct PlayerMotion { /// it travels on the server: `isLocalInstanceAuthoritative` is false, so /// its moves check no fall damage. pub server_copy: bool, + /// The span of `events` a wall hit on the server's copy pushed (sound and + /// damage): `server_travel` keeps them while it drops the simulated moves. + pub wall_hit_events: Option>, /// A client's copy of its own player (`Level.isClientSide`): only the /// server hurts it (`Entity.hurt` does nothing on a client) and ticks its /// food (`ServerPlayer.tick`). Its hurt animation comes from the server. @@ -443,6 +471,7 @@ impl PlayerMotion { fall_fly_ticks: 0, glide_ending: false, glider_wear: 0, + location_effects: LocationEffects::default(), auto_spin_attack_ticks: 0, auto_spin_attack_dmg: 0.0, spin_targets: Vec::new(), @@ -477,6 +506,7 @@ impl PlayerMotion { freeze_immune: false, old_position: position, server_copy: false, + wall_hit_events: None, client_side: false, block_effects: true, powder_snow_entered: Vec::new(), @@ -765,6 +795,10 @@ impl MotionWorld<'_, '_, '_> { .state(self.block(p)) .ok_or("missing scene state")? .name; + // A gliding player passes through vines (`CAN_GLIDE_THROUGH`). + if self.player.fall_flying && self.resources.glide_through.contains(name) { + return Ok(false); + } let climbable = self.resources.climbable.contains(name); if climbable { self.player.last_climbable = Some(p); @@ -834,9 +868,17 @@ impl MotionWorld<'_, '_, '_> { let can_glide = self.player.glider && !self.player.ground.on_ground && !self.player.flying + && self.player.status.levitation.is_none() && !self.player.fluids.was_touching_water && !self.player.is_in_lava(); - if jumping && !toggled && !was_jumping && !self.player.fall_flying && can_glide { + // LocalPlayer.aiStep: `!onClimbable()` before tryToStartFallFlying. + if jumping + && !toggled + && !was_jumping + && !self.climbable()? + && !self.player.fall_flying + && can_glide + { self.player.fall_flying = true; } // LivingEntity.tick fallFlyTicks, then updateFallFlying. @@ -848,8 +890,11 @@ impl MotionWorld<'_, '_, '_> { self.player.fall_distance = 1.0; } self.player.fall_fly_ticks += 1; - // canGlide alone: water and lava don't end a glide. - let still = self.player.glider && !self.player.ground.on_ground && !self.player.flying; + // canGlide alone: water and lava don't end a glide, levitation does. + let still = self.player.glider + && !self.player.ground.on_ground + && !self.player.flying + && self.player.status.levitation.is_none(); if !still { self.player.glide_ending = true; } else if (self.player.fall_fly_ticks + 1) % 10 == 0 @@ -984,6 +1029,7 @@ impl MotionWorld<'_, '_, '_> { ) }); self.player.try_add_frost(on_air)?; + self.update_soul_speed_block()?; if self.player.health.tick_count % 40 == 0 && self.player.is_fully_frozen() && self.player.can_freeze() @@ -996,6 +1042,22 @@ impl MotionWorld<'_, '_, '_> { } Ok(()) } + /// Refresh whether the player stands on a soul speed block, for the + /// `location_changed` enchantment effects (a server's player too, whose + /// client does the walking). + pub fn update_soul_speed_block(&mut self) -> Result<()> { + self.player.location_effects.on_soul_speed_block = self.on_soul_speed_block()?; + Ok(()) + } + /// `MovementAffectedByPredicate` for `#minecraft:soul_speed_blocks`. + fn on_soul_speed_block(&mut self) -> Result { + let on = self.support(movement_support::MOVEMENT_SUPPORT_OFFSET)?; + Ok(self + .assets + .registry + .state(self.block(on)) + .is_some_and(|s| self.resources.soul_speed_blocks.contains(&s.name))) + } /// Player.travel: swim steering, then LivingEntity.travel (fluids first, /// then gliding, then air), keeping 0.6 of the vertical speed while flying. fn player_travel(&mut self, input: Vec3) -> Result<()> { @@ -1021,7 +1083,14 @@ impl MotionWorld<'_, '_, '_> { { horizon_world::living_fluid::travel_in_fluid(self, input)?; } else if self.player.fall_flying { - self.travel_fall_flying()?; + // LivingEntity.travelFallFlying: on a climbable the glide ends and + // the player moves like in the air. + if self.climbable()? { + self.travel_in_air(input)?; + self.player.fall_flying = false; + } else { + self.travel_fall_flying()?; + } } else { self.travel_in_air(input)?; } @@ -1048,7 +1117,14 @@ impl MotionWorld<'_, '_, '_> { p.server_copy = false; (p.position, p.ground, p.collision) = (position, ground, collision); (p.history, p.fall_distance, p.steps) = (history, fall_distance, steps); + // The wall hit is the server's own: its sound and damage events stay. + let kept: Vec<_> = p + .wall_hit_events + .take() + .map(|span| p.events.drain(span).collect()) + .unwrap_or_default(); p.events.truncate(events); + p.events.extend(kept); travelled } /// `LivingEntity.checkAutoSpinAttack`: the first living entity in the @@ -1536,7 +1612,7 @@ impl MotionWorld<'_, '_, '_> { let lean = pitch; let look_h = (look.x * look.x + look.z * look.z).sqrt(); let move_h = (v.x * v.x + v.z * v.z).sqrt(); - let gravity = 0.08; + let gravity = living_motion::effective_gravity(self)?; let lift = f64::from(lean.cos()).powi(2); let mut m = Vec3::new(v.x, v.y + gravity * (-1.0 + lift * 0.75), v.z); if m.y < 0.0 && look_h > 0.0 { @@ -1564,7 +1640,44 @@ impl MotionWorld<'_, '_, '_> { } self.player.velocity = Vec3::new(m.x * 0.99, m.y * 0.98, m.z * 0.99); let movement = self.player.velocity; - self.move_self(movement) + self.move_self(movement)?; + // LivingEntity.handleFallFlyingCollisions: only the server hurts. + if !self.player.client_side && self.player.collision.horizontal { + let new_h = { + let v = self.player.velocity; + (v.x * v.x + v.z * v.z).sqrt() + }; + let dmg = ((move_h - new_h) * 10.0 - 3.0) as f32; + if dmg > 0.0 { + let first = self.player.events.len(); + // getFallDamageSound((int) dmg) + let sound = if dmg as i32 > 4 { + crate::landing::SceneSound::BigFall + } else { + crate::landing::SceneSound::SmallFall + }; + self.player + .events + .push(MotionEvent::Fall(crate::landing::FallEvent::Sound { + sound, + position: None, + volume: 1.0, + pitch: 1.0, + })); + let id = self + .resources + .health + .damage + .id("minecraft:fly_into_wall") + .ok_or("missing fly_into_wall damage type")?; + let rules = self.scene.health_rules; + self.player.hurt(&self.resources.health, rules, id, dmg)?; + if self.player.server_copy { + self.player.wall_hit_events = Some(first..self.player.events.len()); + } + } + } + Ok(()) } /// `LocalPlayer.move`: the move, then `updateAutoJump` with the float /// horizontal displacement. @@ -1842,6 +1955,10 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> { if self.player.status.slow_falling || self.player.status.levitation.is_some() { self.player.fall_distance = 0.0; } + // LivingEntity.checkFallDamage: a landing runs onChangedBlock. + if grounded && self.player.fall_distance > 0.0 { + self.player.location_effects.landed = true; + } if self.player.spawn_extra_particles_on_fall && grounded && self.player.fall_distance > 0.0 { self.player.events.push(MotionEvent::SmashLanding { diff --git a/crates/horizon-client/src/motion/environment.rs b/crates/horizon-client/src/motion/environment.rs index fc3c63c77..5e9bdfec8 100644 --- a/crates/horizon-client/src/motion/environment.rs +++ b/crates/horizon-client/src/motion/environment.rs @@ -161,6 +161,29 @@ pub(crate) fn fire_contact( } damage } +/// `CactusBlock.entityInside`: the box (deflated by `1.0E-5`, as in +/// `Entity.checkInsideBlocks`) touches a cactus; its inside shape is the +/// whole block. +pub(crate) fn cactus_contact( + world: &World, + registry: &horizon_world::registry::BlockRegistry, + bounds: Aabb, +) -> bool { + let b = bounds.deflate(Vec3::new(1e-5, 1e-5, 1e-5)); + for x in b.min_position().x.floor() as i32..=b.max_position().x.floor() as i32 { + for y in b.min_position().y.floor() as i32..=b.max_position().y.floor() as i32 { + for z in b.min_position().z.floor() as i32..=b.max_position().z.floor() as i32 { + if registry + .state(world.block(x, y, z)) + .is_some_and(|s| s.name == "minecraft:cactus") + { + return true; + } + } + } + } + false +} impl LivingFluidWorld for MotionWorld<'_, '_, '_> { fn in_water(&mut self) -> Result { Ok(self.player.fluids.was_touching_water) diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 61fda9878..a40d11258 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -67,6 +67,7 @@ pub enum Opt { ReducedDebugInfo, HighContrast, ShowSubtitles, + MusicFrequency, NotificationDisplayTime, Narrator, TextBackground, @@ -172,6 +173,10 @@ impl Opt { | Opt::MonochromeLogo | Opt::RotateWithMinecarts | Opt::HighContrastBlockOutlines + // Saved, but nothing in rendering reads them yet. + | Opt::ChunkFade + | Opt::ImprovedTransparency + | Opt::ChunkBuilder ) } fn file_key(self) -> Option<&'static str> { @@ -192,6 +197,7 @@ impl Opt { Opt::NarratorHotkey => "narratorHotkey", Opt::RotateWithMinecarts => "rotateWithMinecart", Opt::HighContrastBlockOutlines => "highContrastBlockOutline", + Opt::MusicFrequency => "musicFrequency", _ => return None, }) } @@ -248,6 +254,7 @@ impl Opt { Opt::ReducedDebugInfo => "options.reducedDebugInfo", Opt::HighContrast => "options.accessibility.high_contrast", Opt::ShowSubtitles => "options.showSubtitles", + Opt::MusicFrequency => "options.music_frequency", Opt::NotificationDisplayTime => "options.notifications.display_time", Opt::Narrator => "options.narrator", Opt::TextBackground => "options.accessibility.text_background", @@ -578,6 +585,11 @@ impl Opt { Opt::ReducedDebugInfo => on_off(s.reduced_debug_info), Opt::HighContrast => on_off(s.high_contrast), Opt::ShowSubtitles => on_off(s.show_subtitles), + Opt::MusicFrequency => tr([ + "options.music_frequency.default", + "options.music_frequency.frequent", + "options.music_frequency.constant", + ][s.file.int("musicFrequency").clamp(0, 2) as usize]), Opt::ForceUnicode => on_off(s.force_unicode), Opt::JapaneseGlyphs => on_off(s.japanese_glyphs), Opt::PadEnabled => on_off(s.controller.enabled), @@ -747,6 +759,11 @@ impl Opt { Opt::ReducedDebugInfo => s.reduced_debug_info = !s.reduced_debug_info, Opt::HighContrast => s.high_contrast = !s.high_contrast, Opt::ShowSubtitles => s.show_subtitles = !s.show_subtitles, + Opt::MusicFrequency => { + let n = next(s.file.int("musicFrequency").clamp(0, 2) as u8, 3); + s.file + .set("musicFrequency", crate::options_file::V::Int(i32::from(n))); + } Opt::ForceUnicode => s.force_unicode = !s.force_unicode, Opt::JapaneseGlyphs => s.japanese_glyphs = !s.japanese_glyphs, Opt::PadEnabled => s.controller.enabled = !s.controller.enabled, @@ -1412,6 +1429,9 @@ impl OptionsUi { let others: Vec = (1..SOUND_SOURCES.len()).map(Opt::Volume).collect(); rows.extend(pairs(&others)); rows.extend(pairs(&[Opt::ShowSubtitles])); + // SoundOptionsScreen: Music Frequency starts the next row (with + // Music Toast, not in Horizon yet). + rows.extend(pairs(&[Opt::MusicFrequency])); rows } Page::Controls => { @@ -2533,6 +2553,21 @@ impl OptionsUi { if opt == Opt::Preset { apply_preset(s); } + if opt == Opt::HighContrast { + // Options.highContrast: the built-in pack follows the option. + let on = s.resource_packs.iter().any(|id| id == "high_contrast"); + if on != s.high_contrast { + s.resource_packs.retain(|id| id != "high_contrast"); + if s.high_contrast { + s.resource_packs.push("high_contrast".into()); + } + // PackSelectionScreen reads the repository each time it + // opens: the next one starts from this selection. + self.pack_selection = s.resource_packs.clone(); + self.pack_screen = None; + events.push(Event::Packs(s.resource_packs.clone())); + } + } events.push(Event::Changed); } Act::Extra(item) => { @@ -2701,6 +2736,7 @@ impl OptionsUi { { let ids = p.commit(); s.resource_packs = ids.clone(); + self.pack_selection = ids.clone(); events.push(Event::Packs(ids)); } } diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index fa9dc9c6e..17064c163 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -23,212 +23,7 @@ use std::{ path::Path, }; -macro_rules! particle_types { - ($($variant:ident = $name:literal),* $(,)?) => { - /// Vanilla particle types with a client implementation here. - #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] - pub enum ParticleType { $($variant),* } - impl ParticleType { - pub const ALL: &'static [ParticleType] = &[$(ParticleType::$variant),*]; - /// Registry path (`minecraft:`), also the sprite-set file name. - pub fn name(self) -> &'static str { - match self { $(ParticleType::$variant => $name),* } - } - pub fn from_name(name: &str) -> Option { - let name = name.strip_prefix("minecraft:").unwrap_or(name); - match name { $($name => Some(ParticleType::$variant),)* _ => None } - } - } - }; -} -particle_types! { - Block = "block", - BlockCrumble = "block_crumble", - Trail = "trail", - DustPillar = "dust_pillar", - FallingDust = "falling_dust", - Smoke = "smoke", - LargeSmoke = "large_smoke", - WhiteSmoke = "white_smoke", - Flame = "flame", - SoulFireFlame = "soul_fire_flame", - CopperFireFlame = "copper_fire_flame", - SmallFlame = "small_flame", - Lava = "lava", - DrippingWater = "dripping_water", - FallingWater = "falling_water", - DrippingLava = "dripping_lava", - FallingLava = "falling_lava", - LandingLava = "landing_lava", - DrippingHoney = "dripping_honey", - FallingHoney = "falling_honey", - LandingHoney = "landing_honey", - FallingNectar = "falling_nectar", - FallingSporeBlossom = "falling_spore_blossom", - SporeBlossomAir = "spore_blossom_air", - DrippingObsidianTear = "dripping_obsidian_tear", - FallingObsidianTear = "falling_obsidian_tear", - LandingObsidianTear = "landing_obsidian_tear", - DrippingDripstoneWater = "dripping_dripstone_water", - FallingDripstoneWater = "falling_dripstone_water", - DrippingDripstoneLava = "dripping_dripstone_lava", - FallingDripstoneLava = "falling_dripstone_lava", - Splash = "splash", - Rain = "rain", - Bubble = "bubble", - SulfurBubbles = "sulfur_bubbles", - BubblePop = "bubble_pop", - BubbleColumnUp = "bubble_column_up", - CurrentDown = "current_down", - Underwater = "underwater", - Portal = "portal", - ReversePortal = "reverse_portal", - Enchant = "enchant", - Nautilus = "nautilus", - VaultConnection = "vault_connection", - Crit = "crit", - EnchantedHit = "enchanted_hit", - DamageIndicator = "damage_indicator", - Heart = "heart", - AngryVillager = "angry_villager", - HappyVillager = "happy_villager", - Composter = "composter", - Mycelium = "mycelium", - Dolphin = "dolphin", - EggCrack = "egg_crack", - Poof = "poof", - Explosion = "explosion", - ExplosionEmitter = "explosion_emitter", - CampfireCosySmoke = "campfire_cosy_smoke", - CampfireSignalSmoke = "campfire_signal_smoke", - Note = "note", - Dust = "dust", - TotemOfUndying = "totem_of_undying", - Firework = "firework", - EndRod = "end_rod", - Ash = "ash", - WhiteAsh = "white_ash", - CrimsonSpore = "crimson_spore", - WarpedSpore = "warped_spore", - CherryLeaves = "cherry_leaves", - PaleOakLeaves = "pale_oak_leaves", - TintedLeaves = "tinted_leaves", - Effect = "effect", - InstantEffect = "instant_effect", - EntityEffect = "entity_effect", - Witch = "witch", - Infested = "infested", - Cloud = "cloud", - Sneeze = "sneeze", - Snowflake = "snowflake", - Soul = "soul", - SculkSoul = "sculk_soul", - DragonBreath = "dragon_breath", - Gust = "gust", - SmallGust = "small_gust", - GustEmitterLarge = "gust_emitter_large", - GustEmitterSmall = "gust_emitter_small", - DustColorTransition = "dust_color_transition", - SculkCharge = "sculk_charge", - SculkChargePop = "sculk_charge_pop", - Shriek = "shriek", - SonicBoom = "sonic_boom", - Vibration = "vibration", - SweepAttack = "sweep_attack", - Glow = "glow", - WaxOn = "wax_on", - WaxOff = "wax_off", - ElectricSpark = "electric_spark", - Scrape = "scrape", - SquidInk = "squid_ink", - GlowSquidInk = "glow_squid_ink", - Item = "item", - ItemSlime = "item_slime", - ItemSnowball = "item_snowball", - ItemCobweb = "item_cobweb", - SulfurCubeGoo = "sulfur_cube_goo", - Flash = "flash", - Firefly = "firefly", - TrialSpawnerDetection = "trial_spawner_detection", - TrialSpawnerDetectionOminous = "trial_spawner_detection_ominous", - TrialOmen = "trial_omen", - RaidOmen = "raid_omen", - OminousSpawning = "ominous_spawning", - Spit = "spit", - Fishing = "fishing", - DustPlume = "dust_plume", - RedPoplarLeaves = "red_poplar_leaves", - OrangePoplarLeaves = "orange_poplar_leaves", - YellowPoplarLeaves = "yellow_poplar_leaves", - PauseMobGrowth = "pause_mob_growth", - ResetMobGrowth = "reset_mob_growth", - BlockMarker = "block_marker", -} -impl ParticleType { - /// `ParticleType.getOverrideLimiter` (`ParticleTypes.register(name, true)`): - /// spawned regardless of distance. - pub fn override_limiter(self) -> bool { - matches!( - self, - Self::BlockMarker - | Self::DamageIndicator - | Self::ExplosionEmitter - | Self::Explosion - | Self::Gust - | Self::GustEmitterLarge - | Self::GustEmitterSmall - | Self::SonicBoom - | Self::SculkCharge - | Self::SculkChargePop - | Self::Vibration - | Self::Poof - | Self::Spit - | Self::SquidInk - | Self::SweepAttack - | Self::CampfireCosySmoke - | Self::CampfireSignalSmoke - | Self::GlowSquidInk - | Self::Glow - | Self::WaxOn - | Self::WaxOff - | Self::ElectricSpark - | Self::Scrape - | Self::TrialSpawnerDetection - | Self::TrialSpawnerDetectionOminous - | Self::VaultConnection - | Self::OminousSpawning - ) - } - /// `SingleQuadParticle.Layer.translucent`: types whose vanilla particle class - /// hardcodes the translucent layer, drawn after translucent terrain. - /// `TerrainParticle`, `BreakingItemParticle` and `BlockMarker` resolve their - /// layer from the sprite instead (`Layer.bySprite`); see the `translucent` - /// sprite set on the engine. - pub fn translucent_layer(self) -> bool { - match self { - // CampfireSmokeParticle. - Self::CampfireCosySmoke | Self::CampfireSignalSmoke - // PlayerCloudParticle. - | Self::Cloud | Self::Sneeze - // SpellParticle. - | Self::Effect | Self::InstantEffect | Self::EntityEffect - | Self::Witch | Self::Infested | Self::TrialOmen | Self::RaidOmen - // EmissiveRisingParticle. - | Self::Soul | Self::SculkSoul - // SculkChargeParticle, SculkChargePopParticle, ShriekParticle, - // VibrationSignalParticle, FireflyParticle, OverlayParticle. - | Self::SculkCharge | Self::SculkChargePop | Self::Shriek - | Self::Vibration | Self::Firefly | Self::Flash - // SimpleAnimatedParticle and its subclasses: EndRodParticle, - // SparkParticle (firework), SquidInkParticle, TotemParticle. - | Self::EndRod | Self::Firework | Self::SquidInk | Self::GlowSquidInk - | Self::TotemOfUndying - // FlyTowardsPositionParticle: its LifetimeAlpha(0, 0.6, 0.25, 1) is not opaque. - | Self::VaultConnection => true, - _ => false, - } - } -} +pub use horizon_client_core::particle_type::ParticleType; /// `ParticleOptions` with the parameters of the option classes used here. #[derive(Clone, Debug)] diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 5431adcd6..dc08d90b0 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -2435,28 +2435,7 @@ fn write_saved_data(world: &Path, name: &str, data: Tag) -> Result<()> { Tag::compound([("data", data), ("DataVersion", Tag::Int(DATA_VERSION))]), ) } -pub fn uuid_text(u: [i32; 4]) -> String { - let hex: String = u.iter().map(|v| format!("{:08x}", *v as u32)).collect(); - format!( - "{}-{}-{}-{}-{}", - &hex[0..8], - &hex[8..12], - &hex[12..16], - &hex[16..20], - &hex[20..32] - ) -} -pub fn uuid_from_text(s: &str) -> Option<[i32; 4]> { - let hex: String = s.chars().filter(|c| *c != '-').collect(); - if hex.len() != 32 { - return None; - } - let mut out = [0i32; 4]; - for (i, v) in out.iter_mut().enumerate() { - *v = u32::from_str_radix(&hex[i * 8..i * 8 + 8], 16).ok()? as i32; - } - Some(out) -} +pub use horizon_client_core::uuid::{uuid_from_text, uuid_text}; /// A random (version 4) UUID as vanilla's four-int form. pub fn random_uuid() -> [i32; 4] { let t = std::time::SystemTime::now() @@ -5125,6 +5104,30 @@ mod tests { }; assert_eq!(back.recipes_used.get("minecraft:cooked_porkchop"), Some(&3)); } + /// The world's save (Level.write) writes the rules as they are now, and a + /// world opened again reads them back (#74). + #[test] + fn level_save_keeps_changed_rules() { + use crate::gamerules::{GameRules, Value}; + let dir = + std::env::temp_dir().join(format!("horizon-gamerules-level-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut level = super::Level::default(); + level.write(&dir).unwrap(); + // Rules changed while playing, then saved and loaded again. + let mut rules = GameRules::load(&dir); + assert_eq!(rules, GameRules::default()); + assert!(rules.set("advance_time", Value::Bool(false))); + assert!(rules.set("advance_weather", Value::Bool(false))); + assert!(rules.set("random_tick_speed", Value::Int(0))); + level.game_rules = rules.by_name(); + level.write(&dir).unwrap(); + assert_eq!(GameRules::load(&dir), rules); + let read = super::Level::read(&dir).unwrap(); + assert_eq!(read.game_rules, rules.by_name()); + assert_eq!(read.game_rule("advance_time"), 0); + let _ = std::fs::remove_dir_all(dir); + } /// A save written before the key was namespaced holds an id twice, once bare: vanilla /// refuses such a furnace, so a load merges them under the full id. diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 74c428923..2308794d3 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -5,11 +5,7 @@ use crate::keybinds::KeyBinds; use crate::options_file::{OptionsFile, V}; use std::{fs, path::Path}; -/// SoundSource names in vanilla order. -pub const SOUND_SOURCES: [&str; 11] = [ - "master", "music", "record", "weather", "block", "hostile", "neutral", "player", "ambient", - "voice", "ui", -]; +pub use horizon_client_core::sound_source::SOUND_SOURCES; /// Per-source volumes for the mixer (soundCategory_* except master). static SOURCE_VOLUMES: std::sync::RwLock<[f32; 11]> = std::sync::RwLock::new([1.0; 11]); diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index a307b35cf..c5ed5d881 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -448,6 +448,7 @@ pub fn grindstone_experience( #[derive(Clone, Debug)] pub enum Smithing { Transform { + id: String, template: Ingredient, base: Ingredient, addition: Ingredient, @@ -527,6 +528,7 @@ impl StationRecipes { ); match v["type"].as_str().unwrap_or("") { "minecraft:smithing_transform" => smithing.push(Smithing::Transform { + id, template: ingredient(&v["template"], items), base: ingredient(&v["base"], items), addition: ingredient(&v["addition"], items), @@ -630,6 +632,7 @@ impl StationRecipes { base: b, addition: a, result, + .. } => { if t.test(template) && b.test(base) && a.test(addition) { // SmithingTransformRecipe: transmute the base keeping its components. diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 643a604bc..c0a96f504 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -175,6 +175,11 @@ pub enum Done { } struct Queued { priority: i64, + /// The column the job is for and what it adds to the column's distance + /// (`Streaming::submit`): the priority is computed again from them when + /// the centre moves (`Streaming::requeue`). None for saves, which go first. + at: Option<(i32, i32)>, + bias: i64, order: u64, job: Job, } @@ -222,6 +227,9 @@ pub struct Streaming { /// radius it was last ranked for. decoration_order: DecorationOrder, order_area: Option<((i32, i32), i32)>, + /// What the queued jobs' priorities were computed from (`requeue`): the + /// centre, the loading screen, the band, and the extra areas. + queue_basis: (((i32, i32), bool, Option), Vec<((i32, i32), i32)>), finishing: FxHashSet<(i32, i32)>, decorates: bool, lighting: FxHashMap<(i32, i32), u64>, @@ -544,6 +552,7 @@ impl Streaming { saving: 0, decoration_order: DecorationOrder::default(), order_area: None, + queue_basis: Default::default(), finishing: Default::default(), decorates: generator.decorates(), lighting: Default::default(), @@ -648,15 +657,39 @@ impl Streaming { world.dirty_sections.take_column(x, z); world.chunks.remove(&(x, z)) } - fn submit(&mut self, priority: i64, job: Job) { + /// Queue a job for the column `at`, nearest first: its distance (`distance`) + /// times four plus `bias`, which orders a column's jobs. A job without a + /// column (a save) goes ahead of every other. + fn submit(&mut self, at: Option<(i32, i32)>, bias: i64, job: Job) { self.order += 1; + let priority = at.map_or(i64::MIN, |(x, z)| self.distance(x, z) * 4 + bias); self.shared.queue.lock().unwrap().push(Queued { priority, + at, + bias, order: self.order, job, }); self.shared.ready.notify_one(); } + /// Rank the queued jobs again when what their priorities were computed + /// from changed: the centre, the extra areas, the band, or the loading + /// screen (ring order, `Ranges::rings`, whose values are far above the + /// distances used after it). Vanilla's chunk task queue follows the + /// current ticket levels in the same way. Without it, generation queued + /// while the loading screen was up waited behind every job queued after + /// it, and with it the decoration of the chunks around the player: at + /// render distance 32 nothing was decorated until every proto chunk had + /// been generated. + fn requeue(&mut self) { + let basis = (self.center, self.loading, self.band); + if self.queue_basis.0 == basis && self.queue_basis.1 == self.extra { + return; + } + self.queue_basis = (basis, self.extra.clone()); + let mut queue = self.shared.queue.lock().unwrap(); + rank_again(&mut queue, |x, z| self.distance(x, z)); + } fn receive_decorated(&mut self, x: i32, z: i32, region: [Proto; 9]) { self.generation_scan.exhausted = false; self.decorating -= 1; @@ -686,7 +719,7 @@ impl Streaming { self.saving += 1; // Ahead of every other job: a column generated again meanwhile // would not find them saved. - self.submit(i64::MIN, Job::Save(protos)); + self.submit(None, 0, Job::Save(protos)); } } fn receive_generated(&mut self, mut chunk: Chunk, world: &mut World) { @@ -829,6 +862,7 @@ impl Streaming { return (uploads, Vec::new()); } ExtraCover::refresh(&mut self.cover, &self.extra); + self.requeue(); self.relight_edits(world); let deferred = std::mem::take(&mut self.deferred); let received = std::iter::from_fn(|| self.results.try_recv().ok()); @@ -984,7 +1018,7 @@ impl Streaming { .expect("present proto"); self.finishing.insert((x, z)); self.written.remove(&(x, z)); - self.submit(self.distance(x, z) * 4, Job::Finish(proto)); + self.submit(Some((x, z)), 0, Job::Finish(proto)); } } // Decorate chunks whose 3x3 proto neighbourhood is available, in @@ -1052,7 +1086,7 @@ impl Streaming { w.0 = self.decoration_order.rank_or_append(w.2, w.3); } wanted.sort_unstable(); - for (_, d, x, z) in wanted { + for (_, _, x, z) in wanted { if self.decorating >= workers * 2 { break; } @@ -1091,7 +1125,7 @@ impl Streaming { Err(_) => continue, }; self.decorating += 1; - self.submit(d * 4 + 1, Job::Decorate(x, z, region)); + self.submit(Some((x, z)), 1, Job::Decorate(x, z, region)); } } self.schedule_generation(world, workers); @@ -1111,7 +1145,8 @@ impl Streaming { self.light_snapshots .insert((x, z), self.light_edit_sequence); self.submit( - self.distance(x, z) * 4 + 1, + Some((x, z)), + 1, Job::Light(x, z, region, self.sequence, self.sky_light), ); } @@ -1183,7 +1218,8 @@ impl Streaming { self.sequence += 1; self.meshing.insert((x, sy, z), self.sequence); self.submit( - self.distance(x, z) * 4 + if first { 2 } else { 0 }, + Some((x, z)), + if first { 2 } else { 0 }, Job::Mesh( x, sy, @@ -1222,9 +1258,9 @@ impl Streaming { loading: self.loading, }; if let Some(wanted) = self.generation_scan.candidates(input, workers * 3) { - for (d, x, z) in wanted { + for (_, x, z) in wanted { self.generating.insert((x, z)); - self.submit(d * 4, Job::Generate(x, z)); + self.submit(Some((x, z)), 0, Job::Generate(x, z)); } } } @@ -1381,6 +1417,14 @@ impl Streaming { pub fn band(&self) -> Option { self.band } + /// Rank the chunks `/forceload add` over chunks `(x0, z0)..=(x1, z1)` + /// decorates in vanilla's order (`forced_order`), after every chunk + /// ranked before. + pub fn rank_forced(&mut self, x0: i32, z0: i32, x1: i32, z1: i32) { + for (x, z) in horizon_world::worldgen::decoration_order::forced_order(x0, z0, x1, z1) { + self.decoration_order.rank_or_append(x, z); + } + } /// Generate, light and keep the chunks of `band` (none: stop), and let /// go of what earlier bands held as it falls out of range. The chunks a /// band reaches are ranked for decoration row by row, as they first come @@ -1738,10 +1782,78 @@ fn section_indexes(mut bits: u32) -> impl Iterator { }) }) } +/// The queued jobs' priorities computed again from each one's column +/// `distance` (`Streaming::submit`). +fn rank_again(queue: &mut BinaryHeap, distance: impl Fn(i32, i32) -> i64) { + if queue.is_empty() { + return; + } + let mut jobs = std::mem::take(queue).into_vec(); + for job in &mut jobs { + if let Some((x, z)) = job.at { + job.priority = distance(x, z) * 4 + job.bias; + } + } + *queue = BinaryHeap::from(jobs); +} #[cfg(test)] mod tests { use super::*; + #[test] + fn queued_jobs_follow_the_centre_and_the_loading_screen() { + let forced = HashSet::new(); + let ranges = |center| Ranges { + center, + radius: 32, + extra: &[], + forced: &forced, + cover: None, + band: None, + }; + let generate = |x, z, priority, order| Queued { + priority, + at: Some((x, z)), + bias: 0, + order, + job: Job::Generate(x, z), + }; + let loading = ranges((0, 0)); + let queued = || { + BinaryHeap::from(vec![ + // Queued while the loading screen was up: ring order. + generate(3, 1, loading.priority(3, 1, true) * 4, 1), + // Queued after it closed: plain distances, far below any ring past the first. + generate(20, 0, loading.priority(20, 0, false) * 4, 2), + Queued { + priority: i64::MIN, + at: None, + bias: 0, + order: 3, + job: Job::Save(Vec::new()), + }, + ]) + }; + let pops = |mut queue: BinaryHeap| { + std::iter::from_fn(move || queue.pop()) + .map(|q| q.at) + .collect::>() + }; + assert_eq!( + pops(queued()), + [None, Some((20, 0)), Some((3, 1))], + "the stale order" + ); + let mut queue = queued(); + rank_again(&mut queue, |x, z| loading.priority(x, z, false)); + assert_eq!(pops(queue), [None, Some((3, 1)), Some((20, 0))]); + // The player moved: the job near the new centre goes first. + let mut queue = BinaryHeap::from(vec![generate(3, 1, 0, 1), generate(20, 0, 1, 2)]); + let moved = ranges((19, 0)); + rank_again(&mut queue, |x, z| moved.priority(x, z, false)); + assert_eq!(queue.pop().and_then(|q| q.at), Some((20, 0))); + } + #[test] fn view_distance_is_vanillas_shape() { // ChunkTrackingView.isInViewDistance at render distance 12: a column diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index 604cf7925..01c60ed71 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -9,7 +9,7 @@ use horizon_world::{ }; use std::{ path::Path, - sync::{Arc, OnceLock}, + sync::{Arc, Mutex}, }; /// The `custom_data` key holding an exploration map's search until the game @@ -114,11 +114,13 @@ pub fn has_pending_map(item: &ItemStack) -> bool { }) } -static LOOT: OnceLock>> = OnceLock::new(); +/// None until `loot_data` runs; `Some(None)` when the tables failed to load. +static LOOT: Mutex>>> = Mutex::new(None); /// Loot data of the resource root, loaded once per process. pub fn loot_data(root: &Path) -> Option> { - LOOT.get_or_init(|| match LootData::load(root) { + let mut loot = LOOT.lock().unwrap_or_else(|e| e.into_inner()); + loot.get_or_insert_with(|| match LootData::load(root) { Ok(data) => Some(Arc::new(data)), Err(e) => { log::warn!("Horizon: loot tables unavailable, structure containers stay empty: {e}"); @@ -130,7 +132,16 @@ pub fn loot_data(root: &Path) -> Option> { /// The loot data `loot_data` loaded, if it ran. pub fn loaded_loot_data() -> Option> { - LOOT.get().cloned().flatten() + LOOT.lock() + .unwrap_or_else(|e| e.into_inner()) + .clone() + .flatten() +} + +/// Let go of the loot data: for a preload no world used +/// (game/world_loading.rs). The next `loot_data` loads it again. +pub fn forget_loot_data() { + *LOOT.lock().unwrap_or_else(|e| e.into_inner()) = None; } /// `RandomizableContainer.unpackLootTable` of a container at `pos`: `table` diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index 923818a08..dc729bd8c 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -24,7 +24,9 @@ use horizon_world::{ }; use std::{path::Path, sync::Arc}; mod lod; +mod structure_mobs; use lod::VanillaLodSampler; +use structure_mobs::StructureMobFinalizer; pub struct VanillaTerrain { generator: OverworldGenerator, @@ -32,6 +34,7 @@ pub struct VanillaTerrain { biome_map: Vec, /// Loot tables for generated containers. loot: Option>, + structure_mobs: Arc, /// A worker for structure queries from the game thread. query: std::sync::Mutex>, /// Block state id -> block index, the game's block tick type: worldgen @@ -39,6 +42,8 @@ pub struct VanillaTerrain { tick_blocks: Vec, /// Block index -> default state id: `tick_blocks` the other way. tick_states: Vec, + /// Block state id -> the block entity type of its block, if it has one. + block_entity_types: Vec>, seed: i64, dimension: String, /// When the last proto chunk was generated, in milliseconds since @@ -51,6 +56,51 @@ enum VanillaProto { Ready(Box), Failed(i32, i32), } +/// WorldGenRegion.setBlock gives every block with a block entity a new +/// one: the blocks nothing placed data for (a sculk patch's sensors) get +/// vanilla's defaults. +fn add_default_block_entities(kinds: &[Option<&str>], out: &mut Chunk, raw: &mut Vec) { + let kind = |v: u32| kinds.get(v as usize).copied().flatten(); + let mut states = [0u32; 4096]; + for (si, section) in out.sections.iter().enumerate() { + if !section.blocks.maybe_has(|v| kind(v).is_some()) { + continue; + } + section.unpack(&mut states); + for (i, &v) in states.iter().enumerate() { + let Some(id) = kind(v) else { + continue; + }; + let i = i as i32; + let pos = [ + out.x * 16 + (i & 15), + MIN_Y + si as i32 * 16 + (i >> 8), + out.z * 16 + ((i >> 4) & 15), + ]; + let at = |t: &Tag| { + ["x", "y", "z"] + .iter() + .zip(pos) + .all(|(k, p)| t.get(k) == Some(&Tag::Int(p))) + }; + if raw.iter().any(at) || out.block_entities.iter().any(|(p, _)| *p == pos.into()) { + continue; + } + let tag = Tag::compound([ + ("id", Tag::String(id.into())), + ("x", Tag::Int(pos[0])), + ("y", Tag::Int(pos[1])), + ("z", Tag::Int(pos[2])), + ]); + let tag = crate::block_entity_nbt::canonical(&tag).unwrap_or(tag); + match crate::save::decode_block_entity(&tag) { + Some(modelled) => out.block_entities.push(modelled), + None => raw.push(tag), + } + } + } +} + impl VanillaTerrain { fn client_surface(&self, surface: SurfaceSample) -> crate::lod::Surface { crate::lod::Surface { @@ -119,6 +169,7 @@ impl VanillaTerrain { } let mut tick_blocks = Vec::with_capacity(registry.len()); let mut tick_states = Vec::new(); + let mut block_entity_types = Vec::with_capacity(registry.len()); let mut last: Option<&str> = None; let mut index = 0u32; for id in 0..registry.len() { @@ -133,20 +184,31 @@ impl VanillaTerrain { } last = Some(name); tick_blocks.push(index); + block_entity_types.push(crate::lan::chunks::block_entity_type(name)); } Ok(Self { generator, biome_map, loot, + structure_mobs: Arc::new(StructureMobFinalizer::new( + dir.parent().unwrap_or(dir).to_owned(), + dimension, + )), query: std::sync::Mutex::new(None), tick_blocks, tick_states, + block_entity_types, seed, dimension: dimension.to_owned(), last_proto: std::sync::atomic::AtomicU64::new(0), created: std::time::Instant::now(), }) } + /// The difficulty (0 peaceful to 3 hard) and overworld clock structure + /// mobs are finalized with. + pub fn set_spawn_conditions(&self, difficulty: u8, day_time: i64) { + self.structure_mobs.set_conditions(difficulty, day_time); + } /// A proto chunk's blocks, biomes, scheduled ticks and post-processing /// marks as a column. fn column(&self, chunk: &ProtoChunk) -> Chunk { @@ -333,15 +395,23 @@ impl VanillaTerrain { u64::try_from(self.created.elapsed().as_millis()).unwrap_or(u64::MAX) } } +static SHARED_DATA: std::sync::Mutex)>> = + std::sync::Mutex::new(Vec::new()); +/// Let go of the bundles `shared_data` loaded: for a preload no world used +/// (game/world_loading.rs). A generator that holds one keeps it. +pub fn forget_shared_data() { + SHARED_DATA + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clear(); +} /// The worldgen bundle at `dir`, loaded once and shared by every generator /// and by live feature placement (sapling growth, bone meal). pub fn shared_data( dir: &Path, registry: &'static BlockRegistry, ) -> crate::Result> { - static CACHE: std::sync::Mutex)>> = - std::sync::Mutex::new(Vec::new()); - let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner()); + let mut cache = SHARED_DATA.lock().unwrap_or_else(|e| e.into_inner()); if let Some((_, data)) = cache.iter().find(|(path, _)| path == dir) { return Ok(data.clone()); } @@ -354,7 +424,9 @@ pub fn shared_data( impl ChunkGenerator for VanillaTerrain { type Worker = GeneratorWorker; fn worker(&self) -> GeneratorWorker { - self.generator.worker() + let mut worker = self.generator.worker(); + worker.set_structure_mobs(self.structure_mobs.clone()); + worker } fn lod_sampler(self: Arc) -> Box { Box::new(VanillaLodSampler::new(self)) @@ -553,7 +625,7 @@ impl ChunkGenerator for VanillaTerrain { // The block entities Horizon does not model (decorated pots with their // sherds and loot table, brushable blocks) stay as placed, like a // loaded chunk's. - let unmodelled: Vec = chunk + let mut unmodelled: Vec = chunk .block_entities .iter() .filter(|(pos, _)| { @@ -573,6 +645,7 @@ impl ChunkGenerator for VanillaTerrain { Some(Tag::Compound(nbt)) }) .collect(); + add_default_block_entities(&self.block_entity_types, &mut out, &mut unmodelled); if !unmodelled.is_empty() || !rolled_loot.is_empty() { let mut extras = out .saved @@ -596,3 +669,35 @@ impl ChunkGenerator for VanillaTerrain { out } } + +#[cfg(test)] +mod default_block_entity_tests { + use super::*; + + #[test] + fn generated_blocks_get_their_block_entities() { + let mut out = Chunk::empty(-2, 3); + out.set(4, -40, 9, 7); + out.set(5, -40, 9, 6); + let mut kinds = vec![None; 8]; + kinds[6] = Some("minecraft:potent_sulfur"); + kinds[7] = Some("minecraft:sculk_sensor"); + let mut raw = vec![]; + add_default_block_entities(&kinds, &mut out, &mut raw); + assert!(matches!( + out.block_entities[..], + [((-28, -40, 57), crate::containers::BlockEntity::Sculk(_))] + )); + assert_eq!(raw.len(), 1); + assert_eq!( + raw[0].get("id"), + Some(&Tag::String("minecraft:potent_sulfur".into())) + ); + add_default_block_entities(&kinds, &mut out, &mut raw); + assert_eq!( + (out.block_entities.len(), raw.len()), + (1, 1), + "a placed block entity is kept, not doubled" + ); + } +} diff --git a/crates/horizon-client/src/vanillagen/structure_mobs.rs b/crates/horizon-client/src/vanillagen/structure_mobs.rs new file mode 100644 index 000000000..dec5aa92b --- /dev/null +++ b/crates/horizon-client/src/vanillagen/structure_mobs.rs @@ -0,0 +1,446 @@ +//! `Mob.finalizeSpawn(level, level.getCurrentDifficultyAt(pos), STRUCTURE, null)` +//! of the mobs structures place (StructureTemplate.placeEntities with +//! finalizeEntities, ocean ruin drowned, mansion illagers, witch huts, +//! monuments), run as decoration places them, with the WorldGenRegion's random. +use crate::{ + enchant::Enchantments, + entity_nbt, + items::Items, + mobs::{ + Mob, MobType, MobTypes, + finalize::{self, Ctx, FinalizeLevel, Reason, SpawnData, SpawnRegistries}, + spawning::{LocalDifficulty, MOON_BRIGHTNESS}, + }, +}; +use chrono::Datelike; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::{LegacyRandom, RandomSource, XoroshiroRandom}, +}; +use horizon_world::{ + nbt::{Compound, Tag}, + worldgen::{generator::StructureMobs, structure::legacy::PieceRandom}, +}; +use std::{ + collections::{HashMap, HashSet}, + path::PathBuf, + sync::{ + Arc, OnceLock, + atomic::{AtomicI64, AtomicU8, Ordering}, + }, +}; + +struct Data { + types: HashMap>, + biome_tags: HashMap>, + registries: SpawnRegistries, + enchantments: Enchantments, + items: Items, + camel_husk: (f32, f32), +} +fn load(root: &std::path::Path) -> Option { + let types = MobTypes::load(root).ok()?.types; + let camel = types.get("minecraft:camel_husk")?; + let camel_husk = (camel.width as f32, camel.height as f32); + Some(Data { + types: types.into_iter().map(|(k, t)| (k, Arc::new(t))).collect(), + biome_tags: crate::items::load_tags(root, "worldgen/biome").unwrap_or_default(), + registries: SpawnRegistries::load(root), + enchantments: Enchantments::load(root), + items: Items::tags_only(root).ok()?, + camel_husk, + }) +} + +pub struct StructureMobFinalizer { + root: PathBuf, + dimension: String, + data: OnceLock>, + /// The level's difficulty (0 peaceful to 3 hard) and overworld clock. + difficulty: AtomicU8, + day_time: AtomicI64, +} +impl StructureMobFinalizer { + pub fn new(root: PathBuf, dimension: &str) -> Self { + Self { + root, + dimension: dimension.to_owned(), + data: OnceLock::new(), + difficulty: AtomicU8::new(2), + day_time: AtomicI64::new(0), + } + } + pub fn set_conditions(&self, difficulty: u8, day_time: i64) { + self.difficulty.store(difficulty, Ordering::Relaxed); + self.day_time.store(day_time, Ordering::Relaxed); + } +} + +struct Level<'a> { + data: &'a Data, + biome: &'a str, + structures: &'a [String], + difficulty: u8, + day_time: i64, + next_id: u32, +} +impl FinalizeLevel for Level<'_> { + fn biome(&self, _: [i32; 3]) -> String { + self.biome.to_owned() + } + fn biome_tag(&self, tag: &str, _: [i32; 3]) -> bool { + self.data + .biome_tags + .get(tag) + .is_some_and(|b| b.contains(self.biome)) + } + fn structures_with_piece_at(&self, _: [i32; 3]) -> Vec { + self.structures.to_vec() + } + fn moon_phase(&self, _: [i32; 3]) -> usize { + self.day_time.div_euclid(24000).rem_euclid(8) as usize + } + fn spawning_monsters(&self) -> bool { + self.difficulty != 0 + } + // No block collision: only a husk's camel asks, and no structure places husks. + fn no_collision(&self, _: Aabb) -> bool { + true + } + // WorldGenRegion holds no entities. + fn free_chicken(&self, _: Aabb) -> Option { + None + } + fn ride_chicken(&mut self, _: u32, _: u32) {} + fn game_time(&self) -> i64 { + self.day_time + } + fn halloween(&self) -> bool { + let today = chrono::Local::now(); + (today.month(), today.day()) == (10, 31) + } + fn create(&mut self, kind: &str, _: Reason) -> Option { + if self.difficulty == 0 && !finalize::allowed_in_peaceful(kind) { + return None; + } + let t = self.data.types.get(kind)?.clone(); + self.next_id += 1; + Some(Mob::new(self.next_id, t, Vec3::ZERO, 0.0)) + } +} + +fn run( + level: &mut Level<'_>, + random: &mut R, + difficulty: LocalDifficulty, + data: &SpawnData<'_>, + m: &mut Mob, +) -> Vec { + let mut cx = Ctx { + level, + random, + difficulty, + data, + created: Vec::new(), + }; + cx.finalize(m, Reason::Structure, None); + cx.created +} + +/// The saved compound of mob `i` with the mobs riding it under `Passengers`. +fn tree(mobs: &[(Mob, Option)], i: usize, dimension: &str) -> Compound { + let (m, raw) = &mobs[i]; + let Tag::Compound(mut c) = entity_nbt::mob_to_nbt(m, [0; 4], raw.as_ref()) else { + return Compound::new(); + }; + c.remove(&"UUID".into()); + entity_nbt::put_brain(&mut c, m, dimension); + let riders: Vec = (0..mobs.len()) + .filter(|&j| mobs[j].0.extra.mount == Some(m.id)) + .map(|j| Tag::Compound(tree(mobs, j, dimension))) + .collect(); + if !riders.is_empty() { + c.insert("Passengers".into(), Tag::List(riders)); + } + c +} + +impl StructureMobs for StructureMobFinalizer { + fn finalize( + &self, + nbt: &mut Compound, + biome: &str, + structures: &[String], + random: &mut dyn PieceRandom, + ) -> bool { + let Some(data) = self.data.get_or_init(|| { + let data = load(&self.root); + if data.is_none() { + log::error!("Horizon: no mob data, structure mobs are finalized when loaded"); + } + data + }) else { + return false; + }; + let mut raw = Tag::Compound(nbt.clone()); + if let Tag::Compound(c) = &mut raw { + c.remove(&"horizon:finalize".into()); + } + let Some(mut m) = entity_nbt::mob_from_nbt(&raw, &data.types, 1) else { + // Not a mob: vanilla finalizes only Mob instances. + return true; + }; + let base = self.difficulty.load(Ordering::Relaxed); + let day_time = self.day_time.load(Ordering::Relaxed); + let mut level = Level { + data, + biome, + structures, + difficulty: base, + day_time, + next_id: 1, + }; + let moon = MOON_BRIGHTNESS[level.moon_phase([0; 3])]; + // WorldGenRegion.getCurrentDifficultyAt: no inhabited time. + let difficulty = LocalDifficulty::new(base, day_time, 0, moon); + let spawn = SpawnData { + registries: &data.registries, + enchantments: &data.enchantments, + items: &data.items, + camel_husk_size: data.camel_husk, + }; + let any = random.as_any(); + let created = if let Some(r) = any.downcast_mut::() { + run(&mut level, r, difficulty, &spawn, &mut m) + } else if let Some(r) = any.downcast_mut::() { + run(&mut level, r, difficulty, &spawn, &mut m) + } else { + log::error!("Horizon: unknown region random, structure mobs are finalized when loaded"); + return false; + }; + let mut mobs = vec![(m, Some(raw))]; + mobs.extend(created.into_iter().map(|c| (c, None))); + let root = mobs + .iter() + .position(|(m, _)| m.extra.mount.is_none()) + .unwrap_or(0); + *nbt = tree(&mobs, root, &self.dimension); + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The bastion's crossbow piglin keeps its crossbow (STRUCTURE skips + /// createSpawnWeapon) and saves what Piglin.addAdditionalSaveData writes. + #[test] + fn bastion_crossbow_piglin_finalizes_as_structure() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES").map(PathBuf::from) else { + return; + }; + let file = root.join("worldgen/structure/minecraft/bastion/mobs/crossbow_piglin.nbt"); + let mut bytes = Vec::new(); + std::io::Read::read_to_end( + &mut flate2::read::GzDecoder::new(std::fs::File::open(file).unwrap()), + &mut bytes, + ) + .unwrap(); + let limits = horizon_world::nbt::Limits::templates(); + let template = horizon_world::nbt::read_named(&bytes, limits) + .unwrap() + .0 + .tag; + let Some(Tag::List(entities)) = template.get("entities") else { + panic!("no entities"); + }; + let Some(Tag::Compound(mut nbt)) = entities[0].get("nbt").cloned() else { + panic!("no nbt"); + }; + nbt.remove(&"UUID".into()); + let hook = StructureMobFinalizer::new(root, "minecraft:the_nether"); + let mut random = LegacyRandom::new(12345); + hook.finalize(&mut nbt, "minecraft:nether_wastes", &[], &mut random); + let keys: Vec = { + let mut k: Vec = nbt.keys().map(|k| k.to_string_lossy()).collect(); + k.sort(); + k + }; + assert_eq!( + keys, + [ + "AbsorptionAmount", + "Air", + "Brain", + "CanPickUpLoot", + "CannotHunt", + "DeathTime", + "FallFlying", + "Fire", + "Health", + "HurtTime", + "Inventory", + "Invulnerable", + "IsBaby", + "IsImmuneToZombification", + "LeftHanded", + "Motion", + "OnGround", + "PersistenceRequired", + "PortalCooldown", + "Pos", + "Rotation", + "TimeInOverworld", + "attributes", + "current_impulse_context_reset_grace_time", + "equipment", + "fall_distance", + "id", + ] + ); + let tag = Tag::Compound(nbt); + let held = tag.get("equipment").and_then(|e| e.get("mainhand")); + assert!( + matches!(held.and_then(|h| h.get("id")), Some(Tag::String(s)) if s.to_string_lossy() == "minecraft:crossbow") + ); + let hunted = tag + .get("Brain") + .and_then(|b| b.get("memories")) + .and_then(|m| m.get("minecraft:hunted_recently")); + assert!(matches!( + hunted.and_then(|h| h.get("ttl")), + Some(Tag::Long(600..=2400)) + )); + let Some(Tag::List(attributes)) = tag.get("attributes") else { + panic!("no attributes"); + }; + assert!(attributes.iter().any(|a| { + matches!(a.get("id"), Some(Tag::String(s)) if s.to_string_lossy() == "minecraft:follow_range") + && matches!(a.get("modifiers"), Some(Tag::List(m)) if m.len() == 1) + })); + } + + fn id(t: Option<&Tag>) -> String { + match t.and_then(|t| t.get("id")) { + Some(Tag::String(s)) => s.to_string_lossy().trim_start_matches("minecraft:").into(), + _ => "-".into(), + } + } + /// What a vanilla world saves of a structure mob that finalizeSpawn decides. + fn describe(mob: &Tag) -> String { + let eq = mob.get("equipment"); + let gear: Vec = ["mainhand", "head", "chest", "legs", "feet"] + .iter() + .map(|slot| id(eq.and_then(|e| e.get(slot)))) + .collect(); + let ttl = match mob + .get("Brain") + .and_then(|b| b.get("memories")) + .and_then(|m| m.get("minecraft:hunted_recently")) + .and_then(|h| h.get("ttl")) + { + Some(Tag::Long(t)) => t.to_string(), + _ => "-".into(), + }; + let bonus = crate::entity_nbt::spawn_bonus(mob).unwrap_or(f64::NAN); + let flag = |k: &str| matches!(mob.get(k), Some(Tag::Byte(1))); + let riders = match mob.get("Passengers") { + Some(Tag::List(p)) => format!( + " [{}]", + p.iter().map(describe).collect::>().join("; ") + ), + _ => String::new(), + }; + format!( + "{} {} ttl={ttl} bonus={bonus:.6} left={} baby={}{riders}", + id(Some(mob)), + gear.join(","), + flag("LeftHanded"), + flag("IsBaby") || matches!(mob.get("Age"), Some(Tag::Int(a)) if *a < 0), + ) + } + /// The described entities of chunk (x, z) after decorating the 3x3 around it. + fn chunk_mobs( + root: &std::path::Path, + seed: i64, + dimension: &str, + x: i32, + z: i32, + ) -> Vec { + use crate::streaming::{ChunkGenerator, Proto}; + let assets = crate::assets::Assets::load(root).unwrap(); + let biomes = crate::biome::Biomes::load(root).unwrap(); + let terrain = super::super::VanillaTerrain::for_dimension( + &root.join("worldgen"), + assets.registry, + &biomes, + seed, + dimension, + ) + .unwrap(); + let mut worker = terrain.worker(); + let mut region: [Proto; 9] = std::array::from_fn(|i| { + terrain.proto(&mut worker, x + i as i32 % 3 - 1, z + i as i32 / 3 - 1) + }); + terrain.decorate(&mut worker, &mut region); + let center = std::mem::replace(&mut region[4], Box::new(())); + let mut got: Vec = terrain + .finish(center) + .entities + .iter() + .map(describe) + .collect(); + got.sort(); + got + } + /// Seed 12345's bastion at chunk (-21, 8): the mobs of chunk (-23, 8) as two + /// vanilla 26.3 runs saved them (weapons and armour, hunting memory, follow + /// range bonus, handedness), from the region random of that chunk. The + /// memories are as placed: vanilla saved them 13 brain ticks later. + #[test] + fn bastion_chunk_mobs_match_vanilla() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES").map(PathBuf::from) else { + return; + }; + let got = chunk_mobs(&root, 12345, "minecraft:the_nether", -23, 8); + let mut expected = [ + "piglin golden_sword,-,golden_chestplate,-,- ttl=1760 bonus=0.013784", + "piglin crossbow,-,-,-,- ttl=806 bonus=-0.011458", + "piglin golden_sword,-,-,-,- ttl=1315 bonus=-0.084585", + "piglin golden_sword,-,-,-,- ttl=1489 bonus=-0.038292", + "piglin_brute golden_axe,-,-,-,- ttl=- bonus=-0.020574", + "piglin crossbow,-,-,-,- ttl=1620 bonus=-0.079135", + "hoglin -,-,-,-,- ttl=- bonus=-0.012052", + "piglin golden_sword,-,-,-,- ttl=783 bonus=-0.077071", + "piglin crossbow,-,-,golden_leggings,- ttl=1431 bonus=0.007058", + ] + .map(|e| format!("{e} left=false baby=false")); + expected.sort(); + assert_eq!(got, expected); + } + + /// Seed 12345's ocean ruin at (53, 39, 424): Drowned.finalizeSpawn mounts the + /// trident drowned on a zombie nautilus, as vanilla saved chunk (3, 26). + #[test] + fn ocean_ruin_drowned_match_vanilla() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES").map(PathBuf::from) else { + return; + }; + let got = chunk_mobs(&root, 12345, "minecraft:overworld", 3, 26); + let d = |gear: &str, bonus: &str| { + format!("drowned {gear},-,-,-,- ttl=- bonus={bonus} left=false baby=false") + }; + let mut expected = vec![ + d("-", "0.001996"), + format!( + "zombie_nautilus -,-,-,-,- ttl=- bonus=-0.044983 left=false baby=false [{}]", + d("trident", "-0.045604") + ), + d("fishing_rod", "-0.059079"), + d("-", "0.021658"), + ]; + expected.sort(); + assert_eq!(got, expected); + } +} diff --git a/crates/horizon-command/Cargo.toml b/crates/horizon-command/Cargo.toml new file mode 100644 index 000000000..10191ed6f --- /dev/null +++ b/crates/horizon-command/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "horizon-command" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version = "1.90" +description = "Commands (Brigadier): the vanilla command tree, argument types, selectors, parsing, suggestions and the network form of the tree" + +[dependencies] +horizon-client-core = { path = "../horizon-client-core" } +horizon-protocol = { path = "../horizon-protocol" } +horizon-world = { path = "../horizon-world" } + +[lints] +workspace = true diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-command/src/args.rs similarity index 87% rename from crates/horizon-client/src/command/args.rs rename to crates/horizon-command/src/args.rs index ccced67a7..9d24d672f 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-command/src/args.rs @@ -1,192 +1,8 @@ //! Argument types (Brigadier's and Minecraft's `ArgumentType`s): parsing with //! the vanilla error messages and completion suggestions. use super::{CmdResult, CommandError, Context, Reader, SuggestionsBuilder}; -use std::collections::BTreeMap; -/// Registry contents and source state used to validate and complete arguments. -#[derive(Clone, Debug, Default)] -pub struct Registries { - /// Permission level of the command source. - pub permission: u8, - pub items: Vec, - pub item_tags: Vec, - /// Block id -> (property, allowed values). - pub blocks: BTreeMap)>>, - pub block_tags: Vec, - /// Entity types that `summon` can create. - pub summonable: Vec, - /// Every entity type (selector `type=`). - pub entity_types: Vec, - pub effects: Vec, - pub enchantments: Vec, - pub structures: Vec, - pub biomes: Vec, - pub dimensions: Vec, - pub clocks: Vec, - pub timelines: Vec, - pub time_markers: Vec, - pub advancements: Vec, - /// Game rule name -> integer-valued. - pub game_rules: Vec<(String, bool)>, - pub players: Vec, - /// Scoreboard objective names, team names and tracked score holders. - pub objectives: Vec, - pub teams: Vec, - pub tracked: Vec, - /// Loaded datapack functions (`ns:path`) and function tags (`ns:path`). - pub functions: Vec, - /// `/data ... storage` ids. - pub storages: Vec, - /// Boss bar ids and datapack predicate ids. - pub bossbars: Vec, - pub predicates: Vec, - pub item_modifiers: Vec, - pub schedules: Vec, - pub stopwatches: Vec, - pub recipes: Vec, - pub sounds: Vec, - pub damage_types: Vec, - pub attributes: Vec, - pub loot_tables: Vec, - pub templates: Vec, - pub random_sequences: Vec, - pub datapacks_enabled: Vec, - pub datapacks_disabled: Vec, - pub function_tags: Vec, - /// The block the source is looking at (relevant coordinates). - pub target_block: Option<[i32; 3]>, - /// Every registry's element and tag ids (`minecraft:item` -> ...), as - /// the server's registry access and reloadable registries hold them. - pub by_registry: BTreeMap, - /// Blocks whose default state has a block entity. - pub block_entities: std::collections::BTreeSet, - /// Block tag -> member blocks. - pub block_tag_members: BTreeMap>, - /// Data component types with a codec (not transient). - pub persistent_components: Vec, - /// Recipes `/recipe` can give (not special). - pub learnable_recipes: Vec, - /// Advancement id -> criterion names. - pub advancement_criteria: BTreeMap>, - /// World clock -> time markers shown in commands. - pub clock_time_markers: BTreeMap>, - /// Trigger objectives the source may use (`/trigger` suggestions). - pub trigger_objectives: Vec, - /// Objectives with the `trigger` criterion -> holder -> whether its score is locked. - pub trigger_scores: BTreeMap>, -} -/// The ids and tag ids of one registry. -#[derive(Clone, Debug, Default)] -pub struct RegistryIds { - pub ids: Vec, - pub tags: Vec, -} -const EMPTY: &[String] = &[]; -impl Registries { - /// Fill what the game did not build itself from vanilla's exported - /// registries (`command-registries.json`, written by - /// `VanillaCommandParseOracle registries`): built-in registries such as - /// mob effects, data component types and dialogs, block entities and tag - /// members. Registries that data packs reload stay with the game. - pub fn fill_from_export(&mut self, r: &serde_json::Value) { - fn strings(v: &serde_json::Value) -> Vec { - v.as_array() - .map(|a| { - a.iter() - .filter_map(|x| x.as_str().map(str::to_owned)) - .collect() - }) - .unwrap_or_default() - } - let fill = |field: &mut Vec, key: &str| { - if field.is_empty() { - *field = strings(&r[key]); - } - }; - fill(&mut self.effects, "effects"); - fill(&mut self.enchantments, "enchantments"); - fill(&mut self.attributes, "attributes"); - fill(&mut self.damage_types, "damage_types"); - fill(&mut self.templates, "templates"); - fill(&mut self.persistent_components, "persistent_components"); - fill(&mut self.learnable_recipes, "learnable_recipes"); - const RELOADED: [&str; 5] = [ - "minecraft:advancement", - "minecraft:recipe", - "minecraft:loot_table", - "minecraft:predicate", - "minecraft:item_modifier", - ]; - for (name, entry) in r["by_registry"].as_object().into_iter().flatten() { - if RELOADED.contains(&name.as_str()) || self.by_registry.contains_key(name) { - continue; - } - self.by_registry.insert( - name.clone(), - RegistryIds { - ids: strings(&entry["ids"]), - tags: strings(&entry["tags"]), - }, - ); - } - if self.block_entities.is_empty() { - self.block_entities = strings(&r["block_entities"]).into_iter().collect(); - } - if self.block_tag_members.is_empty() { - for (tag, members) in r["block_tag_members"].as_object().into_iter().flatten() { - self.block_tag_members.insert(tag.clone(), strings(members)); - } - } - if self.clock_time_markers.is_empty() { - for (clock, markers) in r["clock_time_markers"].as_object().into_iter().flatten() { - self.clock_time_markers - .insert(clock.clone(), strings(markers)); - } - } - if self.advancement_criteria.is_empty() { - for (id, criteria) in r["advancement_criteria"].as_object().into_iter().flatten() { - self.advancement_criteria - .insert(id.clone(), strings(criteria)); - } - } - } - /// The element ids of a registry (sorted). - pub fn ids(&self, registry: &str) -> &[String] { - if let Some(r) = self.by_registry.get(registry) { - return &r.ids; - } - match registry { - "minecraft:item" => &self.items, - "minecraft:entity_type" => &self.entity_types, - "minecraft:mob_effect" => &self.effects, - "minecraft:enchantment" => &self.enchantments, - "minecraft:worldgen/structure" => &self.structures, - "minecraft:worldgen/biome" => &self.biomes, - "minecraft:world_clock" => &self.clocks, - "minecraft:timeline" => &self.timelines, - "minecraft:attribute" => &self.attributes, - "minecraft:damage_type" => &self.damage_types, - "minecraft:sound_event" => &self.sounds, - "minecraft:predicate" => &self.predicates, - "minecraft:item_modifier" => &self.item_modifiers, - "minecraft:loot_table" => &self.loot_tables, - "minecraft:recipe" => &self.recipes, - "minecraft:advancement" => &self.advancements, - _ => EMPTY, - } - } - /// The tag ids of a registry (sorted). - pub fn tags(&self, registry: &str) -> &[String] { - if let Some(r) = self.by_registry.get(registry) { - return &r.tags; - } - match registry { - "minecraft:item" => &self.item_tags, - "minecraft:block" => &self.block_tags, - _ => EMPTY, - } - } -} +pub use horizon_client_core::registries::{Registries, RegistryIds}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Resource { @@ -637,22 +453,7 @@ pub fn read_identifier(reader: &mut Reader) -> CmdResult { } } } -/// Identifier.parse: `ns:path` or `path`, validated. -pub fn parse_identifier(raw: &str) -> Option { - let (ns, path) = match raw.split_once(':') { - Some(("", path)) => ("minecraft", path), - Some((ns, path)) => (ns, path), - None => ("minecraft", raw), - }; - let ns_ok = ns != ".." - && ns - .chars() - .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-')); - let path_ok = path.chars().all(|c| { - c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/') - }); - (ns_ok && path_ok).then(|| format!("{ns}:{path}")) -} +pub use horizon_client_core::identifier::parse_identifier; pub fn normalize(id: &str) -> String { match id.split_once(':') { Some(("", path)) => format!("minecraft:{path}"), @@ -1220,7 +1021,10 @@ impl ArgType { reader.cursor = start; return Err(CommandError::tr_at( "argument.float.low", - &[&crate::snbt::java_float(*min), &crate::snbt::java_float(v)], + &[ + &horizon_client_core::snbt::java_float(*min), + &horizon_client_core::snbt::java_float(v), + ], reader, )); } @@ -1228,7 +1032,10 @@ impl ArgType { reader.cursor = start; return Err(CommandError::tr_at( "argument.float.big", - &[&crate::snbt::java_float(*max), &crate::snbt::java_float(v)], + &[ + &horizon_client_core::snbt::java_float(*max), + &horizon_client_core::snbt::java_float(v), + ], reader, )); } @@ -1241,8 +1048,8 @@ impl ArgType { return Err(CommandError::tr_at( "argument.double.low", &[ - &crate::snbt::java_double(*min), - &crate::snbt::java_double(v), + &horizon_client_core::snbt::java_double(*min), + &horizon_client_core::snbt::java_double(v), ], reader, )); @@ -1252,8 +1059,8 @@ impl ArgType { return Err(CommandError::tr_at( "argument.double.big", &[ - &crate::snbt::java_double(*max), - &crate::snbt::java_double(v), + &horizon_client_core::snbt::java_double(*max), + &horizon_client_core::snbt::java_double(v), ], reader, )); @@ -1597,7 +1404,7 @@ impl ArgType { return Err(CommandError::tr_at(key, &[&m], reader)); } let text = &reader.string[start..reader.cursor]; - match crate::component::parse_snbt(text) { + match horizon_client_core::component::parse_snbt(text) { Ok((v, _)) => Arg::Str(v.to_string()), Err(_) => Arg::Str(text.to_owned()), } @@ -1645,7 +1452,7 @@ impl ArgType { } let id = &reader.string[start..reader.cursor]; // ObjectiveCriteria.byName: statistics resolve to their canonical name. - match crate::scoreboard::criteria_by_name(id, reg) { + match horizon_client_core::scoreboard::criteria_by_name(id, reg) { Ok(Some(canonical)) => Arg::Str(canonical), Ok(None) => { reader.cursor = start; @@ -1667,7 +1474,7 @@ impl ArgType { } ArgType::ScoreboardSlot => { let name = reader.read_unquoted_string(); - if !crate::scoreboard::display_slot_valid(name) { + if !horizon_client_core::scoreboard::display_slot_valid(name) { return Err(CommandError::tr_at( "argument.scoreboardDisplaySlot.invalid", &[&name], @@ -1695,7 +1502,7 @@ impl ArgType { } ArgType::TeamColor => { let name = reader.read_unquoted_string(); - if crate::scoreboard::team_color_rgb(name).is_none() { + if horizon_client_core::scoreboard::team_color_rgb(name).is_none() { return Err(CommandError::tr_at( "argument.color.invalid", &[&name], @@ -1743,7 +1550,7 @@ impl ArgType { let id = read_identifier(reader)?; let known = reg.ids("minecraft:particle_type"); let exists = if known.is_empty() { - crate::particles::ParticleType::from_name(&id).is_some() + horizon_client_core::particle_type::ParticleType::from_name(&id).is_some() } else { known.contains(&id) }; @@ -1931,15 +1738,16 @@ impl ArgType { } ArgType::Team => builder.suggest_matching(reg.teams.iter().map(String::as_str)), ArgType::Criteria => { - let mut ids: Vec = crate::scoreboard::CUSTOM_CRITERIA + let mut ids: Vec = horizon_client_core::scoreboard::CUSTOM_CRITERIA .iter() .map(|s| (*s).to_owned()) .collect(); - for c in crate::scoreboard::team_colors() { + for c in horizon_client_core::scoreboard::team_colors() { ids.push(format!("teamkill.{c}")); ids.push(format!("killedByTeam.{c}")); } - let stat = |ty: &str, key: &str| crate::scoreboard::stat_criteria(ty, key); + let stat = + |ty: &str, key: &str| horizon_client_core::scoreboard::stat_criteria(ty, key); ids.extend(reg.blocks.keys().map(|b| stat("mined", b))); for ty in ["crafted", "used", "broken", "picked_up", "dropped"] { ids.extend(reg.items.iter().map(|i| stat(ty, i))); @@ -1948,14 +1756,14 @@ impl ArgType { ids.extend(reg.entity_types.iter().map(|e| stat(ty, e))); } ids.extend( - crate::scoreboard::CUSTOM_STATS + horizon_client_core::scoreboard::CUSTOM_STATS .iter() .map(|c| stat("custom", &format!("minecraft:{c}"))), ); builder.suggest_matching(ids.iter().map(String::as_str)); } ArgType::ScoreboardSlot => { - let slots = crate::scoreboard::display_slots(); + let slots = horizon_client_core::scoreboard::display_slots(); builder.suggest_matching(slots.iter().map(String::as_str)); } ArgType::Operation => builder.suggest_matching(OPERATIONS), @@ -1963,7 +1771,7 @@ impl ArgType { ArgType::Particle => { let known = reg.ids("minecraft:particle_type"); if known.is_empty() { - let names: Vec = crate::particles::ParticleType::ALL + let names: Vec = horizon_client_core::particle_type::ParticleType::ALL .iter() .map(|t| format!("minecraft:{}", t.name())) .collect(); @@ -1999,7 +1807,9 @@ impl ArgType { suggest_resources(builder, reg.ids("minecraft:slot_source"), ""); } ArgType::ResourceOrId(registry) => suggest_resources(builder, reg.ids(registry), ""), - ArgType::TeamColor => builder.suggest_matching(crate::scoreboard::team_colors()), + ArgType::TeamColor => { + builder.suggest_matching(horizon_client_core::scoreboard::team_colors()) + } ArgType::Anchor => builder.suggest_matching(["eyes", "feet"]), ArgType::Component | ArgType::Style | ArgType::NbtTag => super::snbt::suggest(builder), ArgType::Swizzle | ArgType::Message | ArgType::Nbt => {} diff --git a/crates/horizon-client/src/command/block.rs b/crates/horizon-command/src/block.rs similarity index 100% rename from crates/horizon-client/src/command/block.rs rename to crates/horizon-command/src/block.rs diff --git a/crates/horizon-client/src/command/codec.rs b/crates/horizon-command/src/codec.rs similarity index 99% rename from crates/horizon-client/src/command/codec.rs rename to crates/horizon-command/src/codec.rs index 7c4d26682..40f5c1ce0 100644 --- a/crates/horizon-client/src/command/codec.rs +++ b/crates/horizon-command/src/codec.rs @@ -6,7 +6,7 @@ use super::{CmdResult, CommandError, Reader}; use horizon_world::nbt::{Compound, JavaString, Tag}; pub fn snbt(t: &Tag) -> String { - crate::snbt::to_snbt(t) + horizon_client_core::snbt::to_snbt(t) } pub fn not_map(t: &Tag) -> String { format!("Not a map: {}", snbt(t)) diff --git a/crates/horizon-client/src/command/component.rs b/crates/horizon-command/src/component.rs similarity index 98% rename from crates/horizon-client/src/command/component.rs rename to crates/horizon-command/src/component.rs index 15a8fa6a0..2933afeca 100644 --- a/crates/horizon-client/src/command/component.rs +++ b/crates/horizon-command/src/component.rs @@ -164,7 +164,7 @@ fn color(t: &Tag) -> R { _ => partial(format!("Invalid color value: {s}")), }; } - if crate::text::named_color(&s).is_some() { + if horizon_client_core::text::named_color(&s).is_some() { Ok(()) } else { partial(format!("Invalid color name: {s}")) @@ -278,7 +278,7 @@ fn content(kind: &str, map: &Compound) -> bool { "nbt" => { let path_ok = get(map, "nbt") .and_then(string_of) - .is_some_and(|p| crate::nbt_path::NbtPath::parse(&p).is_ok()); + .is_some_and(|p| horizon_client_core::nbt_path::NbtPath::parse(&p).is_ok()); let source = if let Some(e) = get(map, "entity") { selector_string(e) } else if let Some(b) = get(map, "block") { diff --git a/crates/horizon-client/src/command/item.rs b/crates/horizon-command/src/item.rs similarity index 99% rename from crates/horizon-client/src/command/item.rs rename to crates/horizon-command/src/item.rs index f2abc91ef..da9c4b8b0 100644 --- a/crates/horizon-client/src/command/item.rs +++ b/crates/horizon-command/src/item.rs @@ -72,9 +72,9 @@ pub fn decode_component(id: &str, t: &Tag) -> Result<(), String> { } else { format!("minecraft:{id}") }; - let known = crate::block_entity_nbt::TYPES + let known = horizon_client_core::block_entity_nbt::TYPES .iter() - .chain(&crate::block_entity_nbt::NEWEST) + .chain(&horizon_client_core::block_entity_nbt::NEWEST) .any(|k| *k == id); if known { Ok(()) diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-command/src/lib.rs similarity index 99% rename from crates/horizon-client/src/command/mod.rs rename to crates/horizon-command/src/lib.rs index a61c8c08d..838c8de87 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-command/src/lib.rs @@ -3,6 +3,7 @@ //! relevant child and keeps the best result, completion suggestions, smart //! usage text and the vanilla error messages. Argument types live in //! [`args`]; the vanilla command tree in [`vanilla`]. +#![forbid(unsafe_code)] pub mod args; pub mod block; pub mod codec; @@ -21,8 +22,8 @@ pub mod tree_world; pub mod vanilla; mod vanilla_order; -use crate::text::Text; pub use args::{Arg, ArgType, Registries}; +use horizon_client_core::text::Text; /// The command id of a mod's command (`Dispatcher::with_mod_commands`). pub const MOD_COMMAND: &str = "mod"; @@ -623,8 +624,10 @@ impl Suggests { for id in ®.summonable { if args::resource_matches(&contents, id) { let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id)); - let name = - crate::lang::get(&format!("entity.{ns}.{}", path.replace('/', "."))); + let name = horizon_client_core::lang::get(&format!( + "entity.{ns}.{}", + path.replace('/', ".") + )); builder.suggest_tooltip(id.clone(), name); } } diff --git a/crates/horizon-client/src/command/network.rs b/crates/horizon-command/src/network.rs similarity index 100% rename from crates/horizon-client/src/command/network.rs rename to crates/horizon-command/src/network.rs diff --git a/crates/horizon-client/src/command/packrat.rs b/crates/horizon-command/src/packrat.rs similarity index 99% rename from crates/horizon-client/src/command/packrat.rs rename to crates/horizon-command/src/packrat.rs index 42f42d9f4..ebe9df09d 100644 --- a/crates/horizon-client/src/command/packrat.rs +++ b/crates/horizon-command/src/packrat.rs @@ -402,7 +402,7 @@ impl<'g, V: Value> State<'g, V> { Reason::Error(e) => e.clone(), }; } - CommandError::new(crate::text::Text::literal("Failed to parse")) + CommandError::new(horizon_client_core::text::Text::literal("Failed to parse")) } /// CachedParseState.parse: a named rule, memoised per position. pub fn parse(&mut self, rule: RuleId) -> Option { diff --git a/crates/horizon-client/src/command/selector.rs b/crates/horizon-command/src/selector.rs similarity index 99% rename from crates/horizon-client/src/command/selector.rs rename to crates/horizon-command/src/selector.rs index eb4e637a4..777124f60 100644 --- a/crates/horizon-client/src/command/selector.rs +++ b/crates/horizon-command/src/selector.rs @@ -687,7 +687,7 @@ impl<'r, 'a> SelectorParser<'r, 'a> { fn fill_selectors(builder: &mut SuggestionsBuilder) { for (s, tip) in SELECTOR_KINDS { - builder.suggest_tooltip(s, crate::lang::get(tip)); + builder.suggest_tooltip(s, horizon_client_core::lang::get(tip)); } } @@ -785,7 +785,9 @@ impl<'r, 'a> SelectorParser<'r, 'a> { if self.can_use(o) && o.starts_with(&lower) { b.suggest_tooltip( format!("{o}="), - crate::lang::get(&format!("argument.entity.options.{o}.description")), + horizon_client_core::lang::get(&format!( + "argument.entity.options.{o}.description" + )), ); } } diff --git a/crates/horizon-client/src/command/snbt.rs b/crates/horizon-command/src/snbt.rs similarity index 100% rename from crates/horizon-client/src/command/snbt.rs rename to crates/horizon-command/src/snbt.rs diff --git a/crates/horizon-client/src/command/tests.rs b/crates/horizon-command/src/tests.rs similarity index 100% rename from crates/horizon-client/src/command/tests.rs rename to crates/horizon-command/src/tests.rs diff --git a/crates/horizon-client/src/command/tree_data.rs b/crates/horizon-command/src/tree_data.rs similarity index 100% rename from crates/horizon-client/src/command/tree_data.rs rename to crates/horizon-command/src/tree_data.rs diff --git a/crates/horizon-client/src/command/tree_execute.rs b/crates/horizon-command/src/tree_execute.rs similarity index 100% rename from crates/horizon-client/src/command/tree_execute.rs rename to crates/horizon-command/src/tree_execute.rs diff --git a/crates/horizon-client/src/command/tree_extra.rs b/crates/horizon-command/src/tree_extra.rs similarity index 100% rename from crates/horizon-client/src/command/tree_extra.rs rename to crates/horizon-command/src/tree_extra.rs diff --git a/crates/horizon-client/src/command/tree_misc.rs b/crates/horizon-command/src/tree_misc.rs similarity index 99% rename from crates/horizon-client/src/command/tree_misc.rs rename to crates/horizon-command/src/tree_misc.rs index a66fd5f37..1bcd880bb 100644 --- a/crates/horizon-client/src/command/tree_misc.rs +++ b/crates/horizon-command/src/tree_misc.rs @@ -230,12 +230,12 @@ fn bossbar(d: &mut Dispatcher, root: usize) { let name = d.argument(name_l, "name", ArgType::Component); d.executes(name, "bossbar.set.name"); let color = d.literal(id, "color"); - for c in crate::bossbar::COLORS { + for c in horizon_client_core::bossbar::COLORS { let l = d.literal(color, c); d.executes(l, "bossbar.set.color"); } let style = d.literal(id, "style"); - for s in crate::bossbar::STYLES { + for s in horizon_client_core::bossbar::STYLES { let l = d.literal(style, s); d.executes(l, "bossbar.set.style"); } diff --git a/crates/horizon-client/src/command/tree_scoreboard.rs b/crates/horizon-command/src/tree_scoreboard.rs similarity index 100% rename from crates/horizon-client/src/command/tree_scoreboard.rs rename to crates/horizon-command/src/tree_scoreboard.rs diff --git a/crates/horizon-client/src/command/tree_world.rs b/crates/horizon-command/src/tree_world.rs similarity index 99% rename from crates/horizon-client/src/command/tree_world.rs rename to crates/horizon-command/src/tree_world.rs index 0bd2edd3b..86ebba0ca 100644 --- a/crates/horizon-client/src/command/tree_world.rs +++ b/crates/horizon-command/src/tree_world.rs @@ -7,7 +7,7 @@ use super::{ args::{ArgType, integer}, vanilla::{ENTITIES, ENTITY, GAMEMASTERS, PLAYERS}, }; -use crate::settings::SOUND_SOURCES; +use horizon_client_core::sound_source::SOUND_SOURCES; fn float(min: f32) -> ArgType { ArgType::Float { min, max: f32::MAX } diff --git a/crates/horizon-client/src/command/vanilla.rs b/crates/horizon-command/src/vanilla.rs similarity index 99% rename from crates/horizon-client/src/command/vanilla.rs rename to crates/horizon-command/src/vanilla.rs index 2ce892077..37ec1c3de 100644 --- a/crates/horizon-client/src/command/vanilla.rs +++ b/crates/horizon-command/src/vanilla.rs @@ -5,7 +5,7 @@ use super::{ Dispatcher, args::{ArgType, Resource, integer}, }; -use crate::gamerules::{RULES, Value}; +use horizon_client_core::gamerules::{RULES, Value}; /// Permission levels (Commands.LEVEL_*). pub const ALL: u8 = 0; diff --git a/crates/horizon-client/src/command/vanilla_order.rs b/crates/horizon-command/src/vanilla_order.rs similarity index 100% rename from crates/horizon-client/src/command/vanilla_order.rs rename to crates/horizon-command/src/vanilla_order.rs diff --git a/crates/horizon-mod-sdk/examples/beacons/Cargo.toml b/crates/horizon-mod-sdk/examples/beacons/Cargo.toml new file mode 100644 index 000000000..c001614e8 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/beacons/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "beacons" +version = "0.1.0" +edition.workspace = true +license.workspace = true +publish = false +description = "Example Horizon server mod: /beacon lights a pillar beside you, /ground says what you stand on" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +horizon-mod-sdk = { path = "../.." } + +[lints] +workspace = true diff --git a/crates/horizon-mod-sdk/examples/beacons/horizon-mod.toml b/crates/horizon-mod-sdk/examples/beacons/horizon-mod.toml new file mode 100644 index 000000000..5b58273c6 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/beacons/horizon-mod.toml @@ -0,0 +1,8 @@ +id = "beacons" +name = "Beacons" +version = "0.1.0" +description = "/beacon [height] lights a pillar of glowstone beside you; /ground [pos] says what you are standing on (or what is at pos), and in which biome." +authors = ["Horizon"] +api = "0.3" +side = "server" +capabilities = ["players", "world"] diff --git a/crates/horizon-mod-sdk/examples/beacons/src/lib.rs b/crates/horizon-mod-sdk/examples/beacons/src/lib.rs new file mode 100644 index 000000000..4a4de5cc1 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/beacons/src/lib.rs @@ -0,0 +1,103 @@ +//! Example Horizon server mod (`docs/mods.md`, "Server mods") with +//! capability `world` and typed commands: `/beacon [height]` lights a +//! pillar of glowstone two blocks east of the player, `/ground [pos]` reads +//! the block under their feet (or at `pos`) and its biome. +use horizon_mod_sdk::server::{ + Args, Argument, BlockChange, Player, Registration, ServerMod, players, world, +}; + +/// How tall `/beacon` builds when no height is given. +const HEIGHT: i32 = 4; + +struct Beacons; + +/// The block the player stands in: their feet, floored. +fn feet(player: &Player) -> (i32, i32, i32) { + ( + player.x.floor() as i32, + player.y.floor() as i32, + player.z.floor() as i32, + ) +} + +/// The pillar beside `player`: `height` blocks of glowstone, from their feet up. +fn pillar(player: &Player, height: i32) -> Vec { + let (x, y, z) = feet(player); + (0..height) + .map(|dy| BlockChange { + x: x + 2, + y: y + dy, + z, + state: "minecraft:glowstone".into(), + }) + .collect() +} + +impl ServerMod for Beacons { + fn init() -> Result<(Self, Registration), String> { + Ok(( + Beacons, + Registration::new() + .command_with( + "beacon", + [Argument::integer("height", Some(1), Some(64)).optional()], + ) + .command_with("ground", [Argument::block_pos("pos").optional()]), + )) + } + + fn command( + &mut self, + player: &Player, + name: &str, + args: &Args, + ) -> Result, String> { + let (x, y, z) = feet(player); + if name == "beacon" { + let height = args.integer("height").unwrap_or(HEIGHT); + world::set_blocks(&player.dimension, &pillar(player, height))?; + players::broadcast(&format!( + "{} lit a beacon at {} {y} {z}", + player.name, + x + 2 + )); + return Ok(None); + } + let (bx, by, bz) = match args.block_pos("pos") { + Some(p) => (p.x, p.y, p.z), + None => (x, y - 1, z), + }; + let block = + world::get_block(&player.dimension, bx, by, bz).ok_or("That block isn't loaded")?; + let biome = world::get_biome(&player.dimension, bx, by, bz).unwrap_or_default(); + if args.block_pos("pos").is_some() { + return Ok(Some(format!("{bx} {by} {bz} is {block} in {biome}"))); + } + Ok(Some(format!("You are standing on {block} in {biome}"))) + } +} + +horizon_mod_sdk::export_server_mod!(Beacons); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_pillar_stands_two_blocks_east() { + let p = Player { + id: String::new(), + name: "Alex".into(), + x: -0.5, + y: 64.0, + z: 3.2, + dimension: "minecraft:overworld".into(), + game_mode: horizon_mod_sdk::server::GameMode::Survival, + health: 20.0, + }; + let blocks = pillar(&p, HEIGHT); + assert_eq!(blocks.len(), HEIGHT as usize); + assert_eq!((blocks[0].x, blocks[0].y, blocks[0].z), (1, 64, 3)); + assert_eq!(blocks[3].y, 67); + } +} diff --git a/crates/horizon-mod-sdk/examples/beacons/tests/beacons.toml b/crates/horizon-mod-sdk/examples/beacons/tests/beacons.toml new file mode 100644 index 000000000..bab4839f3 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/beacons/tests/beacons.toml @@ -0,0 +1,39 @@ +# /ground [pos] reads the block under the player (or at pos) and the biome; /beacon [height] sets glowstone two to the east. + +[[step]] +join = "Alex" +blocks = [{ x = 0, y = 63, z = 0, state = "minecraft:grass_block[snowy=false]" }] +command = "ground" +expect.feedback = "You are standing on minecraft:grass_block[snowy=false] in minecraft:plains" + +[[step]] +command = "beacon" +expect.broadcast = ["Alex lit a beacon at 2 64 0"] +expect.blocks = [ + { x = 2, y = 64, z = 0, state = "minecraft:glowstone" }, + { x = 2, y = 67, z = 0, state = "minecraft:glowstone" }, + { x = 2, y = 68, z = 0, state = "minecraft:air" }, +] + +# Anywhere the script set nothing is air. +[[step]] +player = { x = 10.5, z = 10.5 } +command = "ground" +expect.feedback = "You are standing on minecraft:air in minecraft:plains" + +# Typed arguments: a height, a position relative to the player. +[[step]] +player = { x = 5.5, y = 64.0, z = 5.5 } +command = "beacon 2" +expect.blocks = [ + { x = 7, y = 65, z = 5, state = "minecraft:glowstone" }, + { x = 7, y = 66, z = 5, state = "minecraft:air" }, +] + +[[step]] +command = "beacon 65" +expect.error = "Integer must not be more than 64, found 65" + +[[step]] +command = "ground ~2 ~1 ~" +expect.feedback = "7 65 5 is minecraft:glowstone in minecraft:plains" diff --git a/crates/horizon-mod-sdk/examples/welcome/src/lib.rs b/crates/horizon-mod-sdk/examples/welcome/src/lib.rs index c45712c88..e5a5ef13e 100644 --- a/crates/horizon-mod-sdk/examples/welcome/src/lib.rs +++ b/crates/horizon-mod-sdk/examples/welcome/src/lib.rs @@ -1,9 +1,10 @@ //! Example Horizon server mod (`docs/mods.md`, "Server mods"): greets each //! player who joins, announces a newcomer to everyone (the players it has //! seen are kept in `storage`), `/online` lists who is on and where, and -//! `/mined` counts the blocks the player broke since the server started. +//! `/mined [player]` counts the blocks a player broke since the server +//! started (typed arguments: the chat box completes the player's name). use horizon_mod_sdk::{ - server::{BlockPos, Player, Registration, ServerMod, players}, + server::{Args, Argument, BlockPos, Player, Registration, ServerMod, players}, storage, }; use std::collections::HashMap; @@ -25,8 +26,8 @@ impl ServerMod for Welcome { }) .unwrap_or_default(); let hooks = Registration::new() - .command("online") - .command("mined") + .command_with("online", []) + .command_with("mined", [Argument::player("player").optional()]) .on_joins() .on_blocks(); Ok(( @@ -55,7 +56,7 @@ impl ServerMod for Welcome { &mut self, player: &Player, name: &str, - _args: &str, + args: &Args, ) -> Result, String> { Ok(Some(match name { "online" => players::online() @@ -69,10 +70,16 @@ impl ServerMod for Welcome { }) .collect::>() .join(", "), - _ => { - let n = self.mined.get(&player.id).copied().unwrap_or(0); - format!("You broke {n} block(s)") - } + _ => match args.player("player") { + Some(other) if other.id != player.id => { + let n = self.mined.get(&other.id).copied().unwrap_or(0); + format!("{} broke {n} block(s)", other.name) + } + _ => { + let n = self.mined.get(&player.id).copied().unwrap_or(0); + format!("You broke {n} block(s)") + } + }, })) } diff --git a/crates/horizon-mod-sdk/examples/welcome/tests/commands.toml b/crates/horizon-mod-sdk/examples/welcome/tests/commands.toml index 5f0018346..a55bd421d 100644 --- a/crates/horizon-mod-sdk/examples/welcome/tests/commands.toml +++ b/crates/horizon-mod-sdk/examples/welcome/tests/commands.toml @@ -1,4 +1,4 @@ -# /online lists the players and their dimension; /mined counts the acting player's blocks. +# /online lists the players and their dimension; /mined [player] counts a player's blocks. [[step]] join = "Alex" @@ -29,3 +29,18 @@ expect.feedback = "You broke 2 block(s)" as = "Steve" command = "mined" expect.feedback = "You broke 0 block(s)" + +[[step]] +as = "Steve" +command = "mined alex" +expect.feedback = "Alex broke 2 block(s)" + +# The server parses the arguments before the mod: vanilla's errors. +[[step]] +as = "Steve" +command = "mined Herobrine" +expect.error = "No player was found" + +[[step]] +command = "online now" +expect.error = "Incorrect argument for command" diff --git a/crates/horizon-mod-sdk/src/lib.rs b/crates/horizon-mod-sdk/src/lib.rs index 679fdc7b8..1e7120091 100644 --- a/crates/horizon-mod-sdk/src/lib.rs +++ b/crates/horizon-mod-sdk/src/lib.rs @@ -39,7 +39,9 @@ wit_bindgen::generate!({ pub use exports::horizon::mods::events::{Guest as __Guest, Registration}; pub use exports::horizon::mods::ui_events::Guest as __UiEventsGuest; -pub use horizon::mods::{chat, command, game, hud, input, log, render, storage, ui}; +pub use horizon::mods::{ + browser, chat, command, game, hud, input, log, recipes, render, storage, ui, +}; /// The game's calls into a mod. Only the hooks [`Registration`] asks for /// are called; the others may stay as their defaults. @@ -192,8 +194,12 @@ pub mod server { }, }); - pub use exports::horizon::mods::server_events::{BlockPos, Guest as __Guest, Registration}; + pub use exports::horizon::mods::server_events::{ + Argument, ArgumentKind, ArgumentValue, BlockPos, Guest as __Guest, Registration, + ServerCommand, + }; pub use horizon::mods::players::{self, GameMode, Player}; + pub use horizon::mods::world::{self, BlockChange}; /// The server's calls into a mod. Only the hooks [`Registration`] asks /// for are called; the others may stay as their defaults. @@ -208,13 +214,14 @@ pub mod server { fn player_left(&mut self, _player: &Player) {} /// A chat message a player sent, when [`Registration::chat`] is set. fn chat(&mut self, _player: &Player, _text: &str) {} - /// `/name args` typed by `player`. `Ok(Some(text))` is their - /// feedback, `Err(text)` their error in red. + /// `/name args` typed by `player`, parsed as the command's + /// arguments say ([`Registration::command_with`]). `Ok(Some(text))` + /// is their feedback, `Err(text)` their error in red. fn command( &mut self, _player: &Player, _name: &str, - _args: &str, + _args: &Args, ) -> Result, String> { Err("This command does nothing".into()) } @@ -234,9 +241,23 @@ pub mod server { blocks: false, } } - /// Adds `/name`. - pub fn command(mut self, name: &str) -> Self { - self.commands.push(name.into()); + /// Adds `/name`, taking free text ([`Args::text`]): one optional + /// `text` argument named `args`. + pub fn command(self, name: &str) -> Self { + self.command_with(name, [Argument::text("args").optional()]) + } + /// Adds `/name` with typed arguments (none: nothing after the name): + /// players' chat boxes complete and check them, and the server + /// parses them into [`Args`]. + pub fn command_with( + mut self, + name: &str, + arguments: impl IntoIterator, + ) -> Self { + self.commands.push(ServerCommand { + name: name.into(), + arguments: arguments.into_iter().collect(), + }); self } pub fn on_tick(mut self) -> Self { @@ -261,6 +282,105 @@ pub mod server { Self::new() } } + + impl Argument { + fn of(name: &str, kind: ArgumentKind) -> Self { + Self { + name: name.into(), + kind, + optional: false, + } + } + /// One word: letters, digits and `_ - . +`. + pub fn word(name: &str) -> Self { + Self::of(name, ArgumentKind::Word) + } + /// The rest of the line: only last. + pub fn text(name: &str) -> Self { + Self::of(name, ArgumentKind::Text) + } + /// A whole number, at least `min` and at most `max` when given. + pub fn integer(name: &str, min: Option, max: Option) -> Self { + Self::of(name, ArgumentKind::Integer((min, max))) + } + pub fn number(name: &str) -> Self { + Self::of(name, ArgumentKind::Number) + } + pub fn boolean(name: &str) -> Self { + Self::of(name, ArgumentKind::Boolean) + } + /// One online player: a name, `@s` or `@p`. + pub fn player(name: &str) -> Self { + Self::of(name, ArgumentKind::Player) + } + /// `x y z`, each one also `~` or `~n`. + pub fn block_pos(name: &str) -> Self { + Self::of(name, ArgumentKind::BlockPos) + } + /// May be left out; optional arguments come after the required ones. + pub fn optional(mut self) -> Self { + self.optional = true; + self + } + } + + /// A command's arguments: the line as typed, and the values the server + /// parsed from it, by argument name. + #[derive(Clone, Debug, Default)] + pub struct Args { + text: String, + values: Vec<(String, ArgumentValue)>, + } + impl Args { + pub fn new(text: String, values: Vec<(String, ArgumentValue)>) -> Self { + Self { text, values } + } + /// The line after the command's name, as typed. + pub fn text(&self) -> &str { + &self.text + } + /// The value of argument `name`; `None` when it was left out. + pub fn get(&self, name: &str) -> Option<&ArgumentValue> { + self.values.iter().find(|(n, _)| n == name).map(|(_, v)| v) + } + pub fn integer(&self, name: &str) -> Option { + match self.get(name)? { + ArgumentValue::Integer(n) => Some(*n), + _ => None, + } + } + pub fn number(&self, name: &str) -> Option { + match self.get(name)? { + ArgumentValue::Number(n) => Some(*n), + _ => None, + } + } + /// A `word` or `text` argument. + pub fn string(&self, name: &str) -> Option<&str> { + match self.get(name)? { + ArgumentValue::Word(s) | ArgumentValue::Text(s) => Some(s), + _ => None, + } + } + pub fn boolean(&self, name: &str) -> Option { + match self.get(name)? { + ArgumentValue::Boolean(b) => Some(*b), + _ => None, + } + } + pub fn player(&self, name: &str) -> Option<&Player> { + match self.get(name)? { + ArgumentValue::Player(p) => Some(p), + _ => None, + } + } + pub fn block_pos(&self, name: &str) -> Option { + match self.get(name)? { + ArgumentValue::BlockPos(p) => Some(*p), + _ => None, + } + } + } } /// Exports a [`ServerMod`](server::ServerMod) as the component's @@ -270,7 +390,7 @@ macro_rules! export_server_mod { ($t:ty) => { const _: () = { use ::std::cell::RefCell; - use $crate::server::{BlockPos, Player, Registration, ServerMod}; + use $crate::server::{Args, ArgumentValue, BlockPos, Player, Registration, ServerMod}; ::std::thread_local! { static STATE: RefCell> = const { RefCell::new(None) }; } @@ -304,8 +424,10 @@ macro_rules! export_server_mod { player: Player, name: String, args: String, + values: Vec<(String, ArgumentValue)>, ) -> Result, String> { let mut out = Err("The mod is not running".to_string()); + let args = Args::new(args, values); with(|m| out = m.command(&player, &name, &args)); out } diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index d9bb9f5c2..e75bb3cac 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -439,6 +439,181 @@ interface events { chat: func(text: string); } +/// Capability `recipes` (experimental): the recipes and items the game +/// knows, for recipe viewers. In single player and on Horizon's servers +/// they are the world's; on any other server they are vanilla 26.3's (a +/// client is sent no others), while `known` follows that server's book. +interface recipes { + /// An item of `items`, by its index there, with a count and the + /// components it has beyond the item's own, in vanilla's item syntax + /// (`[potion_contents={potion:"minecraft:swiftness"}]`), or "". + record stack { + item: u32, + count: u32, + components: string, + } + /// The station a recipe is made at. + enum kind { + crafting-shaped, + crafting-shapeless, + smelting, + blasting, + smoking, + campfire, + stonecutting, + smithing, + brewing, + } + record recipe { + /// `minecraft:oak_planks`. + id: string, + kind: kind, + /// The recipe book's tab (`crafting_building_blocks`, + /// `furnace_food`), or "". + category: string, + /// Recipes the book shows on one button share a group, or "". + group: string, + /// A shaped recipe's grid: `slots` holds its cells row by row. + /// 0 for the other kinds. + width: u32, + height: u32, + /// Each slot's stacks, any one of which fits; an empty list is an + /// empty cell. Cooking and stonecutting: the input. Smithing: the + /// template, the base, the addition. Brewing: the bottle, the + /// reagent. + slots: list>, + /// What it makes; several when that varies (a trim on any armour). + results: list, + /// Cooking: game ticks and experience; 0 for the other kinds. + cooking-time: u32, + experience: f32, + /// The recipe book's id for it (one per way the book shows it), as + /// `known` lists them; -1 for the kinds the book doesn't show + /// (campfire, stonecutting, smithing, brewing). + book-id: s32, + } + record item { + /// `minecraft:diamond`, `:`. + id: string, + /// In the player's language. + name: string, + /// Its item tags, without the `#`. + tags: list, + } + /// Every item, in the registry's order: `stack.item` indexes this list. + items: func() -> list; + /// Every recipe: the book's in its order, then campfire, stonecutting, + /// smithing and brewing. They don't change while a world is open. + all: func() -> list; + /// The `book-id`s of the recipes the player's recipe book holds now. + known: func() -> list; + /// Places a recipe in the open screen's grid as a click in the recipe + /// book does (`ServerboundPlaceRecipePacket`): the inventory's grid or + /// a crafting table. `all` places as many as the items allow, as with + /// Shift. Refused while no such screen is open, for a recipe the + /// player's book doesn't hold and for one that can't be placed; one + /// missing items shows as a ghost in the grid, as in the book. + place: func(book-id: s32, all: bool) -> result<_, string>; + /// Creative mode only: gives the player the stack, as taking it from + /// the creative inventory does (`ServerboundSetCreativeModeSlot`): the + /// selected slot first, then the hotbar, then the inventory. The count + /// is cut to one stack of the item (64, 16 or 1). + give: func(stack: stack) -> result<_, string>; +} + +/// Capability `ui` (experimental): a recipe viewer's panel beside the +/// game's inventory and container screens (not the creative inventory), on +/// the right of the screen. The game draws it with its own widgets and +/// slots, pages it and keeps its search box; the mod says what it holds. +/// The first loaded mod with a panel shows. +interface browser { + /// An item to show: its id, a count (1 draws none) and its components + /// beyond the item's own, in vanilla's item syntax, or "". + record stack { + item: string, + count: u32, + components: string, + } + /// A click on an item of the panel, by its index in `set-items`'s list. + record click { + index: u32, + right: bool, + } + /// A key the mod registered (`input.register-key`) went down while the + /// pointer was on an item: a slot of the screen's, or the panel's. + record item-key { + key: string, + stack: stack, + } + /// A click on a slot of a recipe the panel shows (`set-recipes`). + record slot-click { + /// The recipe's index in `set-recipes`'s list and the slot's in + /// it; the results come after the slots. + recipe: u32, + slot: u32, + /// The stack the slot showed at that moment. + stack: stack, + right: bool, + } + variant event { + clicked(click), + /// The search box's text, each time the player changes it. + search(string), + key(item-key), + slot-clicked(slot-click), + /// The action button of the recipe at this index in + /// `set-recipes`'s list. + action(u32), + /// The player turned the recipes' page (`set-recipes`): the index + /// of the first recipe now shown. + page(u32), + /// The back button of `set-recipes`. + back, + /// The player picked the tab at this index of `set-recipes`' tabs. + tab(u32), + } + /// How the game lays out a recipe of `set-recipes`. + enum layout { + /// A crafting grid of `width` x `height` slots, an arrow and the + /// result. + grid, + /// One input over a flame, an arrow and the result (furnaces, + /// smokers, campfires). + cooking, + /// One input, an arrow and the result (the stonecutter). + single, + /// Template, base and addition, an arrow and the result. + smithing, + /// A potion and an ingredient, an arrow and the result. + brewing, + } + /// A recipe to show. Each slot, and the result, cycles through its + /// stacks, one a second; an empty slot shows nothing. + record recipe-view { + layout: layout, + /// The grid's size (`grid` only), at most 3 x 3. + width: u32, + height: u32, + slots: list>, + results: list, + /// A short line under the recipe (a cooking time), or "". + note: string, + /// The action button beside it: none, enabled, or shown greyed. + action: option, + } + /// The panel's items, at most 8192 (an empty list hides the panel). + set-items: func(items: list); + /// Shows these recipes in the panel instead of its items, as many as + /// fit a page, under `title` and a back button, with a row of `tabs` + /// (each an icon; `tab` is the selected one) between them; an empty + /// list of recipes shows the items again. At most 256 recipes and 16 + /// tabs. + set-recipes: func(title: string, tabs: list, tab: u32, recipes: list); + /// What the player did on the panel since the last poll, at most 256 + /// kept. + poll: func() -> list; +} + /// Capability `players`, server mods only (manifest `api = "0.3"`, /// experimental): the players on the server, and messages to them. interface players { @@ -472,16 +647,94 @@ interface players { broadcast: func(text: string); } +/// Capability `world`, server mods only (manifest `api = "0.3"`, +/// experimental): the blocks of the server's loaded chunks, and changes to +/// them through the server's own block updates. +interface %world { + record block-change { + x: s32, + y: s32, + z: s32, + /// `minecraft:oak_log[axis=y]`; properties left out take the block's + /// defaults, `minecraft:stone` alone is the default state. + state: string, + } + /// The block state at a position in a dimension (`minecraft:overworld`, + /// ...), as `minecraft:oak_log[axis=y]`, as of this call: none where the + /// server has no chunk loaded there. + get-block: func(dimension: string, x: s32, y: s32, z: s32) -> option; + /// The biome at a position (`minecraft:plains`, ...), as the server + /// stores it (one per 4 x 4 x 4 cell): none where no chunk is loaded. + get-biome: func(dimension: string, x: s32, y: s32, z: s32) -> option; + /// Sets blocks as `/setblock` does: the old block entity removed, + /// neighbours and shapes updated, light, and every player told. Every + /// state is checked now (an error queues nothing); the changes are made + /// in order after this call returns, before that dimension's next tick; + /// one in a chunk not loaded then is skipped. At most 4096 per call. + set-blocks: func(dimension: string, blocks: list) -> result<_, string>; +} + /// What the server calls in a server mod (manifest `api = "0.3"`, /// experimental). Only the hooks `init` asks for are ever called. The player /// in each event is as the server saw them when it happened. interface server-events { use players.{player}; + record block-pos { + x: s32, + y: s32, + z: s32, + } + /// What an argument of a command takes. The server sends each command + /// and its arguments to players' games, whose chat box completes and + /// colours them as vanilla's; the server parses them before the mod's + /// `command` hook gets their values. + variant argument-kind { + /// One word: letters, digits and `_ - . +`. + word, + /// The rest of the line, spaces included: only last. + text, + /// A whole number, within the bounds given. + integer(tuple, option>), + /// A number with or without decimals. + number, + /// `true` or `false`. + boolean, + /// One online player: a name, or `@s` or `@p` (whoever typed it, + /// as vanilla picks for a player). + player, + /// A block position: three whole numbers, each one also `~` or + /// `~n`, relative to whoever typed it. + block-pos, + } + record argument { + /// Shown in the chat box's hint (``) and the key of its value. + name: string, + kind: argument-kind, + /// Optional arguments come after every required one. + optional: bool, + } + record server-command { + /// Without the slash. A name vanilla already uses is refused + /// (vanilla's command runs). + name: string, + /// In order; none: the command takes nothing after its name. Free + /// text is one optional `text` argument. + arguments: list, + } + /// An argument's value, parsed as its kind says. + variant argument-value { + word(string), + text(string), + integer(s32), + number(f64), + boolean(bool), + player(player), + block-pos(block-pos), + } record registration { - /// Commands players may type, without the slash. A name vanilla - /// already uses is refused (vanilla's command runs). - commands: list, + /// Commands players may type. + commands: list, /// Call `tick` every server tick (20 per second). tick: bool, /// Call `player-joined` and `player-left`. @@ -491,11 +744,6 @@ interface server-events { /// Call `block-broken` and `block-placed`. blocks: bool, } - record block-pos { - x: s32, - y: s32, - z: s32, - } /// Once, after loading. An error keeps the mod off and is logged. init: func() -> result; /// Each server tick, with the server's tick counter. @@ -507,8 +755,10 @@ interface server-events { /// A chat message a player sent, as plain text. chat: func(player: player, text: string); /// `/name args` typed by `player`: ok(some(text)) is their feedback, - /// err(text) their error in red. - command: func(player: player, name: string, args: string) -> result, string>; + /// err(text) their error in red. `values` holds each argument given, by + /// name, in order (an optional one left out isn't there); a line that + /// doesn't parse never reaches the mod: the player gets vanilla's error. + command: func(player: player, name: string, args: string, values: list>) -> result, string>; /// A player broke the block at `pos` in their dimension: `state` is what /// was there, as `minecraft:oak_log[axis=y]`. block-broken: func(player: player, pos: block-pos, state: string); @@ -534,6 +784,7 @@ world horizon-server-mod { import log; import storage; import players; + import %world; export server-events; } @@ -545,6 +796,8 @@ world horizon-ui-mod { import ui; import render; import input; + import recipes; + import browser; export ui-events; } @@ -559,3 +812,9 @@ world render-host { import render; import input; } + +/// The game's side of capability `recipes` (imports only). +world recipes-host { + import recipes; + import browser; +} diff --git a/crates/horizon-mods/src/api_level.rs b/crates/horizon-mods/src/api_level.rs index bf87d0cfa..073262bf9 100644 --- a/crates/horizon-mods/src/api_level.rs +++ b/crates/horizon-mods/src/api_level.rs @@ -7,13 +7,13 @@ //! version's level so the launcher can tell before it installs. /// The newest level this Horizon serves. -pub const LEVEL: u32 = 3; +pub const LEVEL: u32 = 6; /// Every function the game offers mods, as `interface.function`, with its /// level. Level 0 is the contract of Horizon 0.2.67 to 0.2.69. A new /// function takes the next level and raises [`LEVEL`] (the `api_reference` /// test fails until it is listed here). -pub const FUNCTIONS: [(&str, u32); 34] = [ +pub const FUNCTIONS: [(&str, u32); 45] = [ ("log.write", 0), ("game.get-player", 0), ("game.get-clock", 0), @@ -48,6 +48,17 @@ pub const FUNCTIONS: [(&str, u32); 34] = [ ("players.broadcast", 1), ("game.raycast", 2), ("command.run-quiet", 3), + ("world.get-block", 4), + ("world.get-biome", 4), + ("world.set-blocks", 4), + ("recipes.items", 5), + ("recipes.all", 5), + ("recipes.known", 5), + ("browser.set-items", 6), + ("browser.poll", 6), + ("browser.set-recipes", 6), + ("recipes.place", 6), + ("recipes.give", 6), ]; /// What the game's program carries so the launcher can read its level diff --git a/crates/horizon-mods/src/commands.rs b/crates/horizon-mods/src/commands.rs new file mode 100644 index 000000000..4421b47ba --- /dev/null +++ b/crates/horizon-mods/src/commands.rs @@ -0,0 +1,301 @@ +//! Server mods' typed commands: an argument line parsed as the command's +//! arguments say, the way vanilla's Brigadier parsers read them, with +//! vanilla's error messages. The game sends the same arguments to players' +//! command trees, so their chat box checks them before the server does. +use crate::runtime::{Argument, ArgumentKind, ArgumentValue, BlockPos, ServerPlayer}; + +/// The values of `args`, typed by `player`, for `arguments` (in order; +/// optional ones left out aren't there), or the error the player reads. +pub fn parse( + arguments: &[Argument], + args: &str, + player: &ServerPlayer, + online: &[ServerPlayer], +) -> Result, String> { + let mut values = Vec::new(); + let mut rest = args; + for (i, argument) in arguments.iter().enumerate() { + if i > 0 && !rest.is_empty() { + rest = rest.strip_prefix(' ').ok_or( + "Expected whitespace to end one argument, but found trailing data".to_string(), + )?; + } + if rest.is_empty() { + if argument.optional { + break; + } + return Err("Unknown or incomplete command, see below for error".into()); + } + let (value, after) = one(&argument.kind, rest, player, online)?; + values.push((argument.name.clone(), value)); + rest = after; + } + if !rest.is_empty() { + return Err("Incorrect argument for command".into()); + } + Ok(values) +} + +/// StringReader.isAllowedInUnquotedString. +fn unquoted(c: char) -> bool { + c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '+') +} + +/// The unquoted string at the start of `s`, and what follows it. +fn word(s: &str) -> (&str, &str) { + let end = s.find(|c: char| !unquoted(c)).unwrap_or(s.len()); + s.split_at(end) +} + +/// One argument from the start of `s`, and what follows it. +fn one<'a>( + kind: &ArgumentKind, + s: &'a str, + player: &ServerPlayer, + online: &[ServerPlayer], +) -> Result<(ArgumentValue, &'a str), String> { + Ok(match kind { + ArgumentKind::Word => { + let (w, rest) = word(s); + if w.is_empty() { + return Err("Expected string".into()); + } + (ArgumentValue::Word(w.into()), rest) + } + ArgumentKind::Text => (ArgumentValue::Text(s.into()), ""), + ArgumentKind::Integer((min, max)) => { + let (n, rest) = integer(s)?; + if let Some(min) = min.filter(|m| n < *m) { + return Err(format!("Integer must not be less than {min}, found {n}")); + } + if let Some(max) = max.filter(|m| n > *m) { + return Err(format!("Integer must not be more than {max}, found {n}")); + } + (ArgumentValue::Integer(n), rest) + } + ArgumentKind::Number => { + let (n, rest) = double(s)?; + (ArgumentValue::Number(n), rest) + } + ArgumentKind::Boolean => { + let (w, rest) = word(s); + let b = match w { + "true" => true, + "false" => false, + "" => return Err("Expected bool".into()), + _ => { + return Err(format!( + "Invalid boolean, expected 'true' or 'false' but found '{w}'" + )); + } + }; + (ArgumentValue::Boolean(b), rest) + } + ArgumentKind::Player => { + if let Some(selector) = s.strip_prefix('@') { + let (kind, rest) = word(selector); + return match kind { + // A player's @p is themselves (the nearest to where they are). + "s" | "p" => Ok((ArgumentValue::Player(player.clone()), rest)), + "a" | "e" | "r" | "n" => { + Err("Only one player is allowed, but the provided selector allows more than one".into()) + } + _ => Err(format!("Unknown selector type '@{kind}'")), + }; + } + let (name, rest) = word(s); + if name.is_empty() { + return Err("Invalid name or UUID".into()); + } + let found = online + .iter() + .find(|p| p.name.eq_ignore_ascii_case(name)) + .ok_or("No player was found")?; + (ArgumentValue::Player(found.clone()), rest) + } + ArgumentKind::BlockPos => { + let (x, rest) = coordinate(s, player.x)?; + let rest = rest + .strip_prefix(' ') + .ok_or("Incomplete (expected 3 coordinates)")?; + let (y, rest) = coordinate(rest, player.y)?; + let rest = rest + .strip_prefix(' ') + .ok_or("Incomplete (expected 3 coordinates)")?; + let (z, rest) = coordinate(rest, player.z)?; + (ArgumentValue::BlockPos(BlockPos { x, y, z }), rest) + } + }) +} + +/// StringReader.readInt. +fn integer(s: &str) -> Result<(i32, &str), String> { + let end = s + .find(|c: char| !(c.is_ascii_digit() || c == '-' || c == '.')) + .unwrap_or(s.len()); + let (n, rest) = s.split_at(end); + if n.is_empty() { + return Err("Expected integer".into()); + } + let n = n.parse().map_err(|_| format!("Invalid integer '{n}'"))?; + Ok((n, rest)) +} + +/// StringReader.readDouble. +fn double(s: &str) -> Result<(f64, &str), String> { + let end = s + .find(|c: char| !(c.is_ascii_digit() || c == '-' || c == '.')) + .unwrap_or(s.len()); + let (n, rest) = s.split_at(end); + if n.is_empty() { + return Err("Expected double".into()); + } + let n = n.parse().map_err(|_| format!("Invalid double '{n}'"))?; + Ok((n, rest)) +} + +/// WorldCoordinate.parseInt, then BlockPos.containing: `~` and `~n` from +/// `base`, a whole number as it is. +fn coordinate(s: &str, base: f64) -> Result<(i32, &str), String> { + if s.starts_with('^') { + return Err( + "Cannot mix world & local coordinates (everything must either use ^ or not)".into(), + ); + } + if let Some(offset) = s.strip_prefix('~') { + if offset.is_empty() || offset.starts_with(' ') { + return Ok((base.floor() as i32, offset)); + } + let (n, rest) = double(offset)?; + return Ok(((base + n).floor() as i32, rest)); + } + integer(s) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::runtime::GameMode; + + fn player(name: &str) -> ServerPlayer { + ServerPlayer { + id: format!("id-{name}"), + name: name.into(), + x: 10.7, + y: 64.0, + z: -3.2, + dimension: "minecraft:overworld".into(), + game_mode: GameMode::Survival, + health: 20.0, + } + } + fn arg(name: &str, kind: ArgumentKind, optional: bool) -> Argument { + Argument { + name: name.into(), + kind, + optional, + } + } + + #[test] + fn values_in_order_and_optional_ones_left_out() { + let alex = player("Alex"); + let online = [alex.clone(), player("Steve")]; + let args = [ + arg("who", ArgumentKind::Player, false), + arg("height", ArgumentKind::Integer((Some(1), Some(64))), true), + arg("note", ArgumentKind::Text, true), + ]; + let v = parse(&args, "steve 5 hello there", &alex, &online).unwrap(); + assert_eq!(v[0].0, "who"); + assert!(matches!(&v[0].1, ArgumentValue::Player(p) if p.name == "Steve")); + assert_eq!(v[1], ("height".into(), ArgumentValue::Integer(5))); + assert_eq!( + v[2], + ("note".into(), ArgumentValue::Text("hello there".into())) + ); + let v = parse(&args, "@s", &alex, &online).unwrap(); + assert_eq!(v.len(), 1); + assert!(matches!(&v[0].1, ArgumentValue::Player(p) if p.name == "Alex")); + } + + #[test] + fn vanilla_errors() { + let alex = player("Alex"); + let online = [alex.clone()]; + let height = [arg( + "height", + ArgumentKind::Integer((Some(1), Some(64))), + false, + )]; + let err = |a: &[Argument], s| parse(a, s, &alex, &online).unwrap_err(); + assert_eq!( + err(&height, "0"), + "Integer must not be less than 1, found 0" + ); + assert_eq!( + err(&height, "65"), + "Integer must not be more than 64, found 65" + ); + assert_eq!(err(&height, "x"), "Expected integer"); + assert_eq!(err(&height, "1.5"), "Invalid integer '1.5'"); + assert_eq!( + err(&height, ""), + "Unknown or incomplete command, see below for error" + ); + assert_eq!(err(&height, "3 4"), "Incorrect argument for command"); + let who = [arg("who", ArgumentKind::Player, false)]; + assert_eq!(err(&who, "Herobrine"), "No player was found"); + assert_eq!(err(&who, "@q"), "Unknown selector type '@q'"); + let flag = [arg("on", ArgumentKind::Boolean, false)]; + assert_eq!( + err(&flag, "yes"), + "Invalid boolean, expected 'true' or 'false' but found 'yes'" + ); + let pos = [arg("at", ArgumentKind::BlockPos, false)]; + assert_eq!(err(&pos, "1 2"), "Incomplete (expected 3 coordinates)"); + } + + #[test] + fn block_positions_relative_to_the_player() { + let alex = player("Alex"); + let pos = [arg("at", ArgumentKind::BlockPos, false)]; + let v = parse(&pos, "~ ~1 ~-0.5", &alex, &[]).unwrap(); + assert_eq!( + v[0].1, + ArgumentValue::BlockPos(BlockPos { + x: 10, + y: 65, + z: -4 + }) + ); + let v = parse(&pos, "-5 70 ~", &alex, &[]).unwrap(); + assert_eq!( + v[0].1, + ArgumentValue::BlockPos(BlockPos { + x: -5, + y: 70, + z: -4 + }) + ); + } + + #[test] + fn free_text_is_an_optional_text_argument() { + let alex = player("Alex"); + let free = [arg("args", ArgumentKind::Text, true)]; + assert_eq!(parse(&free, "", &alex, &[]), Ok(Vec::new())); + assert_eq!( + parse(&free, "anything at all", &alex, &[]), + Ok(vec![( + "args".into(), + ArgumentValue::Text("anything at all".into()) + )]) + ); + assert_eq!( + parse(&[], "more", &alex, &[]), + Err("Incorrect argument for command".into()) + ); + assert_eq!(parse(&[], "", &alex, &[]), Ok(Vec::new())); + } +} diff --git a/crates/horizon-mods/src/lib.rs b/crates/horizon-mods/src/lib.rs index 20f475165..983df73d4 100644 --- a/crates/horizon-mods/src/lib.rs +++ b/crates/horizon-mods/src/lib.rs @@ -6,6 +6,8 @@ //! Nothing here runs unless a mod is installed and turned on: an empty //! [`Mods`] makes no engine and every hook returns at once. pub mod api_level; +#[cfg(feature = "runtime")] +pub mod commands; pub mod content; #[cfg(feature = "index")] pub mod index; diff --git a/crates/horizon-mods/src/manifest.rs b/crates/horizon-mods/src/manifest.rs index 5ad7823aa..c2f2f61fc 100644 --- a/crates/horizon-mods/src/manifest.rs +++ b/crates/horizon-mods/src/manifest.rs @@ -97,9 +97,15 @@ pub enum Capability { Input, /// The players on the server and messages to them (server mods). Players, + /// Blocks in the server's loaded chunks, and changes to them (server + /// mods; client mods later, where the game runs the world). + World, + /// The recipes and items the game knows, for recipe viewers + /// (interface `recipes`). + Recipes, } impl Capability { - pub const ALL: [Capability; 10] = [ + pub const ALL: [Capability; 12] = [ Capability::GameRead, Capability::Chat, Capability::Hud, @@ -110,10 +116,15 @@ impl Capability { Capability::Render, Capability::Input, Capability::Players, + Capability::World, + Capability::Recipes, ]; /// Whether a server mod may have it: the others act on a local player. pub fn on_server(self) -> bool { - matches!(self, Capability::Storage | Capability::Players) + matches!( + self, + Capability::Storage | Capability::Players | Capability::World + ) } /// The WIT interface it grants, in `horizon:mods`. pub fn interface(self) -> &'static str { @@ -128,6 +139,8 @@ impl Capability { Capability::Render => "render", Capability::Input => "input", Capability::Players => "players", + Capability::World => "world", + Capability::Recipes => "recipes", } } /// May change in any release: a mod uses it only with @@ -135,7 +148,7 @@ impl Capability { pub fn is_experimental(self) -> bool { matches!( self, - Capability::Ui | Capability::Render | Capability::Input + Capability::Ui | Capability::Render | Capability::Input | Capability::Recipes ) } /// What the player reads before turning the mod on: "May ". @@ -153,6 +166,10 @@ impl Capability { "see the keys you hold and your clicks, take over the use button on its own items and the mouse wheel, and add keys" } Capability::Players => "see who is on the server and message them", + Capability::World => "read and change the world's blocks", + Capability::Recipes => { + "read the game's recipes and items and which recipes you know, place recipes in your crafting grid and, in creative mode, give you items" + } } } /// The capability a component import needs, `Ok(None)` for one every @@ -167,6 +184,10 @@ impl Capability { if interface == "log" { return Ok(None); } + // A recipe viewer's panel is part of capability `ui`. + if interface == "browser" { + return Ok(Some(Capability::Ui)); + } Capability::ALL .into_iter() .filter(|c| *c != Capability::Registries) @@ -188,6 +209,8 @@ impl fmt::Display for Capability { Capability::Render => "render", Capability::Input => "input", Capability::Players => "players", + Capability::World => "world", + Capability::Recipes => "recipes", }; f.write_str(name) } diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index ce48f2317..a75dd5a43 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -1,12 +1,13 @@ //! Loading and calling mods with wasmtime's component model. use crate::manifest::{Manifest, Package, Side}; use server_bindings::{ - HorizonServerMod, exports::horizon::mods::server_events::Registration as ServerRegistration, - horizon::mods::players, + HorizonServerMod, + exports::horizon::mods::server_events::Registration as ServerRegistration, + horizon::mods::{players, world as mod_world}, }; use std::{ path::{Path, PathBuf}, - sync::Arc, + sync::{Arc, Mutex}, time::{Duration, Instant, SystemTime}, }; use wasmtime::{ @@ -25,6 +26,7 @@ mod server_bindings { wasmtime::component::bindgen!({ path: "../horizon-mod-sdk/wit", world: "horizon-server-mod", + additional_derives: [PartialEq], with: { "horizon:mods/log": super::bindings::horizon::mods::log, "horizon:mods/storage": super::bindings::horizon::mods::storage, @@ -50,8 +52,11 @@ use bindings::{ horizon::mods::{chat, command, game, hud, log as mod_log, storage}, }; pub use server_bindings::{ - exports::horizon::mods::server_events::BlockPos, + exports::horizon::mods::server_events::{ + Argument, ArgumentKind, ArgumentValue, BlockPos, ServerCommand, + }, horizon::mods::players::{GameMode, Player as ServerPlayer}, + horizon::mods::world::BlockChange, }; type ClientEvents = bindings::exports::horizon::mods::events::Guest; type ServerEvents = server_bindings::exports::horizon::mods::server_events::Guest; @@ -78,6 +83,24 @@ pub use render_bindings::horizon::mods::render::{ Zoom as ModZoom, }; use render_bindings::{RenderHost, horizon::mods::render}; +/// Capability `recipes`'s imports (docs/mods.md): the game's recipes and items. +mod recipes_bindings { + wasmtime::component::bindgen!({ + path: "../horizon-mod-sdk/wit", + world: "recipes-host", + }); +} +/// Capability `ui`'s recipe viewer panel (WIT `interface browser`). +pub use recipes_bindings::horizon::mods::browser::{ + Click as BrowserClick, Event as BrowserEvent, ItemKey as BrowserItemKey, + Layout as BrowserLayout, RecipeView as BrowserRecipe, SlotClick as BrowserSlotClick, + Stack as BrowserStack, +}; +/// What capability `recipes` reads (WIT `interface recipes`). +pub use recipes_bindings::horizon::mods::recipes::{ + Item as RecipeItem, Kind as RecipeKind, Recipe, Stack as RecipeStack, +}; +use recipes_bindings::{RecipesHost, horizon::mods::browser, horizon::mods::recipes}; /// A mod's linear memory cap. const MEMORY: usize = 64 << 20; @@ -87,6 +110,8 @@ const FUEL_INIT: u64 = 2_000_000_000; const FUEL_TICK: u64 = 50_000_000; const FUEL_FRAME: u64 = 10_000_000; const FUEL_EVENT: u64 = 100_000_000; +/// Blocks a mod may set per `world.set-blocks` call. +pub const BLOCKS_PER_CALL: usize = 4096; /// Chat lines a mod may show per call, HUD lines and their length. const CHAT_PER_CALL: usize = 8; /// `command.run-quiet` lines one call of a mod may queue (a quiet payload's @@ -133,6 +158,23 @@ pub struct Snapshot { /// its distance from the eye, for `game.raycast`; the game works it out /// only while a mod calls it ([`Mods::wants_raycast`]). pub view_hit: Option<(f32, Hit)>, + /// Every item and recipe, for capability `recipes`; the game makes them + /// once, and only while a mod reads them ([`Mods::wants_recipes`]). + pub recipes: Option>, + /// The `book-id`s of the recipes the player's book holds. + pub known_recipes: Arc<[i32]>, + /// The open screen takes recipes (`recipes.place`). + pub placing: bool, + /// The player is in creative mode (`recipes.give`). + pub creative: bool, +} + +/// Capability `recipes`'s tables: `items` in the registry's order, which +/// each [`RecipeStack::item`] indexes. +#[derive(Clone, Debug, Default)] +pub struct Recipes { + pub items: Vec, + pub recipes: Vec, } /// Which mods a game starts: the window's game the client mods, the game @@ -182,6 +224,13 @@ pub enum Output { text: String, error: bool, }, + /// `world.set-blocks`: changes to make in `dimension`, in order, each + /// state checked by the [`WorldView`] lent for the call. + SetBlocks { + name: String, + dimension: String, + blocks: Vec, + }, /// `ui.open-screen`: the mod's entry in `entries()`; what it shows is /// [`Mods::screen`]. OpenScreen { owner: usize }, @@ -189,8 +238,34 @@ pub enum Output { CloseScreen { owner: usize }, /// `render.shake`: strength 0 to 1, fading out over `seconds` (≤ 10). Shake { strength: f32, seconds: f32 }, + /// `recipes.place`: the recipe book's click on this display id, all of + /// it when `all`. + PlaceRecipe { book_id: i32, all: bool }, + /// `recipes.give`: a stack for a creative player. + Give { + item: String, + count: u32, + components: String, + }, } +/// The game's world as capability `world` reads it during a call: the +/// game lends one with [`Mods::lend_world`] and takes it back after. +pub trait WorldView: std::any::Any + Send { + /// The block state at a position, `minecraft:oak_log[axis=y]`; `None` + /// where no chunk of that dimension is loaded. + fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option; + /// The biome at a position, `minecraft:plains`; `None` as for blocks. + fn biome(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option; + /// Whether `dimension` is one the server has. + fn has_dimension(&self, dimension: &str) -> bool; + /// `Err` (why) for a state string that names no block state. + fn check_state(&self, state: &str) -> Result<(), String>; +} + +/// The view lent for the current calls, shared by every mod's store. +type WorldSlot = Arc>>>; + /// A mod's text panel, drawn every frame until it changes. #[derive(Clone, Debug)] pub struct Panel { @@ -241,6 +316,8 @@ struct Running { hooks: Hooks, /// It imports `game.raycast`. raycasts: bool, + /// It imports capability `recipes`. + reads_recipes: bool, } /// A running mod's exports and the hooks its `init` asked for. @@ -261,10 +338,10 @@ impl Hooks { Hooks::Client(..) => None, } } - fn commands(&self) -> &[String] { + fn commands(&self) -> Vec<&str> { match self { - Hooks::Client(_, r) => &r.commands, - Hooks::Server(_, r) => &r.commands, + Hooks::Client(_, r) => r.commands.iter().map(String::as_str).collect(), + Hooks::Server(_, r) => r.commands.iter().map(|c| c.name.as_str()).collect(), } } } @@ -282,6 +359,46 @@ struct UiState { close: bool, } +/// Capability `ui`'s panel beside container screens (`browser`). +#[derive(Default)] +struct BrowserState { + items: Vec, + /// Which `set-items` or `set-recipes` call the panel is from, unique + /// across mods and reloads, so the game converts them once. + version: u64, + /// `set-recipes`' title and recipes, shown instead of the items. + recipes: Option, + events: std::collections::VecDeque, +} +/// What `browser.set-recipes` shows: a title, tabs (`tab` the selected +/// one) and the recipes. +#[derive(Clone, Debug)] +pub struct RecipePage { + pub title: String, + pub tabs: Vec, + pub tab: u32, + pub recipes: Vec, +} +static BROWSER_VERSION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); +/// Items a panel may hold, and events kept for `browser.poll`. +const BROWSER_ITEMS: usize = 8192; +/// `recipes.place` and `give` calls a hook call may make. +const RECIPE_ACTIONS: usize = 36; +/// Recipes `set-recipes` may show, slots in one, and stacks a slot cycles. +const BROWSER_RECIPES: usize = 256; +const RECIPE_SLOTS: usize = 9; +const RECIPE_TABS: usize = 16; +const SLOT_STACKS: usize = 64; +const BROWSER_EVENTS: usize = 256; +impl BrowserState { + fn push(&mut self, event: BrowserEvent) { + if self.events.len() == BROWSER_EVENTS { + self.events.pop_front(); + } + self.events.push_back(event); + } +} + struct State { name: String, id: String, @@ -298,6 +415,7 @@ struct State { /// Capability `render`'s minimap, when the mod shows one. minimap: Option, input: InputState, + browser: BrowserState, /// Capability `storage`'s folder; made on first `set`. data_dir: PathBuf, /// Bytes `storage::set` may still write before this hook call ends @@ -306,6 +424,7 @@ struct State { /// needs its own budget. storage_budget: u64, limits: StoreLimits, + world: WorldSlot, } /// The installed mods and the engine running them. `Mods::default()` is @@ -316,9 +435,40 @@ pub struct Mods { entries: Vec, snapshot: Arc, out: Vec, + world: WorldSlot, + /// Moves on whenever a mod starts or stops: the game resends the server + /// mods' commands to players when it changes. + generation: u64, } impl Mods { + /// Changes whenever the running mods (so their commands) change. + pub fn generation(&self) -> u64 { + self.generation + } + /// Whether a running mod may use capability `world`: only then is a + /// view worth lending. + pub fn wants_world(&self) -> bool { + self.entries.iter().any(|e| { + e.status == Status::Running + && e.manifest + .as_ref() + .is_some_and(|m| m.capabilities.contains(&crate::Capability::World)) + }) + } + /// Lends the game's world to capability `world` for the calls until + /// [`Mods::take_world`]; with none lent, `get-block` finds nothing and + /// `set-blocks` checks only its count. + pub fn lend_world(&mut self, view: Box) { + if let Ok(mut slot) = self.world.lock() { + *slot = Some(view); + } + } + /// The view [`Mods::lend_world`] lent, back to the game. + pub fn take_world(&mut self) -> Option> { + self.world.lock().ok()?.take() + } + /// Reads every mod at `paths` and starts those `enabled` says are on, /// client and server mods alike. A command that `reserved` (vanilla's /// commands) or an earlier mod already uses is refused. @@ -388,10 +538,14 @@ impl Mods { .map_err(|e| e.to_string())?; players::add_to_linker::>(&mut linker, |s| s) .map_err(|e| e.to_string())?; + mod_world::add_to_linker::>(&mut linker, |s| s) + .map_err(|e| e.to_string())?; UiHost::add_to_linker::>(&mut linker, |s| s) .map_err(|e| e.to_string())?; RenderHost::add_to_linker::>(&mut linker, |s| s) .map_err(|e| e.to_string())?; + RecipesHost::add_to_linker::>(&mut linker, |s| s) + .map_err(|e| e.to_string())?; self.engine = Some((engine, linker)); } Ok(self.engine.as_ref().expect("made above")) @@ -426,9 +580,11 @@ impl Mods { .iter() .filter_map(|e| e.run.as_ref()) .filter(|r| r.hooks.server().is_some() == server) - .flat_map(|r| r.hooks.commands().iter().cloned()) + .flat_map(|r| r.hooks.commands()) + .map(str::to_owned) .collect(); let snapshot = self.snapshot.clone(); + let world = self.world.clone(); let (engine, linker) = self.engine()?; let component = Component::new(engine, wasm).map_err(|e| format!("not a component: {e}"))?; @@ -461,12 +617,14 @@ impl Mods { zoom: None, minimap: None, input: InputState::default(), + browser: BrowserState::default(), data_dir, storage_budget: STORAGE_WRITE_BUDGET, limits: StoreLimitsBuilder::new() .memory_size(MEMORY) .instances(16) .build(), + world, }; let mut store = Store::new(engine, state); store.limiter(|s| &mut s.limits); @@ -492,23 +650,37 @@ impl Mods { .map_err(|e| reason(&e))??; (Hooks::Client(exports, r), ui) }; - let commands = match &mut hooks { - Hooks::Client(_, r) => &mut r.commands, - Hooks::Server(_, r) => &mut r.commands, - }; - commands.retain(|c| { - let free = !reserved(c) && !taken.contains(c); + let free = |c: &str| { + let free = !reserved(c) && !taken.iter().any(|t| t == c); if !free { log::warn!("Horizon: mod {} cannot take /{c}: already a command", m.id); } free - }); + }; + match &mut hooks { + Hooks::Client(_, r) => r.commands.retain(|c| free(c)), + Hooks::Server(_, r) => { + r.commands.retain(|c| free(&c.name)); + for c in &mut r.commands { + if let Err(e) = check_arguments(&c.arguments) { + log::warn!( + "Horizon: mod {}'s /{}: {e}; it takes free text", + m.id, + c.name + ); + c.arguments.clear(); + } + } + } + } + self.generation += 1; self.out.append(&mut store.data_mut().out); Ok(Some(Running { store, ui, hooks, raycasts: functions.iter().any(|f| f == "game.raycast"), + reads_recipes: functions.iter().any(|f| f.starts_with("recipes.")), })) } @@ -619,6 +791,7 @@ impl Mods { }); entry.status = Status::Failed(reason); entry.run = None; + self.generation += 1; None } } @@ -643,7 +816,7 @@ impl Mods { fn command_owner(&self, server: bool, name: &str) -> Option { self.entries.iter().position(|e| { e.run.as_ref().is_some_and(|r| { - r.hooks.server().is_some() == server && r.hooks.commands().iter().any(|c| c == name) + r.hooks.server().is_some() == server && r.hooks.commands().contains(&name) }) }) } @@ -676,7 +849,7 @@ impl Mods { .iter() .filter_map(|e| e.run.as_ref()) .filter(move |r| r.hooks.server().is_some() == server) - .flat_map(|r| r.hooks.commands().iter().map(String::as_str)) + .flat_map(|r| r.hooks.commands()) } /// A server tick. @@ -719,9 +892,13 @@ impl Mods { |m, s| m.call_block_placed(s, player, pos, state), ); } - /// The commands running server mods own, for the server's command tree. - pub fn server_commands(&self) -> impl Iterator { - self.owned_commands(true) + /// The commands running server mods own and their arguments, for the + /// server's command tree. + pub fn server_commands(&self) -> impl Iterator { + self.entries + .iter() + .filter_map(|e| e.run.as_ref()?.hooks.server()) + .flat_map(|r| r.commands.iter()) } /// Runs `line` (without its slash), typed by `player`, if a server mod /// owns its command; its feedback is an [`Output::Reply`]. False when @@ -731,18 +908,35 @@ impl Mods { let Some(i) = self.command_owner(true, name) else { return false; }; - let result = self.call(i, FUEL_EVENT, |run| match &run.hooks { - Hooks::Server(m, _) => { - m.horizon_mods_server_events() - .call_command(&mut run.store, player, name, args) - } - Hooks::Client(..) => Ok(Ok(None)), - }); let reply = |text, error| Output::Reply { player: player.id.clone(), text, error, }; + let arguments = self.entries[i] + .run + .as_ref() + .and_then(|r| r.hooks.server()) + .and_then(|r| r.commands.iter().find(|c| c.name == name)) + .map(|c| c.arguments.as_slice()) + .unwrap_or_default(); + let values = match crate::commands::parse(arguments, args, player, &self.snapshot.players) { + Ok(values) => values, + Err(e) => { + self.out.push(reply(e, true)); + return true; + } + }; + let result = self.call(i, FUEL_EVENT, |run| match &run.hooks { + Hooks::Server(m, _) => m.horizon_mods_server_events().call_command( + &mut run.store, + player, + name, + args, + &values, + ), + Hooks::Client(..) => Ok(Ok(None)), + }); match result { Some(Ok(Some(text))) => self.out.push(reply(text, false)), Some(Err(text)) => self.out.push(reply(text, true)), @@ -769,6 +963,58 @@ impl Mods { .iter() .any(|e| e.run.as_ref().is_some_and(|r| r.raycasts)) } + /// The panel beside container screens (`browser.set-items`): the first + /// running mod with items or recipes, its index, the panel's version and + /// the items. + pub fn browser_items(&self) -> Option<(usize, u64, &[BrowserStack])> { + self.entries.iter().enumerate().find_map(|(i, e)| { + let b = &e.run.as_ref()?.store.data().browser; + (!b.items.is_empty() || b.recipes.is_some()).then_some(( + i, + b.version, + b.items.as_slice(), + )) + }) + } + /// What mod `owner`'s panel shows instead of its items + /// (`browser.set-recipes`). + pub fn browser_recipes(&self, owner: usize) -> Option<&RecipePage> { + let b = &self.entries.get(owner)?.run.as_ref()?.store.data().browser; + b.recipes.as_ref() + } + /// The player did `event` on mod `owner`'s panel. + pub fn browser_event(&mut self, owner: usize, event: BrowserEvent) { + if let Some(run) = self.entries.get_mut(owner).and_then(|e| e.run.as_mut()) { + run.store.data_mut().browser.push(event); + } + } + /// The key `key` went down with the pointer on `stack` in a container + /// screen: each mod with a key on it hears its own name for it. + pub fn browser_key(&mut self, key: &str, stack: &BrowserStack) { + for run in self.entries.iter_mut().filter_map(|e| e.run.as_mut()) { + let data = run.store.data_mut(); + let names: Vec = data + .input + .keys + .iter() + .filter(|k| k.key == key) + .map(|k| k.name.clone()) + .collect(); + for key in names { + data.browser.push(BrowserEvent::Key(BrowserItemKey { + key, + stack: stack.clone(), + })); + } + } + } + /// Some running mod reads capability `recipes`: the snapshot needs + /// [`Snapshot::recipes`] and [`Snapshot::known_recipes`]. + pub fn wants_recipes(&self) -> bool { + self.entries + .iter() + .any(|e| e.run.as_ref().is_some_and(|r| r.reads_recipes)) + } /// Some running mod has a `frame` hook: the game refreshes the snapshot /// every frame for it. pub fn wants_frames(&self) -> bool { @@ -1016,6 +1262,7 @@ impl Mods { continue; } any = true; + self.generation += 1; self.entries[i].modified = now; self.entries[i].run = None; let path = self.entries[i].path.clone(); @@ -1041,6 +1288,34 @@ impl Mods { } } +/// A command's arguments are well formed: names given and distinct, +/// optional ones last, free text only last. +fn check_arguments(arguments: &[Argument]) -> Result<(), String> { + for (i, a) in arguments.iter().enumerate() { + if a.name.is_empty() + || !a + .name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_') + { + return Err(format!("argument name '{}' isn't [A-Za-z0-9_]+", a.name)); + } + if arguments[..i].iter().any(|b| b.name == a.name) { + return Err(format!("two arguments are named {}", a.name)); + } + if i > 0 && arguments[i - 1].optional && !a.optional { + return Err(format!("{} is required after an optional argument", a.name)); + } + if a.kind == ArgumentKind::Text && i + 1 < arguments.len() { + return Err(format!( + "{} takes the rest of the line, so it must be last", + a.name + )); + } + } + Ok(()) +} + fn modified(path: &Path) -> Option { let meta = std::fs::metadata(path).ok()?; if meta.is_dir() { @@ -1064,7 +1339,10 @@ fn reason(e: &wasmtime::Error) -> String { } fn clip(text: String) -> String { - match text.char_indices().nth(LINE_CHARS) { + clip_to(text, LINE_CHARS) +} +fn clip_to(text: String, chars: usize) -> String { + match text.char_indices().nth(chars) { Some((at, _)) => text[..at].to_string(), None => text, } @@ -1125,6 +1403,125 @@ impl game::Host for State { (*at <= distance.min(RAYCAST_MAX) && !distance.is_nan()).then(|| hit.clone()) } } +impl browser::Host for State { + fn set_items(&mut self, items: Vec) { + self.browser.items = items + .into_iter() + .take(BROWSER_ITEMS) + .map(|s| BrowserStack { + item: clip(s.item), + components: clip_to(s.components, 4096), + ..s + }) + .collect(); + self.browser.version = BROWSER_VERSION.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + fn set_recipes( + &mut self, + title: String, + tabs: Vec, + tab: u32, + recipes: Vec, + ) { + let stack = |s: BrowserStack| BrowserStack { + item: clip(s.item), + components: clip_to(s.components, 4096), + ..s + }; + let cycle = |list: Vec| -> Vec { + list.into_iter().take(SLOT_STACKS).map(stack).collect() + }; + self.browser.recipes = (!recipes.is_empty()).then(|| { + let recipes = recipes + .into_iter() + .take(BROWSER_RECIPES) + .map(|r| BrowserRecipe { + width: r.width.clamp(1, 3), + height: r.height.clamp(1, 3), + slots: r.slots.into_iter().take(RECIPE_SLOTS).map(cycle).collect(), + results: cycle(r.results), + note: clip(r.note), + ..r + }) + .collect(); + RecipePage { + title: clip(title), + tabs: tabs.into_iter().take(RECIPE_TABS).map(stack).collect(), + tab, + recipes, + } + }); + self.browser.version = BROWSER_VERSION.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + fn poll(&mut self) -> Vec { + self.browser.events.drain(..).collect() + } +} +impl recipes::Host for State { + fn items(&mut self) -> Vec { + self.snapshot + .recipes + .as_ref() + .map_or_else(Vec::new, |r| r.items.clone()) + } + fn all(&mut self) -> Vec { + self.snapshot + .recipes + .as_ref() + .map_or_else(Vec::new, |r| r.recipes.clone()) + } + fn known(&mut self) -> Vec { + self.snapshot.known_recipes.to_vec() + } + fn place(&mut self, book_id: i32, all: bool) -> Result<(), String> { + self.recipe_action()?; + if !self.snapshot.placing { + return Err("no screen that takes recipes is open".into()); + } + if !self.snapshot.known_recipes.contains(&book_id) { + return Err(format!( + "recipe {book_id} is not in the player's recipe book" + )); + } + self.out.push(Output::PlaceRecipe { book_id, all }); + Ok(()) + } + fn give(&mut self, stack: RecipeStack) -> Result<(), String> { + self.recipe_action()?; + if !self.snapshot.creative { + return Err("only in creative mode".into()); + } + let item = self + .snapshot + .recipes + .as_ref() + .and_then(|r| r.items.get(stack.item as usize)) + .ok_or_else(|| format!("no item {}", stack.item))? + .id + .clone(); + self.out.push(Output::Give { + item, + count: stack.count.clamp(1, 99), + components: clip_to(stack.components, 4096), + }); + Ok(()) + } +} +impl State { + /// `recipes.place` and `give` take at most [`RECIPE_ACTIONS`] a call. + fn recipe_action(&self) -> Result<(), String> { + let done = self + .out + .iter() + .filter(|o| matches!(o, Output::PlaceRecipe { .. } | Output::Give { .. })) + .count(); + if done < RECIPE_ACTIONS { + Ok(()) + } else { + Err(format!("at most {RECIPE_ACTIONS} places and gives a call")) + } + } +} impl State { /// Queues a chat line unless the call already sent [`CHAT_PER_CALL`]. fn say(&mut self, line: impl FnOnce(String) -> Output) -> bool { @@ -1153,6 +1550,40 @@ impl chat::Host for State { }); } } +impl mod_world::Host for State { + fn get_block(&mut self, dimension: String, x: i32, y: i32, z: i32) -> Option { + let view = self.world.lock().ok()?; + view.as_ref()?.block(&dimension, x, y, z) + } + fn get_biome(&mut self, dimension: String, x: i32, y: i32, z: i32) -> Option { + let view = self.world.lock().ok()?; + view.as_ref()?.biome(&dimension, x, y, z) + } + fn set_blocks(&mut self, dimension: String, blocks: Vec) -> Result<(), String> { + if blocks.len() > BLOCKS_PER_CALL { + return Err(format!( + "{} blocks: at most {BLOCKS_PER_CALL} per call", + blocks.len() + )); + } + if let Some(view) = self.world.lock().ok().as_ref().and_then(|v| v.as_ref()) { + if !view.has_dimension(&dimension) { + return Err(format!("no dimension {dimension}")); + } + for b in &blocks { + view.check_state(&b.state)?; + } + } + if !blocks.is_empty() { + self.out.push(Output::SetBlocks { + name: self.name.clone(), + dimension, + blocks, + }); + } + Ok(()) + } +} impl players::Host for State { fn online(&mut self) -> Vec { self.snapshot.players.clone() diff --git a/crates/horizon-mods/src/testing.rs b/crates/horizon-mods/src/testing.rs index 3a7422377..0fe821074 100644 --- a/crates/horizon-mods/src/testing.rs +++ b/crates/horizon-mods/src/testing.rs @@ -29,6 +29,54 @@ pub struct TestGame { /// Every name that joined, for their id. names: Vec, tick: u64, + /// Capability `world`'s Overworld: the blocks a script set or the mod + /// changed; every other block, and the other dimensions, are air. Every + /// biome is the dimension's plainest: plains, nether wastes, the end. + pub world: std::collections::BTreeMap<(i32, i32, i32), String>, +} + +/// The world a script's mod reads: [`TestGame::world`], copied for a step. +struct ScriptWorld(std::collections::BTreeMap<(i32, i32, i32), String>); + +impl crate::WorldView for ScriptWorld { + fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option { + let here = (dimension == "minecraft:overworld") + .then(|| self.0.get(&(x, y, z)).cloned()) + .flatten(); + Some(here.unwrap_or_else(|| "minecraft:air".into())) + } + fn biome(&self, dimension: &str, _x: i32, _y: i32, _z: i32) -> Option { + let biome = match dimension { + "minecraft:overworld" => "minecraft:plains", + "minecraft:the_nether" => "minecraft:nether_wastes", + "minecraft:the_end" => "minecraft:the_end", + _ => return None, + }; + Some(biome.into()) + } + fn has_dimension(&self, dimension: &str) -> bool { + matches!( + dimension, + "minecraft:overworld" | "minecraft:the_nether" | "minecraft:the_end" + ) + } + fn check_state(&self, state: &str) -> Result<(), String> { + // No registry here: the shape only (the game checks the names). + let name = state.split('[').next().unwrap_or_default(); + let plain = |t: &str| { + !t.is_empty() + && t.bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_.-/".contains(&b)) + }; + let ok = match name.split_once(':') { + Some((ns, path)) => plain(ns) && plain(path), + None => plain(name), + }; + let closed = !state.contains('[') || state.ends_with(']'); + (ok && closed) + .then_some(()) + .ok_or_else(|| format!("{state} is not a block state")) + } } /// Where a script starts: standing at 0.5 64 0.5 in the Overworld, facing @@ -71,6 +119,7 @@ impl TestGame { players: Vec::new(), names: Vec::new(), tick: 0, + world: Default::default(), }; copy_mod(hmod, ©)?; game.start()?; @@ -204,7 +253,7 @@ impl TestGame { } /// The commands the mod registered. pub fn commands(&self) -> Vec { - let server = self.mods.server_commands(); + let server = self.mods.server_commands().map(|c| c.name.as_str()); self.mods .commands() .chain(server) @@ -312,9 +361,10 @@ pub struct ClockSet { } /// One step. Its parts happen in this order: `reload`, `title-screen`, -/// `join`, `player`, `clock`, `ticks`, `frames`, `chat`, `command`, `break`, -/// `place`, `leave`; then `expect` is checked against what the mod showed -/// during the step. For a server mod, `player`, `chat`, `command`, `break` +/// `blocks`, `join`, `player`, `clock`, `ticks`, `frames`, `chat`, `command`, +/// `break`, `place`, `leave`; then the blocks the mod set are made, and +/// `expect` is checked against what the mod showed and changed during the +/// step. For a server mod, `player`, `chat`, `command`, `break` /// and `place` are the doing of the player named by `as`, or of the first /// player on. #[derive(Debug, Default, Deserialize)] @@ -341,6 +391,10 @@ pub struct Step { #[serde(rename = "break")] broken: Option, place: Option, + /// Blocks of the Overworld before the rest of the step (capability + /// `world`); every other block is air. + #[serde(default)] + blocks: Vec, #[serde(default)] expect: Expect, } @@ -363,6 +417,9 @@ pub struct Expect { /// The panel's lines (`[]`: no panel) and its corner. panel: Option>, corner: Option, + /// Blocks of the Overworld after the step, the mod's changes made + /// (capability `world`). + blocks: Option>, /// The mod is turned off during this step, for a reason holding this text. /// Without it, a mod that stops fails the test. stopped: Option, @@ -467,6 +524,11 @@ impl Step { game.player = None; game.clock = None; } + for b in &self.blocks { + game.world.insert((b.x, b.y, b.z), b.state.clone()); + } + game.mods + .lend_world(Box::new(ScriptWorld(game.world.clone()))); if let Some(name) = &self.join { game.join(name); } @@ -531,7 +593,19 @@ impl Step { { return Err(format!("{name} is not on the server")); } + game.mods.take_world(); let out = game.drain(); + for o in &out { + if let Output::SetBlocks { + dimension, blocks, .. + } = o + && dimension == "minecraft:overworld" + { + for b in blocks { + game.world.insert((b.x, b.y, b.z), b.state.clone()); + } + } + } let stopped = out.iter().find_map(|o| match o { Output::Stopped { reason, .. } => Some(reason.as_str()), _ => None, @@ -615,6 +689,18 @@ impl Step { .unwrap_or_default(); same("panel", want, &got)?; } + if let Some(want) = &e.blocks { + for b in want { + let got = game.world.get(&(b.x, b.y, b.z)); + let got = got.map_or("minecraft:air", String::as_str); + if got != b.state { + return Err(format!( + "block at {} {} {}: expected {}, got {got}", + b.x, b.y, b.z, b.state + )); + } + } + } if let Some(want) = &e.corner { let got = game.panel().map(|p| corner_name(p.corner).to_string()); same("corner", &Some(want.clone()), &got)?; diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index c6b835f10..5ca3faf77 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -26,8 +26,8 @@ id = "test_ui_guest" name = "Test UI Guest" version = "0.1.0" api = "0.1" -capabilities = ["game-read", "chat", "command", "ui", "render", "input"] -experimental = ["ui", "render", "input"] +capabilities = ["game-read", "chat", "command", "ui", "render", "input", "recipes"] +experimental = ["ui", "render", "input", "recipes"] "#; /// Builds the mods once and writes their `.hmod` files; returns the folder. @@ -47,6 +47,8 @@ fn mods_dir() -> &'static Path { "-p", "welcome", "-p", + "beacons", + "-p", "horizon-mods-test-guest", "-p", "horizon-mods-test-ui-guest", @@ -70,6 +72,7 @@ fn mods_dir() -> &'static Path { ("coords_hud", example("coords-hud")), ("predator_missile", example("predator-missile")), ("welcome", example("welcome")), + ("beacons", example("beacons")), ("horizon_mods_test_guest", GUEST_MANIFEST.to_string()), ("horizon_mods_test_ui_guest", UI_MANIFEST.to_string()), ]; @@ -202,7 +205,7 @@ fn undeclared_capabilities_are_refused() { /// from the functions they import. #[test] fn a_mod_for_a_newer_horizon_is_refused() { - use horizon_mods::api_level::{LEVEL, imports, needed}; + use horizon_mods::api_level::{imports, needed}; use wit_parser::{ManglingAndAbi, Resolve}; let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); let wit = std::fs::read_to_string(root.join("crates/horizon-mod-sdk/wit/horizon.wit")) @@ -238,8 +241,8 @@ id = "too_new" name = "Too New" version = "0.1.0" api = "0.1" -capabilities = ["game-read", "chat", "hud", "storage", "command", "ui", "render", "input"] -experimental = ["ui", "render", "input"] +capabilities = ["game-read", "chat", "hud", "storage", "command", "ui", "render", "input", "recipes"] +experimental = ["ui", "render", "input", "recipes"] "#; std::fs::write(dir.join("horizon-mod.toml"), manifest).unwrap(); std::fs::write(dir.join("mod.wasm"), wasm).unwrap(); @@ -252,8 +255,8 @@ experimental = ["ui", "render", "input"] needed(imports(&wasm).unwrap().iter().map(String::as_str)).0 }; assert_eq!(level("coords_hud.hmod"), 0); - // The UI guest shows a minimap (`render.set-minimap`). - assert_eq!(level("horizon_mods_test_ui_guest.hmod"), LEVEL); + // The UI guest fills a browser panel (`browser`, level 6). + assert_eq!(level("horizon_mods_test_ui_guest.hmod"), 6); } #[test] @@ -866,7 +869,12 @@ capabilities = ["registries"] fn the_examples_test_scripts_pass() { let examples = Path::new(env!("CARGO_MANIFEST_DIR")).join("../horizon-mod-sdk/examples"); let mut ran = 0; - for (example, hmod) in [("coords-hud", "coords_hud"), ("welcome", "welcome")] { + let examples_and_files = [ + ("coords-hud", "coords_hud"), + ("welcome", "welcome"), + ("beacons", "beacons"), + ]; + for (example, hmod) in examples_and_files { for entry in std::fs::read_dir(examples.join(example).join("tests")).unwrap() { let path = entry.unwrap().path(); let script = Script::parse(&std::fs::read_to_string(&path).unwrap()).unwrap(); @@ -877,7 +885,24 @@ fn the_examples_test_scripts_pass() { ran += 1; } } - assert_eq!(ran, 4); + assert_eq!(ran, 5); +} + +/// Capability `world` without a world lent (the registry's trial run): +/// `get-block` finds nothing, `set-blocks` checks its count and queues. +#[test] +fn a_server_mod_without_a_world_reads_nothing() { + let mut game = TestGame::load(&mods_dir().join("beacons.hmod")).unwrap(); + game.join("Alex"); + let alex = game.players[0].clone(); + assert!(game.player_command(&alex, "ground")); + let out = game.drain(); + assert!( + out.iter() + .any(|o| matches!(o, Output::Reply { text, error: true, .. } + if text == "That block isn't loaded")), + "{out:?}" + ); } #[test] @@ -974,10 +999,12 @@ fn a_server_mod_runs_only_where_the_world_does() { let mut mods = Mods::load_for(Runs::Server, paths, |_| true, |c| c == "give"); assert!(mods.runs_server()); - assert_eq!( - mods.server_commands().collect::>(), - ["online", "mined"] - ); + let commands: Vec<_> = mods.server_commands().map(|c| c.name.as_str()).collect(); + assert_eq!(commands, ["online", "mined"]); + // `/mined [player]`: its argument travels with it, for the command tree. + let mined = mods.server_commands().nth(1).unwrap(); + assert_eq!(mined.arguments[0].kind, horizon_mods::ArgumentKind::Player); + assert!(mined.arguments[0].optional); assert_eq!(mods.commands().count(), 0, "not the window's chat commands"); let alex = alex(); mods.set_snapshot(Snapshot { @@ -1016,3 +1043,247 @@ fn a_server_mod_runs_only_where_the_world_does() { "a server command isn't the window's" ); } + +/// Capability `recipes`: the guest reads tables as big as vanilla's (1,500 +/// items, 1,600 recipes of nine five-item slots) within one command's fuel. +#[test] +fn recipes_reads_the_tables() { + use horizon_mods::{Recipe, RecipeItem, RecipeKind, RecipeStack, Recipes}; + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + let stack = |item| RecipeStack { + item, + count: 1, + components: String::new(), + }; + let items = (0..1500) + .map(|i| RecipeItem { + id: format!("minecraft:item_{i}"), + name: format!("Item {i}"), + tags: vec!["planks".into(), "logs".into()], + }) + .collect(); + let mut recipes: Vec = (0..1600) + .map(|i| Recipe { + id: format!("minecraft:recipe_{i}"), + kind: RecipeKind::CraftingShaped, + category: "crafting_misc".into(), + group: String::new(), + width: 3, + height: 3, + slots: (0..9) + .map(|k| (0..5).map(|j| stack((i + k + j) % 1500)).collect()) + .collect(), + results: vec![RecipeStack { + item: 7, + count: 4, + components: String::new(), + }], + cooking_time: 0, + experience: 0.0, + book_id: i as i32, + }) + .collect(); + recipes[1].kind = RecipeKind::Brewing; + recipes[1].results[0].components = + "[minecraft:potion_contents={potion:\"minecraft:swiftness\"}]".into(); + let mods_recipes = Some(std::sync::Arc::new(Recipes { items, recipes })); + mods.set_snapshot(Snapshot { + recipes: mods_recipes.clone(), + known_recipes: vec![1, 5, 9].into(), + ..Snapshot::default() + }); + let said = |mods: &mut Mods, command: &str| { + assert!(mods.command(command)); + mods.drain() + .into_iter() + .filter_map(|o| match o { + Output::Chat { text, .. } => Some(text), + _ => None, + }) + .collect::>() + }; + assert_eq!( + said(&mut mods, "recipes"), + ["1500 items, 1600 recipes, 3 known, 1 brewing"] + ); + assert_eq!( + said(&mut mods, "recipes minecraft:recipe_1"), + [ + "minecraft:recipe_1 Kind::Brewing 3x3 0t slots 9, the first 1 minecraft:item_1 -> \ + 4 minecraft:item_7[minecraft:potion_contents={potion:\"minecraft:swiftness\"}] known true" + ] + ); + assert!( + mods.entries() + .iter() + .all(|e| e.status == horizon_mods::Status::Running), + "it ran out of fuel" + ); + // Actions: refused without a crafting screen, for an unknown recipe, + // and outside creative mode. + assert_eq!( + said(&mut mods, "recipe_place minecraft:recipe_5"), + ["place minecraft:recipe_5: no screen that takes recipes is open"] + ); + let mut snap = Snapshot { + recipes: mods_recipes.clone(), + known_recipes: vec![1, 5, 9].into(), + placing: true, + ..Snapshot::default() + }; + mods.set_snapshot(snap.clone()); + assert_eq!( + said(&mut mods, "recipe_place minecraft:recipe_6"), + ["place minecraft:recipe_6: recipe 6 is not in the player's recipe book"] + ); + assert!(mods.command("recipe_place minecraft:recipe_5 all")); + assert_eq!( + mods.drain()[0], + Output::PlaceRecipe { + book_id: 5, + all: true + } + ); + assert_eq!( + said(&mut mods, "recipe_give minecraft:item_7 3"), + ["give minecraft:item_7: only in creative mode"] + ); + snap.creative = true; + mods.set_snapshot(snap); + assert!(mods.command("recipe_give minecraft:item_7 3")); + assert_eq!( + mods.drain()[0], + Output::Give { + item: "minecraft:item_7".into(), + count: 3, + components: String::new() + } + ); + // Without the game's tables (no mod read them yet): empty, not a trap. + mods.set_snapshot(Snapshot::default()); + assert_eq!( + said(&mut mods, "recipes"), + ["0 items, 0 recipes, 0 known, 0 brewing"] + ); +} + +#[test] +fn browser_lists_items_and_hears_the_player() { + use horizon_mods::{BrowserClick, BrowserEvent, BrowserStack}; + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + let said = |mods: &mut Mods, command: &str| { + assert!(mods.command(command)); + mods.drain() + .into_iter() + .filter_map(|o| match o { + Output::Chat { text, .. } => Some(text), + _ => None, + }) + .collect::>() + }; + assert!(mods.browser_items().is_none()); + let potion = "[minecraft:potion_contents={potion:\"minecraft:swiftness\"}]"; + assert_eq!( + said( + &mut mods, + &format!("browser minecraft:stone minecraft:potion{potion}") + ), + ["panel of 2"] + ); + let (owner, version, items) = mods.browser_items().unwrap(); + assert_eq!( + (items[0].item.as_str(), items[1].components.as_str()), + ("minecraft:stone", potion) + ); + mods.browser_event( + owner, + BrowserEvent::Clicked(BrowserClick { + index: 1, + right: true, + }), + ); + mods.browser_event(owner, BrowserEvent::Search("oak".into())); + let log = BrowserStack { + item: "minecraft:oak_log".into(), + count: 3, + components: String::new(), + }; + // R is the guest's `recipe`; X is none of its keys. + mods.browser_key("key.keyboard.r", &log); + mods.browser_key("key.keyboard.x", &log); + assert_eq!( + said(&mut mods, "browser_poll"), + [ + "3 events", + "clicked 1 right", + "search \"oak\"", + "key recipe on minecraft:oak_log x3" + ] + ); + // Each `set-items` is a new version; an empty list hides the panel. + said(&mut mods, "browser minecraft:dirt"); + assert_ne!(mods.browser_items().unwrap().1, version); + assert_eq!(said(&mut mods, "browser"), ["panel of 0"]); + assert!(mods.browser_items().is_none()); + // Recipes in the panel's place: the guest shows those making planks. + use horizon_mods::{BrowserLayout, Recipe, RecipeItem, RecipeKind, RecipeStack, Recipes}; + let item = |id: &str| RecipeItem { + id: id.into(), + name: id.into(), + tags: Vec::new(), + }; + let stack = |item| RecipeStack { + item, + count: 1, + components: String::new(), + }; + mods.set_snapshot(Snapshot { + recipes: Some(std::sync::Arc::new(Recipes { + items: vec![item("minecraft:oak_log"), item("minecraft:oak_planks")], + recipes: vec![Recipe { + id: "minecraft:oak_planks".into(), + kind: RecipeKind::CraftingShapeless, + category: "building".into(), + group: "planks".into(), + width: 0, + height: 0, + slots: vec![vec![stack(0)]], + results: vec![RecipeStack { + count: 4, + ..stack(1) + }], + cooking_time: 0, + experience: 0.0, + book_id: 1, + }], + })), + ..Snapshot::default() + }); + said(&mut mods, "browser minecraft:dirt"); + assert_eq!( + said(&mut mods, "browser_recipes minecraft:oak_planks"), + ["recipes shown: 1"] + ); + let page = mods.browser_recipes(owner).unwrap(); + assert_eq!(page.title, "Recipes for minecraft:oak_planks"); + assert_eq!( + (page.tabs[0].item.as_str(), page.tab), + ("minecraft:crafting_table", 0) + ); + let r = &page.recipes[0]; + assert_eq!( + (r.layout, r.width, r.height, r.action), + (BrowserLayout::Grid, 1, 1, Some(false)) + ); + assert_eq!( + (r.slots[0][0].item.as_str(), r.results[0].count), + ("minecraft:oak_log", 4) + ); + assert_eq!(said(&mut mods, "browser_recipes"), ["recipes shown: 0"]); + assert!(mods.browser_recipes(owner).is_none()); + // At most 256 events wait for a poll: the oldest go. + for _ in 0..300 { + mods.browser_event(owner, BrowserEvent::Page(1)); + } + assert_eq!(said(&mut mods, "browser_poll")[0], "256 events"); +} diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index 74fb64350..7a69346ab 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -6,10 +6,19 @@ //! `input`; `/zoom FACTOR SMOOTH TURN` tests `render.set-zoom`; //! `/corner` and `/readings` the calls the official extras mods use; //! `/raycast DISTANCE` says what `game.raycast` sees; `/quiet A;B` runs -//! lines with `command.run-quiet` (`/quiet_many N`: N of them). +//! lines with `command.run-quiet` (`/quiet_many N`: N of them). `/recipes` +//! counts what `recipes` reads; `/recipes ID` describes that recipe. +//! `/browser ID...` fills `browser`'s panel (`/browser N`: the first N +//! items, `/browser` alone empties it) and registers the keys `recipe` (R) +//! and `uses` (U); `/browser_poll` says what the player did on it; +//! `/browser_recipes ID` shows the recipes making ID (`/browser_recipes` +//! alone: the items again). `/recipe_place ID [all]` places that recipe +//! with `recipes.place`; `/recipe_give ITEM [COUNT]` gives with +//! `recipes.give`. use horizon_mod_sdk::{ - Mod, Registration, chat, command, game, + Mod, Registration, browser, chat, command, game, input::{self, Event}, + recipes, render::{self, FillShape, ItemShape, Point, QuadShape, Rect, Shape, SpriteShape, TextShape}, ui::{self, ItemWidget, ListWidget, Screen, TextWidget, Widget}, }; @@ -62,7 +71,11 @@ fn shapes() -> Vec { ] } -struct Guest; +struct Guest { + /// `/recipe_place ID [all] later`: placed on the first tick a crafting + /// screen is open. + pending: Option<(i32, bool, String)>, +} fn widgets() -> Vec { vec![ @@ -102,12 +115,19 @@ impl Mod for Guest { "raycast", "quiet", "quiet_many", + "recipes", + "browser", + "browser_poll", + "browser_recipes", + "recipe_place", + "recipe_give", "corner", "readings", ] .into_iter() - .fold(Registration::new(), Registration::command); - Ok((Guest, hooks)) + .fold(Registration::new(), Registration::command) + .on_tick(); + Ok((Guest { pending: None }, hooks)) } fn command(&mut self, name: &str, args: &str) -> Result, String> { match name { @@ -241,6 +261,203 @@ impl Mod for Guest { None => "no hit".into(), }); } + "recipes" => { + let items = recipes::items(); + let all = recipes::all(); + let known = recipes::known(); + let name = |s: &recipes::Stack| { + let id = items.get(s.item as usize).map_or("?", |i| i.id.as_str()); + format!("{} {id}{}", s.count, s.components) + }; + chat::show(&match all.iter().find(|r| r.id == args) { + Some(r) => format!( + "{} {:?} {}x{} {}t slots {}, the first {} -> {} known {}", + r.id, + r.kind, + r.width, + r.height, + r.cooking_time, + r.slots.len(), + r.slots + .first() + .and_then(|s| s.first()) + .map_or("-".into(), name), + r.results.first().map_or("-".into(), name), + known.contains(&r.book_id) + ), + None => format!( + "{} items, {} recipes, {} known, {} brewing", + items.len(), + all.len(), + known.len(), + all.iter() + .filter(|r| r.kind == recipes::Kind::Brewing) + .count() + ), + }); + } + "browser" => { + let stack = |item: &str| { + let (item, components) = match item.find('[') { + Some(at) => (&item[..at], &item[at..]), + None => (item, ""), + }; + browser::Stack { + item: item.into(), + count: 1, + components: components.into(), + } + }; + let items: Vec = match args.parse::() { + Ok(n) => recipes::items() + .iter() + .skip(1) + .take(n) + .map(|i| stack(&i.id)) + .collect(), + Err(_) => args.split_whitespace().map(stack).collect(), + }; + browser::set_items(&items); + input::register_key("recipe", "Show recipes", "key.keyboard.r")?; + input::register_key("uses", "Show uses", "key.keyboard.u")?; + chat::show(&format!("panel of {}", items.len())); + } + "browser_recipes" => { + let items = recipes::items(); + let id = |i: u32| { + items + .get(i as usize) + .map_or(String::new(), |x| x.id.clone()) + }; + let stack = |s: &recipes::Stack| browser::Stack { + item: id(s.item), + count: s.count, + components: s.components.clone(), + }; + let views: Vec = recipes::all() + .iter() + .filter(|r| !args.is_empty() && r.results.iter().any(|s| id(s.item) == args)) + .map(|r| { + use recipes::Kind; + let crafting = + matches!(r.kind, Kind::CraftingShaped | Kind::CraftingShapeless); + let shapeless = (r.slots.len() as u32).clamp(1, 3); + browser::RecipeView { + layout: match r.kind { + Kind::CraftingShaped | Kind::CraftingShapeless => { + browser::Layout::Grid + } + Kind::Stonecutting => browser::Layout::Single, + Kind::Smithing => browser::Layout::Smithing, + Kind::Brewing => browser::Layout::Brewing, + _ => browser::Layout::Cooking, + }, + width: if r.width == 0 { shapeless } else { r.width }, + height: if r.height == 0 { + (r.slots.len() as u32).div_ceil(3).max(1) + } else { + r.height + }, + slots: r + .slots + .iter() + .map(|s| s.iter().map(stack).collect()) + .collect(), + results: r.results.iter().map(stack).collect(), + note: if r.cooking_time > 0 { + format!("{} ticks", r.cooking_time) + } else { + String::new() + }, + action: crafting.then_some(r.kind == Kind::CraftingShaped), + } + }) + .collect(); + // A tab per layout shown, the first selected. + let mut tabs: Vec = Vec::new(); + for v in &views { + let icon = match v.layout { + browser::Layout::Grid => "minecraft:crafting_table", + browser::Layout::Cooking => "minecraft:furnace", + browser::Layout::Single => "minecraft:stonecutter", + browser::Layout::Smithing => "minecraft:smithing_table", + browser::Layout::Brewing => "minecraft:brewing_stand", + }; + if !tabs.iter().any(|t| t.item == icon) { + tabs.push(browser::Stack { + item: icon.into(), + count: 1, + components: String::new(), + }); + } + } + browser::set_recipes(&format!("Recipes for {args}"), &tabs, 0, &views); + chat::show(&format!("recipes shown: {}", views.len())); + } + "recipe_place" => { + let mut words = args.split_whitespace(); + let id = words.next().unwrap_or_default(); + let rest: Vec<&str> = words.collect(); + let all = rest.contains(&"all"); + let book = recipes::all() + .iter() + .find(|r| r.id == id) + .map(|r| r.book_id); + if let Some(b) = book.filter(|_| rest.contains(&"later")) { + self.pending = Some((b, all, id.to_owned())); + chat::show(&format!("place {id}: waiting")); + return Ok(None); + } + chat::show(&match book.map(|b| recipes::place(b, all)) { + Some(Ok(())) => format!("place {id}: ok"), + Some(Err(e)) => format!("place {id}: {e}"), + None => format!("place {id}: no such recipe"), + }); + } + "recipe_give" => { + let mut words = args.split_whitespace(); + let id = words.next().unwrap_or_default(); + let count = words.next().and_then(|c| c.parse().ok()).unwrap_or(1); + let item = recipes::items().iter().position(|i| i.id == id); + let result = item.map(|i| { + recipes::give(&recipes::Stack { + item: i as u32, + count, + components: String::new(), + }) + }); + chat::show(&match result { + Some(Ok(())) => format!("give {id}: ok"), + Some(Err(e)) => format!("give {id}: {e}"), + None => format!("give {id}: no such item"), + }); + } + "browser_poll" => { + let stack = |s: &browser::Stack| format!("{} x{}{}", s.item, s.count, s.components); + // A hook shows at most 8 chat lines: the count, then the first 7. + let events = browser::poll(); + chat::show(&format!("{} events", events.len())); + for event in events.into_iter().take(7) { + chat::show(&match event { + browser::Event::Clicked(c) => { + format!( + "clicked {} {}", + c.index, + if c.right { "right" } else { "left" } + ) + } + browser::Event::Search(text) => format!("search {text:?}"), + browser::Event::Key(k) => format!("key {} on {}", k.key, stack(&k.stack)), + browser::Event::SlotClicked(c) => { + format!("slot {} {} {}", c.recipe, c.slot, stack(&c.stack)) + } + browser::Event::Action(i) => format!("action {i}"), + browser::Event::Page(first) => format!("page {first}"), + browser::Event::Back => "back".into(), + browser::Event::Tab(i) => format!("tab {i}"), + }); + } + } // Clamped to (1, 10); the two after it shake nothing. "render_shake" => { render::shake(2.0, 99.0); @@ -251,6 +468,15 @@ impl Mod for Guest { } Ok(None) } + fn tick(&mut self, _tick: u64) { + if let Some((book, all, id)) = self.pending.take() { + match recipes::place(book, all) { + Err(e) if e.starts_with("no screen") => self.pending = Some((book, all, id)), + Ok(()) => chat::show(&format!("place {id}: ok")), + Err(e) => chat::show(&format!("place {id}: {e}")), + } + } + } fn ui_select(&mut self, id: u32, row: u32) { chat::show(&format!("selected {id}:{row}")); } diff --git a/crates/horizon-threads/src/lib.rs b/crates/horizon-threads/src/lib.rs index 90c8d128e..917c3b502 100644 --- a/crates/horizon-threads/src/lib.rs +++ b/crates/horizon-threads/src/lib.rs @@ -126,6 +126,38 @@ fn idle() -> bool { false } +/// Give back to the OS the memory the allocator holds free, after something +/// large was dropped: glibc keeps freed pages in the arena of the thread that +/// allocated them, and macOS in its zones until memory runs short. Nothing +/// elsewhere. +pub fn release_free_memory() { + release(); +} + +#[cfg(all(target_os = "linux", target_env = "gnu"))] +fn release() { + // SAFETY: returns free heap pages of every arena to the OS; no live + // allocation moves. + unsafe { + libc::malloc_trim(0); + } +} + +#[cfg(target_vendor = "apple")] +fn release() { + unsafe extern "C" { + fn malloc_zone_pressure_relief(zone: *mut std::ffi::c_void, goal: usize) -> usize; + } + // SAFETY: a null zone means every zone and a goal of 0 as much as it can; + // it frees only pages no allocation uses. + unsafe { + malloc_zone_pressure_relief(std::ptr::null_mut(), 0); + } +} + +#[cfg(not(any(all(target_os = "linux", target_env = "gnu"), target_vendor = "apple")))] +fn release() {} + #[cfg(test)] mod tests { /// The hint holds on the platforms that take it. diff --git a/crates/horizon-world/src/loot.rs b/crates/horizon-world/src/loot.rs index f98afa21f..399c76f69 100644 --- a/crates/horizon-world/src/loot.rs +++ b/crates/horizon-world/src/loot.rs @@ -154,6 +154,8 @@ pub struct LootEntity { pub captain: Option, /// A frog's variant id (`minecraft:warm`). pub frog_variant: Option, + /// A chicken's variant id (`minecraft:warm`). + pub chicken_variant: Option, /// A charged creeper (`Creeper.isPowered`). pub powered: bool, /// Worn and held items by `EquipmentSlot` name (mainhand, offhand, @@ -862,6 +864,9 @@ impl Context<'_, R> { "minecraft:frog/variant" => { e.frog_variant.is_some() && want.as_str() == e.frog_variant.as_deref() } + "minecraft:chicken/variant" => { + e.chicken_variant.is_some() && want.as_str() == e.chicken_variant.as_deref() + } _ => false, }), "minecraft:type_specific/sheep" => e diff --git a/crates/horizon-world/src/worldgen/decoration_order.rs b/crates/horizon-world/src/worldgen/decoration_order.rs index 6b0fb2252..0e53e7d09 100644 --- a/crates/horizon-world/src/worldgen/decoration_order.rs +++ b/crates/horizon-world/src/worldgen/decoration_order.rs @@ -29,7 +29,7 @@ //! overlap), so a chunk may be decorated as soon as no lower-ranked chunk //! within two of it is still waiting: [`DecorationOrder::blocked`]. Chunks //! further apart still decorate in parallel. -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; #[derive(Default)] pub struct DecorationOrder { @@ -121,7 +121,6 @@ fn ticket_hash(x: i32, z: i32) -> u64 { /// The chunks decorated around a player at `center`, in vanilla's order. pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { use std::cmp::Reverse; - use std::collections::{BinaryHeap, VecDeque}; let mut tickets: Vec<(i32, i32)> = (-radius..=radius) .flat_map(|dx| (-radius..=radius).map(move |dz| (center.0 + dx, center.1 + dz))) .collect(); @@ -132,16 +131,31 @@ pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { Reverse(ticket_hash(x, z) & (TICKET_SET_CAPACITY - 1)), ) }); - let mut tickets: VecDeque<_> = tickets.into(); // Every chunk this touches lies within `half` of the centre: tickets // reach `LIGHT_LEVEL - TICKET_LEVEL` further, and FULL tasks decorate - // one more ring. Dense grids over that square replace hash maps. + // one more ring. + let half = radius.max(0) + LIGHT_LEVEL - TICKET_LEVEL + 1; + ticket_order( + tickets.into(), + TICKETS_IN_FLIGHT, + (center.0 - half, center.1 - half), + (2 * half + 1) as usize, + ) +} + +/// The decoration order of `tickets` (level 31) added in turn, at most +/// `in_flight` at a time. Dense grids of `side` chunks from `origin` hold +/// every chunk this touches, in place of hash maps. +fn ticket_order( + mut tickets: VecDeque<(i32, i32)>, + in_flight: usize, + origin: (i32, i32), + side: usize, +) -> Vec<(i32, i32)> { + use std::cmp::Reverse; + use std::collections::BinaryHeap; let reach = LIGHT_LEVEL - TICKET_LEVEL; - let half = radius.max(0) + reach + 1; - let side = (2 * half + 1) as usize; - let cell = |(x, z): (i32, i32)| { - ((x - center.0 + half) as usize) * side + (z - center.1 + half) as usize - }; + let cell = |(x, z): (i32, i32)| ((x - origin.0) as usize) * side + (z - origin.1) as usize; let mut active: Vec<(i32, i32)> = Vec::new(); // Queued task per chunk (level, sequence), `NONE` when there is none; // stale heap entries are skipped. @@ -177,10 +191,9 @@ pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { } } }; - for _ in 0..TICKETS_IN_FLIGHT { - if let Some(t) = tickets.pop_front() { - add(t, &mut active, &mut queued, &mut heap, &full); - } + while active.len() < in_flight { + let Some(t) = tickets.pop_front() else { break }; + add(t, &mut active, &mut queued, &mut heap, &full); } while let Some(Reverse((l, s, chunk))) = heap.pop() { let i = cell(chunk); @@ -202,7 +215,7 @@ pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { full[i] = true; } active.retain(|t| !(-2..=2).all(|dx| (-2..=2).all(|dz| full[cell((t.0 + dx, t.1 + dz))]))); - while active.len() < TICKETS_IN_FLIGHT { + while active.len() < in_flight { let Some(t) = tickets.pop_front() else { break }; add(t, &mut active, &mut queued, &mut heap, &full); } @@ -210,10 +223,36 @@ pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { order } +/// The chunks `/forceload add` over chunks `(x0, z0)..=(x1, z1)` decorates, +/// in vanilla's order: ForceLoadCommand adds a FORCED ticket (level 31) per +/// chunk, x-outer, z-inner, all at once. +pub fn forced_order(x0: i32, z0: i32, x1: i32, z1: i32) -> Vec<(i32, i32)> { + let tickets = (x0..=x1) + .flat_map(|x| (z0..=z1).map(move |z| (x, z))) + .collect(); + let pad = LIGHT_LEVEL - TICKET_LEVEL + 1; + let side = ((x1 - x0).max(z1 - z0) + 2 * pad + 1) as usize; + ticket_order(tickets, usize::MAX, (x0 - pad, z0 - pad), side) +} + #[cfg(test)] mod tests { use super::*; + /// Seed 8675309's geodes in chunks (-26, -1) and (14, -20) run into the + /// trial chambers of (-26, 0) and (14, -19); vanilla decorates the lower + /// z first, wherever the batch lies, so the chambers are drawn over them. + #[test] + fn forced_chunks_decorate_x_outer_z_inner() { + let rank = |order: &[(i32, i32)], c| order.iter().position(|&o| o == c).unwrap(); + let west = forced_order(-32, -16, -17, -1); + assert!(rank(&west, (-26, -1)) < rank(&west, (-26, 0))); + let east = forced_order(0, -32, 15, -17); + assert!(rank(&east, (14, -20)) < rank(&east, (14, -19))); + assert_eq!(west[0], (-33, -17)); + assert_eq!(west.len(), 22 * 22); + } + /// The hash map version this module had before its dense grids. fn hashed_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { use std::cmp::Reverse; diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 7a38608be..f3bf7cab7 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -23,6 +23,7 @@ use super::{ climate::{ClimateSampler, decode_parameter, quantize}, decode_noise, density::DensityRegistry, + generator_structures::Starts, material_condition::{ MaterialConditionRegistry, MaterialConditions, MaterialDensitySources, MaterialRule, MaterialRuleError, MaterialRuleLibrary, MaterialSurfaceQueries, @@ -567,6 +568,9 @@ pub struct ProtoChunk { pub block_entities: Vec<([i32; 3], crate::nbt::Compound)>, /// Structure starts referencing this chunk (STRUCTURE_REFERENCES). pub(super) structure_starts: Vec>, + /// The starts made in this chunk (STRUCTURE_STARTS), also those none of + /// whose pieces reach it (a giant ruined portal next door). + own_starts: Starts, /// Entities placed by structures (`ProtoChunk.addEntity`), as NBT with /// absolute `Pos`. pub entities: Vec, @@ -620,12 +624,7 @@ impl ProtoChunk { } /// The structure starts this chunk holds itself (`structures.starts`). pub fn own_starts(&self) -> Vec> { - let pos = self.position(); - self.structure_starts - .iter() - .filter(|s| s.chunk == pos) - .cloned() - .collect() + self.own_starts.to_vec() } /// Also restores a saved proto chunk that was decorated before it was saved. pub fn set_decorated(&mut self) { @@ -1114,16 +1113,19 @@ where ) .map_err(stage("noise"))?; chunk.set_generation_stage(PreLightChunkStage::Biomes); - let references = match &self.structures { - Some(structures) => structures.references( - &mut StructureQueries { + let (references, own_starts) = match &self.structures { + Some(structures) => { + let mut queries = StructureQueries { pipeline: self, worker, valid: BTreeSet::new(), - }, - pos, - ), - None => Vec::new(), + }; + ( + structures.references(&mut queries, pos), + structures.starts_at(&mut queries, pos), + ) + } + None => (Vec::new(), Starts::default()), }; if let Some(beard) = self .structures @@ -1259,6 +1261,7 @@ where decorated: false, block_entities: Vec::new(), structure_starts: references, + own_starts, entities: Vec::new(), }) } @@ -1648,6 +1651,22 @@ pub(super) struct WorkerState { heights: HashMap<(i32, i32, u8), i32>, /// Decorate with structure pieces only (for structure parity checks). pub(super) structures_only: bool, + pub(super) structure_mobs: Option>, +} +/// `Mob.finalizeSpawn(level, difficulty, STRUCTURE, null)` of the entities a +/// structure places with finalizeEntities, run by the game, which owns mobs. +pub trait StructureMobs: Send + Sync { + /// Finalizes the entity in `nbt` if it is a mob, drawing from the + /// region's random. `biome` is the biome at its block, `structures` the + /// structures with a piece there. False when it could not: the entity + /// keeps its `horizon:finalize` for the game to finish on load. + fn finalize( + &self, + nbt: &mut crate::nbt::Compound, + biome: &str, + structures: &[String], + random: &mut dyn super::structure::legacy::PieceRandom, + ) -> bool; } trait SeededPipeline: Send + Sync { @@ -2464,6 +2483,7 @@ impl OverworldGenerator { carver_biomes: HashMap::new(), timings: StageTimings::default(), structures_only: false, + structure_mobs: None, heights: HashMap::new(), }, } @@ -2590,6 +2610,9 @@ impl GeneratorWorker { pub fn set_structures_only(&mut self, only: bool) { self.state.structures_only = only; } + pub fn set_structure_mobs(&mut self, mobs: Arc) { + self.state.structure_mobs = Some(mobs); + } } #[cfg(test)] @@ -2975,6 +2998,26 @@ mod tests { } } + /// Seed 8675309's giant ruined portal starts in chunk (-26, 23) and lies + /// wholly in (-26, 24): its own chunk still holds the start, as vanilla's + /// getAllStarts does, though no piece reaches it. + #[test] + fn a_chunk_holds_its_starts_whose_pieces_lie_elsewhere() { + let Some(data) = prepared_data() else { + return; + }; + let generator = OverworldGenerator::new(data, 8675309).expect("generator"); + let mut worker = generator.worker(); + let proto = worker + .generate_proto(ChunkPos::new(-26, 23)) + .expect("proto"); + let own: Vec<_> = proto.own_starts().iter().map(|s| s.name.clone()).collect(); + assert!( + own.iter().any(|n| n == "minecraft:ruined_portal_mountain"), + "{own:?}" + ); + } + /// Chunks no ring search can end near are decided without the rings, /// which stay unsearched, and get the starts they get with them. #[test] diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs index fc1cd8bcf..0f3ea6810 100644 --- a/crates/horizon-world/src/worldgen/generator_decoration.rs +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -310,6 +310,7 @@ impl Decoration { Err(e) => return Err(resource(e.to_string())), }; let structures_only = worker.structures_only; + let references = region[4].structure_starts.clone(); let mut block_entities = Vec::new(); for chunk in region.iter_mut() { block_entities.append(&mut chunk.block_entities); @@ -318,6 +319,9 @@ impl Decoration { block_entities, entities: Vec::new(), level_random, + structure_mobs: worker.structure_mobs.clone(), + starts: references.clone(), + biome_names: data.biome_names(), blocks: data .feature_resources .as_ref() @@ -334,7 +338,6 @@ impl Decoration { }; let mut stats = DecorateStats::default(); let blocks = self.blocks; - let references = region[4].structure_starts.clone(); // ChunkGenerator.getWritableArea: the chunk's minimum Y + 1 to its maximum Y. let chunk_box = BoundingBox::new( [center.x * 16, min_y + 1, center.z * 16], @@ -419,15 +422,11 @@ impl Decoration { } // WorldGenRegion.addFreshEntity: into the chunk holding the position. for nbt in std::mem::take(&mut world.entities) { - let Some(crate::nbt::Tag::List(p)) = nbt.get(&"Pos".into()) else { + let Some(at) = block_of(&nbt) else { continue; }; - let coord = |i: usize| match p.get(i) { - Some(crate::nbt::Tag::Double(b)) => f64::from_bits(*b).floor() as i32, - _ => 0, - }; - let index = ((coord(2) >> 4).wrapping_sub(center.z) + 1) * 3 - + (coord(0) >> 4).wrapping_sub(center.x) + let index = ((at[2] >> 4).wrapping_sub(center.z) + 1) * 3 + + (at[0] >> 4).wrapping_sub(center.x) + 1; if let Some(chunk) = usize::try_from(index).ok().and_then(|i| region.get_mut(i)) { chunk.entities.push(nbt); @@ -454,6 +453,9 @@ struct World<'a> { block_entities: Vec<([i32; 3], crate::nbt::Compound)>, entities: Vec, level_random: &'a mut dyn super::structure::legacy::PieceRandom, + structure_mobs: Option>, + starts: Vec>, + biome_names: &'a [Arc], blocks: Option<&'a BlockBehavior>, region: TerrainRegion<'static, GenBlockStates>, biomes: BiomeRegion, @@ -847,10 +849,57 @@ impl PlacementContext for World<'_> { (0..ny).all(|y| (0..nz).all(|z| shape.is_full(x as i32, y as i32, z as i32))) })) } - fn add_entity(&mut self, nbt: crate::nbt::Compound) -> Result<(), PlacementQueryError> { + fn add_entity(&mut self, mut nbt: crate::nbt::Compound) -> Result<(), PlacementQueryError> { + if let Some(mobs) = self.structure_mobs.clone() + && nbt.contains_key(&"horizon:finalize".into()) + { + let at = block_of(&nbt).unwrap_or([0; 3]); + let biome = self + .biome_identity(at) + .ok() + .and_then(|b| self.biome_names.get(b.0 as usize)) + .map_or("", |n| &**n) + .to_owned(); + let structures: Vec = self + .starts + .iter() + .filter(|s| s.pieces.iter().any(|p| p.bounding_box().is_inside(at))) + .map(|s| s.name.clone()) + .collect(); + if mobs.finalize(&mut nbt, &biome, &structures, self.level_random) { + nbt.remove(&"horizon:finalize".into()); + } + } self.entities.push(nbt); Ok(()) } + /// SpikeFeature.placeSpike: the crystal is a fresh entity of the region, + /// saved with the chunk. + fn spawn_end_crystal( + &mut self, + position: [f64; 3], + yaw: f32, + beam_target: Option<[i32; 3]>, + invulnerable: bool, + ) -> Result<(), PlacementQueryError> { + use crate::nbt::Tag; + let mut nbt = crate::nbt::Compound::new(); + nbt.insert("id".into(), Tag::String("minecraft:end_crystal".into())); + nbt.insert( + "Pos".into(), + Tag::List(position.iter().map(|v| Tag::Double(v.to_bits())).collect()), + ); + nbt.insert( + "Rotation".into(), + Tag::List(vec![Tag::Float(yaw.to_bits()), Tag::Float(0)]), + ); + nbt.insert("Invulnerable".into(), Tag::Byte(i8::from(invulnerable))); + nbt.insert("ShowBottom".into(), Tag::Byte(1)); + if let Some(b) = beam_target { + nbt.insert("beam_target".into(), Tag::IntArray(b.to_vec())); + } + self.add_entity(nbt) + } fn set_block_entity( &mut self, position: [i32; 3], @@ -1167,3 +1216,14 @@ impl PlacementContext for World<'_> { Ok(Some(false)) } } + +/// The block an entity's `Pos` is in. +fn block_of(nbt: &crate::nbt::Compound) -> Option<[i32; 3]> { + let Some(crate::nbt::Tag::List(p)) = nbt.get(&"Pos".into()) else { + return None; + }; + Some(std::array::from_fn(|i| match p.get(i) { + Some(crate::nbt::Tag::Double(b)) => f64::from_bits(*b).floor() as i32, + _ => 0, + })) +} diff --git a/crates/horizon-world/src/worldgen/structure/legacy.rs b/crates/horizon-world/src/worldgen/structure/legacy.rs index 785b5fb2e..19d121718 100644 --- a/crates/horizon-world/src/worldgen/structure/legacy.rs +++ b/crates/horizon-world/src/worldgen/structure/legacy.rs @@ -31,14 +31,19 @@ pub type Markers = Vec<(String, [i32; 3])>; pub trait PieceRandom: ProcessorRandom { fn boolean(&mut self) -> bool; fn double(&mut self) -> f64; + /// The concrete random, for callers that need all of `RandomSource`. + fn as_any(&mut self) -> &mut dyn std::any::Any; } -impl PieceRandom for R { +impl PieceRandom for R { fn boolean(&mut self) -> bool { self.next_boolean() } fn double(&mut self) -> f64 { self.next_double() } + fn as_any(&mut self) -> &mut dyn std::any::Any { + self + } } /// Object-safe world access for piece post-processing. diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index c44f27576..3956b6457 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -17,6 +17,8 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`, | `render` | [`render`](#render) | draw on your screen, shake and zoom the camera | | `input` | [`input`](#input) | see the keys you hold and your clicks, take over the use button on its own items and the mouse wheel, and add keys | | `players` | [`players`](#players) | see who is on the server and message them | +| `world` | [`world`](#world) | read and change the world's blocks | +| `recipes` | [`recipes`](#recipes) | read the game's recipes and items and which recipes you know, place recipes in your crafting grid and, in creative mode, give you items | ## World `horizon-mod` @@ -29,14 +31,14 @@ A client mod: runs in the player's game. A server mod (manifest `side = "server"`, `api = "0.3"`, experimental): runs where the world is simulated, on the dedicated server, a LAN host and single player's own server. -- Imports (what the game offers): `log`, `storage`, `players` +- Imports (what the game offers): `log`, `storage`, `players`, `world` - Exports (what the mod provides): `server-events` ## World `horizon-ui-mod` A mod with widgets (capability `ui`): the SDK builds every mod against this world. Mods built for `horizon-mod` alone (no `ui-events` export) still load and simply hear nothing of their widgets. -- Imports (what the game offers): `ui`, `render`, `input`, `log`, `game`, `chat`, `hud`, `storage`, `command` +- Imports (what the game offers): `ui`, `render`, `input`, `recipes`, `browser`, `log`, `game`, `chat`, `hud`, `storage`, `command` - Exports (what the mod provides): `ui-events`, `events` ## World `ui-host` @@ -53,6 +55,13 @@ The game's side of capability `render` (imports only). - Imports (what the game offers): `render`, `input` - Exports (what the mod provides): +## World `recipes-host` + +The game's side of capability `recipes` (imports only). + +- Imports (what the game offers): `recipes`, `browser` +- Exports (what the mod provides): + ## `log` Access: always granted. @@ -461,6 +470,160 @@ What the game calls. Only the hooks `init` asks for are ever called. | `command` | `func(name: string, args: string) -> result, string>` | `/name args`: ok(some(text)) is shown as feedback, err(text) in red. | | `chat` | `func(text: string)` | Each chat line the player receives, as plain text. | +## `recipes` + +Access: capability `recipes`. + +Capability `recipes` (experimental): the recipes and items the game knows, for recipe viewers. In single player and on Horizon's servers they are the world's; on any other server they are vanilla 26.3's (a client is sent no others), while `known` follows that server's book. + +### record `stack` + +An item of `items`, by its index there, with a count and the components it has beyond the item's own, in vanilla's item syntax (`[potion_contents={potion:"minecraft:swiftness"}]`), or "". + +| Field | Type | | +| --- | --- | --- | +| `item` | `u32` | | +| `count` | `u32` | | +| `components` | `string` | | + +### enum `kind` + +The station a recipe is made at. + +| Case | | +| --- | --- | +| `crafting-shaped` | | +| `crafting-shapeless` | | +| `smelting` | | +| `blasting` | | +| `smoking` | | +| `campfire` | | +| `stonecutting` | | +| `smithing` | | +| `brewing` | | + +### record `recipe` + +| Field | Type | | +| --- | --- | --- | +| `id` | `string` | `minecraft:oak_planks`. | +| `kind` | `kind` | | +| `category` | `string` | The recipe book's tab (`crafting_building_blocks`, `furnace_food`), or "". | +| `group` | `string` | Recipes the book shows on one button share a group, or "". | +| `width` | `u32` | A shaped recipe's grid: `slots` holds its cells row by row. 0 for the other kinds. | +| `height` | `u32` | | +| `slots` | `list>` | Each slot's stacks, any one of which fits; an empty list is an empty cell. Cooking and stonecutting: the input. Smithing: the template, the base, the addition. Brewing: the bottle, the reagent. | +| `results` | `list` | What it makes; several when that varies (a trim on any armour). | +| `cooking-time` | `u32` | Cooking: game ticks and experience; 0 for the other kinds. | +| `experience` | `f32` | | +| `book-id` | `s32` | The recipe book's id for it (one per way the book shows it), as `known` lists them; -1 for the kinds the book doesn't show (campfire, stonecutting, smithing, brewing). | + +### record `item` + +| Field | Type | | +| --- | --- | --- | +| `id` | `string` | `minecraft:diamond`, `:`. | +| `name` | `string` | In the player's language. | +| `tags` | `list` | Its item tags, without the `#`. | + +| Function | Signature | What it does | +| --- | --- | --- | +| `items` | `func() -> list` | Every item, in the registry's order: `stack.item` indexes this list. | +| `all` | `func() -> list` | Every recipe: the book's in its order, then campfire, stonecutting, smithing and brewing. They don't change while a world is open. | +| `known` | `func() -> list` | The `book-id`s of the recipes the player's recipe book holds now. | +| `place` | `func(book-id: s32, all: bool) -> result<_, string>` | Places a recipe in the open screen's grid as a click in the recipe book does (`ServerboundPlaceRecipePacket`): the inventory's grid or a crafting table. `all` places as many as the items allow, as with Shift. Refused while no such screen is open, for a recipe the player's book doesn't hold and for one that can't be placed; one missing items shows as a ghost in the grid, as in the book. | +| `give` | `func(stack: stack) -> result<_, string>` | Creative mode only: gives the player the stack, as taking it from the creative inventory does (`ServerboundSetCreativeModeSlot`): the selected slot first, then the hotbar, then the inventory. The count is cut to one stack of the item (64, 16 or 1). | + +## `browser` + +Access: not granted by any capability. + +Capability `ui` (experimental): a recipe viewer's panel beside the game's inventory and container screens (not the creative inventory), on the right of the screen. The game draws it with its own widgets and slots, pages it and keeps its search box; the mod says what it holds. The first loaded mod with a panel shows. + +### record `stack` + +An item to show: its id, a count (1 draws none) and its components beyond the item's own, in vanilla's item syntax, or "". + +| Field | Type | | +| --- | --- | --- | +| `item` | `string` | | +| `count` | `u32` | | +| `components` | `string` | | + +### record `click` + +A click on an item of the panel, by its index in `set-items`'s list. + +| Field | Type | | +| --- | --- | --- | +| `index` | `u32` | | +| `right` | `bool` | | + +### record `item-key` + +A key the mod registered (`input.register-key`) went down while the pointer was on an item: a slot of the screen's, or the panel's. + +| Field | Type | | +| --- | --- | --- | +| `key` | `string` | | +| `stack` | `stack` | | + +### record `slot-click` + +A click on a slot of a recipe the panel shows (`set-recipes`). + +| Field | Type | | +| --- | --- | --- | +| `recipe` | `u32` | The recipe's index in `set-recipes`'s list and the slot's in it; the results come after the slots. | +| `slot` | `u32` | | +| `stack` | `stack` | The stack the slot showed at that moment. | +| `right` | `bool` | | + +### variant `event` + +| Case | Payload | | +| --- | --- | --- | +| `clicked` | `click` | | +| `search` | `string` | The search box's text, each time the player changes it. | +| `key` | `item-key` | | +| `slot-clicked` | `slot-click` | | +| `action` | `u32` | The action button of the recipe at this index in `set-recipes`'s list. | +| `page` | `u32` | The player turned the recipes' page (`set-recipes`): the index of the first recipe now shown. | +| `back` | | The back button of `set-recipes`. | +| `tab` | `u32` | The player picked the tab at this index of `set-recipes`' tabs. | + +### enum `layout` + +How the game lays out a recipe of `set-recipes`. + +| Case | | +| --- | --- | +| `grid` | A crafting grid of `width` x `height` slots, an arrow and the result. | +| `cooking` | One input over a flame, an arrow and the result (furnaces, smokers, campfires). | +| `single` | One input, an arrow and the result (the stonecutter). | +| `smithing` | Template, base and addition, an arrow and the result. | +| `brewing` | A potion and an ingredient, an arrow and the result. | + +### record `recipe-view` + +A recipe to show. Each slot, and the result, cycles through its stacks, one a second; an empty slot shows nothing. + +| Field | Type | | +| --- | --- | --- | +| `layout` | `layout` | | +| `width` | `u32` | The grid's size (`grid` only), at most 3 x 3. | +| `height` | `u32` | | +| `slots` | `list>` | | +| `results` | `list` | | +| `note` | `string` | A short line under the recipe (a cooking time), or "". | +| `action` | `option` | The action button beside it: none, enabled, or shown greyed. | + +| Function | Signature | What it does | +| --- | --- | --- | +| `set-items` | `func(items: list)` | The panel's items, at most 8192 (an empty list hides the panel). | +| `set-recipes` | `func(title: string, tabs: list, tab: u32, recipes: list)` | Shows these recipes in the panel instead of its items, as many as fit a page, under `title` and a back button, with a row of `tabs` (each an icon; `tab` is the selected one) between them; an empty list of recipes shows the items again. At most 256 recipes and 16 tabs. | +| `poll` | `func() -> list` | What the player did on the panel since the last poll, at most 256 kept. | + ## `players` Access: capability `players`. @@ -495,6 +658,27 @@ Capability `players`, server mods only (manifest `api = "0.3"`, experimental): t | `tell` | `func(player: string, text: string) -> bool` | A system message to one player, after the mod's name; false when no player with that id is online. Up to 8 messages per call. | | `broadcast` | `func(text: string)` | A system message to every player and the server's log, after the mod's name. Counts toward the same 8 per call. | +## `world` + +Access: capability `world`. + +Capability `world`, server mods only (manifest `api = "0.3"`, experimental): the blocks of the server's loaded chunks, and changes to them through the server's own block updates. + +### record `block-change` + +| Field | Type | | +| --- | --- | --- | +| `x` | `s32` | | +| `y` | `s32` | | +| `z` | `s32` | | +| `state` | `string` | `minecraft:oak_log[axis=y]`; properties left out take the block's defaults, `minecraft:stone` alone is the default state. | + +| Function | Signature | What it does | +| --- | --- | --- | +| `get-block` | `func(dimension: string, x: s32, y: s32, z: s32) -> option` | The block state at a position in a dimension (`minecraft:overworld`, ...), as `minecraft:oak_log[axis=y]`, as of this call: none where the server has no chunk loaded there. | +| `get-biome` | `func(dimension: string, x: s32, y: s32, z: s32) -> option` | The biome at a position (`minecraft:plains`, ...), as the server stores it (one per 4 x 4 x 4 cell): none where no chunk is loaded. | +| `set-blocks` | `func(dimension: string, blocks: list) -> result<_, string>` | Sets blocks as `/setblock` does: the old block entity removed, neighbours and shapes updated, light, and every player told. Every state is checked now (an error queues nothing); the changes are made in order after this call returns, before that dimension's next tick; one in a chunk not loaded then is skipped. At most 4096 per call. | + ## `server-events` Access: exported by the mod: the game calls it. @@ -505,16 +689,6 @@ What the server calls in a server mod (manifest `api = "0.3"`, experimental). On `type player = player` -### record `registration` - -| Field | Type | | -| --- | --- | --- | -| `commands` | `list` | Commands players may type, without the slash. A name vanilla already uses is refused (vanilla's command runs). | -| `tick` | `bool` | Call `tick` every server tick (20 per second). | -| `joins` | `bool` | Call `player-joined` and `player-left`. | -| `chat` | `bool` | Call `chat` for each chat message a player sends. | -| `blocks` | `bool` | Call `block-broken` and `block-placed`. | - ### record `block-pos` | Field | Type | | @@ -523,6 +697,59 @@ What the server calls in a server mod (manifest `api = "0.3"`, experimental). On | `y` | `s32` | | | `z` | `s32` | | +### variant `argument-kind` + +What an argument of a command takes. The server sends each command and its arguments to players' games, whose chat box completes and colours them as vanilla's; the server parses them before the mod's `command` hook gets their values. + +| Case | Payload | | +| --- | --- | --- | +| `word` | | One word: letters, digits and `_ - . +`. | +| `text` | | The rest of the line, spaces included: only last. | +| `integer` | `tuple, option>` | A whole number, within the bounds given. | +| `number` | | A number with or without decimals. | +| `boolean` | | `true` or `false`. | +| `player` | | One online player: a name, or `@s` or `@p` (whoever typed it, as vanilla picks for a player). | +| `block-pos` | | A block position: three whole numbers, each one also `~` or `~n`, relative to whoever typed it. | + +### record `argument` + +| Field | Type | | +| --- | --- | --- | +| `name` | `string` | Shown in the chat box's hint (``) and the key of its value. | +| `kind` | `argument-kind` | | +| `optional` | `bool` | Optional arguments come after every required one. | + +### record `server-command` + +| Field | Type | | +| --- | --- | --- | +| `name` | `string` | Without the slash. A name vanilla already uses is refused (vanilla's command runs). | +| `arguments` | `list` | In order; none: the command takes nothing after its name. Free text is one optional `text` argument. | + +### variant `argument-value` + +An argument's value, parsed as its kind says. + +| Case | Payload | | +| --- | --- | --- | +| `word` | `string` | | +| `text` | `string` | | +| `integer` | `s32` | | +| `number` | `f64` | | +| `boolean` | `bool` | | +| `player` | `player` | | +| `block-pos` | `block-pos` | | + +### record `registration` + +| Field | Type | | +| --- | --- | --- | +| `commands` | `list` | Commands players may type. | +| `tick` | `bool` | Call `tick` every server tick (20 per second). | +| `joins` | `bool` | Call `player-joined` and `player-left`. | +| `chat` | `bool` | Call `chat` for each chat message a player sends. | +| `blocks` | `bool` | Call `block-broken` and `block-placed`. | + | Function | Signature | What it does | | --- | --- | --- | | `init` | `func() -> result` | Once, after loading. An error keeps the mod off and is logged. | @@ -530,6 +757,6 @@ What the server calls in a server mod (manifest `api = "0.3"`, experimental). On | `player-joined` | `func(player: player)` | A player joined the server; they are in `players.online` already. | | `player-left` | `func(player: player)` | A player left the server; they are no longer in `players.online`. | | `chat` | `func(player: player, text: string)` | A chat message a player sent, as plain text. | -| `command` | `func(player: player, name: string, args: string) -> result, string>` | `/name args` typed by `player`: ok(some(text)) is their feedback, err(text) their error in red. | +| `command` | `func(player: player, name: string, args: string, values: list>) -> result, string>` | `/name args` typed by `player`: ok(some(text)) is their feedback, err(text) their error in red. `values` holds each argument given, by name, in order (an optional one left out isn't there); a line that doesn't parse never reaches the mod: the player gets vanilla's error. | | `block-broken` | `func(player: player, pos: block-pos, state: string)` | A player broke the block at `pos` in their dimension: `state` is what was there, as `minecraft:oak_log[axis=y]`. | | `block-placed` | `func(player: player, pos: block-pos, state: string)` | A player placed `state` at `pos` in their dimension. | diff --git a/docs/api/mods.md b/docs/api/mods.md index 1fc7a834e..55f890cc1 100644 --- a/docs/api/mods.md +++ b/docs/api/mods.md @@ -18,7 +18,7 @@ the player before the mod is turned on, and checked against the component's real | Hooks a mod exports | 5: `init`, `tick`, `frame`, `command`, `chat`; a server mod 8: `init`, `tick`, `player-joined`, `player-left`, `chat`, `command`, `block-broken`, `block-placed` | | Capabilities | 6: `game-read`, `chat`, `hud`, `storage`, `registries`, `players` | | Manifest `api` lines served | 3: `0.1` (code), `0.2` (content), `0.3` (server mods, experimental) | -| SDK | the `Mod` trait (5 methods), `Registration` (4 builders), `export_mod!`, log helpers; `server::ServerMod` (8 methods), `server::Registration` (5 builders), `export_server_mod!` | +| SDK | the `Mod` trait (5 methods), `Registration` (4 builders), `export_mod!`, log helpers; `server::ServerMod` (8 methods), `server::Registration` (6 builders), `server::Argument`, `server::Args`, `export_server_mod!` | | `cargo horizon-mod` | `new` (templates `code` and `content`), `build`, `run`, `test`, `check` | | Example mods | `coords-hud` (code), `ruby-content` (content), `welcome` (server) | @@ -88,11 +88,11 @@ release. What real mods need next, in the order modpacks and servers need it: - **More for server mods** (`api = "0.3"`, [Server mods](../mods.md#server-mods-api-03-experimental)): they run - on the server thread, a LAN host and the dedicated server today, with joins, chat, commands and players' block - breaking and placing; next entity events, game rules, server commands with typed arguments sent to clients' - command trees. -- **World and blocks**: read blocks, block states and biomes in loaded chunks; change them through the server's block - log, so clients and the parity harnesses see vanilla's updates. + on the server thread, a LAN host and the dedicated server today, with joins, chat, typed commands in players' + command trees, players' block breaking and placing, and `world` (read blocks and biomes, set blocks as `/setblock` + does); next entity events, game rules, entity, item and block-state arguments. +- **World and blocks**: blocks, block states and biomes are there for server mods (`world`); next block entities, + and `world` for client mods (raycasts, single player and LAN hosts). - **Items and inventories**: the player's inventory, held item and open container; item stacks with components. - **Entities**: query and change entities near a position; spawn from a mod's own entity types (data first). - **Block entities and menus**: ticking machines with slots and their screens. @@ -106,6 +106,11 @@ What real mods need next, in the order modpacks and servers need it: ## Changelog +- API 0.3: typed server commands: `registration.commands` lists each command's arguments (`argument-kind`: word, + text, integer, number, boolean, player, block-pos), sent in players' command trees and parsed by the server; + `command` gets their values. SDK `Registration::command_with`, `Argument`, `Args`. +- API 0.3: capability `world` (`get-block`, `get-biome`, `set-blocks`); example `beacons`; test scripts' `blocks` and + `expect.blocks`. - Server mods run in the game: single player (server thread and in-frame), LAN hosts, the dedicated server. - API 0.3 (server mods, experimental): world `horizon-server-mod`, capability `players`, the `server-events` hooks; SDK `server::ServerMod`; example `welcome`. diff --git a/docs/api/stability.md b/docs/api/stability.md index df2c1aeb3..9911b79e9 100644 --- a/docs/api/stability.md +++ b/docs/api/stability.md @@ -38,7 +38,7 @@ don't import it); faster, or fixing behaviour to what the reference already says A new WIT function doesn't break older mods, but a mod that calls it can't run on a Horizon from before it. So every function the game offers mods has an **API level**, the one it arrived at (`crates/horizon-mods/src/api_level.rs`): -level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`, level 2 `game.raycast`, level 3 `command.run-quiet`. A mod needs the level of +level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`, level 2 `game.raycast`, level 3 `command.run-quiet`, level 4 server mods' `world`, level 5 `recipes` (`items`, `all`, `known`), level 6 `browser` (`set-items`, `poll`, `set-recipes`) and `recipes.place` and `recipes.give`. A mod needs the level of the newest function it imports (a component imports only the functions it calls). The level is read from the file, never declared: @@ -108,7 +108,7 @@ Deprecations and breaking changes are in bold. The release notes of the game rel | Mod API: `render` (HUD shapes, camera shake and zoom; drawn by the game, no mod shaders) | experimental | manifest `experimental = ["render"]` | | Mod API: `input` (claimed items' use, the mod's keys, the mouse wheel) | experimental | manifest `experimental = ["input"]` | | Content mods (`registries`: data-driven blocks and items) | preview | manifest `api = "0.2"` | -| Server mods: world `horizon-server-mod`, `players`, `server-events` | experimental | manifest `api = "0.3"` | +| Server mods: world `horizon-server-mod`, `players`, `server-events`, `world`, typed `server-command`s | experimental | manifest `api = "0.3"` | | Script mods (Lua run by an interpreter mod, [mods.md](mods.md#ways-in)) | not started | | | `cargo horizon-mod` (`new`, `build`, `run`), `horizon-mod-sdk` | preview | 0.1.0 | | Shader API | not started | | diff --git a/docs/architecture.md b/docs/architecture.md index 0350bd1ea..3aec2338b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -5,8 +5,9 @@ counted only for the game loop because nearly every gameplay change touches it). organised and how to build and test are in [AGENTS.md](../AGENTS.md). Paths: `L/` = `crates/horizon-client/src/`, `G/` = `crates/horizon-client/src/game/`, `W/` = -`crates/horizon-world/src/`. Checks: a bare name is a harness (`python3 tools/parity.py `, script -`tools/test__parity.py`); `lan_e2e ` is `python3 tools/lan_e2e.py --check `. +`crates/horizon-world/src/`, `K/` = `crates/horizon-client-core/src/`, `C/` = `crates/horizon-command/src/`. +Checks: a bare name is a harness (`python3 tools/parity.py `, script `tools/test__parity.py`); +`lan_e2e ` is `python3 tools/lan_e2e.py --check `. For the full set of harnesses a file can affect, ask the runner: `printf '%s\n' > /tmp/p.txt && python3 tools/parity.py --changed-files /tmp/p.txt --list`. @@ -17,7 +18,7 @@ file selects ~103. |---|---|---|---| | 1 | Game loop, tick order, frame pacing (554) | `L/game.rs` (`fn tick`, `fn tick_world`, `fn render`, `about_to_wait`), `L/clock.rs`, `L/window.rs`, `L/spans.rs` | game_loop, frame_limiter, interaction_input, tick | | 2 | Mobs in the game loop, spawning (166) | `G/creatures.rs`, `G/natural_spawning.rs`, `L/mobs/spawning.rs`, `L/mobs/spawn_rules.rs`, `L/mobs/spawn_selection.rs`, `L/mobs/finalize.rs`, `G/spawner.rs`, `G/trial_spawner.rs` | natural_spawn, spawn_rules, finalize_spawn, spawner, trial_spawner, mob_ai | -| 3 | World save and load (163) | `L/save.rs`, `G/saving.rs`, `G/persist.rs` (entities), `L/entity_nbt.rs`, `L/block_entity_nbt.rs`, `W/region.rs`, `W/nbt.rs` | save_roundtrip, world_reopen, world, datafix | +| 3 | World save and load (163) | `L/save.rs`, `G/saving.rs`, `G/persist.rs` (entities), `L/entity_nbt.rs`, `K/block_entity_nbt.rs`, `W/region.rs`, `W/nbt.rs` | save_roundtrip, world_reopen, world, datafix | | 4 | World generation (153) | `W/worldgen.rs`, `W/worldgen/` (`generator*.rs`, `feature_graph.rs`, `structure/`, `placement/`), `L/vanillagen.rs` | chunk_generation, worldgen, server_world_gen, world_spawn, feature_graph, feature_placement, decoration and the other worldgen harnesses | | 5 | Multiplayer client, packets in (145) | `G/remote.rs` (`fn handle_packet`, `fn tick_remote`), `G/remote_*.rs`, `L/net.rs` | dedicated_server, server_entities, lan_e2e (all) | | 6 | Agent control, horizon-ctl (145) | `L/control.rs`, `L/bin/horizon-ctl/`, `G/control.rs`, `G/agent.rs`, `G/events.rs`, `G/ui_control.rs` | `python3 tools/agent_control_e2e.py`; `cargo test -p horizon-client --bin horizon-ctl` | @@ -32,7 +33,7 @@ file selects ~103. | 15 | Items and item use (96) | `L/items.rs`, `L/item_data.rs`, `G/hand.rs`, `G/consume.rs`, `G/potions.rs`, `L/effects.rs`; game.rs `fn use_hand`, `fn use_item` | use_item_on, item_use, item_use_lifecycle, consumable, consume_effect, status_effect | | 16 | Options and settings screens (93) | `L/options_ui.rs`, `G/options.rs`, `L/settings.rs`, `L/options_file.rs`, `L/graphics_ui.rs`, `L/graphics.rs` | options, toggle_keys | | 17 | HUD, chat, tab list (93) | `L/hud.rs`, `L/hud_layout.rs`, `L/hud_overlays.rs`, `L/chat.rs`, `G/chat.rs`, `L/tab_list.rs`, `L/locator_bar.rs`, `G/locator_bar.rs` | hud, tab_list, locator_bar, chat_screen, secure_chat | -| 18 | Command execution (88) | `G/commands.rs`, `G/commands/*.rs`, `L/scoreboard_cmd.rs`, `L/data_cmd.rs`, `G/functions.rs` | command_exec (corpus `tools/command_exec_corpus.py`), scoreboard, server_ops_feedback, lan_e2e commands | +| 18 | Command execution (88) | `G/commands.rs`, `G/commands/*.rs`, `L/scoreboard_cmd.rs`, `L/data_cmd.rs`, `K/scoreboard.rs`, `G/functions.rs` | command_exec (corpus `tools/command_exec_corpus.py`), scoreboard, server_ops_feedback, lan_e2e commands | | 19 | Chunk streaming, light, tickets (85) | `L/streaming.rs`, `L/world.rs`, `L/chunk.rs`, `L/chunk_map.rs`, `L/light.rs`, `L/ticket_levels.rs`, `L/tick_chunk_membership.rs`, `G/world_loading.rs` | light, chunk_status, random_tick_sections; `cargo test -p horizon-client --test streaming_meshes` | | 20 | Mob models and animation (78) | `L/mobs/render.rs`, `L/mobs/anim.rs`, `L/mobs/body_anim.rs`, `L/mobs/keyframes.rs`, `L/entity.wgsl` | entity_model | | 21 | Block behaviour, server side (78) | `W/level/` (`mod.rs`, `tick.rs`, `hooks.rs`, `data.rs`, `redstone.rs`, `place.rs`), `G/block_entity_ticks.rs`, `G/moving_pistons.rs` | block_update, redstone, random_tick, simple_block, piston_movement, block_entity_tickers | @@ -46,12 +47,12 @@ file selects ~103. | 29 | Title, worlds, startup (49) | `L/title.rs` + `L/title/`, `G/startup_menu.rs`, `L/title_edition.rs` | world_options; `cargo test -p horizon-client --lib title` | | 30 | Dedicated server, horizon-server (48) | `G/dedicated.rs`, `G/dedicated/status.rs`, `crates/horizon-server/`, `crates/horizon-server-files/` | dedicated_server, server_files, user_cache, online_mode, server_ops_feedback | | 31 | Particles and client effects (46) | `L/particles.rs`, `G/render_tick.rs`, `G/level_particles.rs`, `L/animate_tick.rs` | particle_providers, block_particles, entity_particles, emitter_particles, marker_particles | -| 32 | Bosses and the End (45) | `G/dragon.rs`, `G/wither.rs`, `G/end.rs` | server_dragon, end_podium, end_gateway | +| 32 | Bosses and the End (45) | `G/dragon.rs`, `G/wither.rs`, `G/end.rs` | server_dragon, forced_end, end_podium, end_gateway | | 33 | Protocol and packets (44) | `crates/horizon-protocol/src/` (`packets/play.rs`, `entity_data.rs`, `connection.rs`) | dedicated_server, online_mode, secure_chat; `cargo test -p horizon-protocol` | | 34 | Multiplayer and LAN screens, friends (44) | `L/multiplayer.rs`, `G/lan_screen.rs`, `G/friends.rs`, `L/friends_screen.rs`, `crates/horizon-friends/`, `crates/horizon-relay/` | lan, world_options; `python3 tools/test_friends.py` | | 35 | Dispensers (43) | `G/dispenser.rs`, `G/dispense_fixture.rs` (the harness side) | dispenser | | 36 | Audio and music (38) | `L/audio.rs`, `L/sound_engine.rs`, `L/sound_events.rs`, `L/music.rs`, `G/music.rs`, `L/ambience.rs`, `G/subtitle_hud.rs` | sound_engine, sound_event, music, situational_music, ambient_sound, subtitle | | 37 | Integrated server and levels (34) | `G/integrated.rs`, `G/levels.rs`, `G/server_travel.rs` | server_dimension_players, `lan_e2e` (server-thread by default; portals, levels, distance, lava) | -| 38 | Command parsing (34) | `L/command/` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`) | command_parse (corpus `tools/command_parse_corpus.py`) | +| 38 | Command parsing (34) | `C/` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`); `cargo test -p horizon-command` | command_parse (corpus `tools/command_parse_corpus.py`) | | 39 | Benchmarks and telemetry (34) | `L/benchmark.rs`, `tools/perf_bench.py`, `L/telemetry.rs`, `crates/horizon-telemetry*/`, `crates/horizon-bench/` | `python3 -m unittest tests.test_perf_bench`; [benchmark.md](benchmark.md) | | 40 | Explosions and TNT (31) | `G/explosion.rs`, `G/tnt.rs` | lan_e2e blast; no dedicated harness yet | diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index 1e9fb7722..db3c6a03a 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -50,9 +50,11 @@ Start the client. horizon-launcher play +- `--instance`: The instance to play (its name or id; default: the selected one) - `--world`: Open or create this world (a folder under saves) at once - `--creative`: Creative mode for a new world - `--join`: Join a friend's world with its invite code +- `--server`: Join this server at once: an address, or a server of the list by name or position - `--arg`: An extra argument for the game, passed through as-is (repeatable), for example --server-thread MCP: `play`, then the `game_*` tools. @@ -257,6 +259,233 @@ Upload a benchmark report (docs/benchmark-report.md); it is printed first. MCP: `data_benchmark`, only when the player asks. +## `horizon-launcher instance list` + +The instances, each with its game folder (* = the one Play starts). + + horizon-launcher instance list + +MCP: `instance_list`. + +## `horizon-launcher instance create` + +Make an instance: empty but for your options and name, or a copy of another one's worlds, options and packs. + + horizon-launcher instance create + +- `NAME` +- `--copy`: The instance to copy (its name or id) + +MCP: `instance_create`. + +## `horizon-launcher instance rename` + +Rename an instance (its folder stays). + + horizon-launcher instance rename + +- `INSTANCE` +- `NAME` + +MCP: `instance_rename`. + +## `horizon-launcher instance icon` + +Set an instance's icon: a block or item name from your prepared files (grass_block), a colour (#3fa7d6), or none. + + horizon-launcher instance icon + +- `INSTANCE` +- `ICON` + +MCP: `instance_icon`. + +## `horizon-launcher instance group` + +Put an instance in a sidebar group, or take it out with no group. + + horizon-launcher instance group [GROUP] + +- `INSTANCE` +- `GROUP` + +MCP: `instance_group`. + +## `horizon-launcher instance select` + +Make Play start this instance. + + horizon-launcher instance select + +- `INSTANCE` + +MCP: `instance_select`. + +## `horizon-launcher instance version` + +Keep an instance on one installed Horizon version, or "latest" to follow updates again. + + horizon-launcher instance version + +- `INSTANCE` + +MCP: `instance_version`. + +## `horizon-launcher worlds list` + +The worlds: name, mode, version, last played and size (the default). + + horizon-launcher worlds list + +- `--instance`: The instance (default: the selected one) + +MCP: `worlds_list`. + +## `horizon-launcher worlds backup` + +Zip a world into the instance's backups/ folder, as the game's Make Backup does. + + horizon-launcher worlds backup + +- `WORLD`: Its folder or name +- `--instance` + +MCP: `worlds_backup`. + +## `horizon-launcher worlds copy` + +Copy a world beside it, as " (1)". + + horizon-launcher worlds copy + +- `WORLD` +- `--instance` + +MCP: `worlds_copy`. + +## `horizon-launcher worlds delete` + +Move a world to the system's trash. + + horizon-launcher worlds delete + +- `WORLD` +- `--instance` + +MCP: `worlds_delete`, needs `confirm: true`. + +## `horizon-launcher packs list` + +The resource and shader packs, and which are on (the default). + + horizon-launcher packs list + +- `--kind` (resource, shader): Only this kind +- `--instance`: The instance (default: the selected one) + +MCP: `packs_list`. + +## `horizon-launcher packs add` + +Copy a pack file in: a resource pack .zip, a shader pack .zip or a .hshader. + + horizon-launcher packs add + +- `FILE` +- `--instance` + +MCP: `packs_add`. + +## `horizon-launcher packs on` + +Turn a pack on (a resource pack goes on top; a shader pack replaces the one that was on). + + horizon-launcher packs on + +- `PACK`: Its file name or title +- `--kind` (resource, shader) +- `--instance` + +MCP: `packs_on`. + +## `horizon-launcher packs off` + +Turn a pack off. + + horizon-launcher packs off + +- `PACK` +- `--kind` (resource, shader) +- `--instance` + +MCP: `packs_off`. + +## `horizon-launcher packs remove` + +Turn a pack off and move it to the system's trash. + + horizon-launcher packs remove + +- `PACK` +- `--kind` (resource, shader) +- `--instance` + +MCP: `packs_remove`, needs `confirm: true`. + +## `horizon-launcher screenshots list` + +The screenshots, the newest first, with their files (the default). + + horizon-launcher screenshots list + +- `--instance`: The instance (default: the selected one) + +MCP: `screenshots_list`. + +## `horizon-launcher screenshots delete` + +Move a screenshot to the system's trash. + + horizon-launcher screenshots delete + +- `SCREENSHOT`: Its file name, with or without .png +- `--instance` + +MCP: `screenshots_delete`, needs `confirm: true`. + +## `horizon-launcher multiplayer list` + +The servers of the game's Multiplayer screen (the default). + + horizon-launcher multiplayer list + +- `--instance`: The instance (default: the selected one) + +MCP: `multiplayer_list`. + +## `horizon-launcher multiplayer add` + +Add a server to the list. + + horizon-launcher multiplayer add
+ +- `ADDRESS`: Its address, as in the game's Add Server (host or host:port) +- `--name`: Its name in the list (default: Minecraft Server) +- `--instance` + +MCP: `multiplayer_add`. + +## `horizon-launcher multiplayer remove` + +Remove a server from the list: its position from 1, name or address. + + horizon-launcher multiplayer remove + +- `SERVER` +- `--instance` + +MCP: `multiplayer_remove`, needs `confirm: true`. + ## `horizon-launcher modpack list` The imported packs and their coverage (the default). diff --git a/docs/mods.md b/docs/mods.md index a68b6d123..d2f76ac5a 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -15,7 +15,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | The contract (WIT) | `crates/horizon-mod-sdk/wit/horizon.wit` | 0.1: log, game-read, chat, hud, storage, command, ui; tick, frame, chat and command hooks | | SDK for mod authors | `crates/horizon-mod-sdk` | 0.1 | | Example mods | `crates/horizon-mod-sdk/examples/coords-hud`, `examples/predator-missile` | coordinates, facing and time HUD, `/where`, `/coords`; `/missile`, a guided missile from vanilla commands | -| Horizon's official mods | `mods/official/` | the extras moving to the registry: FPS Counter (`fps-overlay`), Keystrokes, Zoom, Minimap | +| Horizon's official mods | `mods/official/` | the extras moving to the registry: FPS Counter (`fps-overlay`), Keystrokes, Zoom, Minimap; and Recipes, a recipe viewer | | Runtime | `crates/horizon-mods` | wasmtime 48 LTS, component model | | Authoring tool | `crates/cargo-horizon-mod` | `cargo horizon-mod new [--template code\|content] / build / run / test / check`, and the registry's CI (`registry build / review / list`) | | In the game | `crates/horizon-client/src/game/mods.rs`, Options > Mods | client mods | @@ -88,9 +88,10 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | `hud` | `hud` | `set-panel(corner, lines)`, `clear()`: up to 16 lines of 256 characters | | `storage` | `storage` | `get(key)`, `set(key, value)`, `delete(key)`: a per-mod folder of up to 64 files, 4 MiB total, at most 1 MiB written per call | | `command` | `command` | `run(line)`: a vanilla command run as the player, with the player's permissions, after the hook returns (8 per call); mods' own commands are not run. `run-quiet(lines)`: up to 256 a call, the same rights, nothing in the chat (single player and Horizon's servers run them 64 a tick and log one line a batch; elsewhere they go as chat commands and their feedback shows) | -| `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, item and list widgets the game lays out and draws with its own menus' code. **Experimental:** the manifest needs `experimental = ["ui"]` | +| `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, item and list widgets the game lays out and draws with its own menus' code; `browser.set-items`, `browser.poll`: a recipe viewer's panel of items right of the inventory and container screens (not the creative one), which the game pages and draws with its own slots and search box, and the mod hears its clicks, its searches and the mod's own keys (`input.register-key`) pressed over any item on the screen; `browser.set-recipes`: recipes in the panel's place (crafting grids, cooking, stonecutting, smithing and brewing layouts, their slots cycling through their stacks, a note and an action button each), paged by the game, with clicks on their slots, action buttons, page turns and a back button. **Experimental:** the manifest needs `experimental = ["ui"]` | | `render` | `render` | `set-hud(shapes)`: up to 1024 fills, four-cornered shapes, GUI sprites, items and text, kept on the HUD (over the hotbar, under chat and screens, hidden with F1) until replaced; `set-corner(corner, w, h, shapes)`: a box the game places in a corner, stacked with its overlays and other panels, as `hud`'s panels are; `text-width(text)`; `frame-stats()`: the game's FPS, min and 1% low; `gui-size()`; `shake(strength, seconds)`: the view turns, the player doesn't, scaled by Distortion Effects; `set-zoom(zoom)`: the field of view divided by up to 10, eased or at once, with slower turning, while playing and not through a spyglass (the strongest of several mods' zooms counts); `set-minimap(minimap)`: a map of the world around the player in a corner, as a map item colours it (the floor underground and under roofs), square or round, turning with the player or north up, with the player's arrow; the game keeps its tiles within its own frame budget (one map at a time, the first loaded mod's). The game's own HUD renderer draws them: a mod never supplies shader code. **Experimental:** `experimental = ["render"]` | | `input` | `input` | `claim-items(ids)`: the use button on those items is the mod's (`use-start`, `use-stop` with the ticks held; the game doesn't place, eat or swing); `register-key(name, label, key)`: up to 16 keys (`key.keyboard.r`), heard while playing as `key-down` / `key-up` (the game's own mapping on that key still runs; a screen opening lets held keys up), mouse buttons as `key.mouse.4`. The player rebinds them on the mod's page in Options > Mods, where the game lists them first as Key Binds rows (click, then press a key or mouse button; Esc binds none), even for a mod without `ui`; the choice is kept in `horizon-mods.txt` (`key..:key.keyboard.z`) and wins over `register-key`'s default; `claim-wheel(on)`: the wheel's steps become `wheel` events and the hotbar doesn't move (the one input a mod takes from the game; a mod's keys never do); `held()`; `mapping(name)`: a movement or click mapping's key label and whether it is held; `clicks-per-second()`; `poll()` returns the events, at most 256 kept. **Experimental:** `experimental = ["input"]` | +| `recipes` | `recipes` | `items()`: every item in the registry's order, with its name in the player's language and its tags; `all()`: every recipe (crafting, smelting, blasting, smoking, campfire, stonecutting, smithing, brewing), its slots as the stacks that fit each, its results, cooking time and experience, and the recipe book's id for it; `known()`: the book ids the player's recipe book holds; `place(book-id, all)`: the recipe book's click on a recipe, in the open inventory's or crafting table's grid (refused for a recipe the player's book doesn't hold, as vanilla's server refuses it); `give(stack)`: in creative mode, the stack into the player's inventory, as from the creative inventory. The recipes are the world's in single player and on Horizon's servers, vanilla 26.3's on any other server (a client is sent no others), while `known` follows that server's book. The game makes the tables once, when a mod first reads them. **Experimental:** `experimental = ["recipes"]` | | Hook (export) | When | |---|---| @@ -116,7 +117,6 @@ loading. Ordered by what the first native ports need: | `keys` | keybinds | registered binds appear in Controls; press/release events | | `target` | the crosshair's block or entity, with its state and NBT summary | Jade/WTHIT-style tooltips | | `inventory-read` | the player's inventory, held item, open container | AppleSkin, recipe viewers | -| `recipes` | the recipe registry and lookups | JEI/EMI-style viewers | | `world-read` | blocks and biomes around the player, within the render distance | minimaps, schematics | | `render` (world) | world-space lines, boxes and billboards, beside the HUD shapes `render` has | Litematica-style placement, waypoints | | `registries` | new blocks, items, entities and recipes, mostly data: JSON models, textures, loot and recipes in the `.hmod`'s `assets/` and `data/` | server side; see [Multiplayer](#multiplayer) | @@ -285,6 +285,7 @@ A step's parts happen in this order: | --- | --- | | `reload = true` | stops the mod and starts it again, as a rebuild does in the game: its memory starts over, its `storage` stays | | `title-screen = true` | no player and no clock until a step sets them | +| `blocks = [{ x = 0, y = 63, z = 0, state = "minecraft:stone" }]` | server mods with `world`: those blocks of the Overworld, before the rest of the step (every other block is air, every biome the dimension's plainest: plains, nether wastes, the end) | | `player = { x = 3.0, ... }`, `clock = { day-time = 0 }` | changes those fields (`x y z yaw pitch health food dimension`, `game-time day-time`) | | `ticks = n`, `frames = n` | that many ticks (the game's tick counter and the clock move on), then frames 1/60 s apart | | `chat = " hi"` | a chat line the player receives | @@ -310,6 +311,7 @@ checked: | `feedback = "..."`, `error = "..."` | the command's answer, shown plain or in red | | `panel = ["..."]`, `corner = "top-left"` | its HUD panel's lines (`[]`: no panel) and corner | | `told = ["Alex: Welcome!"]`, `broadcast = ["..."]` | server mods: every `players.tell` (as `name: text`) and `players.broadcast`, in order | +| `blocks = [{ x = 2, y = 64, z = 0, state = "minecraft:glowstone" }]` | server mods with `world`: those blocks of the Overworld after the step, the mod's `set-blocks` made (the script checks a state's shape; the game checks its name) | | `stopped = "panic"` | the mod was turned off, for a reason holding this text; without it, a mod that traps, panics or overruns fails the test | Unknown keys are errors, so a typo never passes silently. The same runner is @@ -478,6 +480,7 @@ its component targets the WIT world `horizon-server-mod` instead of | `log` | always | as for client mods | | `storage` | `storage` | as for client mods, in the server's `horizon-mods/` | | `players` | `players` | `online()`: id, name, position, dimension, game mode, health of each player on; `tell(id, text)`, `broadcast(text)`: system messages after the mod's name, 8 per call | +| `world` | `world` | `get-block(dimension, x, y, z)`: the state in a loaded chunk, `minecraft:oak_log[axis=y]`; `get-biome(dimension, x, y, z)`: `minecraft:plains`, ...; `set-blocks(dimension, changes)`: up to 4096 per call, checked at once, made as `/setblock` makes them (neighbours, light, block entities, every player told) after the call, before that dimension's next tick | | Hook (export `server-events`) | When | |---|---| @@ -485,13 +488,51 @@ its component targets the WIT world `horizon-server-mod` instead of | `tick(tick)` | each server tick | | `player-joined(player)`, `player-left(player)` | `registration.joins` | | `chat(player, text)` | `registration.chat`: each chat message a player sends | -| `command(player, name, args)` | `/name args` typed by a player, for a command it registered; `ok(some)` is that player's feedback, `err` their red error | +| `command(player, name, args, values)` | `/name args` typed by a player, for a command it registered, with its arguments' values (below); `ok(some)` is that player's feedback, `err` their red error | | `block-broken(player, pos, state)`, `block-placed(player, pos, state)` | `registration.blocks`, with the state as `minecraft:oak_log[axis=y]` | Capabilities that act on a local player (`game-read`, `chat`, `hud`) are for client mods; `players` is for server mods. In Rust: `impl horizon_mod_sdk::server::ServerMod` and `export_server_mod!`; the example is -[`welcome`](../crates/horizon-mod-sdk/examples/welcome/src/lib.rs). +[`welcome`](../crates/horizon-mod-sdk/examples/welcome/src/lib.rs), and with +`world`, [`beacons`](../crates/horizon-mod-sdk/examples/beacons/src/lib.rs). + +**Typed commands.** Each command in `registration.commands` lists its +arguments, in order: a name and a kind, required or optional (optional ones +last). The server adds them to the command tree every player receives, after +vanilla's commands, so a player's chat box completes and colours them as it +does vanilla's (player names, coordinates, bounds); when a player sends one, +the server parses the line the way vanilla's parsers do and gives the mod the +values, by argument name, or answers with vanilla's error (`Integer must not +be more than 64, found 65`, `No player was found`) without calling the mod. + +| Kind | Takes | Value | Chat box parser | +|---|---|---|---| +| `word` | one word: letters, digits, `_ - . +` | `word(string)` | `brigadier:string` (word) | +| `text` | the rest of the line, only last | `text(string)` | `brigadier:string` (greedy) | +| `integer(min, max)` | a whole number within the bounds given | `integer(s32)` | `brigadier:integer` | +| `number` | a number | `number(f64)` | `brigadier:double` | +| `boolean` | `true` or `false` | `boolean(bool)` | `brigadier:bool` | +| `player` | an online player's name, `@s` or `@p` (whoever typed it) | `player(player)` | `minecraft:entity` (one player) | +| `block-pos` | `x y z`, each a whole number, `~` or `~n` (from whoever typed it) | `block-pos(block-pos)` | `minecraft:block_pos` | + +A command with no arguments takes nothing after its name. In Rust, +`Registration::command_with("beacon", [Argument::integer("height", Some(1), +Some(64)).optional()])`, read with `args.integer("height")`; `command(name)` +alone takes free text, an optional `text` argument named `args` +(`args.text()` is the line as typed either way). + +**Capability `world`.** Reads are of the server's loaded chunks as they are +during the call: the game lends a server mod's call the levels' chunk maps +(moved, not copied, and only while a running mod has `world`), so a read +costs a map lookup and no copy of the world. A dimension with no chunk loaded +at a position reads as none. Writes go through the same code as `/setblock`, +so block updates, light, block entities and every client (LAN guests, +dedicated server players) see them as vanilla's; the parity harnesses test +that code. Changes for a dimension whose level isn't ticking wait for it +(in-frame single player ticks only the player's), up to 65,536 blocks; a +change in a chunk that isn't loaded when it is made is skipped, as `/setblock` +refuses one. **Where they run.** The game that simulates the world starts the server mods that are on, and only that one: @@ -521,10 +562,11 @@ chat for the in-frame player and a system message for a connection; on, each of these points costs one branch (measured in the PR that added them). -**Not yet.** Clients aren't sent server mods' commands with vanilla's -command tree, so a player's chat box doesn't complete or colour them; typing -them works. Block events are a player's own breaking and placing, not -explosions, pistons or other mods. +**Not yet.** Block events are a player's own breaking and placing, not +explosions, pistons or other mods. Command arguments don't take entities, +items or block states yet, and `^` coordinates; in-frame single player's chat +box lists server mods' commands by name only (the server still parses their +arguments). ## Publish your mod @@ -555,7 +597,7 @@ says how). The formats: [api/mod-index.md](api/mod-index.md). ### Horizon's official mods -The Horizon extras that are mods now live in `mods/official//`, one crate each in the game's workspace, so +The Horizon extras that are mods now, and Horizon's own recipe viewer, live in `mods/official//`, one crate each in the game's workspace, so `cargo clippy --workspace` and pr_ready cover them. They use only the public API, like any other mod, with the same options on their settings page as the extra had and the same look. Each is published by a maintainer: build it on `main` with the toolchain CI uses (`cd mods/official/ && cargo horizon-mod build`), then open a pull request in @@ -569,6 +611,7 @@ so the same rustc and `Cargo.lock` give the same file. | Keystrokes | `keystrokes` | Extras > Keystrokes | `corner`: as above, default `top_left`; `cps`: `true` (default), `false` | | Zoom | `zoom` | Extras > Zoom | `level`: `2`, `3`, `4` (default), `6`, `8`, `10`; `smooth`: `true` (default), `false`; `sensitivity` (slower turning): `true` (default), `false`. The key is the game's: `key.zoom.zoom` in `horizon-mods.txt`, default `key.keyboard.z` | | Minimap | `minimap` | Extras > Minimap | `corner`: as above, default `top_right`; `size`: `64`, `96` (default), `128`; `shape`: `square` (default), `round`; `zoom` (blocks per pixel): `0.5`, `1` (default), `2`, `4`; `rotate`: `false` (default), `true`. The game draws the map (`render.set-minimap`) | +| Recipes | `recipes` | nothing (new) | `give` (a click on the item panel gives the item in creative mode: one, a stack with a right click): `false` (default), `true`. The keys are the game's: `key.recipes.recipe` (default `key.keyboard.r`) and `key.recipes.uses` (default `key.keyboard.u`) in `horizon-mods.txt`. Every item sits in the item panel (`browser`) with a search box (words in the name or id, `@namespace`, `#tag`); R or a click shows an item's recipes, U or a right click its uses, a tab per station, and + fills the grid with a recipe the player knows (`recipes.place`). On servers that are not Horizon it shows the game's own 26.3 recipes; known recipes and + follow the server's recipe book | ## Versions and compatibility diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index 27505d9de..6cb235c3c 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -44,6 +44,17 @@ Harnesses can also run on the Mac mini, the desktop and playhorizon (`tools/pari Harnesses a host can't run are listed in the file: `local_only` (`save_roundtrip` runs the game on a virtual screen) and each host's `exclude`. The Mac excludes nothing: vanilla's `Math.sin`, `pow`, `log` and the like don't round the same on an Apple silicon Mac as on Linux (HotSpot uses fdlibm there, Intel's stubs on x86-64), and Rust's float functions round like neither (they call the platform libm), so code that mirrors a vanilla `Math` call uses `horizon_core::jmath`, which computes what HotSpot computes on the host architecture. The ThinkPad no longer runs harnesses (2026-10-26): playhorizon is the Linux host that is always on. +### Any command on playhorizon: `tools/remote.sh` + +For Linux work that doesn't need a whole parity run (a crate's tests, a few harnesses, a server build), `tools/remote.sh ` runs the command on playhorizon at the worktree's commit and streams its output back; its exit status is the command's. Commit and push first: the host fetches the commit from GitHub, and nothing else leaves this machine (no files, no credentials, no environment). Each worktree keeps one checkout there, `~/remote-work/` with its own `target/`, so the next run only rebuilds what changed, and one run per name goes at a time. The command runs niced in the host's CI slice, pinned to CPUs 4-7 (`--cpus`; 0-3 stay free for benchmarks), with scratch game and launcher homes and the vanilla data linked as CI links it; a command naming `parity`, `lan_e2e` or `horizon-prepare` also gets `.local/horizon-client`, prepared as CI prepares it. Whatever the command leaves running (a game, a daemon) is stopped when it ends, and stopping `remote.sh` (or losing the connection) stops the command on the host. Logs stay in `~/remote-work/.logs/`; `--list` shows the checkouts, `--gc [DAYS]` removes old ones. + +```sh +tools/remote.sh .claude/worktrees/my-fix cargo test -p horizon-world --lib # 33 s, warm +tools/remote.sh . python3 tools/parity.py food # 19 s warm (4 min the first time); here: 188 s, 229 CPU-seconds +``` + +The host is lent by a partner who keeps hypervisor access: send it no secret, token or credential, and never take a result from it as a CI result. + ### Shards and Rust scopes A harness can declare, at the top level of its script: @@ -53,7 +64,7 @@ A harness can declare, at the top level of its script: ### Which harnesses a change affects -`--changed` and `--changed-files` narrow each harness's Rust sources to those its probes can reach (`tools/parity_reach.py`), so a change to one module of `horizon-client` no longer reruns every harness whose probe links the crate. The narrowing works on items, not files: from the probe modules a harness ran (or the binary it built), a free item (fn, type, const, static) is reached when a reached item names it in its own module, through a path or an import of a module that is named, or through a glob import; an inherent impl's methods count one by one once their type is reached and their name is mentioned; a trait impl counts once its trait and its type are reached (std's traits and types always are); a macro counts once invoked. Names match by spelling, so the result only over-approximates. A reached file's parent modules count through their `mod` declarations of it, compared with the merge base; Rust files a change adds take part, a dependency that was deleted counts as changed, code under `#[cfg(test)]` never counts, and a harness whose probe can't be found keeps every source. Parses are cached by content in `reach-cache.json` of the shared parity folder (beside `passes/`), so a new worktree starts warm; a harness's search stops as soon as it reaches a changed file, and after `PARITY_REACH_BUDGET` seconds (default 180) the remaining harnesses count every source their probes link, so choosing never holds a slow machine for long. `--by-crate` turns the narrowing off. On the last 20 pull requests merged on 2026-10-25, the harnesses picked went from 2255 to 1061 (2384 to 1592 harness-minutes; game-binary harnesses, which link all of `game/`, set the floor), and every harness a CI parity run failed in the week before was still picked; every source file a sample of probes executed (LLVM `-C instrument-coverage`) is among those kept. Building the graph takes 15 s cold, under a second warm, and up to a minute and a half on a change that reaches many harnesses. +`--changed` and `--changed-files` narrow each harness's Rust sources to those its probes can reach (`tools/parity_reach.py`), so a change to one module of `horizon-client` no longer reruns every harness whose probe links the crate. The narrowing works on items, not files: from the probe modules a harness ran (or the binary it built), a free item (fn, type, const, static) is reached when a reached item names it in its own module, through a path or an import of a module that is named, or through a glob import; an inherent impl's methods count one by one once their type is reached and their name is mentioned; a trait impl counts once its trait and its type are reached (std's traits and types always are); a macro counts once invoked. Names match by spelling, so the result only over-approximates. A reached file's parent modules count through their `mod` declarations of it, compared with the merge base; Rust files a change adds take part, a dependency that was deleted counts as changed, code under `#[cfg(test)]` never counts, and a harness whose probe can't be found keeps every source. Parses are cached by content in `reach-cache.json` of the shared parity folder (beside `passes/`), so a new worktree starts warm; a harness's search stops as soon as it reaches a changed file, and after `PARITY_REACH_BUDGET` seconds (default 180) the remaining harnesses count every source their probes link, so choosing never holds a slow machine for long. `--by-crate` turns the narrowing off. With `--changed`, `Cargo.lock` and `Cargo.toml` changes that only add, remove or move workspace crates (a crate split: no registry or git package, version, feature, dependency or build setting changed across them, compared with the merge base) don't count: the moved code counts through its sources. A workspace crate's feature that such a change defines or turns on is allowed only where every source naming it changed too (the new crate's own files). #2160's split went from 352 harnesses to 123 this way (its own changes to the runner still select them all). On the last 20 pull requests merged on 2026-10-25, the harnesses picked went from 2255 to 1061 (2384 to 1592 harness-minutes; game-binary harnesses, which link all of `game/`, set the floor), and every harness a CI parity run failed in the week before was still picked; every source file a sample of probes executed (LLVM `-C instrument-coverage`) is among those kept. Building the graph takes 15 s cold, under a second warm, and up to a minute and a half on a change that reaches many harnesses. ## The gate @@ -133,6 +144,13 @@ when named and in the nightly audit (`--all`). LAN writes `results.json` with the host mode and each result beside its screenshots and logs. A skipped case is recorded explicitly and does not count as passing coverage. +`known_flaky` in `tools/parity_hosts.json` lists harnesses that fail now and then for a +cause not fixed yet, each with its reason. One that fails runs once more from +scratch, and a pass then counts. `parity.py` prints a `RETRIED` line for it +in its summary and in the CI job's summary (PR parity and parity-main), so the +flake stays visible. No other harness gets this retry. Fix the cause, then take +the harness off the list. + The game-binary fixture audit keeps these complementary direct rule tests: - `command_harness.rs`: command feedback, styled spans and result callbacks, diff --git a/docs/release-flow.md b/docs/release-flow.md index ce7934824..ed7be2418 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -13,7 +13,7 @@ reopened; labels never start it): | Job | Runs on | What | Time | | --- | --- | --- | --- | | `verify` | GitHub `ubuntu-latest` | Public-tree check, Python tests, rustfmt, clippy with warnings denied, Rust tests. Dependencies and the workspace build come from a cache saved by main's runs | ~4 min cold, less warm | -| `parity / parity` | A runner with the label `horizon-game`: the Mac mini's two, and the desktop's while nobody uses it (below) | Only for a change to a harness, an oracle, a probe or the runner (or the `run-parity` label): the vanilla harnesses the change can affect (`tools/parity.py --changed `). Other pull requests skip it: [parity-main](#parity-on-main) checks them on main | seconds when nothing is affected; minutes per affected harness | +| `parity / parity` | A runner with the label `horizon-game`: the Mac mini's and playhorizon's (below) | Only for a change to a harness, an oracle, a probe or the runner (or the `run-parity` label): the vanilla harnesses the change can affect (`tools/parity.py --changed `). Other pull requests skip it: [parity-main](#parity-on-main) checks them on main | seconds when nothing is affected; minutes per affected harness | Pushes to main run `verify` only; the nightly audit covers main's harnesses. @@ -27,11 +27,23 @@ quick steps and finishes in seconds. The job is `.github/workflows/parity.yml`, a reusable workflow: `checks` calls it for pull requests from this repository, `run-parity.yml` for a fork's pull request a maintainer labels `run-parity`. +A pull request every harness reaches (a crate split moves files every probe links: #2160 ran all 352 harnesses, 71 +minutes on a Mac mini runner, while five other pull requests' jobs queued behind it) carries the `full-parity` label: +its job runs on playhorizon's runner only (4 harnesses at a time), and waits for it while that runner is busy +instead of taking the Mac mini's. Labels don't start `checks`: add it when opening the pull request +(`gh pr create --label full-parity`), or before the next push. + Horizon never downloads the game, so harnesses that compare with vanilla run only where the maintainer's own -copy is: the Mac mini, his Linux desktop and playhorizon (below). Their runners run as the maintainer's account and keep their checkout +copy is: the Mac mini and playhorizon (below). Their runners run as the maintainer's account and keep their checkout between runs (`clean: false`), so the probes build incrementally into `.local/parity-target` and earlier passes stand. +The job tests the pull request's head merged into main's current tip, which is what merging it would land: harness +and game fixes that reached main after the branch was made apply to it too, and an old branch runs main's runner +scripts and selection unless it changes them. The base for the selection is that main commit, so only the pull +request's own changes count. The job summary names the main commit. A head that conflicts with main is tested +alone, with a warning. The check is still reported on the head. + 1. `tools/ci/runner-env.sh` puts the machine's Python 3.13 and the JDK `research-lock.json` pins on the PATH (Homebrew and `java_home` on the Mac; on Linux what `linux-runner.sh` pinned, else nixpkgs), and sccache when the machine has it. @@ -50,9 +62,6 @@ stand. modules, Java oracles and every Rust source their probes compile) changed since the merge base, plus any harness nothing is recorded about yet, and runs those that have no pass for their current inputs. A change to `Cargo.lock` or `research-lock.json` affects every harness. Each harness has 25 minutes, the job 45. - The selection runs with main's `tools/parity.py` and `tools/parity_reach.py` (`--changed --list`), so a - branch made before a better selection landed gets it too, and the head's own `parity.py` then runs the named - harnesses. A branch that changes either file selects with its own code. Failed harnesses' logs are uploaded as the `parity-logs` artifact. @@ -74,8 +83,9 @@ release's macOS build back. Each keeps its own checkout, `target/` and Rust inst `_work/horizon/shared-local` links to the first's, so they share the vanilla data, the preparations (one at a time, under a lock) and the parity passes and slots. -**The desktop's runner.** `ludodesktop-horizon` (labels `self-hosted`, `Linux`, `X64`, `ludodesktop`, and -`horizon-game` once a full trial has passed there) runs on the maintainer's Linux desktop while nobody uses it: its +**The desktop's runner (retired).** On 2026-10-26 the maintainer asked that CI stop using his desktop: its services are +stopped and `ludodesktop-horizon` has no label a job asks for (only `self-hosted`, `Linux`, `X64`), so nothing waits for +it. What follows describes it as it ran. It ran on the maintainer's Linux desktop while nobody used it: its screen locked, or untouched for 15 minutes (his rule, 2026-10-26). `tools/ci/linux-runner.sh install`, run there as him, registers it and installs two systemd user services: `horizon-runner` (the runner, in `~/.actions-runners/horizon`, nice 19, in `horizon-ci.slice` with CPU and I/O weight 20, half the threads (on all of @@ -96,12 +106,16 @@ and its failures bisect and comment on merges. **playhorizon's runner.** `playhorizon-horizon` runs on a server a hosting partner lends the project (Ubuntu, 8 AMD EPYC threads, 30 GB, in Detroit; reachable only through the maintainer's tailnet). Nobody sits at it, so the -watcher never pauses it except by hand, and it gets the machine: `RUNNER_CPUS=7 RUNNER_MEMORY=24 RUNNER_JOBS=6`. +watcher never pauses it except by hand. It gets half the machine: `RUNNER_MEMORY=24`, `CARGO_BUILD_JOBS` and the +harness slots at 4, and a drop-in (`~/.config/systemd/user/horizon-runner.service.d/cpus.conf`) that starts it under +`taskset -c 4-7`, so CPUs 0-3 stay free for benchmarks pinned there (the user slice can't set `AllowedCPUs`: systemd +doesn't delegate the cpuset controller to it). Without Nix, `linux-runner.sh` takes the build libraries, the JDK, sccache, Xvfb and Mesa's software Vulkan (lavapipe; there is no GPU) from apt, and Python 3.13 from uv. The partner can reach the machine, so gh is not logged in there: the registration token comes from another machine (`RUNNER_TOKEN`), and no job with secrets may -run there (parity has none). It is also a parity host (`playhorizon` in `tools/parity_hosts.json`, 6 jobs). Like -the desktop's, it gets the `horizon-game` label only once a full trial has passed there. +run there (parity has none). It is also a parity host (`playhorizon` in `tools/parity_hosts.json`, 6 jobs). Since +2026-10-26 it has the `horizon-game` label: pull requests' parity jobs run there or on the Mac mini, and `full-parity` +ones only there. ## Merging @@ -209,6 +223,7 @@ How releases are numbered, and how installs from before 0.2 reach it: [versionin | `release-now` | Releases as soon as main's checks pass, without waiting for merges to settle | | `skip-release` | Doesn't trigger a release and isn't listed in the notes | | `run-parity` | Runs the parity job once on a fork's pull request | +| `full-parity` | Runs the pull request's parity job on playhorizon's runner only (a change every harness reaches) | | `parity-regression` | Opened by the nightly audit for a harness that fails on main | | `release-blocker` | On an issue: no game release is published while it is open ([One channel](#one-channel)) | diff --git a/docs/version-ports.md b/docs/version-ports.md index 623e3c082..4ecad210f 100644 --- a/docs/version-ports.md +++ b/docs/version-ports.md @@ -43,7 +43,7 @@ to players. Players still prepare their own copy from their official launcher (` | `crates/horizon-client/src/lan/tracking.rs` | `generate_entity_tracking.py` | decompiled `EntityTypes` | | `crates/horizon-client/src/lan/command_suggestions.rs` | `generate_command_suggestions.py` | `VanillaCommandSuggestionsExporter` | | `crates/horizon-client/src/lan/command_order.rs` | `generate_lan_command_order.py` | vanilla's command tree | - | `crates/horizon-client/src/command/vanilla_order.rs` | `generate_command_order.py` | command-parse harness export | + | `crates/horizon-command/src/vanilla_order.rs` | `generate_command_order.py` | command-parse harness export | | `crates/horizon-world/src/datafix/block_state_data.txt` | `gen_block_state_data.py` | decompiled `BlockStateData` | | `crates/horizon-world/src/datafix/flat_tables.rs` | `gen_flat_tables.py` | 1.13 flattening fixers (never change) | diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock index dd9313df6..422c2ace9 100644 --- a/launcher/Cargo.lock +++ b/launcher/Cargo.lock @@ -70,6 +70,15 @@ dependencies = [ "equator", ] +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + [[package]] name = "anstream" version = "1.0.0" @@ -919,6 +928,17 @@ dependencies = [ "zeroize", ] +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link 0.2.1", +] + [[package]] name = "cipher" version = "0.4.4" @@ -981,6 +1001,15 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" +[[package]] +name = "cobs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "cocoa" version = "0.25.0" @@ -1635,6 +1664,18 @@ dependencies = [ "winreg", ] +[[package]] +name = "embedded-io" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced" + +[[package]] +name = "embedded-io" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" + [[package]] name = "encoding_rs" version = "0.8.42" @@ -2354,7 +2395,7 @@ dependencies = [ "wayland-protocols-plasma", "windows 0.61.3", "windows-core 0.61.2", - "windows-numerics", + "windows-numerics 0.2.0", "windows-registry 0.5.3", "x11-clipboard", "x11rb", @@ -2693,6 +2734,8 @@ dependencies = [ name = "horizon-launcher" version = "0.2.0" dependencies = [ + "base64", + "chrono", "clap", "dirs 5.0.1", "flate2", @@ -2708,6 +2751,7 @@ dependencies = [ "horizon-release-sign", "horizon-telemetry", "horizon-theme", + "horizon-world", "image", "keyring", "objc2-app-kit", @@ -2720,6 +2764,8 @@ dependencies = [ "sha1", "sha2 0.10.9", "tar", + "toml 1.1.8+spec-1.1.0", + "trash", "ureq", "winresource", "zip", @@ -2801,6 +2847,21 @@ dependencies = [ name = "horizon-theme" version = "0.1.0" +[[package]] +name = "horizon-world" +version = "0.1.0" +dependencies = [ + "flate2", + "horizon-core", + "libm", + "lz4_flex", + "postcard", + "serde", + "serde_json", + "sha2 0.10.9", + "xxhash-rust", +] + [[package]] name = "http" version = "1.5.0" @@ -2907,6 +2968,30 @@ dependencies = [ "tracing", ] +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core 0.61.2", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + [[package]] name = "icu_collections" version = "2.3.0" @@ -3425,6 +3510,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "lz4_flex" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecbdfe44b1bd960b68170b417450a628c43f7cf56bb3c5317e61cb230ee7f226" + [[package]] name = "mac" version = "0.1.1" @@ -4263,6 +4354,18 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "postcard" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" +dependencies = [ + "cobs", + "embedded-io 0.4.0", + "embedded-io 0.6.1", + "serde", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -6187,6 +6290,24 @@ dependencies = [ "once_cell", ] +[[package]] +name = "trash" +version = "5.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be89b3fe156965d29ac4f8522f3a640c655affdd9f21cb4f36857f0c92c00317" +dependencies = [ + "chrono", + "libc", + "log", + "objc2", + "objc2-foundation", + "once_cell", + "percent-encoding", + "scopeguard", + "urlencoding", + "windows 0.62.2", +] + [[package]] name = "try-lock" version = "0.2.5" @@ -6367,6 +6488,12 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + [[package]] name = "usvg" version = "0.45.1" @@ -6820,11 +6947,23 @@ version = "0.61.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" dependencies = [ - "windows-collections", + "windows-collections 0.2.0", "windows-core 0.61.2", - "windows-future", + "windows-future 0.2.1", "windows-link 0.1.3", - "windows-numerics", + "windows-numerics 0.2.0", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections 0.3.2", + "windows-core 0.62.2", + "windows-future 0.3.2", + "windows-numerics 0.3.1", ] [[package]] @@ -6837,7 +6976,7 @@ dependencies = [ "rayon", "thiserror 2.0.21", "windows 0.61.3", - "windows-future", + "windows-future 0.2.1", ] [[package]] @@ -6849,6 +6988,15 @@ dependencies = [ "windows-core 0.61.2", ] +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core 0.62.2", +] + [[package]] name = "windows-core" version = "0.57.0" @@ -6874,6 +7022,19 @@ dependencies = [ "windows-strings 0.4.2", ] +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement 0.60.2", + "windows-interface 0.59.3", + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + [[package]] name = "windows-future" version = "0.2.1" @@ -6882,7 +7043,18 @@ checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" dependencies = [ "windows-core 0.61.2", "windows-link 0.1.3", - "windows-threading", + "windows-threading 0.1.0", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", + "windows-threading 0.2.1", ] [[package]] @@ -6951,6 +7123,16 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", +] + [[package]] name = "windows-registry" version = "0.4.0" @@ -6991,6 +7173,15 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link 0.2.1", +] + [[package]] name = "windows-strings" version = "0.3.1" @@ -7009,6 +7200,15 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link 0.2.1", +] + [[package]] name = "windows-sys" version = "0.48.0" @@ -7111,6 +7311,15 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link 0.2.1", +] + [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" @@ -7423,6 +7632,12 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" +[[package]] +name = "xxhash-rust" +version = "0.8.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7" + [[package]] name = "y4m" version = "0.8.0" diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml index a97f128b8..356e8ae2e 100644 --- a/launcher/Cargo.toml +++ b/launcher/Cargo.toml @@ -19,6 +19,7 @@ sha2 = "0.10" pulldown-cmark = { version = "0.12", default-features = false } flate2 = "1" tar = { version = "0.4", default-features = false } +toml = "1.1" zip = { version = "2", default-features = false, features = ["deflate"] } dirs = "5" self-replace = "1" @@ -37,6 +38,13 @@ horizon-mods = { path = "../crates/horizon-mods", features = ["index"] } horizon-release-sign = { path = "../crates/horizon-release-sign" } # Opt-in data collection: the consent, the outbox and its upload (docs/telemetry.md). horizon-telemetry = { path = "../crates/horizon-telemetry" } +# level.dat and servers.dat (the worlds and server lists of instances) +horizon-world = { path = "../crates/horizon-world" } +# Deleting a world moves it to the system's trash +trash = "5" +# Backup names carry the local time, as vanilla's do +base64 = "0.22" +chrono = { version = "0.4", default-features = false, features = ["clock"] } # The session file's random name. getrandom = "0.3" # Players' heads on the Servers page, from the default skins in the player's own game files (already diff --git a/launcher/README.md b/launcher/README.md index 9c6f3a9d9..aeeb4f288 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -69,6 +69,37 @@ The opening, then Play ([clip](docs/opening.webm)): access controls, one click changes them so friends you share with reach only the server's port (Remove the limit undoes it); custom access controls are never rewritten, the page gives the rule to add instead. Horizon never turns on Funnel. +- **Instances**: separate game folders, each with its own worlds, options and packs. The game's + folder stays the first one, "Horizon", exactly where it was; imported and registry modpacks are + instances too, in their own folders as before; new ones go to `instances//` in the game's + folder, empty but for the player's options and name, or a copy of another instance (never its + sign-in sessions, logs or data collection state). Names, icons (a block or item texture from the + player's prepared files, or a colour) and groups are kept in `instances.json` in the launcher's + data folder, so renaming moves nothing. Every instance follows the launcher's data collection + answer and No AI. In the window, **+** beside Instances makes one, the sidebar lists them by + group (click one to play it), and Home's Instance row has Edit (name, group, icon), Copy and + Open folder. The Instance row shows its play time and when it was last played: every run started + from the window or `horizon-launcher play` adds to it (`instance list` shows it too). Each + instance plays the launcher's version, which follows updates, unless the Play page's version + picker keeps it on another installed one (to keep an old world on the version it was made + with); picking the version marked "follows updates" lets it follow again. +- **Worlds**: Home lists the selected instance's worlds (picture, mode, version, last played, + size). **Back up** zips one into the instance's `backups/` as the game's Make Backup does + (`_